Fix libnldbl_nonshared.a references to internal libm symbols (bug 23735).
[glibc.git] / hurd / hurdsig.c
blobaa82f63413539620d45388cdd6934506114057a4
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 #include <libc-diag.h>
38 const char *_hurdsig_getenv (const char *);
40 struct mutex _hurd_siglock;
41 int _hurd_stopped;
43 /* Port that receives signals and other miscellaneous messages. */
44 mach_port_t _hurd_msgport;
46 /* Thread listening on it. */
47 thread_t _hurd_msgport_thread;
49 /* Thread which receives task-global signals. */
50 thread_t _hurd_sigthread;
52 /* These are set up by _hurdsig_init. */
53 unsigned long int __hurd_sigthread_stack_base;
54 unsigned long int __hurd_sigthread_stack_end;
56 /* Linked-list of per-thread signal state. */
57 struct hurd_sigstate *_hurd_sigstates;
59 /* Timeout for RPC's after interrupt_operation. */
60 mach_msg_timeout_t _hurd_interrupted_rpc_timeout = 3000;
62 static void
63 default_sigaction (struct sigaction actions[NSIG])
65 int signo;
67 __sigemptyset (&actions[0].sa_mask);
68 actions[0].sa_flags = SA_RESTART;
69 actions[0].sa_handler = SIG_DFL;
71 for (signo = 1; signo < NSIG; ++signo)
72 actions[signo] = actions[0];
75 struct hurd_sigstate *
76 _hurd_thread_sigstate (thread_t thread)
78 struct hurd_sigstate *ss;
79 __mutex_lock (&_hurd_siglock);
80 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
81 if (ss->thread == thread)
82 break;
83 if (ss == NULL)
85 ss = malloc (sizeof (*ss));
86 if (ss == NULL)
87 __libc_fatal ("hurd: Can't allocate thread sigstate\n");
88 ss->thread = thread;
89 __spin_lock_init (&ss->lock);
91 /* Initialize default state. */
92 __sigemptyset (&ss->blocked);
93 __sigemptyset (&ss->pending);
94 memset (&ss->sigaltstack, 0, sizeof (ss->sigaltstack));
95 ss->preemptors = NULL;
96 ss->suspended = MACH_PORT_NULL;
97 ss->intr_port = MACH_PORT_NULL;
98 ss->context = NULL;
100 /* Initialize the sigaction vector from the default signal receiving
101 thread's state, and its from the system defaults. */
102 if (thread == _hurd_sigthread)
103 default_sigaction (ss->actions);
104 else
106 struct hurd_sigstate *s;
107 for (s = _hurd_sigstates; s != NULL; s = s->next)
108 if (s->thread == _hurd_sigthread)
109 break;
110 if (s)
112 __spin_lock (&s->lock);
113 memcpy (ss->actions, s->actions, sizeof (s->actions));
114 __spin_unlock (&s->lock);
116 else
117 default_sigaction (ss->actions);
120 ss->next = _hurd_sigstates;
121 _hurd_sigstates = ss;
123 __mutex_unlock (&_hurd_siglock);
124 return ss;
126 libc_hidden_def (_hurd_thread_sigstate)
128 /* Signal delivery itself is on this page. */
130 #include <hurd/fd.h>
131 #include <hurd/crash.h>
132 #include <hurd/resource.h>
133 #include <hurd/paths.h>
134 #include <setjmp.h>
135 #include <fcntl.h>
136 #include <sys/wait.h>
137 #include <thread_state.h>
138 #include <hurd/msg_server.h>
139 #include <hurd/msg_reply.h> /* For __msg_sig_post_reply. */
140 #include <hurd/interrupt.h>
141 #include <assert.h>
142 #include <unistd.h>
145 /* Call the crash dump server to mummify us before we die.
146 Returns nonzero if a core file was written. */
147 static int
148 write_corefile (int signo, const struct hurd_signal_detail *detail)
150 error_t err;
151 mach_port_t coreserver;
152 file_t file, coredir;
153 const char *name;
155 /* Don't bother locking since we just read the one word. */
156 rlim_t corelimit = _hurd_rlimits[RLIMIT_CORE].rlim_cur;
158 if (corelimit == 0)
159 /* No core dumping, thank you very much. Note that this makes
160 `ulimit -c 0' prevent crash-suspension too, which is probably
161 what the user wanted. */
162 return 0;
164 /* XXX RLIMIT_CORE:
165 When we have a protocol to make the server return an error
166 for RLIMIT_FSIZE, then tell the corefile fs server the RLIMIT_CORE
167 value in place of the RLIMIT_FSIZE value. */
169 /* First get a port to the core dumping server. */
170 coreserver = MACH_PORT_NULL;
171 name = _hurdsig_getenv ("CRASHSERVER");
172 if (name != NULL)
173 coreserver = __file_name_lookup (name, 0, 0);
174 if (coreserver == MACH_PORT_NULL)
175 coreserver = __file_name_lookup (_SERVERS_CRASH, 0, 0);
176 if (coreserver == MACH_PORT_NULL)
177 return 0;
179 /* Get a port to the directory where the new core file will reside. */
180 file = MACH_PORT_NULL;
181 name = _hurdsig_getenv ("COREFILE");
182 if (name == NULL)
183 name = "core";
184 coredir = __file_name_split (name, (char **) &name);
185 if (coredir != MACH_PORT_NULL)
186 /* Create the new file, but don't link it into the directory yet. */
187 __dir_mkfile (coredir, O_WRONLY|O_CREAT,
188 0600 & ~_hurd_umask, /* XXX ? */
189 &file);
191 /* Call the core dumping server to write the core file. */
192 err = __crash_dump_task (coreserver,
193 __mach_task_self (),
194 file,
195 signo, detail->code, detail->error,
196 detail->exc, detail->exc_code, detail->exc_subcode,
197 _hurd_ports[INIT_PORT_CTTYID].port,
198 MACH_MSG_TYPE_COPY_SEND);
199 __mach_port_deallocate (__mach_task_self (), coreserver);
201 if (! err && file != MACH_PORT_NULL)
202 /* The core dump into FILE succeeded, so now link it into the
203 directory. */
204 err = __dir_link (coredir, file, name, 1);
205 __mach_port_deallocate (__mach_task_self (), file);
206 __mach_port_deallocate (__mach_task_self (), coredir);
207 return !err && file != MACH_PORT_NULL;
211 /* The lowest-numbered thread state flavor value is 1,
212 so we use bit 0 in machine_thread_all_state.set to
213 record whether we have done thread_abort. */
214 #define THREAD_ABORTED 1
216 /* SS->thread is suspended. Abort the thread and get its basic state. */
217 static void
218 abort_thread (struct hurd_sigstate *ss, struct machine_thread_all_state *state,
219 void (*reply) (void))
221 if (!(state->set & THREAD_ABORTED))
223 error_t err = __thread_abort (ss->thread);
224 assert_perror (err);
225 /* Clear all thread state flavor set bits, because thread_abort may
226 have changed the state. */
227 state->set = THREAD_ABORTED;
230 if (reply)
231 (*reply) ();
233 machine_get_basic_state (ss->thread, state);
236 /* Find the location of the MiG reply port cell in use by the thread whose
237 state is described by THREAD_STATE. If SIGTHREAD is nonzero, make sure
238 that this location can be set without faulting, or else return NULL. */
240 static mach_port_t *
241 interrupted_reply_port_location (thread_t thread,
242 struct machine_thread_all_state *thread_state,
243 int sigthread)
245 mach_port_t *portloc = &THREAD_TCB(thread, thread_state)->reply_port;
247 if (sigthread && _hurdsig_catch_memory_fault (portloc))
248 /* Faulted trying to read the TCB. */
249 return NULL;
251 DIAG_PUSH_NEEDS_COMMENT;
252 /* GCC 6 and before seem to be confused by the setjmp call inside
253 _hurdsig_catch_memory_fault and think that we may be returning a second
254 time to here with portloc uninitialized (but we never do). */
255 DIAG_IGNORE_NEEDS_COMMENT (6, "-Wmaybe-uninitialized");
256 /* Fault now if this pointer is bogus. */
257 *(volatile mach_port_t *) portloc = *portloc;
258 DIAG_POP_NEEDS_COMMENT;
260 if (sigthread)
261 _hurdsig_end_catch_fault ();
263 return portloc;
266 #include <hurd/sigpreempt.h>
267 #include <intr-msg.h>
269 /* Timeout on interrupt_operation calls. */
270 mach_msg_timeout_t _hurdsig_interrupt_timeout = 1000;
272 /* SS->thread is suspended.
274 Abort any interruptible RPC operation the thread is doing.
276 This uses only the constant member SS->thread and the unlocked, atomically
277 set member SS->intr_port, so no locking is needed.
279 If successfully sent an interrupt_operation and therefore the thread should
280 wait for its pending RPC to return (possibly EINTR) before taking the
281 incoming signal, returns the reply port to be received on. Otherwise
282 returns MACH_PORT_NULL.
284 SIGNO is used to find the applicable SA_RESTART bit. If SIGNO is zero,
285 the RPC fails with EINTR instead of restarting (thread_cancel).
287 *STATE_CHANGE is set nonzero if STATE->basic was modified and should
288 be applied back to the thread if it might ever run again, else zero. */
290 mach_port_t
291 _hurdsig_abort_rpcs (struct hurd_sigstate *ss, int signo, int sigthread,
292 struct machine_thread_all_state *state, int *state_change,
293 void (*reply) (void))
295 extern const void _hurd_intr_rpc_msg_in_trap;
296 mach_port_t rcv_port = MACH_PORT_NULL;
297 mach_port_t intr_port;
299 *state_change = 0;
301 intr_port = ss->intr_port;
302 if (intr_port == MACH_PORT_NULL)
303 /* No interruption needs done. */
304 return MACH_PORT_NULL;
306 /* Abort the thread's kernel context, so any pending message send or
307 receive completes immediately or aborts. */
308 abort_thread (ss, state, reply);
310 if (state->basic.PC < (natural_t) &_hurd_intr_rpc_msg_in_trap)
312 /* The thread is about to do the RPC, but hasn't yet entered
313 mach_msg. Mutate the thread's state so it knows not to try
314 the RPC. */
315 INTR_MSG_BACK_OUT (&state->basic);
316 MACHINE_THREAD_STATE_SET_PC (&state->basic,
317 &_hurd_intr_rpc_msg_in_trap);
318 state->basic.SYSRETURN = MACH_SEND_INTERRUPTED;
319 *state_change = 1;
321 else if (state->basic.PC == (natural_t) &_hurd_intr_rpc_msg_in_trap &&
322 /* The thread was blocked in the system call. After thread_abort,
323 the return value register indicates what state the RPC was in
324 when interrupted. */
325 state->basic.SYSRETURN == MACH_RCV_INTERRUPTED)
327 /* The RPC request message was sent and the thread was waiting for
328 the reply message; now the message receive has been aborted, so
329 the mach_msg call will return MACH_RCV_INTERRUPTED. We must tell
330 the server to interrupt the pending operation. The thread must
331 wait for the reply message before running the signal handler (to
332 guarantee that the operation has finished being interrupted), so
333 our nonzero return tells the trampoline code to finish the message
334 receive operation before running the handler. */
336 mach_port_t *reply = interrupted_reply_port_location (ss->thread,
337 state,
338 sigthread);
339 error_t err = __interrupt_operation (intr_port, _hurdsig_interrupt_timeout);
341 if (err)
343 if (reply)
345 /* The interrupt didn't work.
346 Destroy the receive right the thread is blocked on. */
347 __mach_port_destroy (__mach_task_self (), *reply);
348 *reply = MACH_PORT_NULL;
351 /* The system call return value register now contains
352 MACH_RCV_INTERRUPTED; when mach_msg resumes, it will retry the
353 call. Since we have just destroyed the receive right, the
354 retry will fail with MACH_RCV_INVALID_NAME. Instead, just
355 change the return value here to EINTR so mach_msg will not
356 retry and the EINTR error code will propagate up. */
357 state->basic.SYSRETURN = EINTR;
358 *state_change = 1;
360 else if (reply)
361 rcv_port = *reply;
363 /* All threads whose RPCs were interrupted by the interrupt_operation
364 call above will retry their RPCs unless we clear SS->intr_port.
365 So we clear it for the thread taking a signal when SA_RESTART is
366 clear, so that its call returns EINTR. */
367 if (! signo || !(ss->actions[signo].sa_flags & SA_RESTART))
368 ss->intr_port = MACH_PORT_NULL;
371 return rcv_port;
375 /* Abort the RPCs being run by all threads but this one;
376 all other threads should be suspended. If LIVE is nonzero, those
377 threads may run again, so they should be adjusted as necessary to be
378 happy when resumed. STATE is clobbered as a scratch area; its initial
379 contents are ignored, and its contents on return are not useful. */
381 static void
382 abort_all_rpcs (int signo, struct machine_thread_all_state *state, int live)
384 /* We can just loop over the sigstates. Any thread doing something
385 interruptible must have one. We needn't bother locking because all
386 other threads are stopped. */
388 struct hurd_sigstate *ss;
389 size_t nthreads;
390 mach_port_t *reply_ports;
392 /* First loop over the sigstates to count them.
393 We need to know how big a vector we will need for REPLY_PORTS. */
394 nthreads = 0;
395 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
396 ++nthreads;
398 reply_ports = alloca (nthreads * sizeof *reply_ports);
400 nthreads = 0;
401 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next, ++nthreads)
402 if (ss->thread == _hurd_msgport_thread)
403 reply_ports[nthreads] = MACH_PORT_NULL;
404 else
406 int state_changed;
407 state->set = 0; /* Reset scratch area. */
409 /* Abort any operation in progress with interrupt_operation.
410 Record the reply port the thread is waiting on.
411 We will wait for all the replies below. */
412 reply_ports[nthreads] = _hurdsig_abort_rpcs (ss, signo, 1,
413 state, &state_changed,
414 NULL);
415 if (live)
417 if (reply_ports[nthreads] != MACH_PORT_NULL)
419 /* We will wait for the reply to this RPC below, so the
420 thread must issue a new RPC rather than waiting for the
421 reply to the one it sent. */
422 state->basic.SYSRETURN = EINTR;
423 state_changed = 1;
425 if (state_changed)
426 /* Aborting the RPC needed to change this thread's state,
427 and it might ever run again. So write back its state. */
428 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
429 (natural_t *) &state->basic,
430 MACHINE_THREAD_STATE_COUNT);
434 /* Wait for replies from all the successfully interrupted RPCs. */
435 while (nthreads-- > 0)
436 if (reply_ports[nthreads] != MACH_PORT_NULL)
438 error_t err;
439 mach_msg_header_t head;
440 err = __mach_msg (&head, MACH_RCV_MSG|MACH_RCV_TIMEOUT, 0, sizeof head,
441 reply_ports[nthreads],
442 _hurd_interrupted_rpc_timeout, MACH_PORT_NULL);
443 switch (err)
445 case MACH_RCV_TIMED_OUT:
446 case MACH_RCV_TOO_LARGE:
447 break;
449 default:
450 assert_perror (err);
455 struct hurd_signal_preemptor *_hurdsig_preemptors = 0;
456 sigset_t _hurdsig_preempted_set;
458 /* XXX temporary to deal with spelling fix */
459 weak_alias (_hurdsig_preemptors, _hurdsig_preempters)
461 /* Mask of stop signals. */
462 #define STOPSIGS (sigmask (SIGTTIN) | sigmask (SIGTTOU) | \
463 sigmask (SIGSTOP) | sigmask (SIGTSTP))
465 /* Deliver a signal. SS is not locked. */
466 void
467 _hurd_internal_post_signal (struct hurd_sigstate *ss,
468 int signo, struct hurd_signal_detail *detail,
469 mach_port_t reply_port,
470 mach_msg_type_name_t reply_port_type,
471 int untraced)
473 error_t err;
474 struct machine_thread_all_state thread_state;
475 enum { stop, ignore, core, term, handle } act;
476 sighandler_t handler;
477 sigset_t pending;
478 int ss_suspended;
480 /* Reply to this sig_post message. */
481 __typeof (__msg_sig_post_reply) *reply_rpc
482 = (untraced ? __msg_sig_post_untraced_reply : __msg_sig_post_reply);
483 void reply (void)
485 error_t err;
486 if (reply_port == MACH_PORT_NULL)
487 return;
488 err = (*reply_rpc) (reply_port, reply_port_type, 0);
489 reply_port = MACH_PORT_NULL;
490 if (err != MACH_SEND_INVALID_DEST) /* Ignore dead reply port. */
491 assert_perror (err);
494 /* Mark the signal as pending. */
495 void mark_pending (void)
497 __sigaddset (&ss->pending, signo);
498 /* Save the details to be given to the handler when SIGNO is
499 unblocked. */
500 ss->pending_data[signo] = *detail;
503 /* Suspend the process with SIGNO. */
504 void suspend (void)
506 /* Stop all other threads and mark ourselves stopped. */
507 __USEPORT (PROC,
509 /* Hold the siglock while stopping other threads to be
510 sure it is not held by another thread afterwards. */
511 __mutex_lock (&_hurd_siglock);
512 __proc_dostop (port, _hurd_msgport_thread);
513 __mutex_unlock (&_hurd_siglock);
514 abort_all_rpcs (signo, &thread_state, 1);
515 reply ();
516 __proc_mark_stop (port, signo, detail->code);
517 }));
518 _hurd_stopped = 1;
520 /* Resume the process after a suspension. */
521 void resume (void)
523 /* Resume the process from being stopped. */
524 thread_t *threads;
525 mach_msg_type_number_t nthreads, i;
526 error_t err;
528 if (! _hurd_stopped)
529 return;
531 /* Tell the proc server we are continuing. */
532 __USEPORT (PROC, __proc_mark_cont (port));
533 /* Fetch ports to all our threads and resume them. */
534 err = __task_threads (__mach_task_self (), &threads, &nthreads);
535 assert_perror (err);
536 for (i = 0; i < nthreads; ++i)
538 if (threads[i] != _hurd_msgport_thread &&
539 (act != handle || threads[i] != ss->thread))
541 err = __thread_resume (threads[i]);
542 assert_perror (err);
544 err = __mach_port_deallocate (__mach_task_self (),
545 threads[i]);
546 assert_perror (err);
548 __vm_deallocate (__mach_task_self (),
549 (vm_address_t) threads,
550 nthreads * sizeof *threads);
551 _hurd_stopped = 0;
552 if (act == handle)
553 /* The thread that will run the handler is already suspended. */
554 ss_suspended = 1;
557 if (signo == 0)
559 if (untraced)
560 /* This is PTRACE_CONTINUE. */
561 resume ();
563 /* This call is just to check for pending signals. */
564 __spin_lock (&ss->lock);
565 goto check_pending_signals;
568 post_signal:
570 thread_state.set = 0; /* We know nothing. */
572 __spin_lock (&ss->lock);
574 /* Check for a preempted signal. Preempted signals can arrive during
575 critical sections. */
577 inline sighandler_t try_preemptor (struct hurd_signal_preemptor *pe)
578 { /* PE cannot be null. */
581 if (HURD_PREEMPT_SIGNAL_P (pe, signo, detail->code))
583 if (pe->preemptor)
585 sighandler_t handler = (*pe->preemptor) (pe, ss,
586 &signo, detail);
587 if (handler != SIG_ERR)
588 return handler;
590 else
591 return pe->handler;
593 pe = pe->next;
594 } while (pe != 0);
595 return SIG_ERR;
598 handler = ss->preemptors ? try_preemptor (ss->preemptors) : SIG_ERR;
600 /* If no thread-specific preemptor, check for a global one. */
601 if (handler == SIG_ERR && __sigismember (&_hurdsig_preempted_set, signo))
603 __mutex_lock (&_hurd_siglock);
604 handler = try_preemptor (_hurdsig_preemptors);
605 __mutex_unlock (&_hurd_siglock);
609 ss_suspended = 0;
611 if (handler == SIG_IGN)
612 /* Ignore the signal altogether. */
613 act = ignore;
614 else if (handler != SIG_ERR)
615 /* Run the preemption-provided handler. */
616 act = handle;
617 else
619 /* No preemption. Do normal handling. */
621 if (!untraced && __sigismember (&_hurdsig_traced, signo))
623 /* We are being traced. Stop to tell the debugger of the signal. */
624 if (_hurd_stopped)
625 /* Already stopped. Mark the signal as pending;
626 when resumed, we will notice it and stop again. */
627 mark_pending ();
628 else
629 suspend ();
630 __spin_unlock (&ss->lock);
631 reply ();
632 return;
635 handler = ss->actions[signo].sa_handler;
637 if (handler == SIG_DFL)
638 /* Figure out the default action for this signal. */
639 switch (signo)
641 case 0:
642 /* A sig_post msg with SIGNO==0 is sent to
643 tell us to check for pending signals. */
644 act = ignore;
645 break;
647 case SIGTTIN:
648 case SIGTTOU:
649 case SIGSTOP:
650 case SIGTSTP:
651 act = stop;
652 break;
654 case SIGCONT:
655 case SIGIO:
656 case SIGURG:
657 case SIGCHLD:
658 case SIGWINCH:
659 act = ignore;
660 break;
662 case SIGQUIT:
663 case SIGILL:
664 case SIGTRAP:
665 case SIGIOT:
666 case SIGEMT:
667 case SIGFPE:
668 case SIGBUS:
669 case SIGSEGV:
670 case SIGSYS:
671 act = core;
672 break;
674 case SIGINFO:
675 if (_hurd_pgrp == _hurd_pid)
677 /* We are the process group leader. Since there is no
678 user-specified handler for SIGINFO, we use a default one
679 which prints something interesting. We use the normal
680 handler mechanism instead of just doing it here to avoid
681 the signal thread faulting or blocking in this
682 potentially hairy operation. */
683 act = handle;
684 handler = _hurd_siginfo_handler;
686 else
687 act = ignore;
688 break;
690 default:
691 act = term;
692 break;
694 else if (handler == SIG_IGN)
695 act = ignore;
696 else
697 act = handle;
699 if (__sigmask (signo) & STOPSIGS)
700 /* Stop signals clear a pending SIGCONT even if they
701 are handled or ignored (but not if preempted). */
702 __sigdelset (&ss->pending, SIGCONT);
703 else
705 if (signo == SIGCONT)
706 /* Even if handled or ignored (but not preempted), SIGCONT clears
707 stop signals and resumes the process. */
708 ss->pending &= ~STOPSIGS;
710 if (_hurd_stopped && act != stop && (untraced || signo == SIGCONT))
711 resume ();
715 if (_hurd_orphaned && act == stop &&
716 (__sigmask (signo) & (__sigmask (SIGTTIN) | __sigmask (SIGTTOU) |
717 __sigmask (SIGTSTP))))
719 /* If we would ordinarily stop for a job control signal, but we are
720 orphaned so noone would ever notice and continue us again, we just
721 quietly die, alone and in the dark. */
722 detail->code = signo;
723 signo = SIGKILL;
724 act = term;
727 /* Handle receipt of a blocked signal, or any signal while stopped. */
728 if (act != ignore && /* Signals ignored now are forgotten now. */
729 __sigismember (&ss->blocked, signo) ||
730 (signo != SIGKILL && _hurd_stopped))
732 mark_pending ();
733 act = ignore;
736 /* Perform the chosen action for the signal. */
737 switch (act)
739 case stop:
740 if (_hurd_stopped)
742 /* We are already stopped, but receiving an untraced stop
743 signal. Instead of resuming and suspending again, just
744 notify the proc server of the new stop signal. */
745 error_t err = __USEPORT (PROC, __proc_mark_stop
746 (port, signo, detail->code));
747 assert_perror (err);
749 else
750 /* Suspend the process. */
751 suspend ();
752 break;
754 case ignore:
755 if (detail->exc)
756 /* Blocking or ignoring a machine exception is fatal.
757 Otherwise we could just spin on the faulting instruction. */
758 goto fatal;
760 /* Nobody cares about this signal. If there was a call to resume
761 above in SIGCONT processing and we've left a thread suspended,
762 now's the time to set it going. */
763 if (ss_suspended)
765 err = __thread_resume (ss->thread);
766 assert_perror (err);
767 ss_suspended = 0;
769 break;
771 sigbomb:
772 /* We got a fault setting up the stack frame for the handler.
773 Nothing to do but die; BSD gets SIGILL in this case. */
774 detail->code = signo; /* XXX ? */
775 signo = SIGILL;
777 fatal:
778 act = core;
779 /* FALLTHROUGH */
781 case term: /* Time to die. */
782 case core: /* And leave a rotting corpse. */
783 /* Have the proc server stop all other threads in our task. */
784 err = __USEPORT (PROC, __proc_dostop (port, _hurd_msgport_thread));
785 assert_perror (err);
786 /* No more user instructions will be executed.
787 The signal can now be considered delivered. */
788 reply ();
789 /* Abort all server operations now in progress. */
790 abort_all_rpcs (signo, &thread_state, 0);
793 int status = W_EXITCODE (0, signo);
794 /* Do a core dump if desired. Only set the wait status bit saying we
795 in fact dumped core if the operation was actually successful. */
796 if (act == core && write_corefile (signo, detail))
797 status |= WCOREFLAG;
798 /* Tell proc how we died and then stick the saber in the gut. */
799 _hurd_exit (status);
800 /* NOTREACHED */
803 case handle:
804 /* Call a handler for this signal. */
806 struct sigcontext *scp, ocontext;
807 int wait_for_reply, state_changed;
809 /* Stop the thread and abort its pending RPC operations. */
810 if (! ss_suspended)
812 err = __thread_suspend (ss->thread);
813 assert_perror (err);
816 /* Abort the thread's kernel context, so any pending message send
817 or receive completes immediately or aborts. If an interruptible
818 RPC is in progress, abort_rpcs will do this. But we must always
819 do it before fetching the thread's state, because
820 thread_get_state is never kosher before thread_abort. */
821 abort_thread (ss, &thread_state, NULL);
823 if (ss->context)
825 /* We have a previous sigcontext that sigreturn was about
826 to restore when another signal arrived. */
828 mach_port_t *loc;
830 if (_hurdsig_catch_memory_fault (ss->context))
832 /* We faulted reading the thread's stack. Forget that
833 context and pretend it wasn't there. It almost
834 certainly crash if this handler returns, but that's it's
835 problem. */
836 ss->context = NULL;
838 else
840 /* Copy the context from the thread's stack before
841 we start diddling the stack to set up the handler. */
842 ocontext = *ss->context;
843 ss->context = &ocontext;
845 _hurdsig_end_catch_fault ();
847 if (! machine_get_basic_state (ss->thread, &thread_state))
848 goto sigbomb;
849 loc = interrupted_reply_port_location (ss->thread,
850 &thread_state, 1);
851 if (loc && *loc != MACH_PORT_NULL)
852 /* This is the reply port for the context which called
853 sigreturn. Since we are abandoning that context entirely
854 and restoring SS->context instead, destroy this port. */
855 __mach_port_destroy (__mach_task_self (), *loc);
857 /* The thread was in sigreturn, not in any interruptible RPC. */
858 wait_for_reply = 0;
860 assert (! __spin_lock_locked (&ss->critical_section_lock));
862 else
864 int crit = __spin_lock_locked (&ss->critical_section_lock);
866 wait_for_reply
867 = (_hurdsig_abort_rpcs (ss,
868 /* In a critical section, any RPC
869 should be cancelled instead of
870 restarted, regardless of
871 SA_RESTART, so the entire
872 "atomic" operation can be aborted
873 as a unit. */
874 crit ? 0 : signo, 1,
875 &thread_state, &state_changed,
876 &reply)
877 != MACH_PORT_NULL);
879 if (crit)
881 /* The thread is in a critical section. Mark the signal as
882 pending. When it finishes the critical section, it will
883 check for pending signals. */
884 mark_pending ();
885 if (state_changed)
886 /* Some cases of interrupting an RPC must change the
887 thread state to back out the call. Normally this
888 change is rolled into the warping to the handler and
889 sigreturn, but we are not running the handler now
890 because the thread is in a critical section. Instead,
891 mutate the thread right away for the RPC interruption
892 and resume it; the RPC will return early so the
893 critical section can end soon. */
894 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
895 (natural_t *) &thread_state.basic,
896 MACHINE_THREAD_STATE_COUNT);
897 /* */
898 ss->intr_port = MACH_PORT_NULL;
899 __thread_resume (ss->thread);
900 break;
904 /* Call the machine-dependent function to set the thread up
905 to run the signal handler, and preserve its old context. */
906 scp = _hurd_setup_sighandler (ss, handler, signo, detail,
907 wait_for_reply, &thread_state);
908 if (scp == NULL)
909 goto sigbomb;
911 /* Set the machine-independent parts of the signal context. */
914 /* Fetch the thread variable for the MiG reply port,
915 and set it to MACH_PORT_NULL. */
916 mach_port_t *loc = interrupted_reply_port_location (ss->thread,
917 &thread_state,
919 if (loc)
921 scp->sc_reply_port = *loc;
922 *loc = MACH_PORT_NULL;
924 else
925 scp->sc_reply_port = MACH_PORT_NULL;
927 /* Save the intr_port in use by the interrupted code,
928 and clear the cell before running the trampoline. */
929 scp->sc_intr_port = ss->intr_port;
930 ss->intr_port = MACH_PORT_NULL;
932 if (ss->context)
934 /* After the handler runs we will restore to the state in
935 SS->context, not the state of the thread now. So restore
936 that context's reply port and intr port. */
938 scp->sc_reply_port = ss->context->sc_reply_port;
939 scp->sc_intr_port = ss->context->sc_intr_port;
941 ss->context = NULL;
945 /* Backdoor extra argument to signal handler. */
946 scp->sc_error = detail->error;
948 /* Block requested signals while running the handler. */
949 scp->sc_mask = ss->blocked;
950 __sigorset (&ss->blocked, &ss->blocked, &ss->actions[signo].sa_mask);
952 /* Also block SIGNO unless we're asked not to. */
953 if (! (ss->actions[signo].sa_flags & (SA_RESETHAND | SA_NODEFER)))
954 __sigaddset (&ss->blocked, signo);
956 /* Reset to SIG_DFL if requested. SIGILL and SIGTRAP cannot
957 be automatically reset when delivered; the system silently
958 enforces this restriction. */
959 if (ss->actions[signo].sa_flags & SA_RESETHAND
960 && signo != SIGILL && signo != SIGTRAP)
961 ss->actions[signo].sa_handler = SIG_DFL;
963 /* Start the thread running the handler (or possibly waiting for an
964 RPC reply before running the handler). */
965 err = __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
966 (natural_t *) &thread_state.basic,
967 MACHINE_THREAD_STATE_COUNT);
968 assert_perror (err);
969 err = __thread_resume (ss->thread);
970 assert_perror (err);
971 thread_state.set = 0; /* Everything we know is now wrong. */
972 break;
976 /* The signal has either been ignored or is now being handled. We can
977 consider it delivered and reply to the killer. */
978 reply ();
980 /* We get here unless the signal was fatal. We still hold SS->lock.
981 Check for pending signals, and loop to post them. */
983 /* Return nonzero if SS has any signals pending we should worry about.
984 We don't worry about any pending signals if we are stopped, nor if
985 SS is in a critical section. We are guaranteed to get a sig_post
986 message before any of them become deliverable: either the SIGCONT
987 signal, or a sig_post with SIGNO==0 as an explicit poll when the
988 thread finishes its critical section. */
989 inline int signals_pending (void)
991 if (_hurd_stopped || __spin_lock_locked (&ss->critical_section_lock))
992 return 0;
993 return pending = ss->pending & ~ss->blocked;
996 check_pending_signals:
997 untraced = 0;
999 if (signals_pending ())
1001 for (signo = 1; signo < NSIG; ++signo)
1002 if (__sigismember (&pending, signo))
1004 deliver_pending:
1005 __sigdelset (&ss->pending, signo);
1006 *detail = ss->pending_data[signo];
1007 __spin_unlock (&ss->lock);
1008 goto post_signal;
1012 /* No pending signals left undelivered for this thread.
1013 If we were sent signal 0, we need to check for pending
1014 signals for all threads. */
1015 if (signo == 0)
1017 __spin_unlock (&ss->lock);
1018 __mutex_lock (&_hurd_siglock);
1019 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
1021 __spin_lock (&ss->lock);
1022 for (signo = 1; signo < NSIG; ++signo)
1023 if (__sigismember (&ss->pending, signo)
1024 && (!__sigismember (&ss->blocked, signo)
1025 /* We "deliver" immediately pending blocked signals whose
1026 action might be to ignore, so that if ignored they are
1027 dropped right away. */
1028 || ss->actions[signo].sa_handler == SIG_IGN
1029 || ss->actions[signo].sa_handler == SIG_DFL))
1031 __mutex_unlock (&_hurd_siglock);
1032 goto deliver_pending;
1034 __spin_unlock (&ss->lock);
1036 __mutex_unlock (&_hurd_siglock);
1038 else
1040 /* No more signals pending; SS->lock is still locked.
1041 Wake up any sigsuspend call that is blocking SS->thread. */
1042 if (ss->suspended != MACH_PORT_NULL)
1044 /* There is a sigsuspend waiting. Tell it to wake up. */
1045 error_t err;
1046 mach_msg_header_t msg;
1047 msg.msgh_bits = MACH_MSGH_BITS (MACH_MSG_TYPE_MAKE_SEND, 0);
1048 msg.msgh_remote_port = ss->suspended;
1049 msg.msgh_local_port = MACH_PORT_NULL;
1050 /* These values do not matter. */
1051 msg.msgh_id = 8675309; /* Jenny, Jenny. */
1052 ss->suspended = MACH_PORT_NULL;
1053 err = __mach_msg (&msg, MACH_SEND_MSG, sizeof msg, 0,
1054 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
1055 MACH_PORT_NULL);
1056 assert_perror (err);
1058 __spin_unlock (&ss->lock);
1062 /* All pending signals delivered to all threads.
1063 Now we can send the reply message even for signal 0. */
1064 reply ();
1067 /* Decide whether REFPORT enables the sender to send us a SIGNO signal.
1068 Returns zero if so, otherwise the error code to return to the sender. */
1070 static error_t
1071 signal_allowed (int signo, mach_port_t refport)
1073 if (signo < 0 || signo >= NSIG)
1074 return EINVAL;
1076 if (refport == __mach_task_self ())
1077 /* Can send any signal. */
1078 goto win;
1080 /* Avoid needing to check for this below. */
1081 if (refport == MACH_PORT_NULL)
1082 return EPERM;
1084 switch (signo)
1086 case SIGINT:
1087 case SIGQUIT:
1088 case SIGTSTP:
1089 case SIGHUP:
1090 case SIGINFO:
1091 case SIGTTIN:
1092 case SIGTTOU:
1093 case SIGWINCH:
1094 /* Job control signals can be sent by the controlling terminal. */
1095 if (__USEPORT (CTTYID, port == refport))
1096 goto win;
1097 break;
1099 case SIGCONT:
1101 /* A continue signal can be sent by anyone in the session. */
1102 mach_port_t sessport;
1103 if (! __USEPORT (PROC, __proc_getsidport (port, &sessport)))
1105 __mach_port_deallocate (__mach_task_self (), sessport);
1106 if (refport == sessport)
1107 goto win;
1110 break;
1112 case SIGIO:
1113 case SIGURG:
1115 /* Any io object a file descriptor refers to might send us
1116 one of these signals using its async ID port for REFPORT.
1118 This is pretty wide open; it is not unlikely that some random
1119 process can at least open for reading something we have open,
1120 get its async ID port, and send us a spurious SIGIO or SIGURG
1121 signal. But BSD is actually wider open than that!--you can set
1122 the owner of an io object to any process or process group
1123 whatsoever and send them gratuitous signals.
1125 Someday we could implement some reasonable scheme for
1126 authorizing SIGIO and SIGURG signals properly. */
1128 int d;
1129 int lucky = 0; /* True if we find a match for REFPORT. */
1130 __mutex_lock (&_hurd_dtable_lock);
1131 for (d = 0; !lucky && (unsigned) d < (unsigned) _hurd_dtablesize; ++d)
1133 struct hurd_userlink ulink;
1134 io_t port;
1135 mach_port_t asyncid;
1136 if (_hurd_dtable[d] == NULL)
1137 continue;
1138 port = _hurd_port_get (&_hurd_dtable[d]->port, &ulink);
1139 if (! __io_get_icky_async_id (port, &asyncid))
1141 if (refport == asyncid)
1142 /* Break out of the loop on the next iteration. */
1143 lucky = 1;
1144 __mach_port_deallocate (__mach_task_self (), asyncid);
1146 _hurd_port_free (&_hurd_dtable[d]->port, &ulink, port);
1148 __mutex_unlock (&_hurd_dtable_lock);
1149 /* If we found a lucky winner, we've set D to -1 in the loop. */
1150 if (lucky)
1151 goto win;
1155 /* If this signal is legit, we have done `goto win' by now.
1156 When we return the error, mig deallocates REFPORT. */
1157 return EPERM;
1159 win:
1160 /* Deallocate the REFPORT send right; we are done with it. */
1161 __mach_port_deallocate (__mach_task_self (), refport);
1163 return 0;
1166 /* Implement the sig_post RPC from <hurd/msg.defs>;
1167 sent when someone wants us to get a signal. */
1168 kern_return_t
1169 _S_msg_sig_post (mach_port_t me,
1170 mach_port_t reply_port, mach_msg_type_name_t reply_port_type,
1171 int signo, natural_t sigcode,
1172 mach_port_t refport)
1174 error_t err;
1175 struct hurd_signal_detail d;
1177 if (err = signal_allowed (signo, refport))
1178 return err;
1180 d.code = sigcode;
1181 d.exc = 0;
1183 /* Post the signal to the designated signal-receiving thread. This will
1184 reply when the signal can be considered delivered. */
1185 _hurd_internal_post_signal (_hurd_thread_sigstate (_hurd_sigthread),
1186 signo, &d, reply_port, reply_port_type,
1187 0); /* Stop if traced. */
1189 return MIG_NO_REPLY; /* Already replied. */
1192 /* Implement the sig_post_untraced RPC from <hurd/msg.defs>;
1193 sent when the debugger wants us to really get a signal
1194 even if we are traced. */
1195 kern_return_t
1196 _S_msg_sig_post_untraced (mach_port_t me,
1197 mach_port_t reply_port,
1198 mach_msg_type_name_t reply_port_type,
1199 int signo, natural_t sigcode,
1200 mach_port_t refport)
1202 error_t err;
1203 struct hurd_signal_detail d;
1205 if (err = signal_allowed (signo, refport))
1206 return err;
1208 d.code = sigcode;
1209 d.exc = 0;
1211 /* Post the signal to the designated signal-receiving thread. This will
1212 reply when the signal can be considered delivered. */
1213 _hurd_internal_post_signal (_hurd_thread_sigstate (_hurd_sigthread),
1214 signo, &d, reply_port, reply_port_type,
1215 1); /* Untraced flag. */
1217 return MIG_NO_REPLY; /* Already replied. */
1220 extern void __mig_init (void *);
1222 #include <mach/task_special_ports.h>
1224 /* Initialize the message port and _hurd_sigthread and start the signal
1225 thread. */
1227 void
1228 _hurdsig_init (const int *intarray, size_t intarraysize)
1230 error_t err;
1231 vm_size_t stacksize;
1232 struct hurd_sigstate *ss;
1234 __mutex_init (&_hurd_siglock);
1236 err = __mach_port_allocate (__mach_task_self (),
1237 MACH_PORT_RIGHT_RECEIVE,
1238 &_hurd_msgport);
1239 assert_perror (err);
1241 /* Make a send right to the signal port. */
1242 err = __mach_port_insert_right (__mach_task_self (),
1243 _hurd_msgport,
1244 _hurd_msgport,
1245 MACH_MSG_TYPE_MAKE_SEND);
1246 assert_perror (err);
1248 /* Initialize the main thread's signal state. */
1249 ss = _hurd_self_sigstate ();
1251 /* Copy inherited values from our parent (or pre-exec process state)
1252 into the signal settings of the main thread. */
1253 if (intarraysize > INIT_SIGMASK)
1254 ss->blocked = intarray[INIT_SIGMASK];
1255 if (intarraysize > INIT_SIGPENDING)
1256 ss->pending = intarray[INIT_SIGPENDING];
1257 if (intarraysize > INIT_SIGIGN && intarray[INIT_SIGIGN] != 0)
1259 int signo;
1260 for (signo = 1; signo < NSIG; ++signo)
1261 if (intarray[INIT_SIGIGN] & __sigmask(signo))
1262 ss->actions[signo].sa_handler = SIG_IGN;
1265 /* Set the default thread to receive task-global signals
1266 to this one, the main (first) user thread. */
1267 _hurd_sigthread = ss->thread;
1269 /* Start the signal thread listening on the message port. */
1271 #pragma weak __cthread_fork
1272 if (!__cthread_fork)
1274 err = __thread_create (__mach_task_self (), &_hurd_msgport_thread);
1275 assert_perror (err);
1277 stacksize = __vm_page_size * 8; /* Small stack for signal thread. */
1278 err = __mach_setup_thread (__mach_task_self (), _hurd_msgport_thread,
1279 _hurd_msgport_receive,
1280 (vm_address_t *) &__hurd_sigthread_stack_base,
1281 &stacksize);
1282 assert_perror (err);
1283 err = __mach_setup_tls (_hurd_msgport_thread);
1284 assert_perror (err);
1286 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + stacksize;
1288 /* Reinitialize the MiG support routines so they will use a per-thread
1289 variable for the cached reply port. */
1290 __mig_init ((void *) __hurd_sigthread_stack_base);
1292 err = __thread_resume (_hurd_msgport_thread);
1293 assert_perror (err);
1295 else
1297 /* When cthreads is being used, we need to make the signal thread a
1298 proper cthread. Otherwise it cannot use mutex_lock et al, which
1299 will be the cthreads versions. Various of the message port RPC
1300 handlers need to take locks, so we need to be able to call into
1301 cthreads code and meet its assumptions about how our thread and
1302 its stack are arranged. Since cthreads puts it there anyway,
1303 we'll let the signal thread's per-thread variables be found as for
1304 any normal cthread, and just leave the magic __hurd_sigthread_*
1305 values all zero so they'll be ignored. */
1306 #pragma weak __cthread_detach
1307 #pragma weak __pthread_getattr_np
1308 #pragma weak __pthread_attr_getstack
1309 __cthread_t thread = __cthread_fork (
1310 (cthread_fn_t) &_hurd_msgport_receive, 0);
1311 __cthread_detach (thread);
1313 if (__pthread_getattr_np)
1315 /* Record signal thread stack layout for fork() */
1316 pthread_attr_t attr;
1317 void *addr;
1318 size_t size;
1320 __pthread_getattr_np ((pthread_t) thread, &attr);
1321 __pthread_attr_getstack (&attr, &addr, &size);
1322 __hurd_sigthread_stack_base = (uintptr_t) addr;
1323 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + size;
1326 /* XXX We need the thread port for the signal thread further on
1327 in this thread (see hurdfault.c:_hurdsigfault_init).
1328 Therefore we block until _hurd_msgport_thread is initialized
1329 by the newly created thread. This really shouldn't be
1330 necessary; we should be able to fetch the thread port for a
1331 cthread from here. */
1332 while (_hurd_msgport_thread == 0)
1333 __swtch_pri (0);
1336 /* Receive exceptions on the signal port. */
1337 #ifdef TASK_EXCEPTION_PORT
1338 __task_set_special_port (__mach_task_self (),
1339 TASK_EXCEPTION_PORT, _hurd_msgport);
1340 #elif defined (EXC_MASK_ALL)
1341 __task_set_exception_ports (__mach_task_self (),
1342 EXC_MASK_ALL & ~(EXC_MASK_SYSCALL
1343 | EXC_MASK_MACH_SYSCALL
1344 | EXC_MASK_RPC_ALERT),
1345 _hurd_msgport,
1346 EXCEPTION_DEFAULT, MACHINE_THREAD_STATE);
1347 #else
1348 # error task_set_exception_port?
1349 #endif
1351 /* Sanity check. Any pending, unblocked signals should have been
1352 taken by our predecessor incarnation (i.e. parent or pre-exec state)
1353 before packing up our init ints. This assert is last (not above)
1354 so that signal handling is all set up to handle the abort. */
1355 assert ((ss->pending &~ ss->blocked) == 0);
1357 \f /* XXXX */
1358 /* Reauthenticate with the proc server. */
1360 static void
1361 reauth_proc (mach_port_t new)
1363 mach_port_t ref, ignore;
1365 ref = __mach_reply_port ();
1366 if (! HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1367 __proc_reauthenticate (port, ref,
1368 MACH_MSG_TYPE_MAKE_SEND) ||
1369 __auth_user_authenticate (new, ref,
1370 MACH_MSG_TYPE_MAKE_SEND,
1371 &ignore))
1372 && ignore != MACH_PORT_NULL)
1373 __mach_port_deallocate (__mach_task_self (), ignore);
1374 __mach_port_destroy (__mach_task_self (), ref);
1376 /* Set the owner of the process here too. */
1377 __mutex_lock (&_hurd_id.lock);
1378 if (!_hurd_check_ids ())
1379 HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1380 __proc_setowner (port,
1381 (_hurd_id.gen.nuids
1382 ? _hurd_id.gen.uids[0] : 0),
1383 !_hurd_id.gen.nuids));
1384 __mutex_unlock (&_hurd_id.lock);
1386 (void) &reauth_proc; /* Silence compiler warning. */
1388 text_set_element (_hurd_reauth_hook, reauth_proc);
1390 /* Like `getenv', but safe for the signal thread to run.
1391 If the environment is trashed, this will just return NULL. */
1393 const char *
1394 _hurdsig_getenv (const char *variable)
1396 if (__libc_enable_secure)
1397 return NULL;
1399 if (_hurdsig_catch_memory_fault (__environ))
1400 /* We bombed in getenv. */
1401 return NULL;
1402 else
1404 const size_t len = strlen (variable);
1405 char *value = NULL;
1406 char *volatile *ep = __environ;
1407 while (*ep)
1409 const char *p = *ep;
1410 _hurdsig_fault_preemptor.first = (long int) p;
1411 _hurdsig_fault_preemptor.last = VM_MAX_ADDRESS;
1412 if (! strncmp (p, variable, len) && p[len] == '=')
1414 size_t valuelen;
1415 p += len + 1;
1416 valuelen = strlen (p);
1417 _hurdsig_fault_preemptor.last = (long int) (p + valuelen);
1418 value = malloc (++valuelen);
1419 if (value)
1420 memcpy (value, p, valuelen);
1421 break;
1423 _hurdsig_fault_preemptor.first = (long int) ++ep;
1424 _hurdsig_fault_preemptor.last = (long int) (ep + 1);
1426 _hurdsig_end_catch_fault ();
1427 return value;