Ruby: signal.c Source File

Ruby 3.0.5p211 (2022-11-24 revision ba5cf0f7c52d4d35cc6a173c89eda98ceffa2dcf)

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