argp: Reformat Makefile.
[glibc.git] / hurd / hurdsig.c
blob78ea59d97da6520fbe9078fbc3c2ea0e4aed93c0
1 /* Copyright (C) 1991-2023 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 <https://www.gnu.org/licenses/>. */
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
22 #include <lock-intern.h> /* For `struct mutex'. */
23 #include <pthreadP.h>
24 #include <mach.h>
25 #include <mach/thread_switch.h>
26 #include <mach/mig_support.h>
27 #include <mach/vm_param.h>
29 #include <hurd.h>
30 #include <hurd/id.h>
31 #include <hurd/signal.h>
33 #include "hurdfault.h"
34 #include "hurdmalloc.h" /* XXX */
35 #include "../locale/localeinfo.h"
37 #include <libc-diag.h>
39 const char *_hurdsig_getenv (const char *);
41 struct mutex _hurd_siglock;
42 int _hurd_stopped;
44 /* Port that receives signals and other miscellaneous messages. */
45 mach_port_t _hurd_msgport;
47 /* Thread listening on it. */
48 thread_t _hurd_msgport_thread;
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 /* Sigstate for the task-global signals. */
58 struct hurd_sigstate *_hurd_global_sigstate;
60 /* Timeout for RPC's after interrupt_operation. */
61 mach_msg_timeout_t _hurd_interrupted_rpc_timeout = 60000;
63 static void
64 default_sigaction (struct sigaction actions[NSIG])
66 int signo;
68 __sigemptyset (&actions[0].sa_mask);
69 actions[0].sa_flags = SA_RESTART;
70 actions[0].sa_handler = SIG_DFL;
72 for (signo = 1; signo < NSIG; ++signo)
73 actions[signo] = actions[0];
76 struct hurd_sigstate *
77 _hurd_thread_sigstate (thread_t thread)
79 struct hurd_sigstate *ss;
80 __mutex_lock (&_hurd_siglock);
81 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
82 if (ss->thread == thread)
83 break;
84 if (ss == NULL)
86 ss = malloc (sizeof (*ss));
87 if (ss == NULL)
88 __libc_fatal ("hurd: Can't allocate sigstate\n");
89 __spin_lock_init (&ss->critical_section_lock);
90 __spin_lock_init (&ss->lock);
91 ss->thread = thread;
93 /* Initialize default state. */
94 __sigemptyset (&ss->blocked);
95 __sigemptyset (&ss->pending);
96 memset (&ss->sigaltstack, 0, sizeof (ss->sigaltstack));
97 ss->sigaltstack.ss_flags |= SS_DISABLE;
98 ss->preemptors = NULL;
99 ss->suspended = MACH_PORT_NULL;
100 ss->intr_port = MACH_PORT_NULL;
101 ss->context = NULL;
102 ss->active_resources = NULL;
103 ss->cancel = 0;
104 ss->cancel_hook = NULL;
106 if (thread == MACH_PORT_NULL)
108 /* Process-wide sigstate, use the system defaults. */
109 default_sigaction (ss->actions);
111 /* The global sigstate is not added to the _hurd_sigstates list.
112 It is created with _hurd_thread_sigstate (MACH_PORT_NULL)
113 but should be accessed through _hurd_global_sigstate. */
115 else
117 error_t err;
119 /* Use the global actions as a default for new threads. */
120 struct hurd_sigstate *s = _hurd_global_sigstate;
121 if (s)
123 __spin_lock (&s->lock);
124 memcpy (ss->actions, s->actions, sizeof (s->actions));
125 __spin_unlock (&s->lock);
127 else
128 default_sigaction (ss->actions);
130 ss->next = _hurd_sigstates;
131 _hurd_sigstates = ss;
133 err = __mach_port_mod_refs (__mach_task_self (), thread,
134 MACH_PORT_RIGHT_SEND, 1);
135 if (err)
136 __libc_fatal ("hurd: Can't add reference on Mach thread\n");
139 __mutex_unlock (&_hurd_siglock);
140 return ss;
142 libc_hidden_def (_hurd_thread_sigstate)
144 /* Destroy a sigstate structure. Called by libpthread just before the
145 * corresponding thread is terminated. */
146 void
147 _hurd_sigstate_delete (thread_t thread)
149 struct hurd_sigstate **ssp, *ss;
151 __mutex_lock (&_hurd_siglock);
152 for (ssp = &_hurd_sigstates; *ssp; ssp = &(*ssp)->next)
153 if ((*ssp)->thread == thread)
154 break;
156 ss = *ssp;
157 if (ss)
158 *ssp = ss->next;
160 __mutex_unlock (&_hurd_siglock);
161 if (ss)
163 if (ss->thread != MACH_PORT_NULL)
164 __mach_port_deallocate (__mach_task_self (), ss->thread);
166 free (ss);
170 /* Make SS a global receiver, with pthread signal semantics. */
171 void
172 _hurd_sigstate_set_global_rcv (struct hurd_sigstate *ss)
174 assert (ss->thread != MACH_PORT_NULL);
175 ss->actions[0].sa_handler = SIG_IGN;
177 libc_hidden_def (_hurd_sigstate_set_global_rcv)
179 /* Check whether SS is a global receiver. */
180 static int
181 sigstate_is_global_rcv (const struct hurd_sigstate *ss)
183 return (_hurd_global_sigstate != NULL)
184 && (ss->actions[0].sa_handler == SIG_IGN);
186 libc_hidden_def (_hurd_sigstate_delete)
188 /* Lock/unlock a hurd_sigstate structure. If the accessors below require
189 it, the global sigstate will be locked as well. */
190 void
191 _hurd_sigstate_lock (struct hurd_sigstate *ss)
193 if (sigstate_is_global_rcv (ss))
194 __spin_lock (&_hurd_global_sigstate->lock);
195 __spin_lock (&ss->lock);
197 libc_hidden_def (_hurd_sigstate_lock)
199 void
200 _hurd_sigstate_unlock (struct hurd_sigstate *ss)
202 __spin_unlock (&ss->lock);
203 if (sigstate_is_global_rcv (ss))
204 __spin_unlock (&_hurd_global_sigstate->lock);
206 libc_hidden_def (_hurd_sigstate_unlock)
208 /* Retrieve a thread's full set of pending signals, including the global
209 ones if appropriate. SS must be locked. */
210 sigset_t
211 _hurd_sigstate_pending (const struct hurd_sigstate *ss)
213 sigset_t pending = ss->pending;
214 if (sigstate_is_global_rcv (ss))
215 __sigorset (&pending, &pending, &_hurd_global_sigstate->pending);
216 return pending;
218 libc_hidden_def (_hurd_sigstate_pending)
220 /* Clear a pending signal and return the associated detailed
221 signal information. SS must be locked, and must have signal SIGNO
222 pending, either directly or through the global sigstate. */
223 static struct hurd_signal_detail
224 sigstate_clear_pending (struct hurd_sigstate *ss, int signo)
226 if (sigstate_is_global_rcv (ss)
227 && __sigismember (&_hurd_global_sigstate->pending, signo))
229 __sigdelset (&_hurd_global_sigstate->pending, signo);
230 return _hurd_global_sigstate->pending_data[signo];
233 assert (__sigismember (&ss->pending, signo));
234 __sigdelset (&ss->pending, signo);
235 return ss->pending_data[signo];
238 /* Retrieve a thread's action vector. SS must be locked. */
239 struct sigaction *
240 _hurd_sigstate_actions (struct hurd_sigstate *ss)
242 if (sigstate_is_global_rcv (ss))
243 return _hurd_global_sigstate->actions;
244 else
245 return ss->actions;
249 /* Signal delivery itself is on this page. */
251 #include <hurd/fd.h>
252 #include <hurd/crash.h>
253 #include <hurd/resource.h>
254 #include <hurd/paths.h>
255 #include <setjmp.h>
256 #include <fcntl.h>
257 #include <sys/wait.h>
258 #include <thread_state.h>
259 #include <hurd/msg_server.h>
260 #include <hurd/msg_reply.h> /* For __msg_sig_post_reply. */
261 #include <hurd/interrupt.h>
262 #include <assert.h>
263 #include <unistd.h>
266 /* Call the crash dump server to mummify us before we die.
267 Returns nonzero if a core file was written. */
268 static int
269 write_corefile (int signo, const struct hurd_signal_detail *detail)
271 error_t err;
272 mach_port_t coreserver;
273 file_t file, coredir;
274 const char *name;
276 /* Don't bother locking since we just read the one word. */
277 rlim_t corelimit = _hurd_rlimits[RLIMIT_CORE].rlim_cur;
279 if (corelimit == 0)
280 /* No core dumping, thank you very much. Note that this makes
281 `ulimit -c 0' prevent crash-suspension too, which is probably
282 what the user wanted. */
283 return 0;
285 /* XXX RLIMIT_CORE:
286 When we have a protocol to make the server return an error
287 for RLIMIT_FSIZE, then tell the corefile fs server the RLIMIT_CORE
288 value in place of the RLIMIT_FSIZE value. */
290 /* First get a port to the core dumping server. */
291 coreserver = MACH_PORT_NULL;
292 name = _hurdsig_getenv ("CRASHSERVER");
293 if (name != NULL)
294 coreserver = __file_name_lookup (name, 0, 0);
295 if (coreserver == MACH_PORT_NULL)
296 coreserver = __file_name_lookup (_SERVERS_CRASH, 0, 0);
297 if (coreserver == MACH_PORT_NULL)
298 return 0;
300 /* Get a port to the directory where the new core file will reside. */
301 file = MACH_PORT_NULL;
302 name = _hurdsig_getenv ("COREFILE");
303 if (name == NULL)
304 name = "core";
305 coredir = __file_name_split (name, (char **) &name);
306 if (coredir != MACH_PORT_NULL)
307 /* Create the new file, but don't link it into the directory yet. */
308 __dir_mkfile (coredir, O_WRONLY|O_CREAT,
309 0600 & ~_hurd_umask, /* XXX ? */
310 &file);
312 /* Call the core dumping server to write the core file. */
313 err = __crash_dump_task (coreserver,
314 __mach_task_self (),
315 file,
316 signo, detail->code, detail->error,
317 detail->exc, detail->exc_code, detail->exc_subcode,
318 _hurd_ports[INIT_PORT_CTTYID].port,
319 MACH_MSG_TYPE_COPY_SEND);
320 __mach_port_deallocate (__mach_task_self (), coreserver);
322 if (! err && file != MACH_PORT_NULL)
323 /* The core dump into FILE succeeded, so now link it into the
324 directory. */
325 err = __dir_link (coredir, file, name, 1);
326 __mach_port_deallocate (__mach_task_self (), file);
327 __mach_port_deallocate (__mach_task_self (), coredir);
328 return !err && file != MACH_PORT_NULL;
332 /* The lowest-numbered thread state flavor value is 1,
333 so we use bit 0 in machine_thread_all_state.set to
334 record whether we have done thread_abort. */
335 #define THREAD_ABORTED 1
337 /* SS->thread is suspended. Abort the thread and get its basic state. */
338 static void
339 abort_thread (struct hurd_sigstate *ss, struct machine_thread_all_state *state,
340 void (*reply) (void))
342 assert (ss->thread != MACH_PORT_NULL);
344 if (!(state->set & THREAD_ABORTED))
346 error_t err = __thread_abort (ss->thread);
347 assert_perror (err);
348 /* Clear all thread state flavor set bits, because thread_abort may
349 have changed the state. */
350 state->set = THREAD_ABORTED;
353 if (reply)
354 (*reply) ();
356 machine_get_basic_state (ss->thread, state);
359 /* Find the location of the MiG reply port cell in use by the thread whose
360 state is described by THREAD_STATE. If SIGTHREAD is nonzero, make sure
361 that this location can be set without faulting, or else return NULL. */
363 static mach_port_t *
364 interrupted_reply_port_location (thread_t thread,
365 struct machine_thread_all_state *thread_state,
366 int sigthread)
368 mach_port_t *portloc = &THREAD_TCB(thread, thread_state)->reply_port;
370 if (sigthread && _hurdsig_catch_memory_fault (portloc))
371 /* Faulted trying to read the TCB. */
372 return NULL;
374 DIAG_PUSH_NEEDS_COMMENT;
375 /* GCC 6 and before seem to be confused by the setjmp call inside
376 _hurdsig_catch_memory_fault and think that we may be returning a second
377 time to here with portloc uninitialized (but we never do). */
378 DIAG_IGNORE_NEEDS_COMMENT (6, "-Wmaybe-uninitialized");
379 /* Fault now if this pointer is bogus. */
380 *(volatile mach_port_t *) portloc = *portloc;
381 DIAG_POP_NEEDS_COMMENT;
383 if (sigthread)
384 _hurdsig_end_catch_fault ();
386 return portloc;
389 #include <hurd/sigpreempt.h>
390 #include <intr-msg.h>
392 /* Timeout on interrupt_operation calls. */
393 mach_msg_timeout_t _hurdsig_interrupt_timeout = 1000;
395 /* SS->thread is suspended.
397 Abort any interruptible RPC operation the thread is doing.
399 This uses only the constant member SS->thread and the unlocked, atomically
400 set member SS->intr_port, so no locking is needed.
402 If successfully sent an interrupt_operation and therefore the thread should
403 wait for its pending RPC to return (possibly EINTR) before taking the
404 incoming signal, returns the reply port to be received on. Otherwise
405 returns MACH_PORT_NULL.
407 SIGNO is used to find the applicable SA_RESTART bit. If SIGNO is zero,
408 the RPC fails with EINTR instead of restarting (thread_cancel).
410 *STATE_CHANGE is set nonzero if STATE->basic was modified and should
411 be applied back to the thread if it might ever run again, else zero. */
413 mach_port_t
414 _hurdsig_abort_rpcs (struct hurd_sigstate *ss, int signo, int sigthread,
415 struct machine_thread_all_state *state, int *state_change,
416 void (*reply) (void))
418 extern const void _hurd_intr_rpc_msg_about_to;
419 extern const void _hurd_intr_rpc_msg_setup_done;
420 extern const void _hurd_intr_rpc_msg_in_trap;
421 mach_port_t rcv_port = MACH_PORT_NULL;
422 mach_port_t intr_port;
424 *state_change = 0;
426 intr_port = ss->intr_port;
427 if (intr_port == MACH_PORT_NULL)
428 /* No interruption needs done. */
429 return MACH_PORT_NULL;
431 /* Abort the thread's kernel context, so any pending message send or
432 receive completes immediately or aborts. */
433 abort_thread (ss, state, reply);
435 if (state->basic.PC >= (uintptr_t) &_hurd_intr_rpc_msg_about_to
436 && state->basic.PC < (uintptr_t) &_hurd_intr_rpc_msg_in_trap)
438 /* The thread is about to do the RPC, but hasn't yet entered
439 mach_msg. Importantly, it may have already checked ss->cancel for
440 the last time before doing the RPC, so setting that is not enough
441 to make it not enter mach_msg. Instead, mutate the thread's state
442 so it knows not to try the RPC.
444 If the thread is past _hurd_intr_rpc_msg_setup_done, just make it
445 jump to after the trap, since we know it's safe to do so. Otherwise,
446 we know that the thread is yet to check for the MACH_SEND_INTERRUPTED
447 value we set below, and will skip the trap by itself. */
448 if (state->basic.PC >= (uintptr_t) &_hurd_intr_rpc_msg_setup_done)
449 MACHINE_THREAD_STATE_SET_PC (&state->basic,
450 &_hurd_intr_rpc_msg_in_trap);
451 state->basic.SYSRETURN = MACH_SEND_INTERRUPTED;
452 *state_change = 1;
454 else if (state->basic.PC == (uintptr_t) &_hurd_intr_rpc_msg_in_trap
455 /* The thread was blocked in the system call. After thread_abort,
456 the return value register indicates what state the RPC was in
457 when interrupted. */
458 && state->basic.SYSRETURN == MACH_RCV_INTERRUPTED)
460 /* The RPC request message was sent and the thread was waiting for the
461 reply message; now the message receive has been aborted, so the
462 mach_msg call will return MACH_RCV_INTERRUPTED. We must tell the
463 server to interrupt the pending operation. The thread must wait for
464 the reply message before running the signal handler (to guarantee that
465 the operation has finished being interrupted), so our nonzero return
466 tells the trampoline code to finish the message receive operation
467 before running the handler. */
469 mach_port_t *reply = interrupted_reply_port_location (ss->thread,
470 state,
471 sigthread);
472 error_t err = __interrupt_operation (intr_port,
473 _hurdsig_interrupt_timeout);
475 if (err)
477 if (reply)
479 /* The interrupt didn't work.
480 Destroy the receive right the thread is blocked on, and
481 replace it with a dead name to keep the name from reuse until
482 the therad is done with it. To do this atomically, first
483 insert a send right, and then destroy the receive right,
484 turning the send right into a dead name. */
485 err = __mach_port_insert_right (__mach_task_self (),
486 *reply, *reply,
487 MACH_MSG_TYPE_MAKE_SEND);
488 assert_perror (err);
489 err = __mach_port_mod_refs (__mach_task_self (), *reply,
490 MACH_PORT_RIGHT_RECEIVE, -1);
491 assert_perror (err);
494 /* The system call return value register now contains
495 MACH_RCV_INTERRUPTED; when mach_msg resumes, it will retry the
496 call. Since we have just destroyed the receive right, the retry
497 will fail with MACH_RCV_INVALID_NAME. Instead, just change the
498 return value here to EINTR so mach_msg will not retry and the
499 EINTR error code will propagate up. */
500 state->basic.SYSRETURN = EINTR;
501 *state_change = 1;
503 else if (reply)
504 rcv_port = *reply;
506 /* All threads whose RPCs were interrupted by the interrupt_operation
507 call above will retry their RPCs unless we clear SS->intr_port. So we
508 clear it for the thread taking a signal when SA_RESTART is clear, so
509 that its call returns EINTR. */
510 if (! signo || !(_hurd_sigstate_actions (ss) [signo].sa_flags & SA_RESTART))
511 ss->intr_port = MACH_PORT_NULL;
514 return rcv_port;
518 /* Abort the RPCs being run by all threads but this one;
519 all other threads should be suspended. If LIVE is nonzero, those
520 threads may run again, so they should be adjusted as necessary to be
521 happy when resumed. STATE is clobbered as a scratch area; its initial
522 contents are ignored, and its contents on return are not useful. */
524 static void
525 abort_all_rpcs (int signo, struct machine_thread_all_state *state, int live)
527 /* We can just loop over the sigstates. Any thread doing something
528 interruptible must have one. We needn't bother locking because all
529 other threads are stopped. */
531 struct hurd_sigstate *ss;
532 size_t nthreads;
533 mach_port_t *reply_ports;
535 /* First loop over the sigstates to count them.
536 We need to know how big a vector we will need for REPLY_PORTS. */
537 nthreads = 0;
538 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
539 ++nthreads;
541 reply_ports = alloca (nthreads * sizeof *reply_ports);
543 nthreads = 0;
544 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next, ++nthreads)
545 if (ss->thread == _hurd_msgport_thread)
546 reply_ports[nthreads] = MACH_PORT_NULL;
547 else
549 int state_changed;
550 state->set = 0; /* Reset scratch area. */
552 /* Abort any operation in progress with interrupt_operation.
553 Record the reply port the thread is waiting on.
554 We will wait for all the replies below. */
555 reply_ports[nthreads] = _hurdsig_abort_rpcs (ss, signo, 1,
556 state, &state_changed,
557 NULL);
558 if (live)
560 if (reply_ports[nthreads] != MACH_PORT_NULL)
562 /* We will wait for the reply to this RPC below, so the
563 thread must issue a new RPC rather than waiting for the
564 reply to the one it sent. */
565 state->basic.SYSRETURN = EINTR;
566 state_changed = 1;
568 if (state_changed)
569 /* Aborting the RPC needed to change this thread's state,
570 and it might ever run again. So write back its state. */
571 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
572 (natural_t *) &state->basic,
573 MACHINE_THREAD_STATE_COUNT);
577 /* Wait for replies from all the successfully interrupted RPCs. */
578 while (nthreads-- > 0)
579 if (reply_ports[nthreads] != MACH_PORT_NULL)
581 error_t err;
582 mach_msg_header_t head;
583 err = __mach_msg (&head, MACH_RCV_MSG|MACH_RCV_TIMEOUT, 0, sizeof head,
584 reply_ports[nthreads],
585 _hurd_interrupted_rpc_timeout, MACH_PORT_NULL);
586 switch (err)
588 case MACH_RCV_TIMED_OUT:
589 case MACH_RCV_TOO_LARGE:
590 break;
592 default:
593 assert_perror (err);
598 /* Wake up any sigsuspend or pselect call that is blocking SS->thread. SS must
599 be locked. */
600 static void
601 wake_sigsuspend (struct hurd_sigstate *ss)
603 error_t err;
604 mach_msg_header_t msg;
606 if (ss->suspended == MACH_PORT_NULL)
607 return;
609 /* There is a sigsuspend waiting. Tell it to wake up. */
610 msg.msgh_bits = MACH_MSGH_BITS (MACH_MSG_TYPE_MAKE_SEND, 0);
611 msg.msgh_remote_port = ss->suspended;
612 msg.msgh_local_port = MACH_PORT_NULL;
613 /* These values do not matter. */
614 msg.msgh_id = 8675309; /* Jenny, Jenny. */
615 ss->suspended = MACH_PORT_NULL;
616 err = __mach_msg (&msg, MACH_SEND_MSG, sizeof msg, 0,
617 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
618 MACH_PORT_NULL);
619 assert_perror (err);
622 struct hurd_signal_preemptor *_hurdsig_preemptors = 0;
623 sigset_t _hurdsig_preempted_set;
625 /* XXX temporary to deal with spelling fix */
626 weak_alias (_hurdsig_preemptors, _hurdsig_preempters)
628 /* Mask of stop signals. */
629 #define STOPSIGS (__sigmask (SIGTTIN) | __sigmask (SIGTTOU) \
630 | __sigmask (SIGSTOP) | __sigmask (SIGTSTP))
632 /* Actual delivery of a single signal. Called with SS unlocked. When
633 the signal is delivered, return SS, locked (or, if SS was originally
634 _hurd_global_sigstate, the sigstate of the actual thread the signal
635 was delivered to). If the signal is being traced, return NULL with
636 SS unlocked. */
637 static struct hurd_sigstate *
638 post_signal (struct hurd_sigstate *ss,
639 int signo, struct hurd_signal_detail *detail,
640 int untraced, void (*reply) (void))
642 struct machine_thread_all_state thread_state;
643 enum { stop, ignore, core, term, handle } act;
644 int ss_suspended;
646 /* sigaction for preemptors */
647 struct sigaction preempt_sigaction = {
648 .sa_flags = SA_RESTART
651 struct sigaction *action;
653 /* Mark the signal as pending. */
654 void mark_pending (void)
656 __sigaddset (&ss->pending, signo);
657 /* Save the details to be given to the handler when SIGNO is
658 unblocked. */
659 ss->pending_data[signo] = *detail;
662 /* Suspend the process with SIGNO. */
663 void suspend (void)
665 /* Stop all other threads and mark ourselves stopped. */
666 __USEPORT (PROC,
668 /* Hold the siglock while stopping other threads to be
669 sure it is not held by another thread afterwards. */
670 __mutex_lock (&_hurd_siglock);
671 __proc_dostop (port, _hurd_msgport_thread);
672 __mutex_unlock (&_hurd_siglock);
673 abort_all_rpcs (signo, &thread_state, 1);
674 reply ();
675 __proc_mark_stop (port, signo, detail->code);
676 }));
677 _hurd_stopped = 1;
679 /* Resume the process after a suspension. */
680 void resume (void)
682 /* Resume the process from being stopped. */
683 thread_t *threads;
684 mach_msg_type_number_t nthreads, i;
685 error_t err;
687 if (! _hurd_stopped)
688 return;
690 /* Tell the proc server we are continuing. */
691 __USEPORT (PROC, __proc_mark_cont (port));
692 /* Fetch ports to all our threads and resume them. */
693 err = __task_threads (__mach_task_self (), &threads, &nthreads);
694 assert_perror (err);
695 for (i = 0; i < nthreads; ++i)
697 if (act == handle && threads[i] == ss->thread)
699 /* The thread that will run the handler is kept suspended. */
700 ss_suspended = 1;
702 else if (threads[i] != _hurd_msgport_thread)
704 err = __thread_resume (threads[i]);
705 assert_perror (err);
707 err = __mach_port_deallocate (__mach_task_self (),
708 threads[i]);
709 assert_perror (err);
711 __vm_deallocate (__mach_task_self (),
712 (vm_address_t) threads,
713 nthreads * sizeof *threads);
714 _hurd_stopped = 0;
717 error_t err;
718 sighandler_t handler;
720 if (signo == 0)
722 if (untraced)
724 /* This is PTRACE_CONTINUE. */
725 act = ignore;
726 resume ();
729 /* This call is just to check for pending signals. */
730 _hurd_sigstate_lock (ss);
731 return ss;
734 thread_state.set = 0; /* We know nothing. */
736 _hurd_sigstate_lock (ss);
738 /* If this is a global signal, try to find a thread ready to accept
739 it right away. This is especially important for untraced signals,
740 since going through the global pending mask would de-untrace them. */
741 if (ss->thread == MACH_PORT_NULL)
743 struct hurd_sigstate *rss;
745 __mutex_lock (&_hurd_siglock);
746 for (rss = _hurd_sigstates; rss != NULL; rss = rss->next)
748 if (! sigstate_is_global_rcv (rss))
749 continue;
751 /* The global sigstate is already locked. */
752 __spin_lock (&rss->lock);
753 if (! __sigismember (&rss->blocked, signo))
755 ss = rss;
756 break;
758 __spin_unlock (&rss->lock);
760 __mutex_unlock (&_hurd_siglock);
763 /* We want the preemptors to be able to update the blocking mask
764 without affecting the delivery of this signal, so we save the
765 current value to test against later. */
766 sigset_t blocked = ss->blocked;
768 /* Check for a preempted signal. Preempted signals can arrive during
769 critical sections. */
771 inline sighandler_t try_preemptor (struct hurd_signal_preemptor *pe)
772 { /* PE cannot be null. */
775 if (HURD_PREEMPT_SIGNAL_P (pe, signo, detail->exc_subcode))
777 if (pe->preemptor)
779 sighandler_t handler = (*pe->preemptor) (pe, ss,
780 &signo, detail);
781 if (handler != SIG_ERR)
782 return handler;
784 else
785 return pe->handler;
787 pe = pe->next;
788 } while (pe != 0);
789 return SIG_ERR;
792 handler = ss->preemptors ? try_preemptor (ss->preemptors) : SIG_ERR;
794 /* If no thread-specific preemptor, check for a global one. */
795 if (handler == SIG_ERR && __sigismember (&_hurdsig_preempted_set, signo))
797 __mutex_lock (&_hurd_siglock);
798 handler = try_preemptor (_hurdsig_preemptors);
799 __mutex_unlock (&_hurd_siglock);
803 ss_suspended = 0;
805 if (handler == SIG_IGN)
806 /* Ignore the signal altogether. */
807 act = ignore;
808 else if (handler != SIG_ERR)
810 /* Run the preemption-provided handler. */
811 action = &preempt_sigaction;
812 act = handle;
814 else
816 /* No preemption. Do normal handling. */
818 action = & _hurd_sigstate_actions (ss) [signo];
820 if (!untraced && __sigismember (&_hurdsig_traced, signo))
822 /* We are being traced. Stop to tell the debugger of the signal. */
823 if (_hurd_stopped)
824 /* Already stopped. Mark the signal as pending;
825 when resumed, we will notice it and stop again. */
826 mark_pending ();
827 else
828 suspend ();
829 _hurd_sigstate_unlock (ss);
830 reply ();
831 return NULL;
834 handler = action->sa_handler;
836 if (handler == SIG_DFL)
837 /* Figure out the default action for this signal. */
838 switch (signo)
840 case 0:
841 /* A sig_post msg with SIGNO==0 is sent to
842 tell us to check for pending signals. */
843 act = ignore;
844 break;
846 case SIGTTIN:
847 case SIGTTOU:
848 case SIGSTOP:
849 case SIGTSTP:
850 act = stop;
851 break;
853 case SIGCONT:
854 case SIGIO:
855 case SIGURG:
856 case SIGCHLD:
857 case SIGWINCH:
858 act = ignore;
859 break;
861 case SIGQUIT:
862 case SIGILL:
863 case SIGTRAP:
864 case SIGIOT:
865 case SIGEMT:
866 case SIGFPE:
867 case SIGBUS:
868 case SIGSEGV:
869 case SIGSYS:
870 act = core;
871 break;
873 case SIGINFO:
874 if (_hurd_pgrp == _hurd_pid)
876 /* We are the process group leader. Since there is no
877 user-specified handler for SIGINFO, we use a default one
878 which prints something interesting. We use the normal
879 handler mechanism instead of just doing it here to avoid
880 the signal thread faulting or blocking in this
881 potentially hairy operation. */
882 act = handle;
883 handler = _hurd_siginfo_handler;
885 else
886 act = ignore;
887 break;
889 default:
890 act = term;
891 break;
893 else if (handler == SIG_IGN)
894 act = ignore;
895 else
896 act = handle;
898 if (__sigmask (signo) & STOPSIGS)
899 /* Stop signals clear a pending SIGCONT even if they
900 are handled or ignored (but not if preempted). */
901 __sigdelset (&ss->pending, SIGCONT);
902 else
904 if (signo == SIGCONT)
905 /* Even if handled or ignored (but not preempted), SIGCONT clears
906 stop signals and resumes the process. */
907 ss->pending &= ~STOPSIGS;
909 if (_hurd_stopped && act != stop && (untraced || signo == SIGCONT))
910 resume ();
914 if (_hurd_orphaned && act == stop
915 && (__sigmask (signo) & (__sigmask (SIGTTIN) | __sigmask (SIGTTOU)
916 | __sigmask (SIGTSTP))))
918 /* If we would ordinarily stop for a job control signal, but we are
919 orphaned so noone would ever notice and continue us again, we just
920 quietly die, alone and in the dark. */
921 detail->code = signo;
922 signo = SIGKILL;
923 act = term;
926 /* Handle receipt of a blocked signal, or any signal while stopped. */
927 if (__sigismember (&blocked, signo) || (signo != SIGKILL && _hurd_stopped))
929 mark_pending ();
930 act = ignore;
933 /* Perform the chosen action for the signal. */
934 switch (act)
936 case stop:
937 if (_hurd_stopped)
939 /* We are already stopped, but receiving an untraced stop
940 signal. Instead of resuming and suspending again, just
941 notify the proc server of the new stop signal. */
942 error_t err = __USEPORT (PROC, __proc_mark_stop
943 (port, signo, detail->code));
944 assert_perror (err);
946 else
947 /* Suspend the process. */
948 suspend ();
949 break;
951 case ignore:
952 if (detail->exc)
953 /* Blocking or ignoring a machine exception is fatal.
954 Otherwise we could just spin on the faulting instruction. */
955 goto fatal;
957 /* Nobody cares about this signal. If there was a call to resume
958 above in SIGCONT processing and we've left a thread suspended,
959 now's the time to set it going. */
960 if (ss_suspended)
962 assert (ss->thread != MACH_PORT_NULL);
963 err = __thread_resume (ss->thread);
964 assert_perror (err);
965 ss_suspended = 0;
967 break;
969 sigbomb:
970 /* We got a fault setting up the stack frame for the handler.
971 Nothing to do but die; BSD gets SIGILL in this case. */
972 detail->code = signo; /* XXX ? */
973 signo = SIGILL;
975 fatal:
976 act = core;
977 /* FALLTHROUGH */
979 case term: /* Time to die. */
980 case core: /* And leave a rotting corpse. */
981 /* Have the proc server stop all other threads in our task. */
982 err = __USEPORT (PROC, __proc_dostop (port, _hurd_msgport_thread));
983 assert_perror (err);
984 /* No more user instructions will be executed.
985 The signal can now be considered delivered. */
986 reply ();
987 /* Abort all server operations now in progress. */
988 abort_all_rpcs (signo, &thread_state, 0);
991 int status = W_EXITCODE (0, signo);
992 /* Do a core dump if desired. Only set the wait status bit saying we
993 in fact dumped core if the operation was actually successful. */
994 if (act == core && write_corefile (signo, detail))
995 status |= WCOREFLAG;
996 /* Tell proc how we died and then stick the saber in the gut. */
997 _hurd_exit (status);
998 /* NOTREACHED */
1001 case handle:
1002 /* Call a handler for this signal. */
1004 struct sigcontext *scp, ocontext;
1005 int wait_for_reply, state_changed;
1007 assert (ss->thread != MACH_PORT_NULL);
1009 /* Stop the thread and abort its pending RPC operations. */
1010 if (! ss_suspended)
1012 err = __thread_suspend (ss->thread);
1013 assert_perror (err);
1016 /* Abort the thread's kernel context, so any pending message send
1017 or receive completes immediately or aborts. If an interruptible
1018 RPC is in progress, abort_rpcs will do this. But we must always
1019 do it before fetching the thread's state, because
1020 thread_get_state is never kosher before thread_abort. */
1021 abort_thread (ss, &thread_state, NULL);
1023 if (ss->context)
1025 /* We have a previous sigcontext that sigreturn was about
1026 to restore when another signal arrived. */
1028 mach_port_t *loc;
1030 if (_hurdsig_catch_memory_fault (ss->context))
1032 /* We faulted reading the thread's stack. Forget that
1033 context and pretend it wasn't there. It almost
1034 certainly crash if this handler returns, but that's it's
1035 problem. */
1036 ss->context = NULL;
1038 else
1040 /* Copy the context from the thread's stack before
1041 we start diddling the stack to set up the handler. */
1042 ocontext = *ss->context;
1043 ss->context = &ocontext;
1045 _hurdsig_end_catch_fault ();
1047 if (! machine_get_basic_state (ss->thread, &thread_state))
1048 goto sigbomb;
1049 loc = interrupted_reply_port_location (ss->thread,
1050 &thread_state, 1);
1051 if (loc && *loc != MACH_PORT_NULL)
1052 /* This is the reply port for the context which called
1053 sigreturn. Since we are abandoning that context entirely
1054 and restoring SS->context instead, destroy this port. */
1055 __mach_port_destroy (__mach_task_self (), *loc);
1057 /* The thread was in sigreturn, not in any interruptible RPC. */
1058 wait_for_reply = 0;
1060 assert (! __spin_lock_locked (&ss->critical_section_lock));
1062 else
1064 int crit = __spin_lock_locked (&ss->critical_section_lock);
1066 wait_for_reply
1067 = (_hurdsig_abort_rpcs (ss,
1068 /* In a critical section, any RPC
1069 should be cancelled instead of
1070 restarted, regardless of
1071 SA_RESTART, so the entire
1072 "atomic" operation can be aborted
1073 as a unit. */
1074 crit ? 0 : signo, 1,
1075 &thread_state, &state_changed,
1076 reply)
1077 != MACH_PORT_NULL);
1079 if (crit)
1081 /* The thread is in a critical section. Mark the signal as
1082 pending. When it finishes the critical section, it will
1083 check for pending signals. */
1084 mark_pending ();
1085 if (state_changed)
1086 /* Some cases of interrupting an RPC must change the
1087 thread state to back out the call. Normally this
1088 change is rolled into the warping to the handler and
1089 sigreturn, but we are not running the handler now
1090 because the thread is in a critical section. Instead,
1091 mutate the thread right away for the RPC interruption
1092 and resume it; the RPC will return early so the
1093 critical section can end soon. */
1094 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
1095 (natural_t *) &thread_state.basic,
1096 MACHINE_THREAD_STATE_COUNT);
1097 /* */
1098 ss->intr_port = MACH_PORT_NULL;
1099 __thread_resume (ss->thread);
1100 break;
1104 /* Call the machine-dependent function to set the thread up
1105 to run the signal handler, and preserve its old context. */
1106 scp = _hurd_setup_sighandler (ss, action, handler, signo, detail,
1107 wait_for_reply, &thread_state);
1108 if (scp == NULL)
1109 goto sigbomb;
1111 /* Set the machine-independent parts of the signal context. */
1114 /* Fetch the thread variable for the MiG reply port,
1115 and set it to MACH_PORT_NULL. */
1116 mach_port_t *loc = interrupted_reply_port_location (ss->thread,
1117 &thread_state,
1119 if (loc)
1121 scp->sc_reply_port = *loc;
1122 *loc = MACH_PORT_NULL;
1124 else
1125 scp->sc_reply_port = MACH_PORT_NULL;
1127 /* Save the intr_port in use by the interrupted code,
1128 and clear the cell before running the trampoline. */
1129 scp->sc_intr_port = ss->intr_port;
1130 ss->intr_port = MACH_PORT_NULL;
1132 if (ss->context)
1134 /* After the handler runs we will restore to the state in
1135 SS->context, not the state of the thread now. So restore
1136 that context's reply port and intr port. */
1138 scp->sc_reply_port = ss->context->sc_reply_port;
1139 scp->sc_intr_port = ss->context->sc_intr_port;
1141 ss->context = NULL;
1145 /* Backdoor extra argument to signal handler. */
1146 scp->sc_error = detail->error;
1148 /* Block requested signals while running the handler. */
1149 scp->sc_mask = ss->blocked;
1150 __sigorset (&ss->blocked, &ss->blocked, &action->sa_mask);
1152 /* Also block SIGNO unless we're asked not to. */
1153 if (! (action->sa_flags & (SA_RESETHAND | SA_NODEFER)))
1154 __sigaddset (&ss->blocked, signo);
1156 /* Reset to SIG_DFL if requested. SIGILL and SIGTRAP cannot
1157 be automatically reset when delivered; the system silently
1158 enforces this restriction. */
1159 if (action->sa_flags & SA_RESETHAND
1160 && signo != SIGILL && signo != SIGTRAP)
1161 action->sa_handler = SIG_DFL;
1163 /* Any sigsuspend call must return after the handler does. */
1164 wake_sigsuspend (ss);
1166 /* Start the thread running the handler (or possibly waiting for an
1167 RPC reply before running the handler). */
1168 err = __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
1169 (natural_t *) &thread_state.basic,
1170 MACHINE_THREAD_STATE_COUNT);
1171 assert_perror (err);
1172 err = __thread_resume (ss->thread);
1173 assert_perror (err);
1174 thread_state.set = 0; /* Everything we know is now wrong. */
1175 break;
1179 return ss;
1182 /* Return the set of pending signals in SS which should be delivered. */
1183 static sigset_t
1184 pending_signals (struct hurd_sigstate *ss)
1186 /* We don't worry about any pending signals if we are stopped, nor if
1187 SS is in a critical section. We are guaranteed to get a sig_post
1188 message before any of them become deliverable: either the SIGCONT
1189 signal, or a sig_post with SIGNO==0 as an explicit poll when the
1190 thread finishes its critical section. */
1191 if (_hurd_stopped || __spin_lock_locked (&ss->critical_section_lock))
1192 return 0;
1194 return _hurd_sigstate_pending (ss) & ~ss->blocked;
1197 /* Post the specified pending signals in SS and return 1. If one of
1198 them is traced, abort immediately and return 0. SS must be locked on
1199 entry and will be unlocked in all cases. */
1200 static int
1201 post_pending (struct hurd_sigstate *ss, sigset_t pending, void (*reply) (void))
1203 int signo;
1204 struct hurd_signal_detail detail;
1206 /* Make sure SS corresponds to an actual thread, since we assume it won't
1207 change in post_signal. */
1208 assert (ss->thread != MACH_PORT_NULL);
1210 for (signo = 1; signo < NSIG; ++signo)
1211 if (__sigismember (&pending, signo))
1213 detail = sigstate_clear_pending (ss, signo);
1214 _hurd_sigstate_unlock (ss);
1216 /* Will reacquire the lock, except if the signal is traced. */
1217 if (! post_signal (ss, signo, &detail, 0, reply))
1218 return 0;
1221 /* No more signals pending; SS->lock is still locked. */
1222 _hurd_sigstate_unlock (ss);
1224 return 1;
1227 /* Post all the pending signals of all threads and return 1. If a traced
1228 signal is encountered, abort immediately and return 0. */
1229 static int
1230 post_all_pending_signals (void (*reply) (void))
1232 struct hurd_sigstate *ss;
1233 sigset_t pending = 0;
1235 for (;;)
1237 __mutex_lock (&_hurd_siglock);
1238 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
1240 _hurd_sigstate_lock (ss);
1242 pending = pending_signals (ss);
1243 if (pending)
1244 /* post_pending() below will unlock SS. */
1245 break;
1247 _hurd_sigstate_unlock (ss);
1249 __mutex_unlock (&_hurd_siglock);
1251 if (! pending)
1252 return 1;
1253 if (! post_pending (ss, pending, reply))
1254 return 0;
1258 /* Deliver a signal. SS is not locked. */
1259 void
1260 _hurd_internal_post_signal (struct hurd_sigstate *ss,
1261 int signo, struct hurd_signal_detail *detail,
1262 mach_port_t reply_port,
1263 mach_msg_type_name_t reply_port_type,
1264 int untraced)
1266 /* Reply to this sig_post message. */
1267 __typeof (__msg_sig_post_reply) *reply_rpc
1268 = (untraced ? __msg_sig_post_untraced_reply : __msg_sig_post_reply);
1269 void reply (void)
1271 error_t err;
1272 if (reply_port == MACH_PORT_NULL)
1273 return;
1274 err = (*reply_rpc) (reply_port, reply_port_type, 0);
1275 reply_port = MACH_PORT_NULL;
1276 if (err != MACH_SEND_INVALID_DEST) /* Ignore dead reply port. */
1277 assert_perror (err);
1280 ss = post_signal (ss, signo, detail, untraced, reply);
1281 if (! ss)
1282 return;
1284 /* The signal was neither fatal nor traced. We still hold SS->lock. */
1285 if (signo != 0 && ss->thread != MACH_PORT_NULL)
1287 /* The signal has either been ignored or is now being handled. We can
1288 consider it delivered and reply to the killer. */
1289 reply ();
1291 /* Post any pending signals for this thread. */
1292 if (! post_pending (ss, pending_signals (ss), reply))
1293 return;
1295 else
1297 /* If this was a process-wide signal or a poll request, we need
1298 to check for pending signals for all threads. */
1299 _hurd_sigstate_unlock (ss);
1300 if (! post_all_pending_signals (reply))
1301 return;
1303 /* All pending signals delivered to all threads.
1304 Now we can send the reply message even for signal 0. */
1305 reply ();
1309 /* Decide whether REFPORT enables the sender to send us a SIGNO signal.
1310 Returns zero if so, otherwise the error code to return to the sender. */
1312 static error_t
1313 signal_allowed (int signo, mach_port_t refport)
1315 if (signo < 0 || signo >= NSIG)
1316 return EINVAL;
1318 if (refport == __mach_task_self ())
1319 /* Can send any signal. */
1320 goto win;
1322 /* Avoid needing to check for this below. */
1323 if (refport == MACH_PORT_NULL)
1324 return EPERM;
1326 switch (signo)
1328 case SIGINT:
1329 case SIGQUIT:
1330 case SIGTSTP:
1331 case SIGHUP:
1332 case SIGINFO:
1333 case SIGTTIN:
1334 case SIGTTOU:
1335 case SIGWINCH:
1336 /* Job control signals can be sent by the controlling terminal. */
1337 if (__USEPORT (CTTYID, port == refport))
1338 goto win;
1339 break;
1341 case SIGCONT:
1343 /* A continue signal can be sent by anyone in the session. */
1344 mach_port_t sessport;
1345 if (! __USEPORT (PROC, __proc_getsidport (port, &sessport)))
1347 __mach_port_deallocate (__mach_task_self (), sessport);
1348 if (refport == sessport)
1349 goto win;
1352 break;
1354 case SIGIO:
1355 case SIGURG:
1357 /* Any io object a file descriptor refers to might send us
1358 one of these signals using its async ID port for REFPORT.
1360 This is pretty wide open; it is not unlikely that some random
1361 process can at least open for reading something we have open,
1362 get its async ID port, and send us a spurious SIGIO or SIGURG
1363 signal. But BSD is actually wider open than that!--you can set
1364 the owner of an io object to any process or process group
1365 whatsoever and send them gratuitous signals.
1367 Someday we could implement some reasonable scheme for
1368 authorizing SIGIO and SIGURG signals properly. */
1370 int d;
1371 int lucky = 0; /* True if we find a match for REFPORT. */
1372 __mutex_lock (&_hurd_dtable_lock);
1373 for (d = 0; !lucky && (unsigned) d < (unsigned) _hurd_dtablesize; ++d)
1375 struct hurd_userlink ulink;
1376 io_t port;
1377 mach_port_t asyncid;
1378 if (_hurd_dtable[d] == NULL)
1379 continue;
1380 port = _hurd_port_get (&_hurd_dtable[d]->port, &ulink);
1381 if (! __io_get_icky_async_id (port, &asyncid))
1383 if (refport == asyncid)
1384 /* Break out of the loop on the next iteration. */
1385 lucky = 1;
1386 __mach_port_deallocate (__mach_task_self (), asyncid);
1388 _hurd_port_free (&_hurd_dtable[d]->port, &ulink, port);
1390 __mutex_unlock (&_hurd_dtable_lock);
1391 /* If we found a lucky winner, we've set D to -1 in the loop. */
1392 if (lucky)
1393 goto win;
1397 /* If this signal is legit, we have done `goto win' by now.
1398 When we return the error, mig deallocates REFPORT. */
1399 return EPERM;
1401 win:
1402 /* Deallocate the REFPORT send right; we are done with it. */
1403 __mach_port_deallocate (__mach_task_self (), refport);
1405 return 0;
1408 /* Implement the sig_post RPC from <hurd/msg.defs>;
1409 sent when someone wants us to get a signal. */
1410 kern_return_t
1411 _S_msg_sig_post (mach_port_t me,
1412 mach_port_t reply_port, mach_msg_type_name_t reply_port_type,
1413 int signo, natural_t sigcode,
1414 mach_port_t refport)
1416 error_t err;
1417 struct hurd_signal_detail d;
1419 if (err = signal_allowed (signo, refport))
1420 return err;
1422 d.code = d.exc_subcode = sigcode;
1423 d.exc = 0;
1425 /* Post the signal to a global receiver thread (or mark it pending in
1426 the global sigstate). This will reply when the signal can be
1427 considered delivered. */
1428 _hurd_internal_post_signal (_hurd_global_sigstate,
1429 signo, &d, reply_port, reply_port_type,
1430 0); /* Stop if traced. */
1432 return MIG_NO_REPLY; /* Already replied. */
1435 /* Implement the sig_post_untraced RPC from <hurd/msg.defs>;
1436 sent when the debugger wants us to really get a signal
1437 even if we are traced. */
1438 kern_return_t
1439 _S_msg_sig_post_untraced (mach_port_t me,
1440 mach_port_t reply_port,
1441 mach_msg_type_name_t reply_port_type,
1442 int signo, natural_t sigcode,
1443 mach_port_t refport)
1445 error_t err;
1446 struct hurd_signal_detail d;
1448 if (err = signal_allowed (signo, refport))
1449 return err;
1451 d.code = d.exc_subcode = sigcode;
1452 d.exc = 0;
1454 /* Post the signal to the designated signal-receiving thread. This will
1455 reply when the signal can be considered delivered. */
1456 _hurd_internal_post_signal (_hurd_global_sigstate,
1457 signo, &d, reply_port, reply_port_type,
1458 1); /* Untraced flag. */
1460 return MIG_NO_REPLY; /* Already replied. */
1463 extern void __mig_init (void *);
1465 #include <mach/task_special_ports.h>
1467 /* Initialize the message port, _hurd_global_sigstate, and start the
1468 signal thread. */
1470 void
1471 _hurdsig_init (const int *intarray, size_t intarraysize)
1473 error_t err;
1474 vm_size_t stacksize;
1475 struct hurd_sigstate *ss;
1477 __mutex_init (&_hurd_siglock);
1479 err = __mach_port_allocate (__mach_task_self (),
1480 MACH_PORT_RIGHT_RECEIVE,
1481 &_hurd_msgport);
1482 assert_perror (err);
1484 /* Make a send right to the signal port. */
1485 err = __mach_port_insert_right (__mach_task_self (),
1486 _hurd_msgport,
1487 _hurd_msgport,
1488 MACH_MSG_TYPE_MAKE_SEND);
1489 assert_perror (err);
1491 /* Initialize the global signal state. */
1492 _hurd_global_sigstate = _hurd_thread_sigstate (MACH_PORT_NULL);
1494 /* We block all signals, and let actual threads pull them from the
1495 pending mask. */
1496 __sigfillset(& _hurd_global_sigstate->blocked);
1498 /* Initialize the main thread's signal state. */
1499 ss = _hurd_self_sigstate ();
1501 /* Mark it as a process-wide signal receiver. Threads in this set use
1502 the common action vector in _hurd_global_sigstate. */
1503 _hurd_sigstate_set_global_rcv (ss);
1505 /* Copy inherited signal settings from our parent (or pre-exec process
1506 state) */
1507 if (intarraysize > INIT_SIGMASK)
1508 ss->blocked = intarray[INIT_SIGMASK];
1509 if (intarraysize > INIT_SIGPENDING)
1510 _hurd_global_sigstate->pending = intarray[INIT_SIGPENDING];
1511 if (intarraysize > INIT_SIGIGN && intarray[INIT_SIGIGN] != 0)
1513 int signo;
1514 for (signo = 1; signo < NSIG; ++signo)
1515 if (intarray[INIT_SIGIGN] & __sigmask(signo))
1516 _hurd_global_sigstate->actions[signo].sa_handler = SIG_IGN;
1519 /* Start the signal thread listening on the message port. */
1521 #pragma weak __pthread_create
1522 if (!__pthread_create)
1524 err = __thread_create (__mach_task_self (), &_hurd_msgport_thread);
1525 assert_perror (err);
1527 stacksize = __vm_page_size * 8; /* Small stack for signal thread. */
1528 err = __mach_setup_thread (__mach_task_self (), _hurd_msgport_thread,
1529 _hurd_msgport_receive,
1530 (vm_address_t *) &__hurd_sigthread_stack_base,
1531 &stacksize);
1532 assert_perror (err);
1533 err = __mach_setup_tls (_hurd_msgport_thread);
1534 assert_perror (err);
1536 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + stacksize;
1538 /* Reinitialize the MiG support routines so they will use a per-thread
1539 variable for the cached reply port. */
1540 __mig_init ((void *) __hurd_sigthread_stack_base);
1542 err = __thread_resume (_hurd_msgport_thread);
1543 assert_perror (err);
1545 else
1547 pthread_t thread;
1548 pthread_attr_t attr;
1549 void *addr;
1550 size_t size;
1552 /* When pthread is being used, we need to make the signal thread a
1553 proper pthread. Otherwise it cannot use mutex_lock et al, which
1554 will be the pthread versions. Various of the message port RPC
1555 handlers need to take locks, so we need to be able to call into
1556 pthread code and meet its assumptions about how our thread and
1557 its stack are arranged. Since pthread puts it there anyway,
1558 we'll let the signal thread's per-thread variables be found as for
1559 any normal pthread, and just leave the magic __hurd_sigthread_*
1560 values all zero so they'll be ignored. */
1562 #pragma weak __pthread_detach
1563 #pragma weak __pthread_getattr_np
1564 #pragma weak __pthread_attr_getstack
1565 __pthread_create(&thread, NULL, &_hurd_msgport_receive, NULL);
1567 /* Record signal thread stack layout for fork() */
1568 __pthread_getattr_np (thread, &attr);
1569 __pthread_attr_getstack (&attr, &addr, &size);
1570 __hurd_sigthread_stack_base = (uintptr_t) addr;
1571 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + size;
1573 __pthread_detach(thread);
1575 /* XXX We need the thread port for the signal thread further on
1576 in this thread (see hurdfault.c:_hurdsigfault_init).
1577 Therefore we block until _hurd_msgport_thread is initialized
1578 by the newly created thread. This really shouldn't be
1579 necessary; we should be able to fetch the thread port for a
1580 pthread from here. */
1581 while (_hurd_msgport_thread == 0)
1582 __swtch_pri (0);
1585 /* Receive exceptions on the signal port. */
1586 #ifdef TASK_EXCEPTION_PORT
1587 __task_set_special_port (__mach_task_self (),
1588 TASK_EXCEPTION_PORT, _hurd_msgport);
1589 #elif defined (EXC_MASK_ALL)
1590 __task_set_exception_ports (__mach_task_self (),
1591 EXC_MASK_ALL & ~(EXC_MASK_SYSCALL
1592 | EXC_MASK_MACH_SYSCALL
1593 | EXC_MASK_RPC_ALERT),
1594 _hurd_msgport,
1595 EXCEPTION_DEFAULT, MACHINE_THREAD_STATE);
1596 #else
1597 # error task_set_exception_port?
1598 #endif
1600 /* Sanity check. Any pending, unblocked signals should have been
1601 taken by our predecessor incarnation (i.e. parent or pre-exec state)
1602 before packing up our init ints. This assert is last (not above)
1603 so that signal handling is all set up to handle the abort. */
1604 assert ((ss->pending &~ ss->blocked) == 0);
1606 \f /* XXXX */
1607 /* Reauthenticate with the proc server. */
1609 static void
1610 reauth_proc (mach_port_t new)
1612 mach_port_t ref, ignore;
1614 ref = __mach_reply_port ();
1615 if (! HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1616 __proc_reauthenticate (port, ref,
1617 MACH_MSG_TYPE_MAKE_SEND)
1618 || __auth_user_authenticate (new, ref,
1619 MACH_MSG_TYPE_MAKE_SEND,
1620 &ignore))
1621 && ignore != MACH_PORT_NULL)
1622 __mach_port_deallocate (__mach_task_self (), ignore);
1623 __mach_port_destroy (__mach_task_self (), ref);
1625 /* Set the owner of the process here too. */
1626 __mutex_lock (&_hurd_id.lock);
1627 if (!_hurd_check_ids ())
1628 HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1629 __proc_setowner (port,
1630 (_hurd_id.gen.nuids
1631 ? _hurd_id.gen.uids[0] : 0),
1632 !_hurd_id.gen.nuids));
1633 __mutex_unlock (&_hurd_id.lock);
1635 (void) &reauth_proc; /* Silence compiler warning. */
1637 text_set_element (_hurd_reauth_hook, reauth_proc);
1639 /* Like `getenv', but safe for the signal thread to run.
1640 If the environment is trashed, this will just return NULL. */
1642 const char *
1643 _hurdsig_getenv (const char *variable)
1645 if (__libc_enable_secure)
1646 return NULL;
1648 if (_hurdsig_catch_memory_fault (__environ))
1649 /* We bombed in getenv. */
1650 return NULL;
1651 else
1653 const size_t len = strlen (variable);
1654 char *value = NULL;
1655 char *volatile *ep = __environ;
1656 while (*ep)
1658 const char *p = *ep;
1659 _hurdsig_fault_preemptor.first = (long int) p;
1660 _hurdsig_fault_preemptor.last = VM_MAX_ADDRESS;
1661 if (! strncmp (p, variable, len) && p[len] == '=')
1663 size_t valuelen;
1664 p += len + 1;
1665 valuelen = strlen (p);
1666 _hurdsig_fault_preemptor.last = (long int) (p + valuelen);
1667 value = malloc (++valuelen);
1668 if (value)
1669 memcpy (value, p, valuelen);
1670 break;
1672 _hurdsig_fault_preemptor.first = (long int) ++ep;
1673 _hurdsig_fault_preemptor.last = (long int) (ep + 1);
1675 _hurdsig_end_catch_fault ();
1676 return value;