Ruby: signal.c Source File

Ruby 3.2.5p208 (2024-07-26 revision 31d0f1a2e7dbfb60731d1f05b868e1d578cda493)

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