Ruby: signal.c Source File

Ruby 4.0.5p0 (2026-05-20 revision 64336ffd0ee9e1f4c05891695a3d7b49cb709721)

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