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