Add a generic scalb implementation
[glibc.git] / hurd / hurdsig.c
blob1e42246ee6cd75d23738c9272bffac5ed9d97129
1 /* Copyright (C) 1991-2020 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 <cthreads.h> /* For `struct mutex'. */
23 #include <pthreadP.h>
24 #include <mach.h>
25 #include <mach/thread_switch.h>
26 #include <mach/mig_support.h>
28 #include <hurd.h>
29 #include <hurd/id.h>
30 #include <hurd/signal.h>
32 #include "hurdfault.h"
33 #include "hurdmalloc.h" /* XXX */
34 #include "../locale/localeinfo.h"
36 #include <libc-diag.h>
38 const char *_hurdsig_getenv (const char *);
40 struct mutex _hurd_siglock;
41 int _hurd_stopped;
43 /* Port that receives signals and other miscellaneous messages. */
44 mach_port_t _hurd_msgport;
46 /* Thread listening on it. */
47 thread_t _hurd_msgport_thread;
49 /* These are set up by _hurdsig_init. */
50 unsigned long int __hurd_sigthread_stack_base;
51 unsigned long int __hurd_sigthread_stack_end;
53 /* Linked-list of per-thread signal state. */
54 struct hurd_sigstate *_hurd_sigstates;
56 /* Sigstate for the task-global signals. */
57 struct hurd_sigstate *_hurd_global_sigstate;
59 /* Timeout for RPC's after interrupt_operation. */
60 mach_msg_timeout_t _hurd_interrupted_rpc_timeout = 60000;
62 static void
63 default_sigaction (struct sigaction actions[NSIG])
65 int signo;
67 __sigemptyset (&actions[0].sa_mask);
68 actions[0].sa_flags = SA_RESTART;
69 actions[0].sa_handler = SIG_DFL;
71 for (signo = 1; signo < NSIG; ++signo)
72 actions[signo] = actions[0];
75 struct hurd_sigstate *
76 _hurd_thread_sigstate (thread_t thread)
78 struct hurd_sigstate *ss;
79 __mutex_lock (&_hurd_siglock);
80 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
81 if (ss->thread == thread)
82 break;
83 if (ss == NULL)
85 ss = malloc (sizeof (*ss));
86 if (ss == NULL)
87 __libc_fatal ("hurd: Can't allocate sigstate\n");
88 ss->thread = thread;
89 __spin_lock_init (&ss->lock);
91 /* Initialize default state. */
92 __sigemptyset (&ss->blocked);
93 __sigemptyset (&ss->pending);
94 memset (&ss->sigaltstack, 0, sizeof (ss->sigaltstack));
95 ss->sigaltstack.ss_flags |= SS_DISABLE;
96 ss->preemptors = NULL;
97 ss->suspended = MACH_PORT_NULL;
98 ss->intr_port = MACH_PORT_NULL;
99 ss->context = NULL;
101 if (thread == MACH_PORT_NULL)
103 /* Process-wide sigstate, use the system defaults. */
104 default_sigaction (ss->actions);
106 /* The global sigstate is not added to the _hurd_sigstates list.
107 It is created with _hurd_thread_sigstate (MACH_PORT_NULL)
108 but should be accessed through _hurd_global_sigstate. */
110 else
112 /* Use the global actions as a default for new threads. */
113 struct hurd_sigstate *s = _hurd_global_sigstate;
114 if (s)
116 __spin_lock (&s->lock);
117 memcpy (ss->actions, s->actions, sizeof (s->actions));
118 __spin_unlock (&s->lock);
120 else
121 default_sigaction (ss->actions);
123 ss->next = _hurd_sigstates;
124 _hurd_sigstates = ss;
127 __mutex_unlock (&_hurd_siglock);
128 return ss;
130 libc_hidden_def (_hurd_thread_sigstate)
132 /* Destroy a sigstate structure. Called by libpthread just before the
133 * corresponding thread is terminated (the kernel thread port must remain valid
134 * until this function is called.) */
135 void
136 _hurd_sigstate_delete (thread_t thread)
138 struct hurd_sigstate **ssp, *ss;
140 __mutex_lock (&_hurd_siglock);
141 for (ssp = &_hurd_sigstates; *ssp; ssp = &(*ssp)->next)
142 if ((*ssp)->thread == thread)
143 break;
145 ss = *ssp;
146 if (ss)
147 *ssp = ss->next;
149 __mutex_unlock (&_hurd_siglock);
150 if (ss)
151 free (ss);
154 /* Make SS a global receiver, with pthread signal semantics. */
155 void
156 _hurd_sigstate_set_global_rcv (struct hurd_sigstate *ss)
158 assert (ss->thread != MACH_PORT_NULL);
159 ss->actions[0].sa_handler = SIG_IGN;
162 /* Check whether SS is a global receiver. */
163 static int
164 sigstate_is_global_rcv (const struct hurd_sigstate *ss)
166 return (_hurd_global_sigstate != NULL)
167 && (ss->actions[0].sa_handler == SIG_IGN);
169 libc_hidden_def (_hurd_sigstate_delete)
171 /* Lock/unlock a hurd_sigstate structure. If the accessors below require
172 it, the global sigstate will be locked as well. */
173 void
174 _hurd_sigstate_lock (struct hurd_sigstate *ss)
176 if (sigstate_is_global_rcv (ss))
177 __spin_lock (&_hurd_global_sigstate->lock);
178 __spin_lock (&ss->lock);
180 void
181 _hurd_sigstate_unlock (struct hurd_sigstate *ss)
183 __spin_unlock (&ss->lock);
184 if (sigstate_is_global_rcv (ss))
185 __spin_unlock (&_hurd_global_sigstate->lock);
187 libc_hidden_def (_hurd_sigstate_set_global_rcv)
189 /* Retreive a thread's full set of pending signals, including the global
190 ones if appropriate. SS must be locked. */
191 sigset_t
192 _hurd_sigstate_pending (const struct hurd_sigstate *ss)
194 sigset_t pending = ss->pending;
195 if (sigstate_is_global_rcv (ss))
196 __sigorset (&pending, &pending, &_hurd_global_sigstate->pending);
197 return pending;
200 /* Clear a pending signal and return the associated detailed
201 signal information. SS must be locked, and must have signal SIGNO
202 pending, either directly or through the global sigstate. */
203 static struct hurd_signal_detail
204 sigstate_clear_pending (struct hurd_sigstate *ss, int signo)
206 if (sigstate_is_global_rcv (ss)
207 && __sigismember (&_hurd_global_sigstate->pending, signo))
209 __sigdelset (&_hurd_global_sigstate->pending, signo);
210 return _hurd_global_sigstate->pending_data[signo];
213 assert (__sigismember (&ss->pending, signo));
214 __sigdelset (&ss->pending, signo);
215 return ss->pending_data[signo];
217 libc_hidden_def (_hurd_sigstate_lock)
218 libc_hidden_def (_hurd_sigstate_unlock)
220 /* Retreive a thread's action vector. SS must be locked. */
221 struct sigaction *
222 _hurd_sigstate_actions (struct hurd_sigstate *ss)
224 if (sigstate_is_global_rcv (ss))
225 return _hurd_global_sigstate->actions;
226 else
227 return ss->actions;
229 libc_hidden_def (_hurd_sigstate_pending)
232 /* Signal delivery itself is on this page. */
234 #include <hurd/fd.h>
235 #include <hurd/crash.h>
236 #include <hurd/resource.h>
237 #include <hurd/paths.h>
238 #include <setjmp.h>
239 #include <fcntl.h>
240 #include <sys/wait.h>
241 #include <thread_state.h>
242 #include <hurd/msg_server.h>
243 #include <hurd/msg_reply.h> /* For __msg_sig_post_reply. */
244 #include <hurd/interrupt.h>
245 #include <assert.h>
246 #include <unistd.h>
249 /* Call the crash dump server to mummify us before we die.
250 Returns nonzero if a core file was written. */
251 static int
252 write_corefile (int signo, const struct hurd_signal_detail *detail)
254 error_t err;
255 mach_port_t coreserver;
256 file_t file, coredir;
257 const char *name;
259 /* Don't bother locking since we just read the one word. */
260 rlim_t corelimit = _hurd_rlimits[RLIMIT_CORE].rlim_cur;
262 if (corelimit == 0)
263 /* No core dumping, thank you very much. Note that this makes
264 `ulimit -c 0' prevent crash-suspension too, which is probably
265 what the user wanted. */
266 return 0;
268 /* XXX RLIMIT_CORE:
269 When we have a protocol to make the server return an error
270 for RLIMIT_FSIZE, then tell the corefile fs server the RLIMIT_CORE
271 value in place of the RLIMIT_FSIZE value. */
273 /* First get a port to the core dumping server. */
274 coreserver = MACH_PORT_NULL;
275 name = _hurdsig_getenv ("CRASHSERVER");
276 if (name != NULL)
277 coreserver = __file_name_lookup (name, 0, 0);
278 if (coreserver == MACH_PORT_NULL)
279 coreserver = __file_name_lookup (_SERVERS_CRASH, 0, 0);
280 if (coreserver == MACH_PORT_NULL)
281 return 0;
283 /* Get a port to the directory where the new core file will reside. */
284 file = MACH_PORT_NULL;
285 name = _hurdsig_getenv ("COREFILE");
286 if (name == NULL)
287 name = "core";
288 coredir = __file_name_split (name, (char **) &name);
289 if (coredir != MACH_PORT_NULL)
290 /* Create the new file, but don't link it into the directory yet. */
291 __dir_mkfile (coredir, O_WRONLY|O_CREAT,
292 0600 & ~_hurd_umask, /* XXX ? */
293 &file);
295 /* Call the core dumping server to write the core file. */
296 err = __crash_dump_task (coreserver,
297 __mach_task_self (),
298 file,
299 signo, detail->code, detail->error,
300 detail->exc, detail->exc_code, detail->exc_subcode,
301 _hurd_ports[INIT_PORT_CTTYID].port,
302 MACH_MSG_TYPE_COPY_SEND);
303 __mach_port_deallocate (__mach_task_self (), coreserver);
305 if (! err && file != MACH_PORT_NULL)
306 /* The core dump into FILE succeeded, so now link it into the
307 directory. */
308 err = __dir_link (coredir, file, name, 1);
309 __mach_port_deallocate (__mach_task_self (), file);
310 __mach_port_deallocate (__mach_task_self (), coredir);
311 return !err && file != MACH_PORT_NULL;
315 /* The lowest-numbered thread state flavor value is 1,
316 so we use bit 0 in machine_thread_all_state.set to
317 record whether we have done thread_abort. */
318 #define THREAD_ABORTED 1
320 /* SS->thread is suspended. Abort the thread and get its basic state. */
321 static void
322 abort_thread (struct hurd_sigstate *ss, struct machine_thread_all_state *state,
323 void (*reply) (void))
325 assert (ss->thread != MACH_PORT_NULL);
327 if (!(state->set & THREAD_ABORTED))
329 error_t err = __thread_abort (ss->thread);
330 assert_perror (err);
331 /* Clear all thread state flavor set bits, because thread_abort may
332 have changed the state. */
333 state->set = THREAD_ABORTED;
336 if (reply)
337 (*reply) ();
339 machine_get_basic_state (ss->thread, state);
342 /* Find the location of the MiG reply port cell in use by the thread whose
343 state is described by THREAD_STATE. If SIGTHREAD is nonzero, make sure
344 that this location can be set without faulting, or else return NULL. */
346 static mach_port_t *
347 interrupted_reply_port_location (thread_t thread,
348 struct machine_thread_all_state *thread_state,
349 int sigthread)
351 mach_port_t *portloc = &THREAD_TCB(thread, thread_state)->reply_port;
353 if (sigthread && _hurdsig_catch_memory_fault (portloc))
354 /* Faulted trying to read the TCB. */
355 return NULL;
357 DIAG_PUSH_NEEDS_COMMENT;
358 /* GCC 6 and before seem to be confused by the setjmp call inside
359 _hurdsig_catch_memory_fault and think that we may be returning a second
360 time to here with portloc uninitialized (but we never do). */
361 DIAG_IGNORE_NEEDS_COMMENT (6, "-Wmaybe-uninitialized");
362 /* Fault now if this pointer is bogus. */
363 *(volatile mach_port_t *) portloc = *portloc;
364 DIAG_POP_NEEDS_COMMENT;
366 if (sigthread)
367 _hurdsig_end_catch_fault ();
369 return portloc;
372 #include <hurd/sigpreempt.h>
373 #include <intr-msg.h>
375 /* Timeout on interrupt_operation calls. */
376 mach_msg_timeout_t _hurdsig_interrupt_timeout = 1000;
378 /* SS->thread is suspended.
380 Abort any interruptible RPC operation the thread is doing.
382 This uses only the constant member SS->thread and the unlocked, atomically
383 set member SS->intr_port, so no locking is needed.
385 If successfully sent an interrupt_operation and therefore the thread should
386 wait for its pending RPC to return (possibly EINTR) before taking the
387 incoming signal, returns the reply port to be received on. Otherwise
388 returns MACH_PORT_NULL.
390 SIGNO is used to find the applicable SA_RESTART bit. If SIGNO is zero,
391 the RPC fails with EINTR instead of restarting (thread_cancel).
393 *STATE_CHANGE is set nonzero if STATE->basic was modified and should
394 be applied back to the thread if it might ever run again, else zero. */
396 mach_port_t
397 _hurdsig_abort_rpcs (struct hurd_sigstate *ss, int signo, int sigthread,
398 struct machine_thread_all_state *state, int *state_change,
399 void (*reply) (void))
401 extern const void _hurd_intr_rpc_msg_about_to;
402 extern const void _hurd_intr_rpc_msg_in_trap;
403 mach_port_t rcv_port = MACH_PORT_NULL;
404 mach_port_t intr_port;
406 *state_change = 0;
408 intr_port = ss->intr_port;
409 if (intr_port == MACH_PORT_NULL)
410 /* No interruption needs done. */
411 return MACH_PORT_NULL;
413 /* Abort the thread's kernel context, so any pending message send or
414 receive completes immediately or aborts. */
415 abort_thread (ss, state, reply);
417 if (state->basic.PC >= (natural_t) &_hurd_intr_rpc_msg_about_to
418 && state->basic.PC < (natural_t) &_hurd_intr_rpc_msg_in_trap)
420 /* The thread is about to do the RPC, but hasn't yet entered
421 mach_msg. Mutate the thread's state so it knows not to try
422 the RPC. */
423 INTR_MSG_BACK_OUT (&state->basic);
424 MACHINE_THREAD_STATE_SET_PC (&state->basic,
425 &_hurd_intr_rpc_msg_in_trap);
426 state->basic.SYSRETURN = MACH_SEND_INTERRUPTED;
427 *state_change = 1;
429 else if (state->basic.PC == (natural_t) &_hurd_intr_rpc_msg_in_trap
430 /* The thread was blocked in the system call. After thread_abort,
431 the return value register indicates what state the RPC was in
432 when interrupted. */
433 && state->basic.SYSRETURN == MACH_RCV_INTERRUPTED)
435 /* The RPC request message was sent and the thread was waiting for
436 the reply message; now the message receive has been aborted, so
437 the mach_msg call will return MACH_RCV_INTERRUPTED. We must tell
438 the server to interrupt the pending operation. The thread must
439 wait for the reply message before running the signal handler (to
440 guarantee that the operation has finished being interrupted), so
441 our nonzero return tells the trampoline code to finish the message
442 receive operation before running the handler. */
444 mach_port_t *reply = interrupted_reply_port_location (ss->thread,
445 state,
446 sigthread);
447 error_t err = __interrupt_operation (intr_port, _hurdsig_interrupt_timeout);
449 if (err)
451 if (reply)
453 /* The interrupt didn't work.
454 Destroy the receive right the thread is blocked on. */
455 __mach_port_destroy (__mach_task_self (), *reply);
456 *reply = MACH_PORT_NULL;
459 /* The system call return value register now contains
460 MACH_RCV_INTERRUPTED; when mach_msg resumes, it will retry the
461 call. Since we have just destroyed the receive right, the
462 retry will fail with MACH_RCV_INVALID_NAME. Instead, just
463 change the return value here to EINTR so mach_msg will not
464 retry and the EINTR error code will propagate up. */
465 state->basic.SYSRETURN = EINTR;
466 *state_change = 1;
468 else if (reply)
469 rcv_port = *reply;
471 /* All threads whose RPCs were interrupted by the interrupt_operation
472 call above will retry their RPCs unless we clear SS->intr_port.
473 So we clear it for the thread taking a signal when SA_RESTART is
474 clear, so that its call returns EINTR. */
475 if (! signo || !(_hurd_sigstate_actions (ss) [signo].sa_flags & SA_RESTART))
476 ss->intr_port = MACH_PORT_NULL;
479 return rcv_port;
483 /* Abort the RPCs being run by all threads but this one;
484 all other threads should be suspended. If LIVE is nonzero, those
485 threads may run again, so they should be adjusted as necessary to be
486 happy when resumed. STATE is clobbered as a scratch area; its initial
487 contents are ignored, and its contents on return are not useful. */
489 static void
490 abort_all_rpcs (int signo, struct machine_thread_all_state *state, int live)
492 /* We can just loop over the sigstates. Any thread doing something
493 interruptible must have one. We needn't bother locking because all
494 other threads are stopped. */
496 struct hurd_sigstate *ss;
497 size_t nthreads;
498 mach_port_t *reply_ports;
500 /* First loop over the sigstates to count them.
501 We need to know how big a vector we will need for REPLY_PORTS. */
502 nthreads = 0;
503 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
504 ++nthreads;
506 reply_ports = alloca (nthreads * sizeof *reply_ports);
508 nthreads = 0;
509 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next, ++nthreads)
510 if (ss->thread == _hurd_msgport_thread)
511 reply_ports[nthreads] = MACH_PORT_NULL;
512 else
514 int state_changed;
515 state->set = 0; /* Reset scratch area. */
517 /* Abort any operation in progress with interrupt_operation.
518 Record the reply port the thread is waiting on.
519 We will wait for all the replies below. */
520 reply_ports[nthreads] = _hurdsig_abort_rpcs (ss, signo, 1,
521 state, &state_changed,
522 NULL);
523 if (live)
525 if (reply_ports[nthreads] != MACH_PORT_NULL)
527 /* We will wait for the reply to this RPC below, so the
528 thread must issue a new RPC rather than waiting for the
529 reply to the one it sent. */
530 state->basic.SYSRETURN = EINTR;
531 state_changed = 1;
533 if (state_changed)
534 /* Aborting the RPC needed to change this thread's state,
535 and it might ever run again. So write back its state. */
536 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
537 (natural_t *) &state->basic,
538 MACHINE_THREAD_STATE_COUNT);
542 /* Wait for replies from all the successfully interrupted RPCs. */
543 while (nthreads-- > 0)
544 if (reply_ports[nthreads] != MACH_PORT_NULL)
546 error_t err;
547 mach_msg_header_t head;
548 err = __mach_msg (&head, MACH_RCV_MSG|MACH_RCV_TIMEOUT, 0, sizeof head,
549 reply_ports[nthreads],
550 _hurd_interrupted_rpc_timeout, MACH_PORT_NULL);
551 switch (err)
553 case MACH_RCV_TIMED_OUT:
554 case MACH_RCV_TOO_LARGE:
555 break;
557 default:
558 assert_perror (err);
563 /* Wake up any sigsuspend call that is blocking SS->thread. SS must be
564 locked. */
565 static void
566 wake_sigsuspend (struct hurd_sigstate *ss)
568 error_t err;
569 mach_msg_header_t msg;
571 if (ss->suspended == MACH_PORT_NULL)
572 return;
574 /* There is a sigsuspend waiting. Tell it to wake up. */
575 msg.msgh_bits = MACH_MSGH_BITS (MACH_MSG_TYPE_MAKE_SEND, 0);
576 msg.msgh_remote_port = ss->suspended;
577 msg.msgh_local_port = MACH_PORT_NULL;
578 /* These values do not matter. */
579 msg.msgh_id = 8675309; /* Jenny, Jenny. */
580 ss->suspended = MACH_PORT_NULL;
581 err = __mach_msg (&msg, MACH_SEND_MSG, sizeof msg, 0,
582 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
583 MACH_PORT_NULL);
584 assert_perror (err);
587 struct hurd_signal_preemptor *_hurdsig_preemptors = 0;
588 sigset_t _hurdsig_preempted_set;
590 /* XXX temporary to deal with spelling fix */
591 weak_alias (_hurdsig_preemptors, _hurdsig_preempters)
593 /* Mask of stop signals. */
594 #define STOPSIGS (sigmask (SIGTTIN) | sigmask (SIGTTOU) \
595 | sigmask (SIGSTOP) | sigmask (SIGTSTP))
597 /* Actual delivery of a single signal. Called with SS unlocked. When
598 the signal is delivered, return SS, locked (or, if SS was originally
599 _hurd_global_sigstate, the sigstate of the actual thread the signal
600 was delivered to). If the signal is being traced, return NULL with
601 SS unlocked. */
602 static struct hurd_sigstate *
603 post_signal (struct hurd_sigstate *ss,
604 int signo, struct hurd_signal_detail *detail,
605 int untraced, void (*reply) (void))
607 struct machine_thread_all_state thread_state;
608 enum { stop, ignore, core, term, handle } act;
609 int ss_suspended;
611 /* Mark the signal as pending. */
612 void mark_pending (void)
614 __sigaddset (&ss->pending, signo);
615 /* Save the details to be given to the handler when SIGNO is
616 unblocked. */
617 ss->pending_data[signo] = *detail;
620 /* Suspend the process with SIGNO. */
621 void suspend (void)
623 /* Stop all other threads and mark ourselves stopped. */
624 __USEPORT (PROC,
626 /* Hold the siglock while stopping other threads to be
627 sure it is not held by another thread afterwards. */
628 __mutex_lock (&_hurd_siglock);
629 __proc_dostop (port, _hurd_msgport_thread);
630 __mutex_unlock (&_hurd_siglock);
631 abort_all_rpcs (signo, &thread_state, 1);
632 reply ();
633 __proc_mark_stop (port, signo, detail->code);
634 }));
635 _hurd_stopped = 1;
637 /* Resume the process after a suspension. */
638 void resume (void)
640 /* Resume the process from being stopped. */
641 thread_t *threads;
642 mach_msg_type_number_t nthreads, i;
643 error_t err;
645 if (! _hurd_stopped)
646 return;
648 /* Tell the proc server we are continuing. */
649 __USEPORT (PROC, __proc_mark_cont (port));
650 /* Fetch ports to all our threads and resume them. */
651 err = __task_threads (__mach_task_self (), &threads, &nthreads);
652 assert_perror (err);
653 for (i = 0; i < nthreads; ++i)
655 if (act == handle && threads[i] == ss->thread)
657 /* The thread that will run the handler is kept suspended. */
658 ss_suspended = 1;
660 else if (threads[i] != _hurd_msgport_thread)
662 err = __thread_resume (threads[i]);
663 assert_perror (err);
665 err = __mach_port_deallocate (__mach_task_self (),
666 threads[i]);
667 assert_perror (err);
669 __vm_deallocate (__mach_task_self (),
670 (vm_address_t) threads,
671 nthreads * sizeof *threads);
672 _hurd_stopped = 0;
675 error_t err;
676 sighandler_t handler;
678 if (signo == 0)
680 if (untraced)
682 /* This is PTRACE_CONTINUE. */
683 act = ignore;
684 resume ();
687 /* This call is just to check for pending signals. */
688 _hurd_sigstate_lock (ss);
689 return ss;
692 thread_state.set = 0; /* We know nothing. */
694 _hurd_sigstate_lock (ss);
696 /* If this is a global signal, try to find a thread ready to accept
697 it right away. This is especially important for untraced signals,
698 since going through the global pending mask would de-untrace them. */
699 if (ss->thread == MACH_PORT_NULL)
701 struct hurd_sigstate *rss;
703 __mutex_lock (&_hurd_siglock);
704 for (rss = _hurd_sigstates; rss != NULL; rss = rss->next)
706 if (! sigstate_is_global_rcv (rss))
707 continue;
709 /* The global sigstate is already locked. */
710 __spin_lock (&rss->lock);
711 if (! __sigismember (&rss->blocked, signo))
713 ss = rss;
714 break;
716 __spin_unlock (&rss->lock);
718 __mutex_unlock (&_hurd_siglock);
721 /* We want the preemptors to be able to update the blocking mask
722 without affecting the delivery of this signal, so we save the
723 current value to test against later. */
724 sigset_t blocked = ss->blocked;
726 /* Check for a preempted signal. Preempted signals can arrive during
727 critical sections. */
729 inline sighandler_t try_preemptor (struct hurd_signal_preemptor *pe)
730 { /* PE cannot be null. */
733 if (HURD_PREEMPT_SIGNAL_P (pe, signo, detail->code))
735 if (pe->preemptor)
737 sighandler_t handler = (*pe->preemptor) (pe, ss,
738 &signo, detail);
739 if (handler != SIG_ERR)
740 return handler;
742 else
743 return pe->handler;
745 pe = pe->next;
746 } while (pe != 0);
747 return SIG_ERR;
750 handler = ss->preemptors ? try_preemptor (ss->preemptors) : SIG_ERR;
752 /* If no thread-specific preemptor, check for a global one. */
753 if (handler == SIG_ERR && __sigismember (&_hurdsig_preempted_set, signo))
755 __mutex_lock (&_hurd_siglock);
756 handler = try_preemptor (_hurdsig_preemptors);
757 __mutex_unlock (&_hurd_siglock);
761 ss_suspended = 0;
763 if (handler == SIG_IGN)
764 /* Ignore the signal altogether. */
765 act = ignore;
766 else if (handler != SIG_ERR)
767 /* Run the preemption-provided handler. */
768 act = handle;
769 else
771 /* No preemption. Do normal handling. */
773 if (!untraced && __sigismember (&_hurdsig_traced, signo))
775 /* We are being traced. Stop to tell the debugger of the signal. */
776 if (_hurd_stopped)
777 /* Already stopped. Mark the signal as pending;
778 when resumed, we will notice it and stop again. */
779 mark_pending ();
780 else
781 suspend ();
782 _hurd_sigstate_unlock (ss);
783 reply ();
784 return NULL;
787 handler = _hurd_sigstate_actions (ss) [signo].sa_handler;
789 if (handler == SIG_DFL)
790 /* Figure out the default action for this signal. */
791 switch (signo)
793 case 0:
794 /* A sig_post msg with SIGNO==0 is sent to
795 tell us to check for pending signals. */
796 act = ignore;
797 break;
799 case SIGTTIN:
800 case SIGTTOU:
801 case SIGSTOP:
802 case SIGTSTP:
803 act = stop;
804 break;
806 case SIGCONT:
807 case SIGIO:
808 case SIGURG:
809 case SIGCHLD:
810 case SIGWINCH:
811 act = ignore;
812 break;
814 case SIGQUIT:
815 case SIGILL:
816 case SIGTRAP:
817 case SIGIOT:
818 case SIGEMT:
819 case SIGFPE:
820 case SIGBUS:
821 case SIGSEGV:
822 case SIGSYS:
823 act = core;
824 break;
826 case SIGINFO:
827 if (_hurd_pgrp == _hurd_pid)
829 /* We are the process group leader. Since there is no
830 user-specified handler for SIGINFO, we use a default one
831 which prints something interesting. We use the normal
832 handler mechanism instead of just doing it here to avoid
833 the signal thread faulting or blocking in this
834 potentially hairy operation. */
835 act = handle;
836 handler = _hurd_siginfo_handler;
838 else
839 act = ignore;
840 break;
842 default:
843 act = term;
844 break;
846 else if (handler == SIG_IGN)
847 act = ignore;
848 else
849 act = handle;
851 if (__sigmask (signo) & STOPSIGS)
852 /* Stop signals clear a pending SIGCONT even if they
853 are handled or ignored (but not if preempted). */
854 __sigdelset (&ss->pending, SIGCONT);
855 else
857 if (signo == SIGCONT)
858 /* Even if handled or ignored (but not preempted), SIGCONT clears
859 stop signals and resumes the process. */
860 ss->pending &= ~STOPSIGS;
862 if (_hurd_stopped && act != stop && (untraced || signo == SIGCONT))
863 resume ();
867 if (_hurd_orphaned && act == stop
868 && (__sigmask (signo) & (__sigmask (SIGTTIN) | __sigmask (SIGTTOU)
869 | __sigmask (SIGTSTP))))
871 /* If we would ordinarily stop for a job control signal, but we are
872 orphaned so noone would ever notice and continue us again, we just
873 quietly die, alone and in the dark. */
874 detail->code = signo;
875 signo = SIGKILL;
876 act = term;
879 /* Handle receipt of a blocked signal, or any signal while stopped. */
880 if (__sigismember (&blocked, signo) || (signo != SIGKILL && _hurd_stopped))
882 mark_pending ();
883 act = ignore;
886 /* Perform the chosen action for the signal. */
887 switch (act)
889 case stop:
890 if (_hurd_stopped)
892 /* We are already stopped, but receiving an untraced stop
893 signal. Instead of resuming and suspending again, just
894 notify the proc server of the new stop signal. */
895 error_t err = __USEPORT (PROC, __proc_mark_stop
896 (port, signo, detail->code));
897 assert_perror (err);
899 else
900 /* Suspend the process. */
901 suspend ();
902 break;
904 case ignore:
905 if (detail->exc)
906 /* Blocking or ignoring a machine exception is fatal.
907 Otherwise we could just spin on the faulting instruction. */
908 goto fatal;
910 /* Nobody cares about this signal. If there was a call to resume
911 above in SIGCONT processing and we've left a thread suspended,
912 now's the time to set it going. */
913 if (ss_suspended)
915 assert (ss->thread != MACH_PORT_NULL);
916 err = __thread_resume (ss->thread);
917 assert_perror (err);
918 ss_suspended = 0;
920 break;
922 sigbomb:
923 /* We got a fault setting up the stack frame for the handler.
924 Nothing to do but die; BSD gets SIGILL in this case. */
925 detail->code = signo; /* XXX ? */
926 signo = SIGILL;
928 fatal:
929 act = core;
930 /* FALLTHROUGH */
932 case term: /* Time to die. */
933 case core: /* And leave a rotting corpse. */
934 /* Have the proc server stop all other threads in our task. */
935 err = __USEPORT (PROC, __proc_dostop (port, _hurd_msgport_thread));
936 assert_perror (err);
937 /* No more user instructions will be executed.
938 The signal can now be considered delivered. */
939 reply ();
940 /* Abort all server operations now in progress. */
941 abort_all_rpcs (signo, &thread_state, 0);
944 int status = W_EXITCODE (0, signo);
945 /* Do a core dump if desired. Only set the wait status bit saying we
946 in fact dumped core if the operation was actually successful. */
947 if (act == core && write_corefile (signo, detail))
948 status |= WCOREFLAG;
949 /* Tell proc how we died and then stick the saber in the gut. */
950 _hurd_exit (status);
951 /* NOTREACHED */
954 case handle:
955 /* Call a handler for this signal. */
957 struct sigcontext *scp, ocontext;
958 int wait_for_reply, state_changed;
960 assert (ss->thread != MACH_PORT_NULL);
962 /* Stop the thread and abort its pending RPC operations. */
963 if (! ss_suspended)
965 err = __thread_suspend (ss->thread);
966 assert_perror (err);
969 /* Abort the thread's kernel context, so any pending message send
970 or receive completes immediately or aborts. If an interruptible
971 RPC is in progress, abort_rpcs will do this. But we must always
972 do it before fetching the thread's state, because
973 thread_get_state is never kosher before thread_abort. */
974 abort_thread (ss, &thread_state, NULL);
976 if (ss->context)
978 /* We have a previous sigcontext that sigreturn was about
979 to restore when another signal arrived. */
981 mach_port_t *loc;
983 if (_hurdsig_catch_memory_fault (ss->context))
985 /* We faulted reading the thread's stack. Forget that
986 context and pretend it wasn't there. It almost
987 certainly crash if this handler returns, but that's it's
988 problem. */
989 ss->context = NULL;
991 else
993 /* Copy the context from the thread's stack before
994 we start diddling the stack to set up the handler. */
995 ocontext = *ss->context;
996 ss->context = &ocontext;
998 _hurdsig_end_catch_fault ();
1000 if (! machine_get_basic_state (ss->thread, &thread_state))
1001 goto sigbomb;
1002 loc = interrupted_reply_port_location (ss->thread,
1003 &thread_state, 1);
1004 if (loc && *loc != MACH_PORT_NULL)
1005 /* This is the reply port for the context which called
1006 sigreturn. Since we are abandoning that context entirely
1007 and restoring SS->context instead, destroy this port. */
1008 __mach_port_destroy (__mach_task_self (), *loc);
1010 /* The thread was in sigreturn, not in any interruptible RPC. */
1011 wait_for_reply = 0;
1013 assert (! __spin_lock_locked (&ss->critical_section_lock));
1015 else
1017 int crit = __spin_lock_locked (&ss->critical_section_lock);
1019 wait_for_reply
1020 = (_hurdsig_abort_rpcs (ss,
1021 /* In a critical section, any RPC
1022 should be cancelled instead of
1023 restarted, regardless of
1024 SA_RESTART, so the entire
1025 "atomic" operation can be aborted
1026 as a unit. */
1027 crit ? 0 : signo, 1,
1028 &thread_state, &state_changed,
1029 reply)
1030 != MACH_PORT_NULL);
1032 if (crit)
1034 /* The thread is in a critical section. Mark the signal as
1035 pending. When it finishes the critical section, it will
1036 check for pending signals. */
1037 mark_pending ();
1038 if (state_changed)
1039 /* Some cases of interrupting an RPC must change the
1040 thread state to back out the call. Normally this
1041 change is rolled into the warping to the handler and
1042 sigreturn, but we are not running the handler now
1043 because the thread is in a critical section. Instead,
1044 mutate the thread right away for the RPC interruption
1045 and resume it; the RPC will return early so the
1046 critical section can end soon. */
1047 __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
1048 (natural_t *) &thread_state.basic,
1049 MACHINE_THREAD_STATE_COUNT);
1050 /* */
1051 ss->intr_port = MACH_PORT_NULL;
1052 __thread_resume (ss->thread);
1053 break;
1057 /* Call the machine-dependent function to set the thread up
1058 to run the signal handler, and preserve its old context. */
1059 scp = _hurd_setup_sighandler (ss, handler, signo, detail,
1060 wait_for_reply, &thread_state);
1061 if (scp == NULL)
1062 goto sigbomb;
1064 /* Set the machine-independent parts of the signal context. */
1067 /* Fetch the thread variable for the MiG reply port,
1068 and set it to MACH_PORT_NULL. */
1069 mach_port_t *loc = interrupted_reply_port_location (ss->thread,
1070 &thread_state,
1072 if (loc)
1074 scp->sc_reply_port = *loc;
1075 *loc = MACH_PORT_NULL;
1077 else
1078 scp->sc_reply_port = MACH_PORT_NULL;
1080 /* Save the intr_port in use by the interrupted code,
1081 and clear the cell before running the trampoline. */
1082 scp->sc_intr_port = ss->intr_port;
1083 ss->intr_port = MACH_PORT_NULL;
1085 if (ss->context)
1087 /* After the handler runs we will restore to the state in
1088 SS->context, not the state of the thread now. So restore
1089 that context's reply port and intr port. */
1091 scp->sc_reply_port = ss->context->sc_reply_port;
1092 scp->sc_intr_port = ss->context->sc_intr_port;
1094 ss->context = NULL;
1098 struct sigaction *action = & _hurd_sigstate_actions (ss) [signo];
1100 /* Backdoor extra argument to signal handler. */
1101 scp->sc_error = detail->error;
1103 /* Block requested signals while running the handler. */
1104 scp->sc_mask = ss->blocked;
1105 __sigorset (&ss->blocked, &ss->blocked, &action->sa_mask);
1107 /* Also block SIGNO unless we're asked not to. */
1108 if (! (action->sa_flags & (SA_RESETHAND | SA_NODEFER)))
1109 __sigaddset (&ss->blocked, signo);
1111 /* Reset to SIG_DFL if requested. SIGILL and SIGTRAP cannot
1112 be automatically reset when delivered; the system silently
1113 enforces this restriction. */
1114 if (action->sa_flags & SA_RESETHAND
1115 && signo != SIGILL && signo != SIGTRAP)
1116 action->sa_handler = SIG_DFL;
1118 /* Any sigsuspend call must return after the handler does. */
1119 wake_sigsuspend (ss);
1121 /* Start the thread running the handler (or possibly waiting for an
1122 RPC reply before running the handler). */
1123 err = __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
1124 (natural_t *) &thread_state.basic,
1125 MACHINE_THREAD_STATE_COUNT);
1126 assert_perror (err);
1127 err = __thread_resume (ss->thread);
1128 assert_perror (err);
1129 thread_state.set = 0; /* Everything we know is now wrong. */
1130 break;
1134 return ss;
1137 /* Return the set of pending signals in SS which should be delivered. */
1138 static sigset_t
1139 pending_signals (struct hurd_sigstate *ss)
1141 /* We don't worry about any pending signals if we are stopped, nor if
1142 SS is in a critical section. We are guaranteed to get a sig_post
1143 message before any of them become deliverable: either the SIGCONT
1144 signal, or a sig_post with SIGNO==0 as an explicit poll when the
1145 thread finishes its critical section. */
1146 if (_hurd_stopped || __spin_lock_locked (&ss->critical_section_lock))
1147 return 0;
1149 return _hurd_sigstate_pending (ss) & ~ss->blocked;
1152 /* Post the specified pending signals in SS and return 1. If one of
1153 them is traced, abort immediately and return 0. SS must be locked on
1154 entry and will be unlocked in all cases. */
1155 static int
1156 post_pending (struct hurd_sigstate *ss, sigset_t pending, void (*reply) (void))
1158 int signo;
1159 struct hurd_signal_detail detail;
1161 /* Make sure SS corresponds to an actual thread, since we assume it won't
1162 change in post_signal. */
1163 assert (ss->thread != MACH_PORT_NULL);
1165 for (signo = 1; signo < NSIG; ++signo)
1166 if (__sigismember (&pending, signo))
1168 detail = sigstate_clear_pending (ss, signo);
1169 _hurd_sigstate_unlock (ss);
1171 /* Will reacquire the lock, except if the signal is traced. */
1172 if (! post_signal (ss, signo, &detail, 0, reply))
1173 return 0;
1176 /* No more signals pending; SS->lock is still locked. */
1177 _hurd_sigstate_unlock (ss);
1179 return 1;
1182 /* Post all the pending signals of all threads and return 1. If a traced
1183 signal is encountered, abort immediately and return 0. */
1184 static int
1185 post_all_pending_signals (void (*reply) (void))
1187 struct hurd_sigstate *ss;
1188 sigset_t pending = 0;
1190 for (;;)
1192 __mutex_lock (&_hurd_siglock);
1193 for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
1195 _hurd_sigstate_lock (ss);
1197 pending = pending_signals (ss);
1198 if (pending)
1199 /* post_pending() below will unlock SS. */
1200 break;
1202 _hurd_sigstate_unlock (ss);
1204 __mutex_unlock (&_hurd_siglock);
1206 if (! pending)
1207 return 1;
1208 if (! post_pending (ss, pending, reply))
1209 return 0;
1213 /* Deliver a signal. SS is not locked. */
1214 void
1215 _hurd_internal_post_signal (struct hurd_sigstate *ss,
1216 int signo, struct hurd_signal_detail *detail,
1217 mach_port_t reply_port,
1218 mach_msg_type_name_t reply_port_type,
1219 int untraced)
1221 /* Reply to this sig_post message. */
1222 __typeof (__msg_sig_post_reply) *reply_rpc
1223 = (untraced ? __msg_sig_post_untraced_reply : __msg_sig_post_reply);
1224 void reply (void)
1226 error_t err;
1227 if (reply_port == MACH_PORT_NULL)
1228 return;
1229 err = (*reply_rpc) (reply_port, reply_port_type, 0);
1230 reply_port = MACH_PORT_NULL;
1231 if (err != MACH_SEND_INVALID_DEST) /* Ignore dead reply port. */
1232 assert_perror (err);
1235 ss = post_signal (ss, signo, detail, untraced, reply);
1236 if (! ss)
1237 return;
1239 /* The signal was neither fatal nor traced. We still hold SS->lock. */
1240 if (signo != 0 && ss->thread != MACH_PORT_NULL)
1242 /* The signal has either been ignored or is now being handled. We can
1243 consider it delivered and reply to the killer. */
1244 reply ();
1246 /* Post any pending signals for this thread. */
1247 if (! post_pending (ss, pending_signals (ss), reply))
1248 return;
1250 else
1252 /* If this was a process-wide signal or a poll request, we need
1253 to check for pending signals for all threads. */
1254 _hurd_sigstate_unlock (ss);
1255 if (! post_all_pending_signals (reply))
1256 return;
1258 /* All pending signals delivered to all threads.
1259 Now we can send the reply message even for signal 0. */
1260 reply ();
1264 /* Decide whether REFPORT enables the sender to send us a SIGNO signal.
1265 Returns zero if so, otherwise the error code to return to the sender. */
1267 static error_t
1268 signal_allowed (int signo, mach_port_t refport)
1270 if (signo < 0 || signo >= NSIG)
1271 return EINVAL;
1273 if (refport == __mach_task_self ())
1274 /* Can send any signal. */
1275 goto win;
1277 /* Avoid needing to check for this below. */
1278 if (refport == MACH_PORT_NULL)
1279 return EPERM;
1281 switch (signo)
1283 case SIGINT:
1284 case SIGQUIT:
1285 case SIGTSTP:
1286 case SIGHUP:
1287 case SIGINFO:
1288 case SIGTTIN:
1289 case SIGTTOU:
1290 case SIGWINCH:
1291 /* Job control signals can be sent by the controlling terminal. */
1292 if (__USEPORT (CTTYID, port == refport))
1293 goto win;
1294 break;
1296 case SIGCONT:
1298 /* A continue signal can be sent by anyone in the session. */
1299 mach_port_t sessport;
1300 if (! __USEPORT (PROC, __proc_getsidport (port, &sessport)))
1302 __mach_port_deallocate (__mach_task_self (), sessport);
1303 if (refport == sessport)
1304 goto win;
1307 break;
1309 case SIGIO:
1310 case SIGURG:
1312 /* Any io object a file descriptor refers to might send us
1313 one of these signals using its async ID port for REFPORT.
1315 This is pretty wide open; it is not unlikely that some random
1316 process can at least open for reading something we have open,
1317 get its async ID port, and send us a spurious SIGIO or SIGURG
1318 signal. But BSD is actually wider open than that!--you can set
1319 the owner of an io object to any process or process group
1320 whatsoever and send them gratuitous signals.
1322 Someday we could implement some reasonable scheme for
1323 authorizing SIGIO and SIGURG signals properly. */
1325 int d;
1326 int lucky = 0; /* True if we find a match for REFPORT. */
1327 __mutex_lock (&_hurd_dtable_lock);
1328 for (d = 0; !lucky && (unsigned) d < (unsigned) _hurd_dtablesize; ++d)
1330 struct hurd_userlink ulink;
1331 io_t port;
1332 mach_port_t asyncid;
1333 if (_hurd_dtable[d] == NULL)
1334 continue;
1335 port = _hurd_port_get (&_hurd_dtable[d]->port, &ulink);
1336 if (! __io_get_icky_async_id (port, &asyncid))
1338 if (refport == asyncid)
1339 /* Break out of the loop on the next iteration. */
1340 lucky = 1;
1341 __mach_port_deallocate (__mach_task_self (), asyncid);
1343 _hurd_port_free (&_hurd_dtable[d]->port, &ulink, port);
1345 __mutex_unlock (&_hurd_dtable_lock);
1346 /* If we found a lucky winner, we've set D to -1 in the loop. */
1347 if (lucky)
1348 goto win;
1352 /* If this signal is legit, we have done `goto win' by now.
1353 When we return the error, mig deallocates REFPORT. */
1354 return EPERM;
1356 win:
1357 /* Deallocate the REFPORT send right; we are done with it. */
1358 __mach_port_deallocate (__mach_task_self (), refport);
1360 return 0;
1363 /* Implement the sig_post RPC from <hurd/msg.defs>;
1364 sent when someone wants us to get a signal. */
1365 kern_return_t
1366 _S_msg_sig_post (mach_port_t me,
1367 mach_port_t reply_port, mach_msg_type_name_t reply_port_type,
1368 int signo, natural_t sigcode,
1369 mach_port_t refport)
1371 error_t err;
1372 struct hurd_signal_detail d;
1374 if (err = signal_allowed (signo, refport))
1375 return err;
1377 d.code = sigcode;
1378 d.exc = 0;
1380 /* Post the signal to a global receiver thread (or mark it pending in
1381 the global sigstate). This will reply when the signal can be
1382 considered delivered. */
1383 _hurd_internal_post_signal (_hurd_global_sigstate,
1384 signo, &d, reply_port, reply_port_type,
1385 0); /* Stop if traced. */
1387 return MIG_NO_REPLY; /* Already replied. */
1390 /* Implement the sig_post_untraced RPC from <hurd/msg.defs>;
1391 sent when the debugger wants us to really get a signal
1392 even if we are traced. */
1393 kern_return_t
1394 _S_msg_sig_post_untraced (mach_port_t me,
1395 mach_port_t reply_port,
1396 mach_msg_type_name_t reply_port_type,
1397 int signo, natural_t sigcode,
1398 mach_port_t refport)
1400 error_t err;
1401 struct hurd_signal_detail d;
1403 if (err = signal_allowed (signo, refport))
1404 return err;
1406 d.code = sigcode;
1407 d.exc = 0;
1409 /* Post the signal to the designated signal-receiving thread. This will
1410 reply when the signal can be considered delivered. */
1411 _hurd_internal_post_signal (_hurd_global_sigstate,
1412 signo, &d, reply_port, reply_port_type,
1413 1); /* Untraced flag. */
1415 return MIG_NO_REPLY; /* Already replied. */
1418 extern void __mig_init (void *);
1420 #include <mach/task_special_ports.h>
1422 /* Initialize the message port, _hurd_global_sigstate, and start the
1423 signal thread. */
1425 void
1426 _hurdsig_init (const int *intarray, size_t intarraysize)
1428 error_t err;
1429 vm_size_t stacksize;
1430 struct hurd_sigstate *ss;
1432 __mutex_init (&_hurd_siglock);
1434 err = __mach_port_allocate (__mach_task_self (),
1435 MACH_PORT_RIGHT_RECEIVE,
1436 &_hurd_msgport);
1437 assert_perror (err);
1439 /* Make a send right to the signal port. */
1440 err = __mach_port_insert_right (__mach_task_self (),
1441 _hurd_msgport,
1442 _hurd_msgport,
1443 MACH_MSG_TYPE_MAKE_SEND);
1444 assert_perror (err);
1446 /* Initialize the global signal state. */
1447 _hurd_global_sigstate = _hurd_thread_sigstate (MACH_PORT_NULL);
1449 /* We block all signals, and let actual threads pull them from the
1450 pending mask. */
1451 __sigfillset(& _hurd_global_sigstate->blocked);
1453 /* Initialize the main thread's signal state. */
1454 ss = _hurd_self_sigstate ();
1456 /* Mark it as a process-wide signal receiver. Threads in this set use
1457 the common action vector in _hurd_global_sigstate. */
1458 _hurd_sigstate_set_global_rcv (ss);
1460 /* Copy inherited signal settings from our parent (or pre-exec process
1461 state) */
1462 if (intarraysize > INIT_SIGMASK)
1463 ss->blocked = intarray[INIT_SIGMASK];
1464 if (intarraysize > INIT_SIGPENDING)
1465 _hurd_global_sigstate->pending = intarray[INIT_SIGPENDING];
1466 if (intarraysize > INIT_SIGIGN && intarray[INIT_SIGIGN] != 0)
1468 int signo;
1469 for (signo = 1; signo < NSIG; ++signo)
1470 if (intarray[INIT_SIGIGN] & __sigmask(signo))
1471 _hurd_global_sigstate->actions[signo].sa_handler = SIG_IGN;
1474 /* Start the signal thread listening on the message port. */
1476 #pragma weak __cthread_fork
1477 if (!__cthread_fork)
1479 err = __thread_create (__mach_task_self (), &_hurd_msgport_thread);
1480 assert_perror (err);
1482 stacksize = __vm_page_size * 8; /* Small stack for signal thread. */
1483 err = __mach_setup_thread (__mach_task_self (), _hurd_msgport_thread,
1484 _hurd_msgport_receive,
1485 (vm_address_t *) &__hurd_sigthread_stack_base,
1486 &stacksize);
1487 assert_perror (err);
1488 err = __mach_setup_tls (_hurd_msgport_thread);
1489 assert_perror (err);
1491 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + stacksize;
1493 /* Reinitialize the MiG support routines so they will use a per-thread
1494 variable for the cached reply port. */
1495 __mig_init ((void *) __hurd_sigthread_stack_base);
1497 err = __thread_resume (_hurd_msgport_thread);
1498 assert_perror (err);
1500 else
1502 /* When cthreads is being used, we need to make the signal thread a
1503 proper cthread. Otherwise it cannot use mutex_lock et al, which
1504 will be the cthreads versions. Various of the message port RPC
1505 handlers need to take locks, so we need to be able to call into
1506 cthreads code and meet its assumptions about how our thread and
1507 its stack are arranged. Since cthreads puts it there anyway,
1508 we'll let the signal thread's per-thread variables be found as for
1509 any normal cthread, and just leave the magic __hurd_sigthread_*
1510 values all zero so they'll be ignored. */
1511 #pragma weak __cthread_detach
1512 #pragma weak __pthread_getattr_np
1513 #pragma weak __pthread_attr_getstack
1514 __cthread_t thread = __cthread_fork (
1515 (cthread_fn_t) &_hurd_msgport_receive, 0);
1516 __cthread_detach (thread);
1518 if (__pthread_getattr_np)
1520 /* Record signal thread stack layout for fork() */
1521 pthread_attr_t attr;
1522 void *addr;
1523 size_t size;
1525 __pthread_getattr_np ((pthread_t) thread, &attr);
1526 __pthread_attr_getstack (&attr, &addr, &size);
1527 __hurd_sigthread_stack_base = (uintptr_t) addr;
1528 __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + size;
1531 /* XXX We need the thread port for the signal thread further on
1532 in this thread (see hurdfault.c:_hurdsigfault_init).
1533 Therefore we block until _hurd_msgport_thread is initialized
1534 by the newly created thread. This really shouldn't be
1535 necessary; we should be able to fetch the thread port for a
1536 cthread from here. */
1537 while (_hurd_msgport_thread == 0)
1538 __swtch_pri (0);
1541 /* Receive exceptions on the signal port. */
1542 #ifdef TASK_EXCEPTION_PORT
1543 __task_set_special_port (__mach_task_self (),
1544 TASK_EXCEPTION_PORT, _hurd_msgport);
1545 #elif defined (EXC_MASK_ALL)
1546 __task_set_exception_ports (__mach_task_self (),
1547 EXC_MASK_ALL & ~(EXC_MASK_SYSCALL
1548 | EXC_MASK_MACH_SYSCALL
1549 | EXC_MASK_RPC_ALERT),
1550 _hurd_msgport,
1551 EXCEPTION_DEFAULT, MACHINE_THREAD_STATE);
1552 #else
1553 # error task_set_exception_port?
1554 #endif
1556 /* Sanity check. Any pending, unblocked signals should have been
1557 taken by our predecessor incarnation (i.e. parent or pre-exec state)
1558 before packing up our init ints. This assert is last (not above)
1559 so that signal handling is all set up to handle the abort. */
1560 assert ((ss->pending &~ ss->blocked) == 0);
1562 \f /* XXXX */
1563 /* Reauthenticate with the proc server. */
1565 static void
1566 reauth_proc (mach_port_t new)
1568 mach_port_t ref, ignore;
1570 ref = __mach_reply_port ();
1571 if (! HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1572 __proc_reauthenticate (port, ref,
1573 MACH_MSG_TYPE_MAKE_SEND)
1574 || __auth_user_authenticate (new, ref,
1575 MACH_MSG_TYPE_MAKE_SEND,
1576 &ignore))
1577 && ignore != MACH_PORT_NULL)
1578 __mach_port_deallocate (__mach_task_self (), ignore);
1579 __mach_port_destroy (__mach_task_self (), ref);
1581 /* Set the owner of the process here too. */
1582 __mutex_lock (&_hurd_id.lock);
1583 if (!_hurd_check_ids ())
1584 HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1585 __proc_setowner (port,
1586 (_hurd_id.gen.nuids
1587 ? _hurd_id.gen.uids[0] : 0),
1588 !_hurd_id.gen.nuids));
1589 __mutex_unlock (&_hurd_id.lock);
1591 (void) &reauth_proc; /* Silence compiler warning. */
1593 text_set_element (_hurd_reauth_hook, reauth_proc);
1595 /* Like `getenv', but safe for the signal thread to run.
1596 If the environment is trashed, this will just return NULL. */
1598 const char *
1599 _hurdsig_getenv (const char *variable)
1601 if (__libc_enable_secure)
1602 return NULL;
1604 if (_hurdsig_catch_memory_fault (__environ))
1605 /* We bombed in getenv. */
1606 return NULL;
1607 else
1609 const size_t len = strlen (variable);
1610 char *value = NULL;
1611 char *volatile *ep = __environ;
1612 while (*ep)
1614 const char *p = *ep;
1615 _hurdsig_fault_preemptor.first = (long int) p;
1616 _hurdsig_fault_preemptor.last = VM_MAX_ADDRESS;
1617 if (! strncmp (p, variable, len) && p[len] == '=')
1619 size_t valuelen;
1620 p += len + 1;
1621 valuelen = strlen (p);
1622 _hurdsig_fault_preemptor.last = (long int) (p + valuelen);
1623 value = malloc (++valuelen);
1624 if (value)
1625 memcpy (value, p, valuelen);
1626 break;
1628 _hurdsig_fault_preemptor.first = (long int) ++ep;
1629 _hurdsig_fault_preemptor.last = (long int) (ep + 1);
1631 _hurdsig_end_catch_fault ();
1632 return value;