1 /**********************************************************************
2 
3   signal.c -
4 
5   $Author: nobu $
6   created at: Tue Dec 20 10:13:44 JST 1994
7 
8   Copyright (C) 1993-2007 Yukihiro Matsumoto
9   Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
10   Copyright (C) 2000  Information-technology Promotion Agency, Japan
11 
12 **********************************************************************/
13 
14 #include "internal.h"
15 #include "vm_core.h"
16 #include <signal.h>
17 #include <stdio.h>
18 #include <errno.h>
19 #include "ruby_atomic.h"
20 #include "eval_intern.h"
21 #ifdef HAVE_UNISTD_H
22 # include <unistd.h>
23 #endif
24 #ifdef HAVE_SYS_UIO_H
25 #include <sys/uio.h>
26 #endif
27 #ifdef HAVE_UCONTEXT_H
28 #include <ucontext.h>
29 #endif
30 
31 #ifdef HAVE_VALGRIND_MEMCHECK_H
32 # include <valgrind/memcheck.h>
33 # ifndef VALGRIND_MAKE_MEM_DEFINED
34 #  define VALGRIND_MAKE_MEM_DEFINED(p, n) VALGRIND_MAKE_READABLE((p), (n))
35 # endif
36 # ifndef VALGRIND_MAKE_MEM_UNDEFINED
37 #  define VALGRIND_MAKE_MEM_UNDEFINED(p, n) VALGRIND_MAKE_WRITABLE((p), (n))
38 # endif
39 #else
40 # define VALGRIND_MAKE_MEM_DEFINED(p, n) 0
41 # define VALGRIND_MAKE_MEM_UNDEFINED(p, n) 0
42 #endif
43 
44 #ifdef NEED_RUBY_ATOMIC_OPS
45 rb_atomic_t
ruby_atomic_exchange(rb_atomic_t * ptr,rb_atomic_t val)46 ruby_atomic_exchange(rb_atomic_t *ptr, rb_atomic_t val)
47 {
48     rb_atomic_t old = *ptr;
49     *ptr = val;
50     return old;
51 }
52 
53 rb_atomic_t
ruby_atomic_compare_and_swap(rb_atomic_t * ptr,rb_atomic_t cmp,rb_atomic_t newval)54 ruby_atomic_compare_and_swap(rb_atomic_t *ptr, rb_atomic_t cmp,
55 			     rb_atomic_t newval)
56 {
57     rb_atomic_t old = *ptr;
58     if (old == cmp) {
59 	*ptr = newval;
60     }
61     return old;
62 }
63 #endif
64 
65 #define FOREACH_SIGNAL(sig, offset) \
66     for (sig = siglist + (offset); sig < siglist + numberof(siglist); ++sig)
67 enum { LONGEST_SIGNAME = 7 }; /* MIGRATE and RETRACT */
68 static const struct signals {
69     char signm[LONGEST_SIGNAME + 1];
70     int  signo;
71 } siglist [] = {
72     {"EXIT", 0},
73 #ifdef SIGHUP
74     {"HUP", SIGHUP},
75 #endif
76     {"INT", SIGINT},
77 #ifdef SIGQUIT
78     {"QUIT", SIGQUIT},
79 #endif
80 #ifdef SIGILL
81     {"ILL", SIGILL},
82 #endif
83 #ifdef SIGTRAP
84     {"TRAP", SIGTRAP},
85 #endif
86 #ifdef SIGABRT
87     {"ABRT", SIGABRT},
88 #endif
89 #ifdef SIGIOT
90     {"IOT", SIGIOT},
91 #endif
92 #ifdef SIGEMT
93     {"EMT", SIGEMT},
94 #endif
95 #ifdef SIGFPE
96     {"FPE", SIGFPE},
97 #endif
98 #ifdef SIGKILL
99     {"KILL", SIGKILL},
100 #endif
101 #ifdef SIGBUS
102     {"BUS", SIGBUS},
103 #endif
104 #ifdef SIGSEGV
105     {"SEGV", SIGSEGV},
106 #endif
107 #ifdef SIGSYS
108     {"SYS", SIGSYS},
109 #endif
110 #ifdef SIGPIPE
111     {"PIPE", SIGPIPE},
112 #endif
113 #ifdef SIGALRM
114     {"ALRM", SIGALRM},
115 #endif
116 #ifdef SIGTERM
117     {"TERM", SIGTERM},
118 #endif
119 #ifdef SIGURG
120     {"URG", SIGURG},
121 #endif
122 #ifdef SIGSTOP
123     {"STOP", SIGSTOP},
124 #endif
125 #ifdef SIGTSTP
126     {"TSTP", SIGTSTP},
127 #endif
128 #ifdef SIGCONT
129     {"CONT", SIGCONT},
130 #endif
131 #if RUBY_SIGCHLD
132     {"CHLD", RUBY_SIGCHLD },
133     {"CLD", RUBY_SIGCHLD },
134 #endif
135 #ifdef SIGTTIN
136     {"TTIN", SIGTTIN},
137 #endif
138 #ifdef SIGTTOU
139     {"TTOU", SIGTTOU},
140 #endif
141 #ifdef SIGIO
142     {"IO", SIGIO},
143 #endif
144 #ifdef SIGXCPU
145     {"XCPU", SIGXCPU},
146 #endif
147 #ifdef SIGXFSZ
148     {"XFSZ", SIGXFSZ},
149 #endif
150 #ifdef SIGVTALRM
151     {"VTALRM", SIGVTALRM},
152 #endif
153 #ifdef SIGPROF
154     {"PROF", SIGPROF},
155 #endif
156 #ifdef SIGWINCH
157     {"WINCH", SIGWINCH},
158 #endif
159 #ifdef SIGUSR1
160     {"USR1", SIGUSR1},
161 #endif
162 #ifdef SIGUSR2
163     {"USR2", SIGUSR2},
164 #endif
165 #ifdef SIGLOST
166     {"LOST", SIGLOST},
167 #endif
168 #ifdef SIGMSG
169     {"MSG", SIGMSG},
170 #endif
171 #ifdef SIGPWR
172     {"PWR", SIGPWR},
173 #endif
174 #ifdef SIGPOLL
175     {"POLL", SIGPOLL},
176 #endif
177 #ifdef SIGDANGER
178     {"DANGER", SIGDANGER},
179 #endif
180 #ifdef SIGMIGRATE
181     {"MIGRATE", SIGMIGRATE},
182 #endif
183 #ifdef SIGPRE
184     {"PRE", SIGPRE},
185 #endif
186 #ifdef SIGGRANT
187     {"GRANT", SIGGRANT},
188 #endif
189 #ifdef SIGRETRACT
190     {"RETRACT", SIGRETRACT},
191 #endif
192 #ifdef SIGSOUND
193     {"SOUND", SIGSOUND},
194 #endif
195 #ifdef SIGINFO
196     {"INFO", SIGINFO},
197 #endif
198 };
199 
200 static const char signame_prefix[3] = "SIG";
201 static const int signame_prefix_len = (int)sizeof(signame_prefix);
202 
203 static int
signm2signo(VALUE * sig_ptr,int negative,int exit,int * prefix_ptr)204 signm2signo(VALUE *sig_ptr, int negative, int exit, int *prefix_ptr)
205 {
206     const struct signals *sigs;
207     VALUE vsig = *sig_ptr;
208     const char *nm;
209     long len, nmlen;
210     int prefix = 0;
211 
212     if (RB_SYMBOL_P(vsig)) {
213 	*sig_ptr = vsig = rb_sym2str(vsig);
214     }
215     else if (!RB_TYPE_P(vsig, T_STRING)) {
216 	VALUE str = rb_check_string_type(vsig);
217 	if (NIL_P(str)) {
218 	    rb_raise(rb_eArgError, "bad signal type %s",
219 		     rb_obj_classname(vsig));
220 	}
221 	*sig_ptr = vsig = str;
222     }
223 
224     rb_must_asciicompat(vsig);
225     RSTRING_GETMEM(vsig, nm, len);
226     if (memchr(nm, '\0', len)) {
227 	rb_raise(rb_eArgError, "signal name with null byte");
228     }
229 
230     if (len > 0 && nm[0] == '-') {
231 	if (!negative)
232 	    rb_raise(rb_eArgError, "negative signal name: % "PRIsVALUE, vsig);
233 	prefix = 1;
234     }
235     else {
236 	negative = 0;
237     }
238     if (len >= prefix + signame_prefix_len) {
239 	if (memcmp(nm + prefix, signame_prefix, sizeof(signame_prefix)) == 0)
240 	    prefix += signame_prefix_len;
241     }
242     if (len <= (long)prefix) {
243       unsupported:
244 	if (prefix == signame_prefix_len) {
245 	    prefix = 0;
246 	}
247 	else if (prefix > signame_prefix_len) {
248 	    prefix -= signame_prefix_len;
249 	    len -= prefix;
250 	    vsig = rb_str_subseq(vsig, prefix, len);
251 	    prefix = 0;
252 	}
253 	else {
254 	    len -= prefix;
255 	    vsig = rb_str_subseq(vsig, prefix, len);
256 	    prefix = signame_prefix_len;
257 	}
258 	rb_raise(rb_eArgError, "unsupported signal `%.*s%"PRIsVALUE"'",
259 		 prefix, signame_prefix, vsig);
260     }
261 
262     if (prefix_ptr) *prefix_ptr = prefix;
263     nmlen = len - prefix;
264     nm += prefix;
265     if (nmlen > LONGEST_SIGNAME) goto unsupported;
266     FOREACH_SIGNAL(sigs, !exit) {
267 	if (memcmp(sigs->signm, nm, nmlen) == 0 &&
268 	    sigs->signm[nmlen] == '\0') {
269 	    return negative ? -sigs->signo : sigs->signo;
270 	}
271     }
272     goto unsupported;
273 }
274 
275 static const char*
signo2signm(int no)276 signo2signm(int no)
277 {
278     const struct signals *sigs;
279 
280     FOREACH_SIGNAL(sigs, 0) {
281 	if (sigs->signo == no)
282 	    return sigs->signm;
283     }
284     return 0;
285 }
286 
287 /*
288  * call-seq:
289  *     Signal.signame(signo)  ->  string or nil
290  *
291  *  Convert signal number to signal name.
292  *  Returns +nil+ if the signo is an invalid signal number.
293  *
294  *     Signal.trap("INT") { |signo| puts Signal.signame(signo) }
295  *     Process.kill("INT", 0)
296  *
297  *  <em>produces:</em>
298  *
299  *     INT
300  */
301 static VALUE
sig_signame(VALUE recv,VALUE signo)302 sig_signame(VALUE recv, VALUE signo)
303 {
304     const char *signame = signo2signm(NUM2INT(signo));
305     if (!signame) return Qnil;
306     return rb_str_new_cstr(signame);
307 }
308 
309 const char *
ruby_signal_name(int no)310 ruby_signal_name(int no)
311 {
312     return signo2signm(no);
313 }
314 
315 static VALUE
rb_signo2signm(int signo)316 rb_signo2signm(int signo)
317 {
318     const char *const signm = signo2signm(signo);
319     if (signm) {
320 	return rb_sprintf("SIG%s", signm);
321     }
322     else {
323 	return rb_sprintf("SIG%u", signo);
324     }
325 }
326 
327 /*
328  * call-seq:
329  *    SignalException.new(sig_name)              ->  signal_exception
330  *    SignalException.new(sig_number [, name])   ->  signal_exception
331  *
332  *  Construct a new SignalException object.  +sig_name+ should be a known
333  *  signal name.
334  */
335 
336 static VALUE
esignal_init(int argc,VALUE * argv,VALUE self)337 esignal_init(int argc, VALUE *argv, VALUE self)
338 {
339     int argnum = 1;
340     VALUE sig = Qnil;
341     int signo;
342 
343     if (argc > 0) {
344 	sig = rb_check_to_integer(argv[0], "to_int");
345 	if (!NIL_P(sig)) argnum = 2;
346 	else sig = argv[0];
347     }
348     rb_check_arity(argc, 1, argnum);
349     if (argnum == 2) {
350 	signo = NUM2INT(sig);
351 	if (signo < 0 || signo > NSIG) {
352 	    rb_raise(rb_eArgError, "invalid signal number (%d)", signo);
353 	}
354 	if (argc > 1) {
355 	    sig = argv[1];
356 	}
357 	else {
358 	    sig = rb_signo2signm(signo);
359 	}
360     }
361     else {
362 	int prefix;
363 	signo = signm2signo(&sig, FALSE, FALSE, &prefix);
364 	if (prefix != signame_prefix_len) {
365 	    sig = rb_str_append(rb_str_new_cstr("SIG"), sig);
366 	}
367     }
368     rb_call_super(1, &sig);
369     rb_ivar_set(self, id_signo, INT2NUM(signo));
370 
371     return self;
372 }
373 
374 /*
375  * call-seq:
376  *    signal_exception.signo   ->  num
377  *
378  *  Returns a signal number.
379  */
380 
381 static VALUE
esignal_signo(VALUE self)382 esignal_signo(VALUE self)
383 {
384     return rb_ivar_get(self, id_signo);
385 }
386 
387 /* :nodoc: */
388 static VALUE
interrupt_init(int argc,VALUE * argv,VALUE self)389 interrupt_init(int argc, VALUE *argv, VALUE self)
390 {
391     VALUE args[2];
392 
393     args[0] = INT2FIX(SIGINT);
394     args[1] = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
395     return rb_call_super(2, args);
396 }
397 
398 #include "debug_counter.h"
399 void rb_malloc_info_show_results(void); /* gc.c */
400 
401 void
ruby_default_signal(int sig)402 ruby_default_signal(int sig)
403 {
404 #if USE_DEBUG_COUNTER
405     rb_debug_counter_show_results("killed by signal.");
406 #endif
407     rb_malloc_info_show_results();
408 
409     signal(sig, SIG_DFL);
410     raise(sig);
411 }
412 
413 static RETSIGTYPE sighandler(int sig);
414 static int signal_ignored(int sig);
415 static void signal_enque(int sig);
416 
417 /*
418  *  call-seq:
419  *     Process.kill(signal, pid, ...)    -> integer
420  *
421  *  Sends the given signal to the specified process id(s) if _pid_ is positive.
422  *  If _pid_ is zero _signal_ is sent to all processes whose group ID is equal
423  *  to the group ID of the process. _signal_ may be an integer signal number or
424  *  a POSIX signal name (either with or without a +SIG+ prefix). If _signal_ is
425  *  negative (or starts with a minus sign), kills process groups instead of
426  *  processes. Not all signals are available on all platforms.
427  *  The keys and values of +Signal.list+ are known signal names and numbers,
428  *  respectively.
429  *
430  *     pid = fork do
431  *        Signal.trap("HUP") { puts "Ouch!"; exit }
432  *        # ... do some work ...
433  *     end
434  *     # ...
435  *     Process.kill("HUP", pid)
436  *     Process.wait
437  *
438  *  <em>produces:</em>
439  *
440  *     Ouch!
441  *
442  *  If _signal_ is an integer but wrong for signal,
443  *  <code>Errno::EINVAL</code> or +RangeError+ will be raised.
444  *  Otherwise unless _signal_ is a +String+ or a +Symbol+, and a known
445  *  signal name, +ArgumentError+ will be raised.
446  *
447  *  Also, <code>Errno::ESRCH</code> or +RangeError+ for invalid _pid_,
448  *  <code>Errno::EPERM</code> when failed because of no privilege,
449  *  will be raised.  In these cases, signals may have been sent to
450  *  preceding processes.
451  */
452 
453 VALUE
rb_f_kill(int argc,const VALUE * argv)454 rb_f_kill(int argc, const VALUE *argv)
455 {
456 #ifndef HAVE_KILLPG
457 #define killpg(pg, sig) kill(-(pg), (sig))
458 #endif
459     int sig;
460     int i;
461     VALUE str;
462 
463     rb_check_arity(argc, 2, UNLIMITED_ARGUMENTS);
464 
465     if (FIXNUM_P(argv[0])) {
466 	sig = FIX2INT(argv[0]);
467     }
468     else {
469 	str = argv[0];
470 	sig = signm2signo(&str, TRUE, FALSE, NULL);
471     }
472 
473     if (argc <= 1) return INT2FIX(0);
474 
475     if (sig < 0) {
476 	sig = -sig;
477 	for (i=1; i<argc; i++) {
478 	    if (killpg(NUM2PIDT(argv[i]), sig) < 0)
479 		rb_sys_fail(0);
480 	}
481     }
482     else {
483 	const rb_pid_t self = (GET_THREAD() == GET_VM()->main_thread) ? getpid() : -1;
484 	int wakeup = 0;
485 
486 	for (i=1; i<argc; i++) {
487 	    rb_pid_t pid = NUM2PIDT(argv[i]);
488 
489 	    if ((sig != 0) && (self != -1) && (pid == self)) {
490 		int t;
491 		/*
492 		 * When target pid is self, many caller assume signal will be
493 		 * delivered immediately and synchronously.
494 		 */
495 		switch (sig) {
496 		  case SIGSEGV:
497 #ifdef SIGBUS
498 		  case SIGBUS:
499 #endif
500 #ifdef SIGKILL
501 		  case SIGKILL:
502 #endif
503 #ifdef SIGILL
504 		  case SIGILL:
505 #endif
506 #ifdef SIGFPE
507 		  case SIGFPE:
508 #endif
509 #ifdef SIGSTOP
510 		  case SIGSTOP:
511 #endif
512 		    kill(pid, sig);
513 		    break;
514 		  default:
515 		    t = signal_ignored(sig);
516 		    if (t) {
517 			if (t < 0 && kill(pid, sig))
518 			    rb_sys_fail(0);
519 			break;
520 		    }
521 		    signal_enque(sig);
522 		    wakeup = 1;
523 		}
524 	    }
525 	    else if (kill(pid, sig) < 0) {
526 		rb_sys_fail(0);
527 	    }
528 	}
529 	if (wakeup) {
530 	    rb_threadptr_check_signal(GET_VM()->main_thread);
531 	}
532     }
533     rb_thread_execute_interrupts(rb_thread_current());
534 
535     return INT2FIX(i-1);
536 }
537 
538 static struct {
539     rb_atomic_t cnt[RUBY_NSIG];
540     rb_atomic_t size;
541 } signal_buff;
542 #if RUBY_SIGCHLD
543 volatile unsigned int ruby_nocldwait;
544 #endif
545 
546 #ifdef __dietlibc__
547 #define sighandler_t sh_t
548 #else
549 #define sighandler_t ruby_sighandler_t
550 #endif
551 
552 typedef RETSIGTYPE (*sighandler_t)(int);
553 #ifdef USE_SIGALTSTACK
554 typedef void ruby_sigaction_t(int, siginfo_t*, void*);
555 #define SIGINFO_ARG , siginfo_t *info, void *ctx
556 #define SIGINFO_CTX ctx
557 #else
558 typedef RETSIGTYPE ruby_sigaction_t(int);
559 #define SIGINFO_ARG
560 #define SIGINFO_CTX 0
561 #endif
562 
563 #ifdef USE_SIGALTSTACK
564 static int
rb_sigaltstack_size(void)565 rb_sigaltstack_size(void)
566 {
567     /* XXX: BSD_vfprintf() uses >1500KiB stack and x86-64 need >5KiB stack. */
568     int size = 16*1024;
569 
570 #ifdef MINSIGSTKSZ
571     if (size < MINSIGSTKSZ)
572 	size = MINSIGSTKSZ;
573 #endif
574 #if defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
575     {
576 	int pagesize;
577 	pagesize = (int)sysconf(_SC_PAGE_SIZE);
578 	if (size < pagesize)
579 	    size = pagesize;
580     }
581 #endif
582 
583     return size;
584 }
585 
586 /* alternate stack for SIGSEGV */
587 void *
rb_register_sigaltstack(void)588 rb_register_sigaltstack(void)
589 {
590     stack_t newSS, oldSS;
591 
592     newSS.ss_size = rb_sigaltstack_size();
593     newSS.ss_sp = xmalloc(newSS.ss_size);
594     newSS.ss_flags = 0;
595 
596     sigaltstack(&newSS, &oldSS); /* ignore error. */
597 
598     return newSS.ss_sp;
599 }
600 #endif /* USE_SIGALTSTACK */
601 
602 #ifdef POSIX_SIGNAL
603 static sighandler_t
ruby_signal(int signum,sighandler_t handler)604 ruby_signal(int signum, sighandler_t handler)
605 {
606     struct sigaction sigact, old;
607 
608 #if 0
609     rb_trap_accept_nativethreads[signum] = 0;
610 #endif
611 
612     sigemptyset(&sigact.sa_mask);
613 #ifdef USE_SIGALTSTACK
614     if (handler == SIG_IGN || handler == SIG_DFL) {
615         sigact.sa_handler = handler;
616         sigact.sa_flags = 0;
617     }
618     else {
619         sigact.sa_sigaction = (ruby_sigaction_t*)handler;
620         sigact.sa_flags = SA_SIGINFO;
621     }
622 #else
623     sigact.sa_handler = handler;
624     sigact.sa_flags = 0;
625 #endif
626 
627     switch (signum) {
628 #if RUBY_SIGCHLD
629       case RUBY_SIGCHLD:
630 	if (handler == SIG_IGN) {
631 	    ruby_nocldwait = 1;
632 # ifdef USE_SIGALTSTACK
633 	    if (sigact.sa_flags & SA_SIGINFO) {
634 		sigact.sa_sigaction = (ruby_sigaction_t*)sighandler;
635 	    }
636 	    else {
637 		sigact.sa_handler = sighandler;
638 	    }
639 # else
640 	    sigact.sa_handler = handler;
641 	    sigact.sa_flags = 0;
642 # endif
643 	}
644 	else {
645 	    ruby_nocldwait = 0;
646 	}
647 	break;
648 #endif
649 #if defined(SA_ONSTACK) && defined(USE_SIGALTSTACK)
650       case SIGSEGV:
651 #ifdef SIGBUS
652       case SIGBUS:
653 #endif
654 	sigact.sa_flags |= SA_ONSTACK;
655 	break;
656 #endif
657     }
658     (void)VALGRIND_MAKE_MEM_DEFINED(&old, sizeof(old));
659     if (sigaction(signum, &sigact, &old) < 0) {
660 	return SIG_ERR;
661     }
662     if (old.sa_flags & SA_SIGINFO)
663 	handler = (sighandler_t)old.sa_sigaction;
664     else
665 	handler = old.sa_handler;
666     ASSUME(handler != SIG_ERR);
667     return handler;
668 }
669 
670 sighandler_t
posix_signal(int signum,sighandler_t handler)671 posix_signal(int signum, sighandler_t handler)
672 {
673     return ruby_signal(signum, handler);
674 }
675 
676 #elif defined _WIN32
677 static inline sighandler_t
ruby_signal(int signum,sighandler_t handler)678 ruby_signal(int signum, sighandler_t handler)
679 {
680     if (signum == SIGKILL) {
681 	errno = EINVAL;
682 	return SIG_ERR;
683     }
684     return signal(signum, handler);
685 }
686 
687 #else /* !POSIX_SIGNAL */
688 #define ruby_signal(sig,handler) (/* rb_trap_accept_nativethreads[(sig)] = 0,*/ signal((sig),(handler)))
689 #if 0 /* def HAVE_NATIVETHREAD */
690 static sighandler_t
691 ruby_nativethread_signal(int signum, sighandler_t handler)
692 {
693     sighandler_t old;
694 
695     old = signal(signum, handler);
696     rb_trap_accept_nativethreads[signum] = 1;
697     return old;
698 }
699 #endif
700 #endif
701 
702 static int
signal_ignored(int sig)703 signal_ignored(int sig)
704 {
705     sighandler_t func;
706 #ifdef POSIX_SIGNAL
707     struct sigaction old;
708     (void)VALGRIND_MAKE_MEM_DEFINED(&old, sizeof(old));
709     if (sigaction(sig, NULL, &old) < 0) return FALSE;
710     func = old.sa_handler;
711 #else
712     sighandler_t old = signal(sig, SIG_DFL);
713     signal(sig, old);
714     func = old;
715 #endif
716     if (func == SIG_IGN) return 1;
717     return func == sighandler ? 0 : -1;
718 }
719 
720 static void
signal_enque(int sig)721 signal_enque(int sig)
722 {
723     ATOMIC_INC(signal_buff.cnt[sig]);
724     ATOMIC_INC(signal_buff.size);
725 }
726 
727 #if RUBY_SIGCHLD
728 static rb_atomic_t sigchld_hit;
729 /* destructive getter than simple predicate */
730 # define GET_SIGCHLD_HIT() ATOMIC_EXCHANGE(sigchld_hit, 0)
731 #else
732 # define GET_SIGCHLD_HIT() 0
733 #endif
734 
735 static RETSIGTYPE
sighandler(int sig)736 sighandler(int sig)
737 {
738     int old_errnum = errno;
739 
740     /* the VM always needs to handle SIGCHLD for rb_waitpid */
741     if (sig == RUBY_SIGCHLD) {
742 #if RUBY_SIGCHLD
743         rb_vm_t *vm = GET_VM();
744         ATOMIC_EXCHANGE(sigchld_hit, 1);
745 
746         /* avoid spurious wakeup in main thread iff nobody uses trap(:CHLD) */
747         if (vm && ACCESS_ONCE(VALUE, vm->trap_list.cmd[sig])) {
748             signal_enque(sig);
749         }
750 #endif
751     }
752     else {
753         signal_enque(sig);
754     }
755     rb_thread_wakeup_timer_thread(sig);
756 #if !defined(BSD_SIGNAL) && !defined(POSIX_SIGNAL)
757     ruby_signal(sig, sighandler);
758 #endif
759 
760     errno = old_errnum;
761 }
762 
763 int
rb_signal_buff_size(void)764 rb_signal_buff_size(void)
765 {
766     return signal_buff.size;
767 }
768 
769 #if HAVE_PTHREAD_H
770 #include <pthread.h>
771 #endif
772 
773 static void
rb_disable_interrupt(void)774 rb_disable_interrupt(void)
775 {
776 #ifdef HAVE_PTHREAD_SIGMASK
777     sigset_t mask;
778     sigfillset(&mask);
779     pthread_sigmask(SIG_SETMASK, &mask, NULL);
780 #endif
781 }
782 
783 static void
rb_enable_interrupt(void)784 rb_enable_interrupt(void)
785 {
786 #ifdef HAVE_PTHREAD_SIGMASK
787     sigset_t mask;
788     sigemptyset(&mask);
789     pthread_sigmask(SIG_SETMASK, &mask, NULL);
790 #endif
791 }
792 
793 int
rb_get_next_signal(void)794 rb_get_next_signal(void)
795 {
796     int i, sig = 0;
797 
798     if (signal_buff.size != 0) {
799 	for (i=1; i<RUBY_NSIG; i++) {
800 	    if (signal_buff.cnt[i] > 0) {
801 		ATOMIC_DEC(signal_buff.cnt[i]);
802 		ATOMIC_DEC(signal_buff.size);
803 		sig = i;
804 		break;
805 	    }
806 	}
807     }
808     return sig;
809 }
810 
811 #if defined SIGSEGV || defined SIGBUS || defined SIGILL || defined SIGFPE
812 static const char *received_signal;
813 # define clear_received_signal() (void)(ruby_disable_gc = 0, received_signal = 0)
814 #else
815 # define clear_received_signal() ((void)0)
816 #endif
817 
818 #if defined(USE_SIGALTSTACK) || defined(_WIN32)
819 NORETURN(void rb_ec_stack_overflow(rb_execution_context_t *ec, int crit));
820 # if defined __HAIKU__
821 #   define USE_UCONTEXT_REG 1
822 # elif !(defined(HAVE_UCONTEXT_H) && (defined __i386__ || defined __x86_64__ || defined __amd64__))
823 # elif defined __linux__
824 #   define USE_UCONTEXT_REG 1
825 # elif defined __APPLE__
826 #   define USE_UCONTEXT_REG 1
827 # elif defined __FreeBSD__
828 #   define USE_UCONTEXT_REG 1
829 # endif
830 #if defined(HAVE_PTHREAD_SIGMASK)
831 # define ruby_sigunmask pthread_sigmask
832 #elif defined(HAVE_SIGPROCMASK)
833 # define ruby_sigunmask sigprocmask
834 #endif
835 static void
reset_sigmask(int sig)836 reset_sigmask(int sig)
837 {
838 #if defined(ruby_sigunmask)
839     sigset_t mask;
840 #endif
841     clear_received_signal();
842 #if defined(ruby_sigunmask)
843     sigemptyset(&mask);
844     sigaddset(&mask, sig);
845     if (ruby_sigunmask(SIG_UNBLOCK, &mask, NULL)) {
846 	rb_bug_errno(STRINGIZE(ruby_sigunmask)":unblock", errno);
847     }
848 #endif
849 }
850 
851 # ifdef USE_UCONTEXT_REG
852 static void
check_stack_overflow(int sig,const uintptr_t addr,const ucontext_t * ctx)853 check_stack_overflow(int sig, const uintptr_t addr, const ucontext_t *ctx)
854 {
855     const DEFINE_MCONTEXT_PTR(mctx, ctx);
856 # if defined __linux__
857 #   if defined REG_RSP
858     const greg_t sp = mctx->gregs[REG_RSP];
859     const greg_t bp = mctx->gregs[REG_RBP];
860 #   else
861     const greg_t sp = mctx->gregs[REG_ESP];
862     const greg_t bp = mctx->gregs[REG_EBP];
863 #   endif
864 # elif defined __APPLE__
865 #   if __DARWIN_UNIX03
866 #     define MCTX_SS_REG(reg) __ss.__##reg
867 #   else
868 #     define MCTX_SS_REG(reg) ss.reg
869 #   endif
870 #   if defined(__LP64__)
871     const uintptr_t sp = mctx->MCTX_SS_REG(rsp);
872     const uintptr_t bp = mctx->MCTX_SS_REG(rbp);
873 #   else
874     const uintptr_t sp = mctx->MCTX_SS_REG(esp);
875     const uintptr_t bp = mctx->MCTX_SS_REG(ebp);
876 #   endif
877 # elif defined __FreeBSD__
878 #   if defined(__amd64__)
879     const __register_t sp = mctx->mc_rsp;
880     const __register_t bp = mctx->mc_rbp;
881 #   else
882     const __register_t sp = mctx->mc_esp;
883     const __register_t bp = mctx->mc_ebp;
884 #   endif
885 # elif defined __HAIKU__
886 #   if defined(__amd64__)
887     const unsigned long sp = mctx->rsp;
888     const unsigned long bp = mctx->rbp;
889 #   else
890     const unsigned long sp = mctx->esp;
891     const unsigned long bp = mctx->ebp;
892 #   endif
893 # endif
894     enum {pagesize = 4096};
895     const uintptr_t sp_page = (uintptr_t)sp / pagesize;
896     const uintptr_t bp_page = (uintptr_t)bp / pagesize;
897     const uintptr_t fault_page = addr / pagesize;
898 
899     /* SP in ucontext is not decremented yet when `push` failed, so
900      * the fault page can be the next. */
901     if (sp_page == fault_page || sp_page == fault_page + 1 ||
902         (sp_page <= fault_page && fault_page <= bp_page)) {
903 	rb_execution_context_t *ec = GET_EC();
904 	int crit = FALSE;
905 	if ((uintptr_t)ec->tag->buf / pagesize <= fault_page + 1) {
906 	    /* drop the last tag if it is close to the fault,
907 	     * otherwise it can cause stack overflow again at the same
908 	     * place. */
909 	    ec->tag = ec->tag->prev;
910 	    crit = TRUE;
911 	}
912 	reset_sigmask(sig);
913 	rb_ec_stack_overflow(ec, crit);
914     }
915 }
916 # else
917 static void
check_stack_overflow(int sig,const void * addr)918 check_stack_overflow(int sig, const void *addr)
919 {
920     int ruby_stack_overflowed_p(const rb_thread_t *, const void *);
921     rb_thread_t *th = GET_THREAD();
922     if (ruby_stack_overflowed_p(th, addr)) {
923 	reset_sigmask(sig);
924 	rb_ec_stack_overflow(th->ec, FALSE);
925     }
926 }
927 # endif
928 # ifdef _WIN32
929 #   define CHECK_STACK_OVERFLOW() check_stack_overflow(sig, 0)
930 # else
931 #   define FAULT_ADDRESS info->si_addr
932 #   ifdef USE_UCONTEXT_REG
933 #     define CHECK_STACK_OVERFLOW() check_stack_overflow(sig, (uintptr_t)FAULT_ADDRESS, ctx)
934 #   else
935 #     define CHECK_STACK_OVERFLOW() check_stack_overflow(sig, FAULT_ADDRESS)
936 #   endif
937 #   define MESSAGE_FAULT_ADDRESS " at %p", FAULT_ADDRESS
938 # endif
939 #else
940 # define CHECK_STACK_OVERFLOW() (void)0
941 #endif
942 #ifndef MESSAGE_FAULT_ADDRESS
943 # define MESSAGE_FAULT_ADDRESS
944 #endif
945 
946 #if defined SIGSEGV || defined SIGBUS || defined SIGILL || defined SIGFPE
947 NOINLINE(static void check_reserved_signal_(const char *name, size_t name_len));
948 /* noinine to reduce stack usage in signal handers */
949 
950 #define check_reserved_signal(name) check_reserved_signal_(name, sizeof(name)-1)
951 
952 #ifdef SIGBUS
953 
954 NORETURN(static ruby_sigaction_t sigbus);
955 
956 static RETSIGTYPE
sigbus(int sig SIGINFO_ARG)957 sigbus(int sig SIGINFO_ARG)
958 {
959     check_reserved_signal("BUS");
960 /*
961  * Mac OS X makes KERN_PROTECTION_FAILURE when thread touch guard page.
962  * and it's delivered as SIGBUS instead of SIGSEGV to userland. It's crazy
963  * wrong IMHO. but anyway we have to care it. Sigh.
964  */
965     /* Seems Linux also delivers SIGBUS. */
966 #if defined __APPLE__ || defined __linux__
967     CHECK_STACK_OVERFLOW();
968 #endif
969     rb_bug_context(SIGINFO_CTX, "Bus Error" MESSAGE_FAULT_ADDRESS);
970 }
971 #endif
972 
973 NORETURN(static void ruby_abort(void));
974 
975 static void
ruby_abort(void)976 ruby_abort(void)
977 {
978 #ifdef __sun
979     /* Solaris's abort() is async signal unsafe. Of course, it is not
980      *  POSIX compliant.
981      */
982     raise(SIGABRT);
983 #else
984     abort();
985 #endif
986 
987 }
988 
989 #ifdef SIGSEGV
990 
991 NORETURN(static ruby_sigaction_t sigsegv);
992 
993 static RETSIGTYPE
sigsegv(int sig SIGINFO_ARG)994 sigsegv(int sig SIGINFO_ARG)
995 {
996     check_reserved_signal("SEGV");
997     CHECK_STACK_OVERFLOW();
998     rb_bug_context(SIGINFO_CTX, "Segmentation fault" MESSAGE_FAULT_ADDRESS);
999 }
1000 #endif
1001 
1002 #ifdef SIGILL
1003 
1004 NORETURN(static ruby_sigaction_t sigill);
1005 
1006 static RETSIGTYPE
sigill(int sig SIGINFO_ARG)1007 sigill(int sig SIGINFO_ARG)
1008 {
1009     check_reserved_signal("ILL");
1010 #if defined __APPLE__
1011     CHECK_STACK_OVERFLOW();
1012 #endif
1013     rb_bug_context(SIGINFO_CTX, "Illegal instruction" MESSAGE_FAULT_ADDRESS);
1014 }
1015 #endif
1016 
1017 static void
check_reserved_signal_(const char * name,size_t name_len)1018 check_reserved_signal_(const char *name, size_t name_len)
1019 {
1020     const char *prev = ATOMIC_PTR_EXCHANGE(received_signal, name);
1021 
1022     if (prev) {
1023 	ssize_t RB_UNUSED_VAR(err);
1024 #define NOZ(name, str) name[sizeof(str)-1] = str
1025 	static const char NOZ(msg1, " received in ");
1026 	static const char NOZ(msg2, " handler\n");
1027 
1028 #ifdef HAVE_WRITEV
1029 	struct iovec iov[4];
1030 
1031 	iov[0].iov_base = (void *)name;
1032 	iov[0].iov_len = name_len;
1033 	iov[1].iov_base = (void *)msg1;
1034 	iov[1].iov_len = sizeof(msg1);
1035 	iov[2].iov_base = (void *)prev;
1036 	iov[2].iov_len = strlen(prev);
1037 	iov[3].iov_base = (void *)msg2;
1038 	iov[3].iov_len = sizeof(msg2);
1039 	err = writev(2, iov, 4);
1040 #else
1041 	err = write(2, name, name_len);
1042 	err = write(2, msg1, sizeof(msg1));
1043 	err = write(2, prev, strlen(prev));
1044 	err = write(2, msg2, sizeof(msg2));
1045 #endif
1046 	ruby_abort();
1047     }
1048 
1049     ruby_disable_gc = 1;
1050 }
1051 #endif
1052 
1053 #if defined SIGPIPE || defined SIGSYS
1054 static RETSIGTYPE
sig_do_nothing(int sig)1055 sig_do_nothing(int sig)
1056 {
1057 }
1058 #endif
1059 
1060 static int
signal_exec(VALUE cmd,int safe,int sig)1061 signal_exec(VALUE cmd, int safe, int sig)
1062 {
1063     rb_execution_context_t *ec = GET_EC();
1064     volatile rb_atomic_t old_interrupt_mask = ec->interrupt_mask;
1065     enum ruby_tag_type state;
1066 
1067     /*
1068      * workaround the following race:
1069      * 1. signal_enque queues signal for execution
1070      * 2. user calls trap(sig, "IGNORE"), setting SIG_IGN
1071      * 3. rb_signal_exec runs on queued signal
1072      */
1073     if (IMMEDIATE_P(cmd))
1074 	return FALSE;
1075 
1076     ec->interrupt_mask |= TRAP_INTERRUPT_MASK;
1077     EC_PUSH_TAG(ec);
1078     if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1079 	VALUE signum = INT2NUM(sig);
1080 	rb_eval_cmd(cmd, rb_ary_new3(1, signum), safe);
1081     }
1082     EC_POP_TAG();
1083     ec = GET_EC();
1084     ec->interrupt_mask = old_interrupt_mask;
1085 
1086     if (state) {
1087 	/* XXX: should be replaced with rb_threadptr_pending_interrupt_enque() */
1088 	EC_JUMP_TAG(ec, state);
1089     }
1090     return TRUE;
1091 }
1092 
1093 void
rb_trap_exit(void)1094 rb_trap_exit(void)
1095 {
1096     rb_vm_t *vm = GET_VM();
1097     VALUE trap_exit = vm->trap_list.cmd[0];
1098 
1099     if (trap_exit) {
1100 	vm->trap_list.cmd[0] = 0;
1101 	signal_exec(trap_exit, vm->trap_list.safe[0], 0);
1102     }
1103 }
1104 
1105 void ruby_waitpid_all(rb_vm_t *); /* process.c */
1106 
1107 void
ruby_sigchld_handler(rb_vm_t * vm)1108 ruby_sigchld_handler(rb_vm_t *vm)
1109 {
1110     if (SIGCHLD_LOSSY || GET_SIGCHLD_HIT()) {
1111         ruby_waitpid_all(vm);
1112     }
1113 }
1114 
1115 /* returns true if a trap handler was run, false otherwise */
1116 int
rb_signal_exec(rb_thread_t * th,int sig)1117 rb_signal_exec(rb_thread_t *th, int sig)
1118 {
1119     rb_vm_t *vm = GET_VM();
1120     VALUE cmd = vm->trap_list.cmd[sig];
1121     int safe = vm->trap_list.safe[sig];
1122 
1123     if (cmd == 0) {
1124 	switch (sig) {
1125 	  case SIGINT:
1126 	    rb_interrupt();
1127 	    break;
1128 #ifdef SIGHUP
1129 	  case SIGHUP:
1130 #endif
1131 #ifdef SIGQUIT
1132 	  case SIGQUIT:
1133 #endif
1134 #ifdef SIGTERM
1135 	  case SIGTERM:
1136 #endif
1137 #ifdef SIGALRM
1138 	  case SIGALRM:
1139 #endif
1140 #ifdef SIGUSR1
1141 	  case SIGUSR1:
1142 #endif
1143 #ifdef SIGUSR2
1144 	  case SIGUSR2:
1145 #endif
1146 	    rb_threadptr_signal_raise(th, sig);
1147 	    break;
1148 	}
1149     }
1150     else if (cmd == Qundef) {
1151 	rb_threadptr_signal_exit(th);
1152     }
1153     else {
1154 	return signal_exec(cmd, safe, sig);
1155     }
1156     return FALSE;
1157 }
1158 
1159 static sighandler_t
default_handler(int sig)1160 default_handler(int sig)
1161 {
1162     sighandler_t func;
1163     switch (sig) {
1164       case SIGINT:
1165 #ifdef SIGHUP
1166       case SIGHUP:
1167 #endif
1168 #ifdef SIGQUIT
1169       case SIGQUIT:
1170 #endif
1171 #ifdef SIGTERM
1172       case SIGTERM:
1173 #endif
1174 #ifdef SIGALRM
1175       case SIGALRM:
1176 #endif
1177 #ifdef SIGUSR1
1178       case SIGUSR1:
1179 #endif
1180 #ifdef SIGUSR2
1181       case SIGUSR2:
1182 #endif
1183 #if RUBY_SIGCHLD
1184       case RUBY_SIGCHLD:
1185 #endif
1186         func = sighandler;
1187         break;
1188 #ifdef SIGBUS
1189       case SIGBUS:
1190         func = (sighandler_t)sigbus;
1191         break;
1192 #endif
1193 #ifdef SIGSEGV
1194       case SIGSEGV:
1195         func = (sighandler_t)sigsegv;
1196         break;
1197 #endif
1198 #ifdef SIGPIPE
1199       case SIGPIPE:
1200         func = sig_do_nothing;
1201         break;
1202 #endif
1203 #ifdef SIGSYS
1204       case SIGSYS:
1205         func = sig_do_nothing;
1206         break;
1207 #endif
1208       default:
1209         func = SIG_DFL;
1210         break;
1211     }
1212 
1213     return func;
1214 }
1215 
1216 static sighandler_t
trap_handler(VALUE * cmd,int sig)1217 trap_handler(VALUE *cmd, int sig)
1218 {
1219     sighandler_t func = sighandler;
1220     VALUE command;
1221 
1222     if (NIL_P(*cmd)) {
1223 	func = SIG_IGN;
1224     }
1225     else {
1226 	command = rb_check_string_type(*cmd);
1227 	if (NIL_P(command) && SYMBOL_P(*cmd)) {
1228 	    command = rb_sym2str(*cmd);
1229 	    if (!command) rb_raise(rb_eArgError, "bad handler");
1230 	}
1231 	if (!NIL_P(command)) {
1232 	    const char *cptr;
1233 	    long len;
1234 	    SafeStringValue(command);	/* taint check */
1235 	    *cmd = command;
1236 	    RSTRING_GETMEM(command, cptr, len);
1237 	    switch (len) {
1238 	      case 0:
1239                 goto sig_ign;
1240 		break;
1241               case 14:
1242 		if (memcmp(cptr, "SYSTEM_DEFAULT", 14) == 0) {
1243                     if (sig == RUBY_SIGCHLD) {
1244                         goto sig_dfl;
1245                     }
1246                     func = SIG_DFL;
1247                     *cmd = 0;
1248 		}
1249                 break;
1250 	      case 7:
1251 		if (memcmp(cptr, "SIG_IGN", 7) == 0) {
1252 sig_ign:
1253                     func = SIG_IGN;
1254                     *cmd = Qtrue;
1255 		}
1256 		else if (memcmp(cptr, "SIG_DFL", 7) == 0) {
1257 sig_dfl:
1258                     func = default_handler(sig);
1259                     *cmd = 0;
1260 		}
1261 		else if (memcmp(cptr, "DEFAULT", 7) == 0) {
1262                     goto sig_dfl;
1263 		}
1264 		break;
1265 	      case 6:
1266 		if (memcmp(cptr, "IGNORE", 6) == 0) {
1267                     goto sig_ign;
1268 		}
1269 		break;
1270 	      case 4:
1271 		if (memcmp(cptr, "EXIT", 4) == 0) {
1272 		    *cmd = Qundef;
1273 		}
1274 		break;
1275 	    }
1276 	}
1277 	else {
1278 	    rb_proc_t *proc;
1279 	    GetProcPtr(*cmd, proc);
1280 	    (void)proc;
1281 	}
1282     }
1283 
1284     return func;
1285 }
1286 
1287 static int
trap_signm(VALUE vsig)1288 trap_signm(VALUE vsig)
1289 {
1290     int sig = -1;
1291 
1292     if (FIXNUM_P(vsig)) {
1293 	sig = FIX2INT(vsig);
1294 	if (sig < 0 || sig >= NSIG) {
1295 	    rb_raise(rb_eArgError, "invalid signal number (%d)", sig);
1296 	}
1297     }
1298     else {
1299 	sig = signm2signo(&vsig, FALSE, TRUE, NULL);
1300     }
1301     return sig;
1302 }
1303 
1304 static VALUE
trap(int sig,sighandler_t func,VALUE command)1305 trap(int sig, sighandler_t func, VALUE command)
1306 {
1307     sighandler_t oldfunc;
1308     VALUE oldcmd;
1309     rb_vm_t *vm = GET_VM();
1310 
1311     /*
1312      * Be careful. ruby_signal() and trap_list.cmd[sig] must be changed
1313      * atomically. In current implementation, we only need to don't call
1314      * RUBY_VM_CHECK_INTS().
1315      */
1316     if (sig == 0) {
1317 	oldfunc = SIG_ERR;
1318     }
1319     else {
1320 	oldfunc = ruby_signal(sig, func);
1321 	if (oldfunc == SIG_ERR) rb_sys_fail_str(rb_signo2signm(sig));
1322     }
1323     oldcmd = vm->trap_list.cmd[sig];
1324     switch (oldcmd) {
1325       case 0:
1326       case Qtrue:
1327 	if (oldfunc == SIG_IGN) oldcmd = rb_str_new2("IGNORE");
1328         else if (oldfunc == SIG_DFL) oldcmd = rb_str_new2("SYSTEM_DEFAULT");
1329 	else if (oldfunc == sighandler) oldcmd = rb_str_new2("DEFAULT");
1330 	else oldcmd = Qnil;
1331 	break;
1332       case Qnil:
1333 	break;
1334       case Qundef:
1335 	oldcmd = rb_str_new2("EXIT");
1336 	break;
1337     }
1338 
1339     ACCESS_ONCE(VALUE, vm->trap_list.cmd[sig]) = command;
1340     vm->trap_list.safe[sig] = rb_safe_level();
1341 
1342     return oldcmd;
1343 }
1344 
1345 static int
reserved_signal_p(int signo)1346 reserved_signal_p(int signo)
1347 {
1348 /* Synchronous signal can't deliver to main thread */
1349 #ifdef SIGSEGV
1350     if (signo == SIGSEGV)
1351 	return 1;
1352 #endif
1353 #ifdef SIGBUS
1354     if (signo == SIGBUS)
1355 	return 1;
1356 #endif
1357 #ifdef SIGILL
1358     if (signo == SIGILL)
1359 	return 1;
1360 #endif
1361 #ifdef SIGFPE
1362     if (signo == SIGFPE)
1363 	return 1;
1364 #endif
1365 
1366 /* used ubf internal see thread_pthread.c. */
1367 #ifdef SIGVTALRM
1368     if (signo == SIGVTALRM)
1369 	return 1;
1370 #endif
1371 
1372     return 0;
1373 }
1374 
1375 /*
1376  * call-seq:
1377  *   Signal.trap( signal, command ) -> obj
1378  *   Signal.trap( signal ) {| | block } -> obj
1379  *
1380  * Specifies the handling of signals. The first parameter is a signal
1381  * name (a string such as ``SIGALRM'', ``SIGUSR1'', and so on) or a
1382  * signal number. The characters ``SIG'' may be omitted from the
1383  * signal name. The command or block specifies code to be run when the
1384  * signal is raised.
1385  * If the command is the string ``IGNORE'' or ``SIG_IGN'', the signal
1386  * will be ignored.
1387  * If the command is ``DEFAULT'' or ``SIG_DFL'', the Ruby's default handler
1388  * will be invoked.
1389  * If the command is ``EXIT'', the script will be terminated by the signal.
1390  * If the command is ``SYSTEM_DEFAULT'', the operating system's default
1391  * handler will be invoked.
1392  * Otherwise, the given command or block will be run.
1393  * The special signal name ``EXIT'' or signal number zero will be
1394  * invoked just prior to program termination.
1395  * trap returns the previous handler for the given signal.
1396  *
1397  *     Signal.trap(0, proc { puts "Terminating: #{$$}" })
1398  *     Signal.trap("CLD")  { puts "Child died" }
1399  *     fork && Process.wait
1400  *
1401  * produces:
1402  *     Terminating: 27461
1403  *     Child died
1404  *     Terminating: 27460
1405  */
1406 static VALUE
sig_trap(int argc,VALUE * argv)1407 sig_trap(int argc, VALUE *argv)
1408 {
1409     int sig;
1410     sighandler_t func;
1411     VALUE cmd;
1412 
1413     rb_check_arity(argc, 1, 2);
1414 
1415     sig = trap_signm(argv[0]);
1416     if (reserved_signal_p(sig)) {
1417         const char *name = signo2signm(sig);
1418         if (name)
1419             rb_raise(rb_eArgError, "can't trap reserved signal: SIG%s", name);
1420         else
1421             rb_raise(rb_eArgError, "can't trap reserved signal: %d", sig);
1422     }
1423 
1424     if (argc == 1) {
1425 	cmd = rb_block_proc();
1426 	func = sighandler;
1427     }
1428     else {
1429 	cmd = argv[1];
1430 	func = trap_handler(&cmd, sig);
1431     }
1432 
1433     if (OBJ_TAINTED(cmd)) {
1434 	rb_raise(rb_eSecurityError, "Insecure: tainted signal trap");
1435     }
1436 
1437     return trap(sig, func, cmd);
1438 }
1439 
1440 /*
1441  * call-seq:
1442  *   Signal.list -> a_hash
1443  *
1444  * Returns a list of signal names mapped to the corresponding
1445  * underlying signal numbers.
1446  *
1447  *   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}
1448  */
1449 static VALUE
sig_list(void)1450 sig_list(void)
1451 {
1452     VALUE h = rb_hash_new();
1453     const struct signals *sigs;
1454 
1455     FOREACH_SIGNAL(sigs, 0) {
1456 	rb_hash_aset(h, rb_fstring_cstr(sigs->signm), INT2FIX(sigs->signo));
1457     }
1458     return h;
1459 }
1460 
1461 #define INSTALL_SIGHANDLER(cond, signame, signum) do {	\
1462 	static const char failed[] = "failed to install "signame" handler"; \
1463 	if (!(cond)) break; \
1464 	if (reserved_signal_p(signum)) rb_bug(failed); \
1465 	perror(failed); \
1466     } while (0)
1467 static int
install_sighandler(int signum,sighandler_t handler)1468 install_sighandler(int signum, sighandler_t handler)
1469 {
1470     sighandler_t old;
1471 
1472     old = ruby_signal(signum, handler);
1473     if (old == SIG_ERR) return -1;
1474     /* signal handler should be inherited during exec. */
1475     if (old != SIG_DFL) {
1476 	ruby_signal(signum, old);
1477     }
1478     return 0;
1479 }
1480 
1481 #  define install_sighandler(signum, handler) \
1482     INSTALL_SIGHANDLER(install_sighandler(signum, handler), #signum, signum)
1483 
1484 #if RUBY_SIGCHLD
1485 static int
init_sigchld(int sig)1486 init_sigchld(int sig)
1487 {
1488     sighandler_t oldfunc;
1489     sighandler_t func = sighandler;
1490 
1491     oldfunc = ruby_signal(sig, SIG_DFL);
1492     if (oldfunc == SIG_ERR) return -1;
1493     ruby_signal(sig, func);
1494     ACCESS_ONCE(VALUE, GET_VM()->trap_list.cmd[sig]) = 0;
1495 
1496     return 0;
1497 }
1498 
1499 #    define init_sigchld(signum) \
1500     INSTALL_SIGHANDLER(init_sigchld(signum), #signum, signum)
1501 #endif
1502 
1503 void
ruby_sig_finalize(void)1504 ruby_sig_finalize(void)
1505 {
1506     sighandler_t oldfunc;
1507 
1508     oldfunc = ruby_signal(SIGINT, SIG_IGN);
1509     if (oldfunc == sighandler) {
1510 	ruby_signal(SIGINT, SIG_DFL);
1511     }
1512 }
1513 
1514 
1515 int ruby_enable_coredump = 0;
1516 
1517 /*
1518  * Many operating systems allow signals to be sent to running
1519  * processes. Some signals have a defined effect on the process, while
1520  * others may be trapped at the code level and acted upon. For
1521  * example, your process may trap the USR1 signal and use it to toggle
1522  * debugging, and may use TERM to initiate a controlled shutdown.
1523  *
1524  *     pid = fork do
1525  *       Signal.trap("USR1") do
1526  *         $debug = !$debug
1527  *         puts "Debug now: #$debug"
1528  *       end
1529  *       Signal.trap("TERM") do
1530  *         puts "Terminating..."
1531  *         shutdown()
1532  *       end
1533  *       # . . . do some work . . .
1534  *     end
1535  *
1536  *     Process.detach(pid)
1537  *
1538  *     # Controlling program:
1539  *     Process.kill("USR1", pid)
1540  *     # ...
1541  *     Process.kill("USR1", pid)
1542  *     # ...
1543  *     Process.kill("TERM", pid)
1544  *
1545  * produces:
1546  *     Debug now: true
1547  *     Debug now: false
1548  *    Terminating...
1549  *
1550  * The list of available signal names and their interpretation is
1551  * system dependent. Signal delivery semantics may also vary between
1552  * systems; in particular signal delivery may not always be reliable.
1553  */
1554 void
Init_signal(void)1555 Init_signal(void)
1556 {
1557     VALUE mSignal = rb_define_module("Signal");
1558 
1559     rb_define_global_function("trap", sig_trap, -1);
1560     rb_define_module_function(mSignal, "trap", sig_trap, -1);
1561     rb_define_module_function(mSignal, "list", sig_list, 0);
1562     rb_define_module_function(mSignal, "signame", sig_signame, 1);
1563 
1564     rb_define_method(rb_eSignal, "initialize", esignal_init, -1);
1565     rb_define_method(rb_eSignal, "signo", esignal_signo, 0);
1566     rb_alias(rb_eSignal, rb_intern_const("signm"), rb_intern_const("message"));
1567     rb_define_method(rb_eInterrupt, "initialize", interrupt_init, -1);
1568 
1569     /* At this time, there is no subthread. Then sigmask guarantee atomics. */
1570     rb_disable_interrupt();
1571 
1572     install_sighandler(SIGINT, sighandler);
1573 #ifdef SIGHUP
1574     install_sighandler(SIGHUP, sighandler);
1575 #endif
1576 #ifdef SIGQUIT
1577     install_sighandler(SIGQUIT, sighandler);
1578 #endif
1579 #ifdef SIGTERM
1580     install_sighandler(SIGTERM, sighandler);
1581 #endif
1582 #ifdef SIGALRM
1583     install_sighandler(SIGALRM, sighandler);
1584 #endif
1585 #ifdef SIGUSR1
1586     install_sighandler(SIGUSR1, sighandler);
1587 #endif
1588 #ifdef SIGUSR2
1589     install_sighandler(SIGUSR2, sighandler);
1590 #endif
1591 
1592     if (!ruby_enable_coredump) {
1593 #ifdef SIGBUS
1594 	install_sighandler(SIGBUS, (sighandler_t)sigbus);
1595 #endif
1596 #ifdef SIGILL
1597 	install_sighandler(SIGILL, (sighandler_t)sigill);
1598 #endif
1599 #ifdef SIGSEGV
1600 	RB_ALTSTACK_INIT(GET_VM()->main_altstack);
1601 	install_sighandler(SIGSEGV, (sighandler_t)sigsegv);
1602 #endif
1603     }
1604 #ifdef SIGPIPE
1605     install_sighandler(SIGPIPE, sig_do_nothing);
1606 #endif
1607 #ifdef SIGSYS
1608     install_sighandler(SIGSYS, sig_do_nothing);
1609 #endif
1610 
1611 #if RUBY_SIGCHLD
1612     init_sigchld(RUBY_SIGCHLD);
1613 #endif
1614 
1615     rb_enable_interrupt();
1616 }
1617 
1618 #if defined(HAVE_GRANTPT)
1619 extern int grantpt(int);
1620 #else
1621 static int
fake_grantfd(int masterfd)1622 fake_grantfd(int masterfd)
1623 {
1624     errno = ENOSYS;
1625     return -1;
1626 }
1627 #define grantpt(fd) fake_grantfd(fd)
1628 #endif
1629 
1630 int
rb_grantpt(int masterfd)1631 rb_grantpt(int masterfd)
1632 {
1633     if (RUBY_SIGCHLD) {
1634         rb_vm_t *vm = GET_VM();
1635         int ret, e;
1636 
1637         /*
1638          * Prevent waitpid calls from Ruby by taking waitpid_lock.
1639          * Pedantically, grantpt(3) is undefined if a non-default
1640          * SIGCHLD handler is defined, but preventing conflicting
1641          * waitpid calls ought to be sufficient.
1642          *
1643          * We could install the default sighandler temporarily, but that
1644          * could cause SIGCHLD to be missed by other threads.  Blocking
1645          * SIGCHLD won't work here, either, unless we stop and restart
1646          * timer-thread (as only timer-thread sees SIGCHLD), but that
1647          * seems like overkill.
1648          */
1649         rb_nativethread_lock_lock(&vm->waitpid_lock);
1650         {
1651             ret = grantpt(masterfd); /* may spawn `pt_chown' and wait on it */
1652             if (ret < 0) e = errno;
1653         }
1654         rb_nativethread_lock_unlock(&vm->waitpid_lock);
1655 
1656         if (ret < 0) errno = e;
1657         return ret;
1658     }
1659     else {
1660         return grantpt(masterfd);
1661     }
1662 }
1663