Add Changelog reference to BZ#23024
[glibc.git] / hurd / hurdsig.c
blob31e8d336e34306db4b75bcd2cef69d3b48ee959c
1 /* Copyright (C) 1991-2018 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <http://www.gnu.org/licenses/>. */
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
22 #include <cthreads.h> /* For `struct mutex'. */
23 #include <pthreadP.h>
24 #include <mach.h>
25 #include <mach/thread_switch.h>
26 #include <mach/mig_support.h>
28 #include <hurd.h>
29 #include <hurd/id.h>
30 #include <hurd/signal.h>
32 #include "hurdfault.h"
33 #include "hurdmalloc.h" /* XXX */
34 #include "../locale/localeinfo.h"
36 const char *_hurdsig_getenv (const char *);
38 struct mutex _hurd_siglock;
39 int _hurd_stopped;
41 /* Port that receives signals and other miscellaneous messages. */
42 mach_port_t _hurd_msgport;
44 /* Thread listening on it. */
45 thread_t _hurd_msgport_thread;
47 /* Thread which receives task-global signals. */
48 thread_t _hurd_sigthread;
50 /* These are set up by _hurdsig_init. */
51 unsigned long int __hurd_sigthread_stack_base;
52 unsigned long int __hurd_sigthread_stack_end;
54 /* Linked-list of per-thread signal state. */
55 struct hurd_sigstate *_hurd_sigstates;
57 /* Timeout for RPC's after interrupt_operation. */
58 mach_msg_timeout_t _hurd_interrupted_rpc_timeout = 3000;
60 static void
61 default_sigaction (struct sigaction actions[NSIG])
63 int signo;
65 __sigemptyset (&actions[0].sa_mask);
66 actions[0].sa_flags = SA_RESTART;
67 actions[0].sa_handler = SIG_DFL;
69 for (signo = 1; signo < NSIG; ++signo)
70 actions[signo] = actions[0];
73 struct hurd_sigstate *
74 _hurd_thread_sigstate (thread_t thread)
76 struct hurd_sigstate *ss;
77 __mutex_lock (&_hurd_siglock);
78 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
79 if (ss->thread == thread)
80 break;
81 if (ss == NULL)
83 ss = malloc (sizeof (*ss));
84 if (ss == NULL)
85 __libc_fatal ("hurd: Can't allocate thread sigstate\n");
86 ss->thread = thread;
87 __spin_lock_init (&ss->lock);
89 /* Initialize default state. */
90 __sigemptyset (&ss->blocked);
91 __sigemptyset (&ss->pending);
92 memset (&ss->sigaltstack, 0, sizeof (ss->sigaltstack));
93 ss->preemptors = NULL;
94 ss->suspended = MACH_PORT_NULL;
95 ss->intr_port = MACH_PORT_NULL;
96 ss->context = NULL;
98 /* Initialize the sigaction vector from the default signal receiving
99 thread's state, and its from the system defaults. */
100 if (thread == _hurd_sigthread)
101 default_sigaction (ss->actions);
102 else
104 struct hurd_sigstate *s;
105 for (s = _hurd_sigstates; s != NULL; s = s->next)
106 if (s->thread == _hurd_sigthread)
107 break;
108 if (s)
110 __spin_lock (&s->lock);
111 memcpy (ss->actions, s->actions, sizeof (s->actions));
112 __spin_unlock (&s->lock);
114 else
115 default_sigaction (ss->actions);
118 ss->next = _hurd_sigstates;
119 _hurd_sigstates = ss;
121 __mutex_unlock (&_hurd_siglock);
122 return ss;
124 libc_hidden_def (_hurd_thread_sigstate)
126 /* Signal delivery itself is on this page. */
128 #include <hurd/fd.h>
129 #include <hurd/crash.h>
130 #include <hurd/resource.h>
131 #include <hurd/paths.h>
132 #include <setjmp.h>
133 #include <fcntl.h>
134 #include <sys/wait.h>
135 #include <thread_state.h>
136 #include <hurd/msg_server.h>
137 #include <hurd/msg_reply.h> /* For __msg_sig_post_reply. */
138 #include <hurd/interrupt.h>
139 #include <assert.h>
140 #include <unistd.h>
143 /* Call the crash dump server to mummify us before we die.
144 Returns nonzero if a core file was written. */
145 static int
146 write_corefile (int signo, const struct hurd_signal_detail *detail)
148 error_t err;
149 mach_port_t coreserver;
150 file_t file, coredir;
151 const char *name;
153 /* Don't bother locking since we just read the one word. */
154 rlim_t corelimit = _hurd_rlimits[RLIMIT_CORE].rlim_cur;
156 if (corelimit == 0)
157 /* No core dumping, thank you very much. Note that this makes
158 `ulimit -c 0' prevent crash-suspension too, which is probably
159 what the user wanted. */
160 return 0;
162 /* XXX RLIMIT_CORE:
163 When we have a protocol to make the server return an error
164 for RLIMIT_FSIZE, then tell the corefile fs server the RLIMIT_CORE
165 value in place of the RLIMIT_FSIZE value. */
167 /* First get a port to the core dumping server. */
168 coreserver = MACH_PORT_NULL;
169 name = _hurdsig_getenv ("CRASHSERVER");
170 if (name != NULL)
171 coreserver = __file_name_lookup (name, 0, 0);
172 if (coreserver == MACH_PORT_NULL)
173 coreserver = __file_name_lookup (_SERVERS_CRASH, 0, 0);
174 if (coreserver == MACH_PORT_NULL)
175 return 0;
177 /* Get a port to the directory where the new core file will reside. */
178 file = MACH_PORT_NULL;
179 name = _hurdsig_getenv ("COREFILE");
180 if (name == NULL)
181 name = "core";
182 coredir = __file_name_split (name, (char **) &name);
183 if (coredir != MACH_PORT_NULL)
184 /* Create the new file, but don't link it into the directory yet. */
185 __dir_mkfile (coredir, O_WRONLY|O_CREAT,
186 0600 & ~_hurd_umask, /* XXX ? */
187 &file);
189 /* Call the core dumping server to write the core file. */
190 err = __crash_dump_task (coreserver,
191 __mach_task_self (),
192 file,
193 signo, detail->code, detail->error,
194 detail->exc, detail->exc_code, detail->exc_subcode,
195 _hurd_ports[INIT_PORT_CTTYID].port,
196 MACH_MSG_TYPE_COPY_SEND);
197 __mach_port_deallocate (__mach_task_self (), coreserver);
199 if (! err && file != MACH_PORT_NULL)
200 /* The core dump into FILE succeeded, so now link it into the
201 directory. */
202 err = __dir_link (coredir, file, name, 1);
203 __mach_port_deallocate (__mach_task_self (), file);
204 __mach_port_deallocate (__mach_task_self (), coredir);
205 return !err && file != MACH_PORT_NULL;
209 /* The lowest-numbered thread state flavor value is 1,
210 so we use bit 0 in machine_thread_all_state.set to
211 record whether we have done thread_abort. */
212 #define THREAD_ABORTED 1
214 /* SS->thread is suspended. Abort the thread and get its basic state. */
215 static void
216 abort_thread (struct hurd_sigstate *ss, struct machine_thread_all_state *state,
217 void (*reply) (void))
219 if (!(state->set & THREAD_ABORTED))
221 error_t err = __thread_abort (ss->thread);
222 assert_perror (err);
223 /* Clear all thread state flavor set bits, because thread_abort may
224 have changed the state. */
225 state->set = THREAD_ABORTED;
228 if (reply)
229 (*reply) ();
231 machine_get_basic_state (ss->thread, state);
234 /* Find the location of the MiG reply port cell in use by the thread whose
235 state is described by THREAD_STATE. If SIGTHREAD is nonzero, make sure
236 that this location can be set without faulting, or else return NULL. */
238 static mach_port_t *
239 interrupted_reply_port_location (thread_t thread,
240 struct machine_thread_all_state *thread_state,
241 int sigthread)
243 mach_port_t *portloc = &THREAD_TCB(thread, thread_state)->reply_port;
245 if (sigthread && _hurdsig_catch_memory_fault (portloc))
246 /* Faulted trying to read the TCB. */
247 return NULL;
249 /* Fault now if this pointer is bogus. */
250 *(volatile mach_port_t *) portloc = *portloc;
252 if (sigthread)
253 _hurdsig_end_catch_fault ();
255 return portloc;
258 #include <hurd/sigpreempt.h>
259 #include <intr-msg.h>
261 /* Timeout on interrupt_operation calls. */
262 mach_msg_timeout_t _hurdsig_interrupt_timeout = 1000;
264 /* SS->thread is suspended.
266 Abort any interruptible RPC operation the thread is doing.
268 This uses only the constant member SS->thread and the unlocked, atomically
269 set member SS->intr_port, so no locking is needed.
271 If successfully sent an interrupt_operation and therefore the thread should
272 wait for its pending RPC to return (possibly EINTR) before taking the
273 incoming signal, returns the reply port to be received on. Otherwise
274 returns MACH_PORT_NULL.
276 SIGNO is used to find the applicable SA_RESTART bit. If SIGNO is zero,
277 the RPC fails with EINTR instead of restarting (thread_cancel).
279 *STATE_CHANGE is set nonzero if STATE->basic was modified and should
280 be applied back to the thread if it might ever run again, else zero. */
282 mach_port_t
283 _hurdsig_abort_rpcs (struct hurd_sigstate *ss, int signo, int sigthread,
284 struct machine_thread_all_state *state, int *state_change,
285 void (*reply) (void))
287 extern const void _hurd_intr_rpc_msg_in_trap;
288 mach_port_t rcv_port = MACH_PORT_NULL;
289 mach_port_t intr_port;
291 *state_change = 0;
293 intr_port = ss->intr_port;
294 if (intr_port == MACH_PORT_NULL)
295 /* No interruption needs done. */
296 return MACH_PORT_NULL;
298 /* Abort the thread's kernel context, so any pending message send or
299 receive completes immediately or aborts. */
300 abort_thread (ss, state, reply);
302 if (state->basic.PC < (natural_t) &_hurd_intr_rpc_msg_in_trap)
304 /* The thread is about to do the RPC, but hasn't yet entered
305 mach_msg. Mutate the thread's state so it knows not to try
306 the RPC. */
307 INTR_MSG_BACK_OUT (&state->basic);
308 MACHINE_THREAD_STATE_SET_PC (&state->basic,
309 &_hurd_intr_rpc_msg_in_trap);
310 state->basic.SYSRETURN = MACH_SEND_INTERRUPTED;
311 *state_change = 1;
313 else if (state->basic.PC == (natural_t) &_hurd_intr_rpc_msg_in_trap &&
314 /* The thread was blocked in the system call. After thread_abort,
315 the return value register indicates what state the RPC was in
316 when interrupted. */
317 state->basic.SYSRETURN == MACH_RCV_INTERRUPTED)
319 /* The RPC request message was sent and the thread was waiting for
320 the reply message; now the message receive has been aborted, so
321 the mach_msg call will return MACH_RCV_INTERRUPTED. We must tell
322 the server to interrupt the pending operation. The thread must
323 wait for the reply message before running the signal handler (to
324 guarantee that the operation has finished being interrupted), so
325 our nonzero return tells the trampoline code to finish the message
326 receive operation before running the handler. */
328 mach_port_t *reply = interrupted_reply_port_location (ss->thread,
329 state,
330 sigthread);
331 error_t err = __interrupt_operation (intr_port, _hurdsig_interrupt_timeout);
333 if (err)
335 if (reply)
337 /* The interrupt didn't work.
338 Destroy the receive right the thread is blocked on. */
339 __mach_port_destroy (__mach_task_self (), *reply);
340 *reply = MACH_PORT_NULL;
343 /* The system call return value register now contains
344 MACH_RCV_INTERRUPTED; when mach_msg resumes, it will retry the
345 call. Since we have just destroyed the receive right, the
346 retry will fail with MACH_RCV_INVALID_NAME. Instead, just
347 change the return value here to EINTR so mach_msg will not
348 retry and the EINTR error code will propagate up. */
349 state->basic.SYSRETURN = EINTR;
350 *state_change = 1;
352 else if (reply)
353 rcv_port = *reply;
355 /* All threads whose RPCs were interrupted by the interrupt_operation
356 call above will retry their RPCs unless we clear SS->intr_port.
357 So we clear it for the thread taking a signal when SA_RESTART is
358 clear, so that its call returns EINTR. */
359 if (! signo || !(ss->actions[signo].sa_flags & SA_RESTART))
360 ss->intr_port = MACH_PORT_NULL;
363 return rcv_port;
367 /* Abort the RPCs being run by all threads but this one;
368 all other threads should be suspended. If LIVE is nonzero, those
369 threads may run again, so they should be adjusted as necessary to be
370 happy when resumed. STATE is clobbered as a scratch area; its initial
371 contents are ignored, and its contents on return are not useful. */
373 static void
374 abort_all_rpcs (int signo, struct machine_thread_all_state *state, int live)
376 /* We can just loop over the sigstates. Any thread doing something
377 interruptible must have one. We needn't bother locking because all
378 other threads are stopped. */
380 struct hurd_sigstate *ss;
381 size_t nthreads;
382 mach_port_t *reply_ports;
384 /* First loop over the sigstates to count them.
385 We need to know how big a vector we will need for REPLY_PORTS. */
386 nthreads = 0;
387 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
388 ++nthreads;
390 reply_ports = alloca (nthreads * sizeof *reply_ports);
392 nthreads = 0;
393 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next, ++nthreads)
394 if (ss->thread == _hurd_msgport_thread)
395 reply_ports[nthreads] = MACH_PORT_NULL;
396 else
398 int state_changed;
399 state->set = 0; /* Reset scratch area. */
401 /* Abort any operation in progress with interrupt_operation.
402 Record the reply port the thread is waiting on.
403 We will wait for all the replies below. */
404 reply_ports[nthreads] = _hurdsig_abort_rpcs (ss, signo, 1,
405 state, &state_changed,
406 NULL);
407 if (live)
409 if (reply_ports[nthreads] != MACH_PORT_NULL)
411 /* We will wait for the reply to this RPC below, so the
412 thread must issue a new RPC rather than waiting for the
413 reply to the one it sent. */
414 state->basic.SYSRETURN = EINTR;
415 state_changed = 1;
417 if (state_changed)
418 /* Aborting the RPC needed to change this thread's state,
419 and it might ever run again. So write back its state. */
420 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
421 (natural_t *) &state->basic,
422 MACHINE_THREAD_STATE_COUNT);
426 /* Wait for replies from all the successfully interrupted RPCs. */
427 while (nthreads-- > 0)
428 if (reply_ports[nthreads] != MACH_PORT_NULL)
430 error_t err;
431 mach_msg_header_t head;
432 err = __mach_msg (&head, MACH_RCV_MSG|MACH_RCV_TIMEOUT, 0, sizeof head,
433 reply_ports[nthreads],
434 _hurd_interrupted_rpc_timeout, MACH_PORT_NULL);
435 switch (err)
437 case MACH_RCV_TIMED_OUT:
438 case MACH_RCV_TOO_LARGE:
439 break;
441 default:
442 assert_perror (err);
447 struct hurd_signal_preemptor *_hurdsig_preemptors = 0;
448 sigset_t _hurdsig_preempted_set;
450 /* XXX temporary to deal with spelling fix */
451 weak_alias (_hurdsig_preemptors, _hurdsig_preempters)
453 /* Mask of stop signals. */
454 #define STOPSIGS (sigmask (SIGTTIN) | sigmask (SIGTTOU) | \
455 sigmask (SIGSTOP) | sigmask (SIGTSTP))
457 /* Deliver a signal. SS is not locked. */
458 void
459 _hurd_internal_post_signal (struct hurd_sigstate *ss,
460 int signo, struct hurd_signal_detail *detail,
461 mach_port_t reply_port,
462 mach_msg_type_name_t reply_port_type,
463 int untraced)
465 error_t err;
466 struct machine_thread_all_state thread_state;
467 enum { stop, ignore, core, term, handle } act;
468 sighandler_t handler;
469 sigset_t pending;
470 int ss_suspended;
472 /* Reply to this sig_post message. */
473 __typeof (__msg_sig_post_reply) *reply_rpc
474 = (untraced ? __msg_sig_post_untraced_reply : __msg_sig_post_reply);
475 void reply (void)
477 error_t err;
478 if (reply_port == MACH_PORT_NULL)
479 return;
480 err = (*reply_rpc) (reply_port, reply_port_type, 0);
481 reply_port = MACH_PORT_NULL;
482 if (err != MACH_SEND_INVALID_DEST) /* Ignore dead reply port. */
483 assert_perror (err);
486 /* Mark the signal as pending. */
487 void mark_pending (void)
489 __sigaddset (&ss->pending, signo);
490 /* Save the details to be given to the handler when SIGNO is
491 unblocked. */
492 ss->pending_data[signo] = *detail;
495 /* Suspend the process with SIGNO. */
496 void suspend (void)
498 /* Stop all other threads and mark ourselves stopped. */
499 __USEPORT (PROC,
501 /* Hold the siglock while stopping other threads to be
502 sure it is not held by another thread afterwards. */
503 __mutex_lock (&_hurd_siglock);
504 __proc_dostop (port, _hurd_msgport_thread);
505 __mutex_unlock (&_hurd_siglock);
506 abort_all_rpcs (signo, &thread_state, 1);
507 reply ();
508 __proc_mark_stop (port, signo, detail->code);
509 }));
510 _hurd_stopped = 1;
512 /* Resume the process after a suspension. */
513 void resume (void)
515 /* Resume the process from being stopped. */
516 thread_t *threads;
517 mach_msg_type_number_t nthreads, i;
518 error_t err;
520 if (! _hurd_stopped)
521 return;
523 /* Tell the proc server we are continuing. */
524 __USEPORT (PROC, __proc_mark_cont (port));
525 /* Fetch ports to all our threads and resume them. */
526 err = __task_threads (__mach_task_self (), &threads, &nthreads);
527 assert_perror (err);
528 for (i = 0; i < nthreads; ++i)
530 if (threads[i] != _hurd_msgport_thread &&
531 (act != handle || threads[i] != ss->thread))
533 err = __thread_resume (threads[i]);
534 assert_perror (err);
536 err = __mach_port_deallocate (__mach_task_self (),
537 threads[i]);
538 assert_perror (err);
540 __vm_deallocate (__mach_task_self (),
541 (vm_address_t) threads,
542 nthreads * sizeof *threads);
543 _hurd_stopped = 0;
544 if (act == handle)
545 /* The thread that will run the handler is already suspended. */
546 ss_suspended = 1;
549 if (signo == 0)
551 if (untraced)
552 /* This is PTRACE_CONTINUE. */
553 resume ();
555 /* This call is just to check for pending signals. */
556 __spin_lock (&ss->lock);
557 goto check_pending_signals;
560 post_signal:
562 thread_state.set = 0; /* We know nothing. */
564 __spin_lock (&ss->lock);
566 /* Check for a preempted signal. Preempted signals can arrive during
567 critical sections. */
569 inline sighandler_t try_preemptor (struct hurd_signal_preemptor *pe)
570 { /* PE cannot be null. */
573 if (HURD_PREEMPT_SIGNAL_P (pe, signo, detail->code))
575 if (pe->preemptor)
577 sighandler_t handler = (*pe->preemptor) (pe, ss,
578 &signo, detail);
579 if (handler != SIG_ERR)
580 return handler;
582 else
583 return pe->handler;
585 pe = pe->next;
586 } while (pe != 0);
587 return SIG_ERR;
590 handler = ss->preemptors ? try_preemptor (ss->preemptors) : SIG_ERR;
592 /* If no thread-specific preemptor, check for a global one. */
593 if (handler == SIG_ERR && __sigismember (&_hurdsig_preempted_set, signo))
595 __mutex_lock (&_hurd_siglock);
596 handler = try_preemptor (_hurdsig_preemptors);
597 __mutex_unlock (&_hurd_siglock);
601 ss_suspended = 0;
603 if (handler == SIG_IGN)
604 /* Ignore the signal altogether. */
605 act = ignore;
606 else if (handler != SIG_ERR)
607 /* Run the preemption-provided handler. */
608 act = handle;
609 else
611 /* No preemption. Do normal handling. */
613 if (!untraced && __sigismember (&_hurdsig_traced, signo))
615 /* We are being traced. Stop to tell the debugger of the signal. */
616 if (_hurd_stopped)
617 /* Already stopped. Mark the signal as pending;
618 when resumed, we will notice it and stop again. */
619 mark_pending ();
620 else
621 suspend ();
622 __spin_unlock (&ss->lock);
623 reply ();
624 return;
627 handler = ss->actions[signo].sa_handler;
629 if (handler == SIG_DFL)
630 /* Figure out the default action for this signal. */
631 switch (signo)
633 case 0:
634 /* A sig_post msg with SIGNO==0 is sent to
635 tell us to check for pending signals. */
636 act = ignore;
637 break;
639 case SIGTTIN:
640 case SIGTTOU:
641 case SIGSTOP:
642 case SIGTSTP:
643 act = stop;
644 break;
646 case SIGCONT:
647 case SIGIO:
648 case SIGURG:
649 case SIGCHLD:
650 case SIGWINCH:
651 act = ignore;
652 break;
654 case SIGQUIT:
655 case SIGILL:
656 case SIGTRAP:
657 case SIGIOT:
658 case SIGEMT:
659 case SIGFPE:
660 case SIGBUS:
661 case SIGSEGV:
662 case SIGSYS:
663 act = core;
664 break;
666 case SIGINFO:
667 if (_hurd_pgrp == _hurd_pid)
669 /* We are the process group leader. Since there is no
670 user-specified handler for SIGINFO, we use a default one
671 which prints something interesting. We use the normal
672 handler mechanism instead of just doing it here to avoid
673 the signal thread faulting or blocking in this
674 potentially hairy operation. */
675 act = handle;
676 handler = _hurd_siginfo_handler;
678 else
679 act = ignore;
680 break;
682 default:
683 act = term;
684 break;
686 else if (handler == SIG_IGN)
687 act = ignore;
688 else
689 act = handle;
691 if (__sigmask (signo) & STOPSIGS)
692 /* Stop signals clear a pending SIGCONT even if they
693 are handled or ignored (but not if preempted). */
694 __sigdelset (&ss->pending, SIGCONT);
695 else
697 if (signo == SIGCONT)
698 /* Even if handled or ignored (but not preempted), SIGCONT clears
699 stop signals and resumes the process. */
700 ss->pending &= ~STOPSIGS;
702 if (_hurd_stopped && act != stop && (untraced || signo == SIGCONT))
703 resume ();
707 if (_hurd_orphaned && act == stop &&
708 (__sigmask (signo) & (__sigmask (SIGTTIN) | __sigmask (SIGTTOU) |
709 __sigmask (SIGTSTP))))
711 /* If we would ordinarily stop for a job control signal, but we are
712 orphaned so noone would ever notice and continue us again, we just
713 quietly die, alone and in the dark. */
714 detail->code = signo;
715 signo = SIGKILL;
716 act = term;
719 /* Handle receipt of a blocked signal, or any signal while stopped. */
720 if (act != ignore && /* Signals ignored now are forgotten now. */
721 __sigismember (&ss->blocked, signo) ||
722 (signo != SIGKILL && _hurd_stopped))
724 mark_pending ();
725 act = ignore;
728 /* Perform the chosen action for the signal. */
729 switch (act)
731 case stop:
732 if (_hurd_stopped)
734 /* We are already stopped, but receiving an untraced stop
735 signal. Instead of resuming and suspending again, just
736 notify the proc server of the new stop signal. */
737 error_t err = __USEPORT (PROC, __proc_mark_stop
738 (port, signo, detail->code));
739 assert_perror (err);
741 else
742 /* Suspend the process. */
743 suspend ();
744 break;
746 case ignore:
747 if (detail->exc)
748 /* Blocking or ignoring a machine exception is fatal.
749 Otherwise we could just spin on the faulting instruction. */
750 goto fatal;
752 /* Nobody cares about this signal. If there was a call to resume
753 above in SIGCONT processing and we've left a thread suspended,
754 now's the time to set it going. */
755 if (ss_suspended)
757 err = __thread_resume (ss->thread);
758 assert_perror (err);
759 ss_suspended = 0;
761 break;
763 sigbomb:
764 /* We got a fault setting up the stack frame for the handler.
765 Nothing to do but die; BSD gets SIGILL in this case. */
766 detail->code = signo; /* XXX ? */
767 signo = SIGILL;
769 fatal:
770 act = core;
771 /* FALLTHROUGH */
773 case term: /* Time to die. */
774 case core: /* And leave a rotting corpse. */
775 /* Have the proc server stop all other threads in our task. */
776 err = __USEPORT (PROC, __proc_dostop (port, _hurd_msgport_thread));
777 assert_perror (err);
778 /* No more user instructions will be executed.
779 The signal can now be considered delivered. */
780 reply ();
781 /* Abort all server operations now in progress. */
782 abort_all_rpcs (signo, &thread_state, 0);
785 int status = W_EXITCODE (0, signo);
786 /* Do a core dump if desired. Only set the wait status bit saying we
787 in fact dumped core if the operation was actually successful. */
788 if (act == core && write_corefile (signo, detail))
789 status |= WCOREFLAG;
790 /* Tell proc how we died and then stick the saber in the gut. */
791 _hurd_exit (status);
792 /* NOTREACHED */
795 case handle:
796 /* Call a handler for this signal. */
798 struct sigcontext *scp, ocontext;
799 int wait_for_reply, state_changed;
801 /* Stop the thread and abort its pending RPC operations. */
802 if (! ss_suspended)
804 err = __thread_suspend (ss->thread);
805 assert_perror (err);
808 /* Abort the thread's kernel context, so any pending message send
809 or receive completes immediately or aborts. If an interruptible
810 RPC is in progress, abort_rpcs will do this. But we must always
811 do it before fetching the thread's state, because
812 thread_get_state is never kosher before thread_abort. */
813 abort_thread (ss, &thread_state, NULL);
815 if (ss->context)
817 /* We have a previous sigcontext that sigreturn was about
818 to restore when another signal arrived. */
820 mach_port_t *loc;
822 if (_hurdsig_catch_memory_fault (ss->context))
824 /* We faulted reading the thread's stack. Forget that
825 context and pretend it wasn't there. It almost
826 certainly crash if this handler returns, but that's it's
827 problem. */
828 ss->context = NULL;
830 else
832 /* Copy the context from the thread's stack before
833 we start diddling the stack to set up the handler. */
834 ocontext = *ss->context;
835 ss->context = &ocontext;
837 _hurdsig_end_catch_fault ();
839 if (! machine_get_basic_state (ss->thread, &thread_state))
840 goto sigbomb;
841 loc = interrupted_reply_port_location (ss->thread,
842 &thread_state, 1);
843 if (loc && *loc != MACH_PORT_NULL)
844 /* This is the reply port for the context which called
845 sigreturn. Since we are abandoning that context entirely
846 and restoring SS->context instead, destroy this port. */
847 __mach_port_destroy (__mach_task_self (), *loc);
849 /* The thread was in sigreturn, not in any interruptible RPC. */
850 wait_for_reply = 0;
852 assert (! __spin_lock_locked (&ss->critical_section_lock));
854 else
856 int crit = __spin_lock_locked (&ss->critical_section_lock);
858 wait_for_reply
859 = (_hurdsig_abort_rpcs (ss,
860 /* In a critical section, any RPC
861 should be cancelled instead of
862 restarted, regardless of
863 SA_RESTART, so the entire
864 "atomic" operation can be aborted
865 as a unit. */
866 crit ? 0 : signo, 1,
867 &thread_state, &state_changed,
868 &reply)
869 != MACH_PORT_NULL);
871 if (crit)
873 /* The thread is in a critical section. Mark the signal as
874 pending. When it finishes the critical section, it will
875 check for pending signals. */
876 mark_pending ();
877 if (state_changed)
878 /* Some cases of interrupting an RPC must change the
879 thread state to back out the call. Normally this
880 change is rolled into the warping to the handler and
881 sigreturn, but we are not running the handler now
882 because the thread is in a critical section. Instead,
883 mutate the thread right away for the RPC interruption
884 and resume it; the RPC will return early so the
885 critical section can end soon. */
886 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
887 (natural_t *) &thread_state.basic,
888 MACHINE_THREAD_STATE_COUNT);
889 /* */
890 ss->intr_port = MACH_PORT_NULL;
891 __thread_resume (ss->thread);
892 break;
896 /* Call the machine-dependent function to set the thread up
897 to run the signal handler, and preserve its old context. */
898 scp = _hurd_setup_sighandler (ss, handler, signo, detail,
899 wait_for_reply, &thread_state);
900 if (scp == NULL)
901 goto sigbomb;
903 /* Set the machine-independent parts of the signal context. */
906 /* Fetch the thread variable for the MiG reply port,
907 and set it to MACH_PORT_NULL. */
908 mach_port_t *loc = interrupted_reply_port_location (ss->thread,
909 &thread_state,
911 if (loc)
913 scp->sc_reply_port = *loc;
914 *loc = MACH_PORT_NULL;
916 else
917 scp->sc_reply_port = MACH_PORT_NULL;
919 /* Save the intr_port in use by the interrupted code,
920 and clear the cell before running the trampoline. */
921 scp->sc_intr_port = ss->intr_port;
922 ss->intr_port = MACH_PORT_NULL;
924 if (ss->context)
926 /* After the handler runs we will restore to the state in
927 SS->context, not the state of the thread now. So restore
928 that context's reply port and intr port. */
930 scp->sc_reply_port = ss->context->sc_reply_port;
931 scp->sc_intr_port = ss->context->sc_intr_port;
933 ss->context = NULL;
937 /* Backdoor extra argument to signal handler. */
938 scp->sc_error = detail->error;
940 /* Block requested signals while running the handler. */
941 scp->sc_mask = ss->blocked;
942 __sigorset (&ss->blocked, &ss->blocked, &ss->actions[signo].sa_mask);
944 /* Also block SIGNO unless we're asked not to. */
945 if (! (ss->actions[signo].sa_flags & (SA_RESETHAND | SA_NODEFER)))
946 __sigaddset (&ss->blocked, signo);
948 /* Reset to SIG_DFL if requested. SIGILL and SIGTRAP cannot
949 be automatically reset when delivered; the system silently
950 enforces this restriction. */
951 if (ss->actions[signo].sa_flags & SA_RESETHAND
952 && signo != SIGILL && signo != SIGTRAP)
953 ss->actions[signo].sa_handler = SIG_DFL;
955 /* Start the thread running the handler (or possibly waiting for an
956 RPC reply before running the handler). */
957 err = __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
958 (natural_t *) &thread_state.basic,
959 MACHINE_THREAD_STATE_COUNT);
960 assert_perror (err);
961 err = __thread_resume (ss->thread);
962 assert_perror (err);
963 thread_state.set = 0; /* Everything we know is now wrong. */
964 break;
968 /* The signal has either been ignored or is now being handled. We can
969 consider it delivered and reply to the killer. */
970 reply ();
972 /* We get here unless the signal was fatal. We still hold SS->lock.
973 Check for pending signals, and loop to post them. */
975 /* Return nonzero if SS has any signals pending we should worry about.
976 We don't worry about any pending signals if we are stopped, nor if
977 SS is in a critical section. We are guaranteed to get a sig_post
978 message before any of them become deliverable: either the SIGCONT
979 signal, or a sig_post with SIGNO==0 as an explicit poll when the
980 thread finishes its critical section. */
981 inline int signals_pending (void)
983 if (_hurd_stopped || __spin_lock_locked (&ss->critical_section_lock))
984 return 0;
985 return pending = ss->pending & ~ss->blocked;
988 check_pending_signals:
989 untraced = 0;
991 if (signals_pending ())
993 for (signo = 1; signo < NSIG; ++signo)
994 if (__sigismember (&pending, signo))
996 deliver_pending:
997 __sigdelset (&ss->pending, signo);
998 *detail = ss->pending_data[signo];
999 __spin_unlock (&ss->lock);
1000 goto post_signal;
1004 /* No pending signals left undelivered for this thread.
1005 If we were sent signal 0, we need to check for pending
1006 signals for all threads. */
1007 if (signo == 0)
1009 __spin_unlock (&ss->lock);
1010 __mutex_lock (&_hurd_siglock);
1011 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
1013 __spin_lock (&ss->lock);
1014 for (signo = 1; signo < NSIG; ++signo)
1015 if (__sigismember (&ss->pending, signo)
1016 && (!__sigismember (&ss->blocked, signo)
1017 /* We "deliver" immediately pending blocked signals whose
1018 action might be to ignore, so that if ignored they are
1019 dropped right away. */
1020 || ss->actions[signo].sa_handler == SIG_IGN
1021 || ss->actions[signo].sa_handler == SIG_DFL))
1023 __mutex_unlock (&_hurd_siglock);
1024 goto deliver_pending;
1026 __spin_unlock (&ss->lock);
1028 __mutex_unlock (&_hurd_siglock);
1030 else
1032 /* No more signals pending; SS->lock is still locked.
1033 Wake up any sigsuspend call that is blocking SS->thread. */
1034 if (ss->suspended != MACH_PORT_NULL)
1036 /* There is a sigsuspend waiting. Tell it to wake up. */
1037 error_t err;
1038 mach_msg_header_t msg;
1039 msg.msgh_bits = MACH_MSGH_BITS (MACH_MSG_TYPE_MAKE_SEND, 0);
1040 msg.msgh_remote_port = ss->suspended;
1041 msg.msgh_local_port = MACH_PORT_NULL;
1042 /* These values do not matter. */
1043 msg.msgh_id = 8675309; /* Jenny, Jenny. */
1044 ss->suspended = MACH_PORT_NULL;
1045 err = __mach_msg (&msg, MACH_SEND_MSG, sizeof msg, 0,
1046 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
1047 MACH_PORT_NULL);
1048 assert_perror (err);
1050 __spin_unlock (&ss->lock);
1054 /* All pending signals delivered to all threads.
1055 Now we can send the reply message even for signal 0. */
1056 reply ();
1059 /* Decide whether REFPORT enables the sender to send us a SIGNO signal.
1060 Returns zero if so, otherwise the error code to return to the sender. */
1062 static error_t
1063 signal_allowed (int signo, mach_port_t refport)
1065 if (signo < 0 || signo >= NSIG)
1066 return EINVAL;
1068 if (refport == __mach_task_self ())
1069 /* Can send any signal. */
1070 goto win;
1072 /* Avoid needing to check for this below. */
1073 if (refport == MACH_PORT_NULL)
1074 return EPERM;
1076 switch (signo)
1078 case SIGINT:
1079 case SIGQUIT:
1080 case SIGTSTP:
1081 case SIGHUP:
1082 case SIGINFO:
1083 case SIGTTIN:
1084 case SIGTTOU:
1085 case SIGWINCH:
1086 /* Job control signals can be sent by the controlling terminal. */
1087 if (__USEPORT (CTTYID, port == refport))
1088 goto win;
1089 break;
1091 case SIGCONT:
1093 /* A continue signal can be sent by anyone in the session. */
1094 mach_port_t sessport;
1095 if (! __USEPORT (PROC, __proc_getsidport (port, &sessport)))
1097 __mach_port_deallocate (__mach_task_self (), sessport);
1098 if (refport == sessport)
1099 goto win;
1102 break;
1104 case SIGIO:
1105 case SIGURG:
1107 /* Any io object a file descriptor refers to might send us
1108 one of these signals using its async ID port for REFPORT.
1110 This is pretty wide open; it is not unlikely that some random
1111 process can at least open for reading something we have open,
1112 get its async ID port, and send us a spurious SIGIO or SIGURG
1113 signal. But BSD is actually wider open than that!--you can set
1114 the owner of an io object to any process or process group
1115 whatsoever and send them gratuitous signals.
1117 Someday we could implement some reasonable scheme for
1118 authorizing SIGIO and SIGURG signals properly. */
1120 int d;
1121 int lucky = 0; /* True if we find a match for REFPORT. */
1122 __mutex_lock (&_hurd_dtable_lock);
1123 for (d = 0; !lucky && (unsigned) d < (unsigned) _hurd_dtablesize; ++d)
1125 struct hurd_userlink ulink;
1126 io_t port;
1127 mach_port_t asyncid;
1128 if (_hurd_dtable[d] == NULL)
1129 continue;
1130 port = _hurd_port_get (&_hurd_dtable[d]->port, &ulink);
1131 if (! __io_get_icky_async_id (port, &asyncid))
1133 if (refport == asyncid)
1134 /* Break out of the loop on the next iteration. */
1135 lucky = 1;
1136 __mach_port_deallocate (__mach_task_self (), asyncid);
1138 _hurd_port_free (&_hurd_dtable[d]->port, &ulink, port);
1140 __mutex_unlock (&_hurd_dtable_lock);
1141 /* If we found a lucky winner, we've set D to -1 in the loop. */
1142 if (lucky)
1143 goto win;
1147 /* If this signal is legit, we have done `goto win' by now.
1148 When we return the error, mig deallocates REFPORT. */
1149 return EPERM;
1151 win:
1152 /* Deallocate the REFPORT send right; we are done with it. */
1153 __mach_port_deallocate (__mach_task_self (), refport);
1155 return 0;
1158 /* Implement the sig_post RPC from <hurd/msg.defs>;
1159 sent when someone wants us to get a signal. */
1160 kern_return_t
1161 _S_msg_sig_post (mach_port_t me,
1162 mach_port_t reply_port, mach_msg_type_name_t reply_port_type,
1163 int signo, natural_t sigcode,
1164 mach_port_t refport)
1166 error_t err;
1167 struct hurd_signal_detail d;
1169 if (err = signal_allowed (signo, refport))
1170 return err;
1172 d.code = sigcode;
1173 d.exc = 0;
1175 /* Post the signal to the designated signal-receiving thread. This will
1176 reply when the signal can be considered delivered. */
1177 _hurd_internal_post_signal (_hurd_thread_sigstate (_hurd_sigthread),
1178 signo, &d, reply_port, reply_port_type,
1179 0); /* Stop if traced. */
1181 return MIG_NO_REPLY; /* Already replied. */
1184 /* Implement the sig_post_untraced RPC from <hurd/msg.defs>;
1185 sent when the debugger wants us to really get a signal
1186 even if we are traced. */
1187 kern_return_t
1188 _S_msg_sig_post_untraced (mach_port_t me,
1189 mach_port_t reply_port,
1190 mach_msg_type_name_t reply_port_type,
1191 int signo, natural_t sigcode,
1192 mach_port_t refport)
1194 error_t err;
1195 struct hurd_signal_detail d;
1197 if (err = signal_allowed (signo, refport))
1198 return err;
1200 d.code = sigcode;
1201 d.exc = 0;
1203 /* Post the signal to the designated signal-receiving thread. This will
1204 reply when the signal can be considered delivered. */
1205 _hurd_internal_post_signal (_hurd_thread_sigstate (_hurd_sigthread),
1206 signo, &d, reply_port, reply_port_type,
1207 1); /* Untraced flag. */
1209 return MIG_NO_REPLY; /* Already replied. */
1212 extern void __mig_init (void *);
1214 #include <mach/task_special_ports.h>
1216 /* Initialize the message port and _hurd_sigthread and start the signal
1217 thread. */
1219 void
1220 _hurdsig_init (const int *intarray, size_t intarraysize)
1222 error_t err;
1223 vm_size_t stacksize;
1224 struct hurd_sigstate *ss;
1226 __mutex_init (&_hurd_siglock);
1228 err = __mach_port_allocate (__mach_task_self (),
1229 MACH_PORT_RIGHT_RECEIVE,
1230 &_hurd_msgport);
1231 assert_perror (err);
1233 /* Make a send right to the signal port. */
1234 err = __mach_port_insert_right (__mach_task_self (),
1235 _hurd_msgport,
1236 _hurd_msgport,
1237 MACH_MSG_TYPE_MAKE_SEND);
1238 assert_perror (err);
1240 /* Initialize the main thread's signal state. */
1241 ss = _hurd_self_sigstate ();
1243 /* Copy inherited values from our parent (or pre-exec process state)
1244 into the signal settings of the main thread. */
1245 if (intarraysize > INIT_SIGMASK)
1246 ss->blocked = intarray[INIT_SIGMASK];
1247 if (intarraysize > INIT_SIGPENDING)
1248 ss->pending = intarray[INIT_SIGPENDING];
1249 if (intarraysize > INIT_SIGIGN && intarray[INIT_SIGIGN] != 0)
1251 int signo;
1252 for (signo = 1; signo < NSIG; ++signo)
1253 if (intarray[INIT_SIGIGN] & __sigmask(signo))
1254 ss->actions[signo].sa_handler = SIG_IGN;
1257 /* Set the default thread to receive task-global signals
1258 to this one, the main (first) user thread. */
1259 _hurd_sigthread = ss->thread;
1261 /* Start the signal thread listening on the message port. */
1263 #pragma weak __cthread_fork
1264 if (!__cthread_fork)
1266 err = __thread_create (__mach_task_self (), &_hurd_msgport_thread);
1267 assert_perror (err);
1269 stacksize = __vm_page_size * 8; /* Small stack for signal thread. */
1270 err = __mach_setup_thread (__mach_task_self (), _hurd_msgport_thread,
1271 _hurd_msgport_receive,
1272 (vm_address_t *) &__hurd_sigthread_stack_base,
1273 &stacksize);
1274 assert_perror (err);
1276 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + stacksize;
1278 /* Reinitialize the MiG support routines so they will use a per-thread
1279 variable for the cached reply port. */
1280 __mig_init ((void *) __hurd_sigthread_stack_base);
1282 err = __thread_resume (_hurd_msgport_thread);
1283 assert_perror (err);
1285 else
1287 /* When cthreads is being used, we need to make the signal thread a
1288 proper cthread. Otherwise it cannot use mutex_lock et al, which
1289 will be the cthreads versions. Various of the message port RPC
1290 handlers need to take locks, so we need to be able to call into
1291 cthreads code and meet its assumptions about how our thread and
1292 its stack are arranged. Since cthreads puts it there anyway,
1293 we'll let the signal thread's per-thread variables be found as for
1294 any normal cthread, and just leave the magic __hurd_sigthread_*
1295 values all zero so they'll be ignored. */
1296 #pragma weak __cthread_detach
1297 #pragma weak __pthread_getattr_np
1298 #pragma weak __pthread_attr_getstack
1299 __cthread_t thread = __cthread_fork (
1300 (cthread_fn_t) &_hurd_msgport_receive, 0);
1301 __cthread_detach (thread);
1303 if (__pthread_getattr_np)
1305 /* Record signal thread stack layout for fork() */
1306 pthread_attr_t attr;
1307 void *addr;
1308 size_t size;
1310 __pthread_getattr_np ((pthread_t) thread, &attr);
1311 __pthread_attr_getstack (&attr, &addr, &size);
1312 __hurd_sigthread_stack_base = (uintptr_t) addr;
1313 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + size;
1316 /* XXX We need the thread port for the signal thread further on
1317 in this thread (see hurdfault.c:_hurdsigfault_init).
1318 Therefore we block until _hurd_msgport_thread is initialized
1319 by the newly created thread. This really shouldn't be
1320 necessary; we should be able to fetch the thread port for a
1321 cthread from here. */
1322 while (_hurd_msgport_thread == 0)
1323 __swtch_pri (0);
1326 /* Receive exceptions on the signal port. */
1327 #ifdef TASK_EXCEPTION_PORT
1328 __task_set_special_port (__mach_task_self (),
1329 TASK_EXCEPTION_PORT, _hurd_msgport);
1330 #elif defined (EXC_MASK_ALL)
1331 __task_set_exception_ports (__mach_task_self (),
1332 EXC_MASK_ALL & ~(EXC_MASK_SYSCALL
1333 | EXC_MASK_MACH_SYSCALL
1334 | EXC_MASK_RPC_ALERT),
1335 _hurd_msgport,
1336 EXCEPTION_DEFAULT, MACHINE_THREAD_STATE);
1337 #else
1338 # error task_set_exception_port?
1339 #endif
1341 /* Sanity check. Any pending, unblocked signals should have been
1342 taken by our predecessor incarnation (i.e. parent or pre-exec state)
1343 before packing up our init ints. This assert is last (not above)
1344 so that signal handling is all set up to handle the abort. */
1345 assert ((ss->pending &~ ss->blocked) == 0);
1347 \f /* XXXX */
1348 /* Reauthenticate with the proc server. */
1350 static void
1351 reauth_proc (mach_port_t new)
1353 mach_port_t ref, ignore;
1355 ref = __mach_reply_port ();
1356 if (! HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1357 __proc_reauthenticate (port, ref,
1358 MACH_MSG_TYPE_MAKE_SEND) ||
1359 __auth_user_authenticate (new, ref,
1360 MACH_MSG_TYPE_MAKE_SEND,
1361 &ignore))
1362 && ignore != MACH_PORT_NULL)
1363 __mach_port_deallocate (__mach_task_self (), ignore);
1364 __mach_port_destroy (__mach_task_self (), ref);
1366 /* Set the owner of the process here too. */
1367 __mutex_lock (&_hurd_id.lock);
1368 if (!_hurd_check_ids ())
1369 HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1370 __proc_setowner (port,
1371 (_hurd_id.gen.nuids
1372 ? _hurd_id.gen.uids[0] : 0),
1373 !_hurd_id.gen.nuids));
1374 __mutex_unlock (&_hurd_id.lock);
1376 (void) &reauth_proc; /* Silence compiler warning. */
1378 text_set_element (_hurd_reauth_hook, reauth_proc);
1380 /* Like `getenv', but safe for the signal thread to run.
1381 If the environment is trashed, this will just return NULL. */
1383 const char *
1384 _hurdsig_getenv (const char *variable)
1386 if (__libc_enable_secure)
1387 return NULL;
1389 if (_hurdsig_catch_memory_fault (__environ))
1390 /* We bombed in getenv. */
1391 return NULL;
1392 else
1394 const size_t len = strlen (variable);
1395 char *value = NULL;
1396 char *volatile *ep = __environ;
1397 while (*ep)
1399 const char *p = *ep;
1400 _hurdsig_fault_preemptor.first = (long int) p;
1401 _hurdsig_fault_preemptor.last = VM_MAX_ADDRESS;
1402 if (! strncmp (p, variable, len) && p[len] == '=')
1404 size_t valuelen;
1405 p += len + 1;
1406 valuelen = strlen (p);
1407 _hurdsig_fault_preemptor.last = (long int) (p + valuelen);
1408 value = malloc (++valuelen);
1409 if (value)
1410 memcpy (value, p, valuelen);
1411 break;
1413 _hurdsig_fault_preemptor.first = (long int) ++ep;
1414 _hurdsig_fault_preemptor.last = (long int) (ep + 1);
1416 _hurdsig_end_catch_fault ();
1417 return value;