Ruby  3.4.0dev (2024-12-06 revision 892c46283a5ea4179500d951c9d4866c0051f27b)
signal.c (892c46283a5ea4179500d951c9d4866c0051f27b)
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() do { \
755  if (GET_VM() != NULL) rb_gc_enable(); \
756  received_signal = 0; \
757 } while (0)
758 #else
759 # define clear_received_signal() ((void)0)
760 #endif
761 
762 #if defined(USE_SIGALTSTACK) || defined(_WIN32)
763 NORETURN(void rb_ec_stack_overflow(rb_execution_context_t *ec, int crit));
764 # if defined __HAIKU__
765 # define USE_UCONTEXT_REG 1
766 # elif !(defined(HAVE_UCONTEXT_H) && (defined __i386__ || defined __x86_64__ || defined __amd64__))
767 # elif defined __linux__
768 # define USE_UCONTEXT_REG 1
769 # elif defined __APPLE__
770 # define USE_UCONTEXT_REG 1
771 # elif defined __FreeBSD__
772 # define USE_UCONTEXT_REG 1
773 # endif
774 #if defined(HAVE_PTHREAD_SIGMASK)
775 # define ruby_sigunmask pthread_sigmask
776 #elif defined(HAVE_SIGPROCMASK)
777 # define ruby_sigunmask sigprocmask
778 #endif
779 static void
780 reset_sigmask(int sig)
781 {
782 #if defined(ruby_sigunmask)
783  sigset_t mask;
784 #endif
785  clear_received_signal();
786 #if defined(ruby_sigunmask)
787  sigemptyset(&mask);
788  sigaddset(&mask, sig);
789  if (ruby_sigunmask(SIG_UNBLOCK, &mask, NULL)) {
790  rb_bug_errno(STRINGIZE(ruby_sigunmask)":unblock", errno);
791  }
792 #endif
793 }
794 
795 # ifdef USE_UCONTEXT_REG
796 static void
797 check_stack_overflow(int sig, const uintptr_t addr, const ucontext_t *ctx)
798 {
799  const DEFINE_MCONTEXT_PTR(mctx, ctx);
800 # if defined __linux__
801 # if defined REG_RSP
802  const greg_t sp = mctx->gregs[REG_RSP];
803  const greg_t bp = mctx->gregs[REG_RBP];
804 # else
805  const greg_t sp = mctx->gregs[REG_ESP];
806  const greg_t bp = mctx->gregs[REG_EBP];
807 # endif
808 # elif defined __APPLE__
809 # include <AvailabilityMacros.h>
810 # if defined(MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
811 # define MCTX_SS_REG(reg) __ss.__##reg
812 # else
813 # define MCTX_SS_REG(reg) ss.reg
814 # endif
815 # if defined(__LP64__)
816  const uintptr_t sp = mctx->MCTX_SS_REG(rsp);
817  const uintptr_t bp = mctx->MCTX_SS_REG(rbp);
818 # else
819  const uintptr_t sp = mctx->MCTX_SS_REG(esp);
820  const uintptr_t bp = mctx->MCTX_SS_REG(ebp);
821 # endif
822 # elif defined __FreeBSD__
823 # if defined(__amd64__)
824  const __register_t sp = mctx->mc_rsp;
825  const __register_t bp = mctx->mc_rbp;
826 # else
827  const __register_t sp = mctx->mc_esp;
828  const __register_t bp = mctx->mc_ebp;
829 # endif
830 # elif defined __HAIKU__
831 # if defined(__amd64__)
832  const unsigned long sp = mctx->rsp;
833  const unsigned long bp = mctx->rbp;
834 # else
835  const unsigned long sp = mctx->esp;
836  const unsigned long bp = mctx->ebp;
837 # endif
838 # endif
839  enum {pagesize = 4096};
840  const uintptr_t sp_page = (uintptr_t)sp / pagesize;
841  const uintptr_t bp_page = (uintptr_t)bp / pagesize;
842  const uintptr_t fault_page = addr / pagesize;
843 
844  /* SP in ucontext is not decremented yet when `push` failed, so
845  * the fault page can be the next. */
846  if (sp_page == fault_page || sp_page == fault_page + 1 ||
847  (sp_page <= fault_page && fault_page <= bp_page)) {
848  rb_execution_context_t *ec = GET_EC();
849  int crit = FALSE;
850  int uplevel = roomof(pagesize, sizeof(*ec->tag)) / 2; /* XXX: heuristic */
851  while ((uintptr_t)ec->tag->buf / pagesize <= fault_page + 1) {
852  /* drop the last tag if it is close to the fault,
853  * otherwise it can cause stack overflow again at the same
854  * place. */
855  if ((crit = (!ec->tag->prev || !--uplevel)) != FALSE) break;
856  ec->tag = ec->tag->prev;
857  }
858  reset_sigmask(sig);
859  rb_ec_stack_overflow(ec, crit);
860  }
861 }
862 # else
863 static void
864 check_stack_overflow(int sig, const void *addr)
865 {
866  int ruby_stack_overflowed_p(const rb_thread_t *, const void *);
867  rb_thread_t *th = GET_THREAD();
868  if (ruby_stack_overflowed_p(th, addr)) {
869  reset_sigmask(sig);
870  rb_ec_stack_overflow(th->ec, FALSE);
871  }
872 }
873 # endif
874 
875 # ifdef _WIN32
876 # define CHECK_STACK_OVERFLOW() check_stack_overflow(sig, 0)
877 # else
878 # define FAULT_ADDRESS info->si_addr
879 # ifdef USE_UCONTEXT_REG
880 # define CHECK_STACK_OVERFLOW_() check_stack_overflow(sig, (uintptr_t)FAULT_ADDRESS, ctx)
881 # else
882 # define CHECK_STACK_OVERFLOW_() check_stack_overflow(sig, FAULT_ADDRESS)
883 # endif
884 # define MESSAGE_FAULT_ADDRESS " at %p", FAULT_ADDRESS
885 # define SIGNAL_FROM_USER_P() ((info)->si_code == SI_USER)
886 # define CHECK_STACK_OVERFLOW() (SIGNAL_FROM_USER_P() ? (void)0 : CHECK_STACK_OVERFLOW_())
887 # endif
888 #else
889 # define CHECK_STACK_OVERFLOW() (void)0
890 #endif
891 #ifndef MESSAGE_FAULT_ADDRESS
892 # define MESSAGE_FAULT_ADDRESS
893 #endif
894 
895 #if defined SIGSEGV || defined SIGBUS || defined SIGILL || defined SIGFPE
896 NOINLINE(static void check_reserved_signal_(const char *name, size_t name_len, int signo));
897 /* noinine to reduce stack usage in signal handers */
898 
899 #define check_reserved_signal(name) check_reserved_signal_(name, sizeof(name)-1, sig)
900 
901 #ifdef SIGBUS
902 
903 static sighandler_t default_sigbus_handler;
904 NORETURN(static ruby_sigaction_t sigbus);
905 
906 static void
907 sigbus(int sig SIGINFO_ARG)
908 {
909  check_reserved_signal("BUS");
910 /*
911  * Mac OS X makes KERN_PROTECTION_FAILURE when thread touch guard page.
912  * and it's delivered as SIGBUS instead of SIGSEGV to userland. It's crazy
913  * wrong IMHO. but anyway we have to care it. Sigh.
914  */
915  /* Seems Linux also delivers SIGBUS. */
916 #if defined __APPLE__ || defined __linux__
917  CHECK_STACK_OVERFLOW();
918 #endif
919  rb_bug_for_fatal_signal(default_sigbus_handler, sig, SIGINFO_CTX, "Bus Error" MESSAGE_FAULT_ADDRESS);
920 }
921 #endif
922 
923 #ifdef SIGSEGV
924 
925 static sighandler_t default_sigsegv_handler;
926 NORETURN(static ruby_sigaction_t sigsegv);
927 
928 static void
929 sigsegv(int sig SIGINFO_ARG)
930 {
931  check_reserved_signal("SEGV");
932  CHECK_STACK_OVERFLOW();
933  rb_bug_for_fatal_signal(default_sigsegv_handler, sig, SIGINFO_CTX, "Segmentation fault" MESSAGE_FAULT_ADDRESS);
934 }
935 #endif
936 
937 #ifdef SIGILL
938 
939 static sighandler_t default_sigill_handler;
940 NORETURN(static ruby_sigaction_t sigill);
941 
942 static void
943 sigill(int sig SIGINFO_ARG)
944 {
945  check_reserved_signal("ILL");
946 #if defined __APPLE__ || defined __linux__
947  CHECK_STACK_OVERFLOW();
948 #endif
949  rb_bug_for_fatal_signal(default_sigill_handler, sig, SIGINFO_CTX, "Illegal instruction" MESSAGE_FAULT_ADDRESS);
950 }
951 #endif
952 
953 #ifndef __sun
954 NORETURN(static void ruby_abort(void));
955 #endif
956 
957 static void
958 ruby_abort(void)
959 {
960 #ifdef __sun
961  /* Solaris's abort() is async signal unsafe. Of course, it is not
962  * POSIX compliant.
963  */
964  raise(SIGABRT);
965 #else
966  abort();
967 #endif
968 }
969 
970 static void
971 check_reserved_signal_(const char *name, size_t name_len, int signo)
972 {
973  const char *prev = ATOMIC_PTR_EXCHANGE(received_signal, name);
974 
975  if (prev) {
976  ssize_t RB_UNUSED_VAR(err);
977  static const int stderr_fd = 2;
978 #define NOZ(name, str) name[sizeof(str)-1] = str
979  static const char NOZ(msg1, " received in ");
980  static const char NOZ(msg2, " handler\n");
981 
982 #ifdef HAVE_WRITEV
983  struct iovec iov[4];
984  int i = 0;
985 # define W(str, len) \
986  iov[i++] = (struct iovec){.iov_base = (void *)(str), .iov_len = (len)}
987 #else
988 # define W(str, len) err = write(stderr_fd, (str), (len))
989 #endif
990 
991 #if __has_feature(address_sanitizer) || \
992  __has_feature(memory_sanitizer) || \
993  defined(HAVE_VALGRIND_MEMCHECK_H)
994  ruby_posix_signal(signo, SIG_DFL);
995 #endif
996  W(name, name_len);
997  W(msg1, sizeof(msg1));
998  W(prev, strlen(prev));
999  W(msg2, sizeof(msg2));
1000 # undef W
1001 #ifdef HAVE_WRITEV
1002  err = writev(stderr_fd, iov, i);
1003 #endif
1004  ruby_abort();
1005  }
1006 
1007  if (GET_VM() != NULL) {
1008  rb_gc_disable_no_rest();
1009  }
1010 }
1011 #endif
1012 
1013 #if defined SIGPIPE || defined SIGSYS
1014 static void
1015 sig_do_nothing(int sig)
1016 {
1017 }
1018 #endif
1019 
1020 static int
1021 signal_exec(VALUE cmd, int sig)
1022 {
1023  rb_execution_context_t *ec = GET_EC();
1024  volatile rb_atomic_t old_interrupt_mask = ec->interrupt_mask;
1025  enum ruby_tag_type state;
1026 
1027  /*
1028  * workaround the following race:
1029  * 1. signal_enque queues signal for execution
1030  * 2. user calls trap(sig, "IGNORE"), setting SIG_IGN
1031  * 3. rb_signal_exec runs on queued signal
1032  */
1033  if (IMMEDIATE_P(cmd))
1034  return FALSE;
1035 
1036  ec->interrupt_mask |= TRAP_INTERRUPT_MASK;
1037  EC_PUSH_TAG(ec);
1038  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1039  VALUE signum = INT2NUM(sig);
1040  rb_eval_cmd_kw(cmd, rb_ary_new3(1, signum), RB_NO_KEYWORDS);
1041  }
1042  EC_POP_TAG();
1043  ec = GET_EC();
1044  ec->interrupt_mask = old_interrupt_mask;
1045 
1046  if (state) {
1047  /* XXX: should be replaced with rb_threadptr_pending_interrupt_enque() */
1048  EC_JUMP_TAG(ec, state);
1049  }
1050  return TRUE;
1051 }
1052 
1053 void
1054 rb_vm_trap_exit(rb_vm_t *vm)
1055 {
1056  VALUE trap_exit = vm->trap_list.cmd[0];
1057 
1058  if (trap_exit) {
1059  vm->trap_list.cmd[0] = 0;
1060  signal_exec(trap_exit, 0);
1061  }
1062 }
1063 
1064 /* returns true if a trap handler was run, false otherwise */
1065 int
1066 rb_signal_exec(rb_thread_t *th, int sig)
1067 {
1068  rb_vm_t *vm = GET_VM();
1069  VALUE cmd = vm->trap_list.cmd[sig];
1070 
1071  if (cmd == 0) {
1072  switch (sig) {
1073  case SIGINT:
1074  rb_interrupt();
1075  break;
1076 #ifdef SIGHUP
1077  case SIGHUP:
1078 #endif
1079 #ifdef SIGQUIT
1080  case SIGQUIT:
1081 #endif
1082 #ifdef SIGTERM
1083  case SIGTERM:
1084 #endif
1085 #ifdef SIGALRM
1086  case SIGALRM:
1087 #endif
1088 #ifdef SIGUSR1
1089  case SIGUSR1:
1090 #endif
1091 #ifdef SIGUSR2
1092  case SIGUSR2:
1093 #endif
1094  rb_threadptr_signal_raise(th, sig);
1095  break;
1096  }
1097  }
1098  else if (UNDEF_P(cmd)) {
1099  rb_threadptr_signal_exit(th);
1100  }
1101  else {
1102  return signal_exec(cmd, sig);
1103  }
1104  return FALSE;
1105 }
1106 
1107 static sighandler_t
1108 default_handler(int sig)
1109 {
1110  sighandler_t func;
1111  switch (sig) {
1112  case SIGINT:
1113 #ifdef SIGHUP
1114  case SIGHUP:
1115 #endif
1116 #ifdef SIGQUIT
1117  case SIGQUIT:
1118 #endif
1119 #ifdef SIGTERM
1120  case SIGTERM:
1121 #endif
1122 #ifdef SIGALRM
1123  case SIGALRM:
1124 #endif
1125 #ifdef SIGUSR1
1126  case SIGUSR1:
1127 #endif
1128 #ifdef SIGUSR2
1129  case SIGUSR2:
1130 #endif
1131 #ifdef RUBY_SIGCHLD
1132  case RUBY_SIGCHLD:
1133 #endif
1134  func = sighandler;
1135  break;
1136 #ifdef SIGBUS
1137  case SIGBUS:
1138  func = (sighandler_t)sigbus;
1139  break;
1140 #endif
1141 #ifdef SIGSEGV
1142  case SIGSEGV:
1143  func = (sighandler_t)sigsegv;
1144  break;
1145 #endif
1146 #ifdef SIGPIPE
1147  case SIGPIPE:
1148  func = sig_do_nothing;
1149  break;
1150 #endif
1151 #ifdef SIGSYS
1152  case SIGSYS:
1153  func = sig_do_nothing;
1154  break;
1155 #endif
1156  default:
1157  func = SIG_DFL;
1158  break;
1159  }
1160 
1161  return func;
1162 }
1163 
1164 static sighandler_t
1165 trap_handler(VALUE *cmd, int sig)
1166 {
1167  sighandler_t func = sighandler;
1168  VALUE command;
1169 
1170  if (NIL_P(*cmd)) {
1171  func = SIG_IGN;
1172  }
1173  else {
1174  command = rb_check_string_type(*cmd);
1175  if (NIL_P(command) && SYMBOL_P(*cmd)) {
1176  command = rb_sym2str(*cmd);
1177  if (!command) rb_raise(rb_eArgError, "bad handler");
1178  }
1179  if (!NIL_P(command)) {
1180  const char *cptr;
1181  long len;
1182  StringValue(command);
1183  *cmd = command;
1184  RSTRING_GETMEM(command, cptr, len);
1185  switch (len) {
1186  sig_ign:
1187  func = SIG_IGN;
1188  *cmd = Qtrue;
1189  break;
1190  sig_dfl:
1191  func = default_handler(sig);
1192  *cmd = 0;
1193  break;
1194  case 0:
1195  goto sig_ign;
1196  break;
1197  case 14:
1198  if (memcmp(cptr, "SYSTEM_DEFAULT", 14) == 0) {
1199  func = SIG_DFL;
1200  *cmd = 0;
1201  }
1202  break;
1203  case 7:
1204  if (memcmp(cptr, "SIG_IGN", 7) == 0) {
1205  goto sig_ign;
1206  }
1207  else if (memcmp(cptr, "SIG_DFL", 7) == 0) {
1208  goto sig_dfl;
1209  }
1210  else if (memcmp(cptr, "DEFAULT", 7) == 0) {
1211  goto sig_dfl;
1212  }
1213  break;
1214  case 6:
1215  if (memcmp(cptr, "IGNORE", 6) == 0) {
1216  goto sig_ign;
1217  }
1218  break;
1219  case 4:
1220  if (memcmp(cptr, "EXIT", 4) == 0) {
1221  *cmd = Qundef;
1222  }
1223  break;
1224  }
1225  }
1226  else {
1227  rb_proc_t *proc;
1228  GetProcPtr(*cmd, proc);
1229  (void)proc;
1230  }
1231  }
1232 
1233  return func;
1234 }
1235 
1236 static int
1237 trap_signm(VALUE vsig)
1238 {
1239  int sig = -1;
1240 
1241  if (FIXNUM_P(vsig)) {
1242  sig = FIX2INT(vsig);
1243  if (sig < 0 || sig >= NSIG) {
1244  rb_raise(rb_eArgError, "invalid signal number (%d)", sig);
1245  }
1246  }
1247  else {
1248  sig = signm2signo(&vsig, FALSE, TRUE, NULL);
1249  }
1250  return sig;
1251 }
1252 
1253 static VALUE
1254 trap(int sig, sighandler_t func, VALUE command)
1255 {
1256  sighandler_t oldfunc;
1257  VALUE oldcmd;
1258  rb_vm_t *vm = GET_VM();
1259 
1260  /*
1261  * Be careful. ruby_signal() and trap_list.cmd[sig] must be changed
1262  * atomically. In current implementation, we only need to don't call
1263  * RUBY_VM_CHECK_INTS().
1264  */
1265  if (sig == 0) {
1266  oldfunc = SIG_ERR;
1267  }
1268  else {
1269  oldfunc = ruby_signal(sig, func);
1270  if (oldfunc == SIG_ERR) rb_sys_fail_str(rb_signo2signm(sig));
1271  }
1272  oldcmd = vm->trap_list.cmd[sig];
1273  switch (oldcmd) {
1274  case 0:
1275  case Qtrue:
1276  if (oldfunc == SIG_IGN) oldcmd = rb_str_new2("IGNORE");
1277  else if (oldfunc == SIG_DFL) oldcmd = rb_str_new2("SYSTEM_DEFAULT");
1278  else if (oldfunc == sighandler) oldcmd = rb_str_new2("DEFAULT");
1279  else oldcmd = Qnil;
1280  break;
1281  case Qnil:
1282  break;
1283  case Qundef:
1284  oldcmd = rb_str_new2("EXIT");
1285  break;
1286  }
1287 
1288  ACCESS_ONCE(VALUE, vm->trap_list.cmd[sig]) = command;
1289 
1290  return oldcmd;
1291 }
1292 
1293 static int
1294 reserved_signal_p(int signo)
1295 {
1296 /* Synchronous signal can't deliver to main thread */
1297 #ifdef SIGSEGV
1298  if (signo == SIGSEGV)
1299  return 1;
1300 #endif
1301 #ifdef SIGBUS
1302  if (signo == SIGBUS)
1303  return 1;
1304 #endif
1305 #ifdef SIGILL
1306  if (signo == SIGILL)
1307  return 1;
1308 #endif
1309 #ifdef SIGFPE
1310  if (signo == SIGFPE)
1311  return 1;
1312 #endif
1313 
1314 /* used ubf internal see thread_pthread.c. */
1315 #ifdef SIGVTALRM
1316  if (signo == SIGVTALRM)
1317  return 1;
1318 #endif
1319 
1320  return 0;
1321 }
1322 
1323 /*
1324  * call-seq:
1325  * Signal.trap( signal, command ) -> obj
1326  * Signal.trap( signal ) {| | block } -> obj
1327  *
1328  * Specifies the handling of signals. The first parameter is a signal
1329  * name (a string such as ``SIGALRM'', ``SIGUSR1'', and so on) or a
1330  * signal number. The characters ``SIG'' may be omitted from the
1331  * signal name. The command or block specifies code to be run when the
1332  * signal is raised.
1333  * If the command is the string ``IGNORE'' or ``SIG_IGN'', the signal
1334  * will be ignored.
1335  * If the command is ``DEFAULT'' or ``SIG_DFL'', the Ruby's default handler
1336  * will be invoked.
1337  * If the command is ``EXIT'', the script will be terminated by the signal.
1338  * If the command is ``SYSTEM_DEFAULT'', the operating system's default
1339  * handler will be invoked.
1340  * Otherwise, the given command or block will be run.
1341  * The special signal name ``EXIT'' or signal number zero will be
1342  * invoked just prior to program termination.
1343  * trap returns the previous handler for the given signal.
1344  *
1345  * Signal.trap(0, proc { puts "Terminating: #{$$}" })
1346  * Signal.trap("CLD") { puts "Child died" }
1347  * fork && Process.wait
1348  *
1349  * <em>produces:</em>
1350  * Terminating: 27461
1351  * Child died
1352  * Terminating: 27460
1353  */
1354 static VALUE
1355 sig_trap(int argc, VALUE *argv, VALUE _)
1356 {
1357  int sig;
1358  sighandler_t func;
1359  VALUE cmd;
1360 
1361  rb_check_arity(argc, 1, 2);
1362 
1363  sig = trap_signm(argv[0]);
1364  if (reserved_signal_p(sig)) {
1365  const char *name = signo2signm(sig);
1366  if (name)
1367  rb_raise(rb_eArgError, "can't trap reserved signal: SIG%s", name);
1368  else
1369  rb_raise(rb_eArgError, "can't trap reserved signal: %d", sig);
1370  }
1371 
1372  if (argc == 1) {
1373  cmd = rb_block_proc();
1374  func = sighandler;
1375  }
1376  else {
1377  cmd = argv[1];
1378  func = trap_handler(&cmd, sig);
1379  }
1380 
1381  if (rb_obj_is_proc(cmd) &&
1382  !rb_ractor_main_p() && !rb_ractor_shareable_p(cmd)) {
1383  cmd = rb_proc_isolate(cmd);
1384  }
1385 
1386  return trap(sig, func, cmd);
1387 }
1388 
1389 /*
1390  * call-seq:
1391  * Signal.list -> a_hash
1392  *
1393  * Returns a list of signal names mapped to the corresponding
1394  * underlying signal numbers.
1395  *
1396  * 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}
1397  */
1398 static VALUE
1399 sig_list(VALUE _)
1400 {
1401  VALUE h = rb_hash_new();
1402  const struct signals *sigs;
1403 
1404  FOREACH_SIGNAL(sigs, 0) {
1405  rb_hash_aset(h, rb_fstring_cstr(sigs->signm), INT2FIX(sigs->signo));
1406  }
1407  return h;
1408 }
1409 
1410 #define INSTALL_SIGHANDLER(cond, signame, signum) do { \
1411  static const char failed[] = "failed to install "signame" handler"; \
1412  if (!(cond)) break; \
1413  if (reserved_signal_p(signum)) rb_bug(failed); \
1414  perror(failed); \
1415  } while (0)
1416 
1417 static int
1418 install_sighandler_core(int signum, sighandler_t handler, sighandler_t *old_handler)
1419 {
1420  sighandler_t old;
1421 
1422  old = ruby_signal(signum, handler);
1423  if (old == SIG_ERR) return -1;
1424  if (old_handler) {
1425  *old_handler = (old == SIG_DFL || old == SIG_IGN) ? 0 : old;
1426  }
1427  else {
1428  /* signal handler should be inherited during exec. */
1429  if (old != SIG_DFL) {
1430  ruby_signal(signum, old);
1431  }
1432  }
1433  return 0;
1434 }
1435 
1436 # define install_sighandler(signum, handler) \
1437  INSTALL_SIGHANDLER(install_sighandler_core(signum, handler, NULL), #signum, signum)
1438 # define force_install_sighandler(signum, handler, old_handler) \
1439  INSTALL_SIGHANDLER(install_sighandler_core(signum, handler, old_handler), #signum, signum)
1440 
1441 void
1443 {
1444  sighandler_t oldfunc;
1445 
1446  oldfunc = ruby_signal(SIGINT, SIG_IGN);
1447  if (oldfunc == sighandler) {
1448  ruby_signal(SIGINT, SIG_DFL);
1449  }
1450 }
1451 
1452 int ruby_enable_coredump = 0;
1453 
1454 /*
1455  * Many operating systems allow signals to be sent to running
1456  * processes. Some signals have a defined effect on the process, while
1457  * others may be trapped at the code level and acted upon. For
1458  * example, your process may trap the USR1 signal and use it to toggle
1459  * debugging, and may use TERM to initiate a controlled shutdown.
1460  *
1461  * pid = fork do
1462  * Signal.trap("USR1") do
1463  * $debug = !$debug
1464  * puts "Debug now: #$debug"
1465  * end
1466  * Signal.trap("TERM") do
1467  * puts "Terminating..."
1468  * shutdown()
1469  * end
1470  * # . . . do some work . . .
1471  * end
1472  *
1473  * Process.detach(pid)
1474  *
1475  * # Controlling program:
1476  * Process.kill("USR1", pid)
1477  * # ...
1478  * Process.kill("USR1", pid)
1479  * # ...
1480  * Process.kill("TERM", pid)
1481  *
1482  * <em>produces:</em>
1483  * Debug now: true
1484  * Debug now: false
1485  * Terminating...
1486  *
1487  * The list of available signal names and their interpretation is
1488  * system dependent. Signal delivery semantics may also vary between
1489  * systems; in particular signal delivery may not always be reliable.
1490  */
1491 void
1492 Init_signal(void)
1493 {
1494  VALUE mSignal = rb_define_module("Signal");
1495 
1496  rb_define_global_function("trap", sig_trap, -1);
1497  rb_define_module_function(mSignal, "trap", sig_trap, -1);
1498  rb_define_module_function(mSignal, "list", sig_list, 0);
1499  rb_define_module_function(mSignal, "signame", sig_signame, 1);
1500 
1501  rb_define_method(rb_eSignal, "initialize", esignal_init, -1);
1502  rb_define_method(rb_eSignal, "signo", esignal_signo, 0);
1503  rb_alias(rb_eSignal, rb_intern_const("signm"), rb_intern_const("message"));
1504  rb_define_method(rb_eInterrupt, "initialize", interrupt_init, -1);
1505 
1506  // It should be ready to call rb_signal_exec()
1507  VM_ASSERT(GET_THREAD()->pending_interrupt_queue);
1508 
1509  /* At this time, there is no subthread. Then sigmask guarantee atomics. */
1510  rb_disable_interrupt();
1511 
1512  install_sighandler(SIGINT, sighandler);
1513 #ifdef SIGHUP
1514  install_sighandler(SIGHUP, sighandler);
1515 #endif
1516 #ifdef SIGQUIT
1517  install_sighandler(SIGQUIT, sighandler);
1518 #endif
1519 #ifdef SIGTERM
1520  install_sighandler(SIGTERM, sighandler);
1521 #endif
1522 #ifdef SIGALRM
1523  install_sighandler(SIGALRM, sighandler);
1524 #endif
1525 #ifdef SIGUSR1
1526  install_sighandler(SIGUSR1, sighandler);
1527 #endif
1528 #ifdef SIGUSR2
1529  install_sighandler(SIGUSR2, sighandler);
1530 #endif
1531 
1532  if (!ruby_enable_coredump) {
1533 #ifdef SIGBUS
1534  force_install_sighandler(SIGBUS, (sighandler_t)sigbus, &default_sigbus_handler);
1535 #endif
1536 #ifdef SIGILL
1537  force_install_sighandler(SIGILL, (sighandler_t)sigill, &default_sigill_handler);
1538 #endif
1539 #ifdef SIGSEGV
1540  RB_ALTSTACK_INIT(GET_VM()->main_altstack, rb_allocate_sigaltstack());
1541  force_install_sighandler(SIGSEGV, (sighandler_t)sigsegv, &default_sigsegv_handler);
1542 #endif
1543  }
1544 #ifdef SIGPIPE
1545  install_sighandler(SIGPIPE, sig_do_nothing);
1546 #endif
1547 #ifdef SIGSYS
1548  install_sighandler(SIGSYS, sig_do_nothing);
1549 #endif
1550 
1551 #ifdef RUBY_SIGCHLD
1552  install_sighandler(RUBY_SIGCHLD, sighandler);
1553 #endif
1554 
1555  rb_enable_interrupt();
1556 }
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:1442
void rb_raise(VALUE exc_class, 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:3761
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:3768
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:4426
#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:3675
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:3051
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition: string.c:2692
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition: string.c:2850
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:1871
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:1362
void rb_alias(VALUE klass, ID dst, ID src)
Resembles alias.
Definition: vm_method.c:2289
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:277
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
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