if_index: Remove unneeded alloca.h include
[glibc.git] / hurd / hurdsig.c
blob85bd46b525d4f627fd0014a508d6d65aafb82293
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;
178 /* Check whether SS is a global receiver. */
179 static int
180 sigstate_is_global_rcv (const struct hurd_sigstate *ss)
182 return (_hurd_global_sigstate != NULL)
183 && (ss->actions[0].sa_handler == SIG_IGN);
185 libc_hidden_def (_hurd_sigstate_delete)
187 /* Lock/unlock a hurd_sigstate structure. If the accessors below require
188 it, the global sigstate will be locked as well. */
189 void
190 _hurd_sigstate_lock (struct hurd_sigstate *ss)
192 if (sigstate_is_global_rcv (ss))
193 __spin_lock (&_hurd_global_sigstate->lock);
194 __spin_lock (&ss->lock);
196 void
197 _hurd_sigstate_unlock (struct hurd_sigstate *ss)
199 __spin_unlock (&ss->lock);
200 if (sigstate_is_global_rcv (ss))
201 __spin_unlock (&_hurd_global_sigstate->lock);
203 libc_hidden_def (_hurd_sigstate_set_global_rcv)
205 /* Retrieve a thread's full set of pending signals, including the global
206 ones if appropriate. SS must be locked. */
207 sigset_t
208 _hurd_sigstate_pending (const struct hurd_sigstate *ss)
210 sigset_t pending = ss->pending;
211 if (sigstate_is_global_rcv (ss))
212 __sigorset (&pending, &pending, &_hurd_global_sigstate->pending);
213 return pending;
216 /* Clear a pending signal and return the associated detailed
217 signal information. SS must be locked, and must have signal SIGNO
218 pending, either directly or through the global sigstate. */
219 static struct hurd_signal_detail
220 sigstate_clear_pending (struct hurd_sigstate *ss, int signo)
222 if (sigstate_is_global_rcv (ss)
223 && __sigismember (&_hurd_global_sigstate->pending, signo))
225 __sigdelset (&_hurd_global_sigstate->pending, signo);
226 return _hurd_global_sigstate->pending_data[signo];
229 assert (__sigismember (&ss->pending, signo));
230 __sigdelset (&ss->pending, signo);
231 return ss->pending_data[signo];
233 libc_hidden_def (_hurd_sigstate_lock)
234 libc_hidden_def (_hurd_sigstate_unlock)
236 /* Retrieve a thread's action vector. SS must be locked. */
237 struct sigaction *
238 _hurd_sigstate_actions (struct hurd_sigstate *ss)
240 if (sigstate_is_global_rcv (ss))
241 return _hurd_global_sigstate->actions;
242 else
243 return ss->actions;
245 libc_hidden_def (_hurd_sigstate_pending)
248 /* Signal delivery itself is on this page. */
250 #include <hurd/fd.h>
251 #include <hurd/crash.h>
252 #include <hurd/resource.h>
253 #include <hurd/paths.h>
254 #include <setjmp.h>
255 #include <fcntl.h>
256 #include <sys/wait.h>
257 #include <thread_state.h>
258 #include <hurd/msg_server.h>
259 #include <hurd/msg_reply.h> /* For __msg_sig_post_reply. */
260 #include <hurd/interrupt.h>
261 #include <assert.h>
262 #include <unistd.h>
265 /* Call the crash dump server to mummify us before we die.
266 Returns nonzero if a core file was written. */
267 static int
268 write_corefile (int signo, const struct hurd_signal_detail *detail)
270 error_t err;
271 mach_port_t coreserver;
272 file_t file, coredir;
273 const char *name;
275 /* Don't bother locking since we just read the one word. */
276 rlim_t corelimit = _hurd_rlimits[RLIMIT_CORE].rlim_cur;
278 if (corelimit == 0)
279 /* No core dumping, thank you very much. Note that this makes
280 `ulimit -c 0' prevent crash-suspension too, which is probably
281 what the user wanted. */
282 return 0;
284 /* XXX RLIMIT_CORE:
285 When we have a protocol to make the server return an error
286 for RLIMIT_FSIZE, then tell the corefile fs server the RLIMIT_CORE
287 value in place of the RLIMIT_FSIZE value. */
289 /* First get a port to the core dumping server. */
290 coreserver = MACH_PORT_NULL;
291 name = _hurdsig_getenv ("CRASHSERVER");
292 if (name != NULL)
293 coreserver = __file_name_lookup (name, 0, 0);
294 if (coreserver == MACH_PORT_NULL)
295 coreserver = __file_name_lookup (_SERVERS_CRASH, 0, 0);
296 if (coreserver == MACH_PORT_NULL)
297 return 0;
299 /* Get a port to the directory where the new core file will reside. */
300 file = MACH_PORT_NULL;
301 name = _hurdsig_getenv ("COREFILE");
302 if (name == NULL)
303 name = "core";
304 coredir = __file_name_split (name, (char **) &name);
305 if (coredir != MACH_PORT_NULL)
306 /* Create the new file, but don't link it into the directory yet. */
307 __dir_mkfile (coredir, O_WRONLY|O_CREAT,
308 0600 & ~_hurd_umask, /* XXX ? */
309 &file);
311 /* Call the core dumping server to write the core file. */
312 err = __crash_dump_task (coreserver,
313 __mach_task_self (),
314 file,
315 signo, detail->code, detail->error,
316 detail->exc, detail->exc_code, detail->exc_subcode,
317 _hurd_ports[INIT_PORT_CTTYID].port,
318 MACH_MSG_TYPE_COPY_SEND);
319 __mach_port_deallocate (__mach_task_self (), coreserver);
321 if (! err && file != MACH_PORT_NULL)
322 /* The core dump into FILE succeeded, so now link it into the
323 directory. */
324 err = __dir_link (coredir, file, name, 1);
325 __mach_port_deallocate (__mach_task_self (), file);
326 __mach_port_deallocate (__mach_task_self (), coredir);
327 return !err && file != MACH_PORT_NULL;
331 /* The lowest-numbered thread state flavor value is 1,
332 so we use bit 0 in machine_thread_all_state.set to
333 record whether we have done thread_abort. */
334 #define THREAD_ABORTED 1
336 /* SS->thread is suspended. Abort the thread and get its basic state. */
337 static void
338 abort_thread (struct hurd_sigstate *ss, struct machine_thread_all_state *state,
339 void (*reply) (void))
341 assert (ss->thread != MACH_PORT_NULL);
343 if (!(state->set & THREAD_ABORTED))
345 error_t err = __thread_abort (ss->thread);
346 assert_perror (err);
347 /* Clear all thread state flavor set bits, because thread_abort may
348 have changed the state. */
349 state->set = THREAD_ABORTED;
352 if (reply)
353 (*reply) ();
355 machine_get_basic_state (ss->thread, state);
358 /* Find the location of the MiG reply port cell in use by the thread whose
359 state is described by THREAD_STATE. If SIGTHREAD is nonzero, make sure
360 that this location can be set without faulting, or else return NULL. */
362 static mach_port_t *
363 interrupted_reply_port_location (thread_t thread,
364 struct machine_thread_all_state *thread_state,
365 int sigthread)
367 mach_port_t *portloc = &THREAD_TCB(thread, thread_state)->reply_port;
369 if (sigthread && _hurdsig_catch_memory_fault (portloc))
370 /* Faulted trying to read the TCB. */
371 return NULL;
373 DIAG_PUSH_NEEDS_COMMENT;
374 /* GCC 6 and before seem to be confused by the setjmp call inside
375 _hurdsig_catch_memory_fault and think that we may be returning a second
376 time to here with portloc uninitialized (but we never do). */
377 DIAG_IGNORE_NEEDS_COMMENT (6, "-Wmaybe-uninitialized");
378 /* Fault now if this pointer is bogus. */
379 *(volatile mach_port_t *) portloc = *portloc;
380 DIAG_POP_NEEDS_COMMENT;
382 if (sigthread)
383 _hurdsig_end_catch_fault ();
385 return portloc;
388 #include <hurd/sigpreempt.h>
389 #include <intr-msg.h>
391 /* Timeout on interrupt_operation calls. */
392 mach_msg_timeout_t _hurdsig_interrupt_timeout = 1000;
394 /* SS->thread is suspended.
396 Abort any interruptible RPC operation the thread is doing.
398 This uses only the constant member SS->thread and the unlocked, atomically
399 set member SS->intr_port, so no locking is needed.
401 If successfully sent an interrupt_operation and therefore the thread should
402 wait for its pending RPC to return (possibly EINTR) before taking the
403 incoming signal, returns the reply port to be received on. Otherwise
404 returns MACH_PORT_NULL.
406 SIGNO is used to find the applicable SA_RESTART bit. If SIGNO is zero,
407 the RPC fails with EINTR instead of restarting (thread_cancel).
409 *STATE_CHANGE is set nonzero if STATE->basic was modified and should
410 be applied back to the thread if it might ever run again, else zero. */
412 mach_port_t
413 _hurdsig_abort_rpcs (struct hurd_sigstate *ss, int signo, int sigthread,
414 struct machine_thread_all_state *state, int *state_change,
415 void (*reply) (void))
417 extern const void _hurd_intr_rpc_msg_about_to;
418 extern const void _hurd_intr_rpc_msg_setup_done;
419 extern const void _hurd_intr_rpc_msg_in_trap;
420 mach_port_t rcv_port = MACH_PORT_NULL;
421 mach_port_t intr_port;
423 *state_change = 0;
425 intr_port = ss->intr_port;
426 if (intr_port == MACH_PORT_NULL)
427 /* No interruption needs done. */
428 return MACH_PORT_NULL;
430 /* Abort the thread's kernel context, so any pending message send or
431 receive completes immediately or aborts. */
432 abort_thread (ss, state, reply);
434 if (state->basic.PC >= (uintptr_t) &_hurd_intr_rpc_msg_about_to
435 && state->basic.PC < (uintptr_t) &_hurd_intr_rpc_msg_in_trap)
437 /* The thread is about to do the RPC, but hasn't yet entered
438 mach_msg. Importantly, it may have already checked ss->cancel for
439 the last time before doing the RPC, so setting that is not enough
440 to make it not enter mach_msg. Instead, mutate the thread's state
441 so it knows not to try the RPC.
443 If the thread is past _hurd_intr_rpc_msg_setup_done, just make it
444 jump to after the trap, since we know it's safe to do so. Otherwise,
445 we know that the thread is yet to check for the MACH_SEND_INTERRUPTED
446 value we set below, and will skip the trap by itself. */
447 if (state->basic.PC >= (uintptr_t) &_hurd_intr_rpc_msg_setup_done)
448 MACHINE_THREAD_STATE_SET_PC (&state->basic,
449 &_hurd_intr_rpc_msg_in_trap);
450 state->basic.SYSRETURN = MACH_SEND_INTERRUPTED;
451 *state_change = 1;
453 else if (state->basic.PC == (uintptr_t) &_hurd_intr_rpc_msg_in_trap
454 /* The thread was blocked in the system call. After thread_abort,
455 the return value register indicates what state the RPC was in
456 when interrupted. */
457 && state->basic.SYSRETURN == MACH_RCV_INTERRUPTED)
459 /* The RPC request message was sent and the thread was waiting for the
460 reply message; now the message receive has been aborted, so the
461 mach_msg call will return MACH_RCV_INTERRUPTED. We must tell the
462 server to interrupt the pending operation. The thread must wait for
463 the reply message before running the signal handler (to guarantee that
464 the operation has finished being interrupted), so our nonzero return
465 tells the trampoline code to finish the message receive operation
466 before running the handler. */
468 mach_port_t *reply = interrupted_reply_port_location (ss->thread,
469 state,
470 sigthread);
471 error_t err = __interrupt_operation (intr_port,
472 _hurdsig_interrupt_timeout);
474 if (err)
476 if (reply)
478 /* The interrupt didn't work.
479 Destroy the receive right the thread is blocked on. */
480 __mach_port_destroy (__mach_task_self (), *reply);
481 *reply = MACH_PORT_NULL;
484 /* The system call return value register now contains
485 MACH_RCV_INTERRUPTED; when mach_msg resumes, it will retry the
486 call. Since we have just destroyed the receive right, the retry
487 will fail with MACH_RCV_INVALID_NAME. Instead, just change the
488 return value here to EINTR so mach_msg will not retry and the
489 EINTR error code will propagate up. */
490 state->basic.SYSRETURN = EINTR;
491 *state_change = 1;
493 else if (reply)
494 rcv_port = *reply;
496 /* All threads whose RPCs were interrupted by the interrupt_operation
497 call above will retry their RPCs unless we clear SS->intr_port. So we
498 clear it for the thread taking a signal when SA_RESTART is clear, so
499 that its call returns EINTR. */
500 if (! signo || !(_hurd_sigstate_actions (ss) [signo].sa_flags & SA_RESTART))
501 ss->intr_port = MACH_PORT_NULL;
504 return rcv_port;
508 /* Abort the RPCs being run by all threads but this one;
509 all other threads should be suspended. If LIVE is nonzero, those
510 threads may run again, so they should be adjusted as necessary to be
511 happy when resumed. STATE is clobbered as a scratch area; its initial
512 contents are ignored, and its contents on return are not useful. */
514 static void
515 abort_all_rpcs (int signo, struct machine_thread_all_state *state, int live)
517 /* We can just loop over the sigstates. Any thread doing something
518 interruptible must have one. We needn't bother locking because all
519 other threads are stopped. */
521 struct hurd_sigstate *ss;
522 size_t nthreads;
523 mach_port_t *reply_ports;
525 /* First loop over the sigstates to count them.
526 We need to know how big a vector we will need for REPLY_PORTS. */
527 nthreads = 0;
528 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
529 ++nthreads;
531 reply_ports = alloca (nthreads * sizeof *reply_ports);
533 nthreads = 0;
534 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next, ++nthreads)
535 if (ss->thread == _hurd_msgport_thread)
536 reply_ports[nthreads] = MACH_PORT_NULL;
537 else
539 int state_changed;
540 state->set = 0; /* Reset scratch area. */
542 /* Abort any operation in progress with interrupt_operation.
543 Record the reply port the thread is waiting on.
544 We will wait for all the replies below. */
545 reply_ports[nthreads] = _hurdsig_abort_rpcs (ss, signo, 1,
546 state, &state_changed,
547 NULL);
548 if (live)
550 if (reply_ports[nthreads] != MACH_PORT_NULL)
552 /* We will wait for the reply to this RPC below, so the
553 thread must issue a new RPC rather than waiting for the
554 reply to the one it sent. */
555 state->basic.SYSRETURN = EINTR;
556 state_changed = 1;
558 if (state_changed)
559 /* Aborting the RPC needed to change this thread's state,
560 and it might ever run again. So write back its state. */
561 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
562 (natural_t *) &state->basic,
563 MACHINE_THREAD_STATE_COUNT);
567 /* Wait for replies from all the successfully interrupted RPCs. */
568 while (nthreads-- > 0)
569 if (reply_ports[nthreads] != MACH_PORT_NULL)
571 error_t err;
572 mach_msg_header_t head;
573 err = __mach_msg (&head, MACH_RCV_MSG|MACH_RCV_TIMEOUT, 0, sizeof head,
574 reply_ports[nthreads],
575 _hurd_interrupted_rpc_timeout, MACH_PORT_NULL);
576 switch (err)
578 case MACH_RCV_TIMED_OUT:
579 case MACH_RCV_TOO_LARGE:
580 break;
582 default:
583 assert_perror (err);
588 /* Wake up any sigsuspend or pselect call that is blocking SS->thread. SS must
589 be locked. */
590 static void
591 wake_sigsuspend (struct hurd_sigstate *ss)
593 error_t err;
594 mach_msg_header_t msg;
596 if (ss->suspended == MACH_PORT_NULL)
597 return;
599 /* There is a sigsuspend waiting. Tell it to wake up. */
600 msg.msgh_bits = MACH_MSGH_BITS (MACH_MSG_TYPE_MAKE_SEND, 0);
601 msg.msgh_remote_port = ss->suspended;
602 msg.msgh_local_port = MACH_PORT_NULL;
603 /* These values do not matter. */
604 msg.msgh_id = 8675309; /* Jenny, Jenny. */
605 ss->suspended = MACH_PORT_NULL;
606 err = __mach_msg (&msg, MACH_SEND_MSG, sizeof msg, 0,
607 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
608 MACH_PORT_NULL);
609 assert_perror (err);
612 struct hurd_signal_preemptor *_hurdsig_preemptors = 0;
613 sigset_t _hurdsig_preempted_set;
615 /* XXX temporary to deal with spelling fix */
616 weak_alias (_hurdsig_preemptors, _hurdsig_preempters)
618 /* Mask of stop signals. */
619 #define STOPSIGS (__sigmask (SIGTTIN) | __sigmask (SIGTTOU) \
620 | __sigmask (SIGSTOP) | __sigmask (SIGTSTP))
622 /* Actual delivery of a single signal. Called with SS unlocked. When
623 the signal is delivered, return SS, locked (or, if SS was originally
624 _hurd_global_sigstate, the sigstate of the actual thread the signal
625 was delivered to). If the signal is being traced, return NULL with
626 SS unlocked. */
627 static struct hurd_sigstate *
628 post_signal (struct hurd_sigstate *ss,
629 int signo, struct hurd_signal_detail *detail,
630 int untraced, void (*reply) (void))
632 struct machine_thread_all_state thread_state;
633 enum { stop, ignore, core, term, handle } act;
634 int ss_suspended;
636 /* sigaction for preemptors */
637 struct sigaction preempt_sigaction = {
638 .sa_flags = SA_RESTART
641 struct sigaction *action;
643 /* Mark the signal as pending. */
644 void mark_pending (void)
646 __sigaddset (&ss->pending, signo);
647 /* Save the details to be given to the handler when SIGNO is
648 unblocked. */
649 ss->pending_data[signo] = *detail;
652 /* Suspend the process with SIGNO. */
653 void suspend (void)
655 /* Stop all other threads and mark ourselves stopped. */
656 __USEPORT (PROC,
658 /* Hold the siglock while stopping other threads to be
659 sure it is not held by another thread afterwards. */
660 __mutex_lock (&_hurd_siglock);
661 __proc_dostop (port, _hurd_msgport_thread);
662 __mutex_unlock (&_hurd_siglock);
663 abort_all_rpcs (signo, &thread_state, 1);
664 reply ();
665 __proc_mark_stop (port, signo, detail->code);
666 }));
667 _hurd_stopped = 1;
669 /* Resume the process after a suspension. */
670 void resume (void)
672 /* Resume the process from being stopped. */
673 thread_t *threads;
674 mach_msg_type_number_t nthreads, i;
675 error_t err;
677 if (! _hurd_stopped)
678 return;
680 /* Tell the proc server we are continuing. */
681 __USEPORT (PROC, __proc_mark_cont (port));
682 /* Fetch ports to all our threads and resume them. */
683 err = __task_threads (__mach_task_self (), &threads, &nthreads);
684 assert_perror (err);
685 for (i = 0; i < nthreads; ++i)
687 if (act == handle && threads[i] == ss->thread)
689 /* The thread that will run the handler is kept suspended. */
690 ss_suspended = 1;
692 else if (threads[i] != _hurd_msgport_thread)
694 err = __thread_resume (threads[i]);
695 assert_perror (err);
697 err = __mach_port_deallocate (__mach_task_self (),
698 threads[i]);
699 assert_perror (err);
701 __vm_deallocate (__mach_task_self (),
702 (vm_address_t) threads,
703 nthreads * sizeof *threads);
704 _hurd_stopped = 0;
707 error_t err;
708 sighandler_t handler;
710 if (signo == 0)
712 if (untraced)
714 /* This is PTRACE_CONTINUE. */
715 act = ignore;
716 resume ();
719 /* This call is just to check for pending signals. */
720 _hurd_sigstate_lock (ss);
721 return ss;
724 thread_state.set = 0; /* We know nothing. */
726 _hurd_sigstate_lock (ss);
728 /* If this is a global signal, try to find a thread ready to accept
729 it right away. This is especially important for untraced signals,
730 since going through the global pending mask would de-untrace them. */
731 if (ss->thread == MACH_PORT_NULL)
733 struct hurd_sigstate *rss;
735 __mutex_lock (&_hurd_siglock);
736 for (rss = _hurd_sigstates; rss != NULL; rss = rss->next)
738 if (! sigstate_is_global_rcv (rss))
739 continue;
741 /* The global sigstate is already locked. */
742 __spin_lock (&rss->lock);
743 if (! __sigismember (&rss->blocked, signo))
745 ss = rss;
746 break;
748 __spin_unlock (&rss->lock);
750 __mutex_unlock (&_hurd_siglock);
753 /* We want the preemptors to be able to update the blocking mask
754 without affecting the delivery of this signal, so we save the
755 current value to test against later. */
756 sigset_t blocked = ss->blocked;
758 /* Check for a preempted signal. Preempted signals can arrive during
759 critical sections. */
761 inline sighandler_t try_preemptor (struct hurd_signal_preemptor *pe)
762 { /* PE cannot be null. */
765 if (HURD_PREEMPT_SIGNAL_P (pe, signo, detail->exc_subcode))
767 if (pe->preemptor)
769 sighandler_t handler = (*pe->preemptor) (pe, ss,
770 &signo, detail);
771 if (handler != SIG_ERR)
772 return handler;
774 else
775 return pe->handler;
777 pe = pe->next;
778 } while (pe != 0);
779 return SIG_ERR;
782 handler = ss->preemptors ? try_preemptor (ss->preemptors) : SIG_ERR;
784 /* If no thread-specific preemptor, check for a global one. */
785 if (handler == SIG_ERR && __sigismember (&_hurdsig_preempted_set, signo))
787 __mutex_lock (&_hurd_siglock);
788 handler = try_preemptor (_hurdsig_preemptors);
789 __mutex_unlock (&_hurd_siglock);
793 ss_suspended = 0;
795 if (handler == SIG_IGN)
796 /* Ignore the signal altogether. */
797 act = ignore;
798 else if (handler != SIG_ERR)
800 /* Run the preemption-provided handler. */
801 action = &preempt_sigaction;
802 act = handle;
804 else
806 /* No preemption. Do normal handling. */
808 action = & _hurd_sigstate_actions (ss) [signo];
810 if (!untraced && __sigismember (&_hurdsig_traced, signo))
812 /* We are being traced. Stop to tell the debugger of the signal. */
813 if (_hurd_stopped)
814 /* Already stopped. Mark the signal as pending;
815 when resumed, we will notice it and stop again. */
816 mark_pending ();
817 else
818 suspend ();
819 _hurd_sigstate_unlock (ss);
820 reply ();
821 return NULL;
824 handler = action->sa_handler;
826 if (handler == SIG_DFL)
827 /* Figure out the default action for this signal. */
828 switch (signo)
830 case 0:
831 /* A sig_post msg with SIGNO==0 is sent to
832 tell us to check for pending signals. */
833 act = ignore;
834 break;
836 case SIGTTIN:
837 case SIGTTOU:
838 case SIGSTOP:
839 case SIGTSTP:
840 act = stop;
841 break;
843 case SIGCONT:
844 case SIGIO:
845 case SIGURG:
846 case SIGCHLD:
847 case SIGWINCH:
848 act = ignore;
849 break;
851 case SIGQUIT:
852 case SIGILL:
853 case SIGTRAP:
854 case SIGIOT:
855 case SIGEMT:
856 case SIGFPE:
857 case SIGBUS:
858 case SIGSEGV:
859 case SIGSYS:
860 act = core;
861 break;
863 case SIGINFO:
864 if (_hurd_pgrp == _hurd_pid)
866 /* We are the process group leader. Since there is no
867 user-specified handler for SIGINFO, we use a default one
868 which prints something interesting. We use the normal
869 handler mechanism instead of just doing it here to avoid
870 the signal thread faulting or blocking in this
871 potentially hairy operation. */
872 act = handle;
873 handler = _hurd_siginfo_handler;
875 else
876 act = ignore;
877 break;
879 default:
880 act = term;
881 break;
883 else if (handler == SIG_IGN)
884 act = ignore;
885 else
886 act = handle;
888 if (__sigmask (signo) & STOPSIGS)
889 /* Stop signals clear a pending SIGCONT even if they
890 are handled or ignored (but not if preempted). */
891 __sigdelset (&ss->pending, SIGCONT);
892 else
894 if (signo == SIGCONT)
895 /* Even if handled or ignored (but not preempted), SIGCONT clears
896 stop signals and resumes the process. */
897 ss->pending &= ~STOPSIGS;
899 if (_hurd_stopped && act != stop && (untraced || signo == SIGCONT))
900 resume ();
904 if (_hurd_orphaned && act == stop
905 && (__sigmask (signo) & (__sigmask (SIGTTIN) | __sigmask (SIGTTOU)
906 | __sigmask (SIGTSTP))))
908 /* If we would ordinarily stop for a job control signal, but we are
909 orphaned so noone would ever notice and continue us again, we just
910 quietly die, alone and in the dark. */
911 detail->code = signo;
912 signo = SIGKILL;
913 act = term;
916 /* Handle receipt of a blocked signal, or any signal while stopped. */
917 if (__sigismember (&blocked, signo) || (signo != SIGKILL && _hurd_stopped))
919 mark_pending ();
920 act = ignore;
923 /* Perform the chosen action for the signal. */
924 switch (act)
926 case stop:
927 if (_hurd_stopped)
929 /* We are already stopped, but receiving an untraced stop
930 signal. Instead of resuming and suspending again, just
931 notify the proc server of the new stop signal. */
932 error_t err = __USEPORT (PROC, __proc_mark_stop
933 (port, signo, detail->code));
934 assert_perror (err);
936 else
937 /* Suspend the process. */
938 suspend ();
939 break;
941 case ignore:
942 if (detail->exc)
943 /* Blocking or ignoring a machine exception is fatal.
944 Otherwise we could just spin on the faulting instruction. */
945 goto fatal;
947 /* Nobody cares about this signal. If there was a call to resume
948 above in SIGCONT processing and we've left a thread suspended,
949 now's the time to set it going. */
950 if (ss_suspended)
952 assert (ss->thread != MACH_PORT_NULL);
953 err = __thread_resume (ss->thread);
954 assert_perror (err);
955 ss_suspended = 0;
957 break;
959 sigbomb:
960 /* We got a fault setting up the stack frame for the handler.
961 Nothing to do but die; BSD gets SIGILL in this case. */
962 detail->code = signo; /* XXX ? */
963 signo = SIGILL;
965 fatal:
966 act = core;
967 /* FALLTHROUGH */
969 case term: /* Time to die. */
970 case core: /* And leave a rotting corpse. */
971 /* Have the proc server stop all other threads in our task. */
972 err = __USEPORT (PROC, __proc_dostop (port, _hurd_msgport_thread));
973 assert_perror (err);
974 /* No more user instructions will be executed.
975 The signal can now be considered delivered. */
976 reply ();
977 /* Abort all server operations now in progress. */
978 abort_all_rpcs (signo, &thread_state, 0);
981 int status = W_EXITCODE (0, signo);
982 /* Do a core dump if desired. Only set the wait status bit saying we
983 in fact dumped core if the operation was actually successful. */
984 if (act == core && write_corefile (signo, detail))
985 status |= WCOREFLAG;
986 /* Tell proc how we died and then stick the saber in the gut. */
987 _hurd_exit (status);
988 /* NOTREACHED */
991 case handle:
992 /* Call a handler for this signal. */
994 struct sigcontext *scp, ocontext;
995 int wait_for_reply, state_changed;
997 assert (ss->thread != MACH_PORT_NULL);
999 /* Stop the thread and abort its pending RPC operations. */
1000 if (! ss_suspended)
1002 err = __thread_suspend (ss->thread);
1003 assert_perror (err);
1006 /* Abort the thread's kernel context, so any pending message send
1007 or receive completes immediately or aborts. If an interruptible
1008 RPC is in progress, abort_rpcs will do this. But we must always
1009 do it before fetching the thread's state, because
1010 thread_get_state is never kosher before thread_abort. */
1011 abort_thread (ss, &thread_state, NULL);
1013 if (ss->context)
1015 /* We have a previous sigcontext that sigreturn was about
1016 to restore when another signal arrived. */
1018 mach_port_t *loc;
1020 if (_hurdsig_catch_memory_fault (ss->context))
1022 /* We faulted reading the thread's stack. Forget that
1023 context and pretend it wasn't there. It almost
1024 certainly crash if this handler returns, but that's it's
1025 problem. */
1026 ss->context = NULL;
1028 else
1030 /* Copy the context from the thread's stack before
1031 we start diddling the stack to set up the handler. */
1032 ocontext = *ss->context;
1033 ss->context = &ocontext;
1035 _hurdsig_end_catch_fault ();
1037 if (! machine_get_basic_state (ss->thread, &thread_state))
1038 goto sigbomb;
1039 loc = interrupted_reply_port_location (ss->thread,
1040 &thread_state, 1);
1041 if (loc && *loc != MACH_PORT_NULL)
1042 /* This is the reply port for the context which called
1043 sigreturn. Since we are abandoning that context entirely
1044 and restoring SS->context instead, destroy this port. */
1045 __mach_port_destroy (__mach_task_self (), *loc);
1047 /* The thread was in sigreturn, not in any interruptible RPC. */
1048 wait_for_reply = 0;
1050 assert (! __spin_lock_locked (&ss->critical_section_lock));
1052 else
1054 int crit = __spin_lock_locked (&ss->critical_section_lock);
1056 wait_for_reply
1057 = (_hurdsig_abort_rpcs (ss,
1058 /* In a critical section, any RPC
1059 should be cancelled instead of
1060 restarted, regardless of
1061 SA_RESTART, so the entire
1062 "atomic" operation can be aborted
1063 as a unit. */
1064 crit ? 0 : signo, 1,
1065 &thread_state, &state_changed,
1066 reply)
1067 != MACH_PORT_NULL);
1069 if (crit)
1071 /* The thread is in a critical section. Mark the signal as
1072 pending. When it finishes the critical section, it will
1073 check for pending signals. */
1074 mark_pending ();
1075 if (state_changed)
1076 /* Some cases of interrupting an RPC must change the
1077 thread state to back out the call. Normally this
1078 change is rolled into the warping to the handler and
1079 sigreturn, but we are not running the handler now
1080 because the thread is in a critical section. Instead,
1081 mutate the thread right away for the RPC interruption
1082 and resume it; the RPC will return early so the
1083 critical section can end soon. */
1084 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
1085 (natural_t *) &thread_state.basic,
1086 MACHINE_THREAD_STATE_COUNT);
1087 /* */
1088 ss->intr_port = MACH_PORT_NULL;
1089 __thread_resume (ss->thread);
1090 break;
1094 /* Call the machine-dependent function to set the thread up
1095 to run the signal handler, and preserve its old context. */
1096 scp = _hurd_setup_sighandler (ss, action, handler, signo, detail,
1097 wait_for_reply, &thread_state);
1098 if (scp == NULL)
1099 goto sigbomb;
1101 /* Set the machine-independent parts of the signal context. */
1104 /* Fetch the thread variable for the MiG reply port,
1105 and set it to MACH_PORT_NULL. */
1106 mach_port_t *loc = interrupted_reply_port_location (ss->thread,
1107 &thread_state,
1109 if (loc)
1111 scp->sc_reply_port = *loc;
1112 *loc = MACH_PORT_NULL;
1114 else
1115 scp->sc_reply_port = MACH_PORT_NULL;
1117 /* Save the intr_port in use by the interrupted code,
1118 and clear the cell before running the trampoline. */
1119 scp->sc_intr_port = ss->intr_port;
1120 ss->intr_port = MACH_PORT_NULL;
1122 if (ss->context)
1124 /* After the handler runs we will restore to the state in
1125 SS->context, not the state of the thread now. So restore
1126 that context's reply port and intr port. */
1128 scp->sc_reply_port = ss->context->sc_reply_port;
1129 scp->sc_intr_port = ss->context->sc_intr_port;
1131 ss->context = NULL;
1135 /* Backdoor extra argument to signal handler. */
1136 scp->sc_error = detail->error;
1138 /* Block requested signals while running the handler. */
1139 scp->sc_mask = ss->blocked;
1140 __sigorset (&ss->blocked, &ss->blocked, &action->sa_mask);
1142 /* Also block SIGNO unless we're asked not to. */
1143 if (! (action->sa_flags & (SA_RESETHAND | SA_NODEFER)))
1144 __sigaddset (&ss->blocked, signo);
1146 /* Reset to SIG_DFL if requested. SIGILL and SIGTRAP cannot
1147 be automatically reset when delivered; the system silently
1148 enforces this restriction. */
1149 if (action->sa_flags & SA_RESETHAND
1150 && signo != SIGILL && signo != SIGTRAP)
1151 action->sa_handler = SIG_DFL;
1153 /* Any sigsuspend call must return after the handler does. */
1154 wake_sigsuspend (ss);
1156 /* Start the thread running the handler (or possibly waiting for an
1157 RPC reply before running the handler). */
1158 err = __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
1159 (natural_t *) &thread_state.basic,
1160 MACHINE_THREAD_STATE_COUNT);
1161 assert_perror (err);
1162 err = __thread_resume (ss->thread);
1163 assert_perror (err);
1164 thread_state.set = 0; /* Everything we know is now wrong. */
1165 break;
1169 return ss;
1172 /* Return the set of pending signals in SS which should be delivered. */
1173 static sigset_t
1174 pending_signals (struct hurd_sigstate *ss)
1176 /* We don't worry about any pending signals if we are stopped, nor if
1177 SS is in a critical section. We are guaranteed to get a sig_post
1178 message before any of them become deliverable: either the SIGCONT
1179 signal, or a sig_post with SIGNO==0 as an explicit poll when the
1180 thread finishes its critical section. */
1181 if (_hurd_stopped || __spin_lock_locked (&ss->critical_section_lock))
1182 return 0;
1184 return _hurd_sigstate_pending (ss) & ~ss->blocked;
1187 /* Post the specified pending signals in SS and return 1. If one of
1188 them is traced, abort immediately and return 0. SS must be locked on
1189 entry and will be unlocked in all cases. */
1190 static int
1191 post_pending (struct hurd_sigstate *ss, sigset_t pending, void (*reply) (void))
1193 int signo;
1194 struct hurd_signal_detail detail;
1196 /* Make sure SS corresponds to an actual thread, since we assume it won't
1197 change in post_signal. */
1198 assert (ss->thread != MACH_PORT_NULL);
1200 for (signo = 1; signo < NSIG; ++signo)
1201 if (__sigismember (&pending, signo))
1203 detail = sigstate_clear_pending (ss, signo);
1204 _hurd_sigstate_unlock (ss);
1206 /* Will reacquire the lock, except if the signal is traced. */
1207 if (! post_signal (ss, signo, &detail, 0, reply))
1208 return 0;
1211 /* No more signals pending; SS->lock is still locked. */
1212 _hurd_sigstate_unlock (ss);
1214 return 1;
1217 /* Post all the pending signals of all threads and return 1. If a traced
1218 signal is encountered, abort immediately and return 0. */
1219 static int
1220 post_all_pending_signals (void (*reply) (void))
1222 struct hurd_sigstate *ss;
1223 sigset_t pending = 0;
1225 for (;;)
1227 __mutex_lock (&_hurd_siglock);
1228 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
1230 _hurd_sigstate_lock (ss);
1232 pending = pending_signals (ss);
1233 if (pending)
1234 /* post_pending() below will unlock SS. */
1235 break;
1237 _hurd_sigstate_unlock (ss);
1239 __mutex_unlock (&_hurd_siglock);
1241 if (! pending)
1242 return 1;
1243 if (! post_pending (ss, pending, reply))
1244 return 0;
1248 /* Deliver a signal. SS is not locked. */
1249 void
1250 _hurd_internal_post_signal (struct hurd_sigstate *ss,
1251 int signo, struct hurd_signal_detail *detail,
1252 mach_port_t reply_port,
1253 mach_msg_type_name_t reply_port_type,
1254 int untraced)
1256 /* Reply to this sig_post message. */
1257 __typeof (__msg_sig_post_reply) *reply_rpc
1258 = (untraced ? __msg_sig_post_untraced_reply : __msg_sig_post_reply);
1259 void reply (void)
1261 error_t err;
1262 if (reply_port == MACH_PORT_NULL)
1263 return;
1264 err = (*reply_rpc) (reply_port, reply_port_type, 0);
1265 reply_port = MACH_PORT_NULL;
1266 if (err != MACH_SEND_INVALID_DEST) /* Ignore dead reply port. */
1267 assert_perror (err);
1270 ss = post_signal (ss, signo, detail, untraced, reply);
1271 if (! ss)
1272 return;
1274 /* The signal was neither fatal nor traced. We still hold SS->lock. */
1275 if (signo != 0 && ss->thread != MACH_PORT_NULL)
1277 /* The signal has either been ignored or is now being handled. We can
1278 consider it delivered and reply to the killer. */
1279 reply ();
1281 /* Post any pending signals for this thread. */
1282 if (! post_pending (ss, pending_signals (ss), reply))
1283 return;
1285 else
1287 /* If this was a process-wide signal or a poll request, we need
1288 to check for pending signals for all threads. */
1289 _hurd_sigstate_unlock (ss);
1290 if (! post_all_pending_signals (reply))
1291 return;
1293 /* All pending signals delivered to all threads.
1294 Now we can send the reply message even for signal 0. */
1295 reply ();
1299 /* Decide whether REFPORT enables the sender to send us a SIGNO signal.
1300 Returns zero if so, otherwise the error code to return to the sender. */
1302 static error_t
1303 signal_allowed (int signo, mach_port_t refport)
1305 if (signo < 0 || signo >= NSIG)
1306 return EINVAL;
1308 if (refport == __mach_task_self ())
1309 /* Can send any signal. */
1310 goto win;
1312 /* Avoid needing to check for this below. */
1313 if (refport == MACH_PORT_NULL)
1314 return EPERM;
1316 switch (signo)
1318 case SIGINT:
1319 case SIGQUIT:
1320 case SIGTSTP:
1321 case SIGHUP:
1322 case SIGINFO:
1323 case SIGTTIN:
1324 case SIGTTOU:
1325 case SIGWINCH:
1326 /* Job control signals can be sent by the controlling terminal. */
1327 if (__USEPORT (CTTYID, port == refport))
1328 goto win;
1329 break;
1331 case SIGCONT:
1333 /* A continue signal can be sent by anyone in the session. */
1334 mach_port_t sessport;
1335 if (! __USEPORT (PROC, __proc_getsidport (port, &sessport)))
1337 __mach_port_deallocate (__mach_task_self (), sessport);
1338 if (refport == sessport)
1339 goto win;
1342 break;
1344 case SIGIO:
1345 case SIGURG:
1347 /* Any io object a file descriptor refers to might send us
1348 one of these signals using its async ID port for REFPORT.
1350 This is pretty wide open; it is not unlikely that some random
1351 process can at least open for reading something we have open,
1352 get its async ID port, and send us a spurious SIGIO or SIGURG
1353 signal. But BSD is actually wider open than that!--you can set
1354 the owner of an io object to any process or process group
1355 whatsoever and send them gratuitous signals.
1357 Someday we could implement some reasonable scheme for
1358 authorizing SIGIO and SIGURG signals properly. */
1360 int d;
1361 int lucky = 0; /* True if we find a match for REFPORT. */
1362 __mutex_lock (&_hurd_dtable_lock);
1363 for (d = 0; !lucky && (unsigned) d < (unsigned) _hurd_dtablesize; ++d)
1365 struct hurd_userlink ulink;
1366 io_t port;
1367 mach_port_t asyncid;
1368 if (_hurd_dtable[d] == NULL)
1369 continue;
1370 port = _hurd_port_get (&_hurd_dtable[d]->port, &ulink);
1371 if (! __io_get_icky_async_id (port, &asyncid))
1373 if (refport == asyncid)
1374 /* Break out of the loop on the next iteration. */
1375 lucky = 1;
1376 __mach_port_deallocate (__mach_task_self (), asyncid);
1378 _hurd_port_free (&_hurd_dtable[d]->port, &ulink, port);
1380 __mutex_unlock (&_hurd_dtable_lock);
1381 /* If we found a lucky winner, we've set D to -1 in the loop. */
1382 if (lucky)
1383 goto win;
1387 /* If this signal is legit, we have done `goto win' by now.
1388 When we return the error, mig deallocates REFPORT. */
1389 return EPERM;
1391 win:
1392 /* Deallocate the REFPORT send right; we are done with it. */
1393 __mach_port_deallocate (__mach_task_self (), refport);
1395 return 0;
1398 /* Implement the sig_post RPC from <hurd/msg.defs>;
1399 sent when someone wants us to get a signal. */
1400 kern_return_t
1401 _S_msg_sig_post (mach_port_t me,
1402 mach_port_t reply_port, mach_msg_type_name_t reply_port_type,
1403 int signo, natural_t sigcode,
1404 mach_port_t refport)
1406 error_t err;
1407 struct hurd_signal_detail d;
1409 if (err = signal_allowed (signo, refport))
1410 return err;
1412 d.code = d.exc_subcode = sigcode;
1413 d.exc = 0;
1415 /* Post the signal to a global receiver thread (or mark it pending in
1416 the global sigstate). This will reply when the signal can be
1417 considered delivered. */
1418 _hurd_internal_post_signal (_hurd_global_sigstate,
1419 signo, &d, reply_port, reply_port_type,
1420 0); /* Stop if traced. */
1422 return MIG_NO_REPLY; /* Already replied. */
1425 /* Implement the sig_post_untraced RPC from <hurd/msg.defs>;
1426 sent when the debugger wants us to really get a signal
1427 even if we are traced. */
1428 kern_return_t
1429 _S_msg_sig_post_untraced (mach_port_t me,
1430 mach_port_t reply_port,
1431 mach_msg_type_name_t reply_port_type,
1432 int signo, natural_t sigcode,
1433 mach_port_t refport)
1435 error_t err;
1436 struct hurd_signal_detail d;
1438 if (err = signal_allowed (signo, refport))
1439 return err;
1441 d.code = d.exc_subcode = sigcode;
1442 d.exc = 0;
1444 /* Post the signal to the designated signal-receiving thread. This will
1445 reply when the signal can be considered delivered. */
1446 _hurd_internal_post_signal (_hurd_global_sigstate,
1447 signo, &d, reply_port, reply_port_type,
1448 1); /* Untraced flag. */
1450 return MIG_NO_REPLY; /* Already replied. */
1453 extern void __mig_init (void *);
1455 #include <mach/task_special_ports.h>
1457 /* Initialize the message port, _hurd_global_sigstate, and start the
1458 signal thread. */
1460 void
1461 _hurdsig_init (const int *intarray, size_t intarraysize)
1463 error_t err;
1464 vm_size_t stacksize;
1465 struct hurd_sigstate *ss;
1467 __mutex_init (&_hurd_siglock);
1469 err = __mach_port_allocate (__mach_task_self (),
1470 MACH_PORT_RIGHT_RECEIVE,
1471 &_hurd_msgport);
1472 assert_perror (err);
1474 /* Make a send right to the signal port. */
1475 err = __mach_port_insert_right (__mach_task_self (),
1476 _hurd_msgport,
1477 _hurd_msgport,
1478 MACH_MSG_TYPE_MAKE_SEND);
1479 assert_perror (err);
1481 /* Initialize the global signal state. */
1482 _hurd_global_sigstate = _hurd_thread_sigstate (MACH_PORT_NULL);
1484 /* We block all signals, and let actual threads pull them from the
1485 pending mask. */
1486 __sigfillset(& _hurd_global_sigstate->blocked);
1488 /* Initialize the main thread's signal state. */
1489 ss = _hurd_self_sigstate ();
1491 /* Mark it as a process-wide signal receiver. Threads in this set use
1492 the common action vector in _hurd_global_sigstate. */
1493 _hurd_sigstate_set_global_rcv (ss);
1495 /* Copy inherited signal settings from our parent (or pre-exec process
1496 state) */
1497 if (intarraysize > INIT_SIGMASK)
1498 ss->blocked = intarray[INIT_SIGMASK];
1499 if (intarraysize > INIT_SIGPENDING)
1500 _hurd_global_sigstate->pending = intarray[INIT_SIGPENDING];
1501 if (intarraysize > INIT_SIGIGN && intarray[INIT_SIGIGN] != 0)
1503 int signo;
1504 for (signo = 1; signo < NSIG; ++signo)
1505 if (intarray[INIT_SIGIGN] & __sigmask(signo))
1506 _hurd_global_sigstate->actions[signo].sa_handler = SIG_IGN;
1509 /* Start the signal thread listening on the message port. */
1511 #pragma weak __pthread_create
1512 if (!__pthread_create)
1514 err = __thread_create (__mach_task_self (), &_hurd_msgport_thread);
1515 assert_perror (err);
1517 stacksize = __vm_page_size * 8; /* Small stack for signal thread. */
1518 err = __mach_setup_thread (__mach_task_self (), _hurd_msgport_thread,
1519 _hurd_msgport_receive,
1520 (vm_address_t *) &__hurd_sigthread_stack_base,
1521 &stacksize);
1522 assert_perror (err);
1523 err = __mach_setup_tls (_hurd_msgport_thread);
1524 assert_perror (err);
1526 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + stacksize;
1528 /* Reinitialize the MiG support routines so they will use a per-thread
1529 variable for the cached reply port. */
1530 __mig_init ((void *) __hurd_sigthread_stack_base);
1532 err = __thread_resume (_hurd_msgport_thread);
1533 assert_perror (err);
1535 else
1537 pthread_t thread;
1538 pthread_attr_t attr;
1539 void *addr;
1540 size_t size;
1542 /* When pthread is being used, we need to make the signal thread a
1543 proper pthread. Otherwise it cannot use mutex_lock et al, which
1544 will be the pthread versions. Various of the message port RPC
1545 handlers need to take locks, so we need to be able to call into
1546 pthread code and meet its assumptions about how our thread and
1547 its stack are arranged. Since pthread puts it there anyway,
1548 we'll let the signal thread's per-thread variables be found as for
1549 any normal pthread, and just leave the magic __hurd_sigthread_*
1550 values all zero so they'll be ignored. */
1552 #pragma weak __pthread_detach
1553 #pragma weak __pthread_getattr_np
1554 #pragma weak __pthread_attr_getstack
1555 __pthread_create(&thread, NULL, &_hurd_msgport_receive, NULL);
1557 /* Record signal thread stack layout for fork() */
1558 __pthread_getattr_np (thread, &attr);
1559 __pthread_attr_getstack (&attr, &addr, &size);
1560 __hurd_sigthread_stack_base = (uintptr_t) addr;
1561 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + size;
1563 __pthread_detach(thread);
1565 /* XXX We need the thread port for the signal thread further on
1566 in this thread (see hurdfault.c:_hurdsigfault_init).
1567 Therefore we block until _hurd_msgport_thread is initialized
1568 by the newly created thread. This really shouldn't be
1569 necessary; we should be able to fetch the thread port for a
1570 pthread from here. */
1571 while (_hurd_msgport_thread == 0)
1572 __swtch_pri (0);
1575 /* Receive exceptions on the signal port. */
1576 #ifdef TASK_EXCEPTION_PORT
1577 __task_set_special_port (__mach_task_self (),
1578 TASK_EXCEPTION_PORT, _hurd_msgport);
1579 #elif defined (EXC_MASK_ALL)
1580 __task_set_exception_ports (__mach_task_self (),
1581 EXC_MASK_ALL & ~(EXC_MASK_SYSCALL
1582 | EXC_MASK_MACH_SYSCALL
1583 | EXC_MASK_RPC_ALERT),
1584 _hurd_msgport,
1585 EXCEPTION_DEFAULT, MACHINE_THREAD_STATE);
1586 #else
1587 # error task_set_exception_port?
1588 #endif
1590 /* Sanity check. Any pending, unblocked signals should have been
1591 taken by our predecessor incarnation (i.e. parent or pre-exec state)
1592 before packing up our init ints. This assert is last (not above)
1593 so that signal handling is all set up to handle the abort. */
1594 assert ((ss->pending &~ ss->blocked) == 0);
1596 \f /* XXXX */
1597 /* Reauthenticate with the proc server. */
1599 static void
1600 reauth_proc (mach_port_t new)
1602 mach_port_t ref, ignore;
1604 ref = __mach_reply_port ();
1605 if (! HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1606 __proc_reauthenticate (port, ref,
1607 MACH_MSG_TYPE_MAKE_SEND)
1608 || __auth_user_authenticate (new, ref,
1609 MACH_MSG_TYPE_MAKE_SEND,
1610 &ignore))
1611 && ignore != MACH_PORT_NULL)
1612 __mach_port_deallocate (__mach_task_self (), ignore);
1613 __mach_port_destroy (__mach_task_self (), ref);
1615 /* Set the owner of the process here too. */
1616 __mutex_lock (&_hurd_id.lock);
1617 if (!_hurd_check_ids ())
1618 HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1619 __proc_setowner (port,
1620 (_hurd_id.gen.nuids
1621 ? _hurd_id.gen.uids[0] : 0),
1622 !_hurd_id.gen.nuids));
1623 __mutex_unlock (&_hurd_id.lock);
1625 (void) &reauth_proc; /* Silence compiler warning. */
1627 text_set_element (_hurd_reauth_hook, reauth_proc);
1629 /* Like `getenv', but safe for the signal thread to run.
1630 If the environment is trashed, this will just return NULL. */
1632 const char *
1633 _hurdsig_getenv (const char *variable)
1635 if (__libc_enable_secure)
1636 return NULL;
1638 if (_hurdsig_catch_memory_fault (__environ))
1639 /* We bombed in getenv. */
1640 return NULL;
1641 else
1643 const size_t len = strlen (variable);
1644 char *value = NULL;
1645 char *volatile *ep = __environ;
1646 while (*ep)
1648 const char *p = *ep;
1649 _hurdsig_fault_preemptor.first = (long int) p;
1650 _hurdsig_fault_preemptor.last = VM_MAX_ADDRESS;
1651 if (! strncmp (p, variable, len) && p[len] == '=')
1653 size_t valuelen;
1654 p += len + 1;
1655 valuelen = strlen (p);
1656 _hurdsig_fault_preemptor.last = (long int) (p + valuelen);
1657 value = malloc (++valuelen);
1658 if (value)
1659 memcpy (value, p, valuelen);
1660 break;
1662 _hurdsig_fault_preemptor.first = (long int) ++ep;
1663 _hurdsig_fault_preemptor.last = (long int) (ep + 1);
1665 _hurdsig_end_catch_fault ();
1666 return value;