(_hurd_internal_post_signal: suspend): Reply after aborting RPCs but before calling...
[platform/upstream/glibc.git] / hurd / hurdsig.c
1 /* Copyright (C) 1991, 1992, 1993, 1994, 1995 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
8
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 Library General Public License for more details.
13
14 You should have received a copy of the GNU Library General Public
15 License along with the GNU C Library; see the file COPYING.LIB.  If
16 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
17 Cambridge, MA 02139, USA.  */
18
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <hurd.h>
22 #include <hurd/signal.h>
23 #include <cthreads.h>           /* For `struct mutex'.  */
24 #include <string.h>
25 #include "hurdfault.h"
26 #include "hurdmalloc.h"         /* XXX */
27
28 const char *_hurdsig_getenv (const char *);
29
30 struct mutex _hurd_siglock;
31 int _hurd_stopped;
32
33 /* Port that receives signals and other miscellaneous messages.  */
34 mach_port_t _hurd_msgport;
35
36 /* Thread listening on it.  */
37 thread_t _hurd_msgport_thread;
38
39 /* Thread which receives task-global signals.  */
40 thread_t _hurd_sigthread;
41
42 /* Linked-list of per-thread signal state.  */
43 struct hurd_sigstate *_hurd_sigstates;
44
45 /* Timeout for RPC's after interrupt_operation. */
46 mach_msg_timeout_t _hurd_interrupted_rpc_timeout = 3000;
47 \f
48 static void
49 default_sigaction (struct sigaction actions[NSIG])
50 {
51   int signo;
52
53   __sigemptyset (&actions[0].sa_mask);
54   actions[0].sa_flags = SA_RESTART;
55   actions[0].sa_handler = SIG_DFL;
56
57   for (signo = 1; signo < NSIG; ++signo)
58     actions[signo] = actions[0];
59 }
60
61 struct hurd_sigstate *
62 _hurd_thread_sigstate (thread_t thread)
63 {
64   struct hurd_sigstate *ss;
65   __mutex_lock (&_hurd_siglock);
66   for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
67     if (ss->thread == thread)
68        break;
69   if (ss == NULL)
70     {
71       ss = malloc (sizeof (*ss));
72       if (ss == NULL)
73         __libc_fatal ("hurd: Can't allocate thread sigstate\n");
74       ss->thread = thread;
75       __spin_lock_init (&ss->lock);
76
77       /* Initialze default state.  */
78       __sigemptyset (&ss->blocked);
79       __sigemptyset (&ss->pending);
80       memset (&ss->sigaltstack, 0, sizeof (ss->sigaltstack));
81       ss->suspended = 0;
82       ss->intr_port = MACH_PORT_NULL;
83       ss->context = NULL;
84
85       /* Initialize the sigaction vector from the default signal receiving
86          thread's state, and its from the system defaults.  */
87       if (thread == _hurd_sigthread)
88         default_sigaction (ss->actions);
89       else
90         {
91           struct hurd_sigstate *s;
92           for (s = _hurd_sigstates; s != NULL; s = s->next)
93             if (s->thread == _hurd_sigthread)
94               break;
95           if (s)
96             {
97               __spin_lock (&s->lock);
98               memcpy (ss->actions, s->actions, sizeof (s->actions));
99               __spin_unlock (&s->lock);
100             }
101           else
102             default_sigaction (ss->actions);
103         }
104
105       ss->next = _hurd_sigstates;
106       _hurd_sigstates = ss;
107     }
108   __mutex_unlock (&_hurd_siglock);
109   return ss;
110 }
111 \f
112 /* Signal delivery itself is on this page.  */
113
114 #include <hurd/fd.h>
115 #include <hurd/crash.h>
116 #include <hurd/paths.h>
117 #include <setjmp.h>
118 #include <fcntl.h>
119 #include <sys/wait.h>
120 #include "thread_state.h"
121 #include <hurd/msg_server.h>
122 #include <hurd/msg_reply.h>     /* For __msg_sig_post_reply.  */
123 #include <assert.h>
124 #include <hurd/interrupt.h>
125
126 int _hurd_core_limit;   /* XXX */
127
128 /* Call the crash dump server to mummify us before we die.
129    Returns nonzero if a core file was written.  */
130 static int
131 write_corefile (int signo, long int sigcode, int sigerror)
132 {
133   error_t err;
134   mach_port_t coreserver;
135   file_t file, coredir;
136   const char *name;
137
138   /* XXX RLIMIT_CORE:
139      When we have a protocol to make the server return an error
140      for RLIMIT_FSIZE, then tell the corefile fs server the RLIMIT_CORE
141      value in place of the RLIMIT_FSIZE value.  */
142
143   /* First get a port to the core dumping server.  */
144   coreserver = MACH_PORT_NULL;
145   name = _hurdsig_getenv ("CRASHSERVER");
146   if (name != NULL)
147     coreserver = __file_name_lookup (name, 0, 0);
148   if (coreserver == MACH_PORT_NULL)
149     coreserver = __file_name_lookup (_SERVERS_CRASH, 0, 0);
150   if (coreserver == MACH_PORT_NULL)
151     return 0;
152
153   /* Get a port to the directory where the new core file will reside.  */
154   name = _hurdsig_getenv ("COREFILE");
155   if (name == NULL)
156     name = "core";
157   coredir = __file_name_split (name, (char **) &name);
158   if (coredir == MACH_PORT_NULL)
159     return 0;
160   /* Create the new file, but don't link it into the directory yet.  */
161   if (err = __dir_mkfile (coredir, O_WRONLY|O_CREAT,
162                           0600 & ~_hurd_umask, /* XXX ? */
163                           &file))
164     return 0;
165
166   /* Call the core dumping server to write the core file.  */
167   err = __crash_dump_task (coreserver,
168                            __mach_task_self (),
169                            file, _hurdsig_getenv ("GNUTARGET"),
170                            signo, sigcode, sigerror);
171   __mach_port_deallocate (__mach_task_self (), coreserver);
172   if (! err)
173     /* The core dump into FILE succeeded, so now link it into the
174        directory.  */
175     err = __dir_link (file, coredir, name);
176   __mach_port_deallocate (__mach_task_self (), file);
177   __mach_port_deallocate (__mach_task_self (), coredir);
178   return !err;
179 }
180
181
182 /* The lowest-numbered thread state flavor value is 1,
183    so we use bit 0 in machine_thread_all_state.set to
184    record whether we have done thread_abort.  */
185 #define THREAD_ABORTED 1
186
187 /* SS->thread is suspended.  Abort the thread and get its basic state.  */
188 static void
189 abort_thread (struct hurd_sigstate *ss, struct machine_thread_all_state *state,
190               void (*reply) (void))
191 {
192   if (!(state->set & THREAD_ABORTED))
193     {
194       error_t err = __thread_abort (ss->thread);
195       assert_perror (err);
196       /* Clear all thread state flavor set bits, because thread_abort may
197          have changed the state.  */
198       state->set = THREAD_ABORTED;
199     }
200
201   if (reply)
202     (*reply) ();
203
204   machine_get_basic_state (ss->thread, state);
205 }
206
207 /* Find the location of the MiG reply port cell in use by the thread whose
208    state is described by THREAD_STATE.  If SIGTHREAD is nonzero, make sure
209    that this location can be set without faulting, or else return NULL.  */
210
211 static mach_port_t *
212 interrupted_reply_port_location (struct machine_thread_all_state *thread_state,
213                                  int sigthread)
214 {
215   mach_port_t *portloc = (mach_port_t *) __hurd_threadvar_location_from_sp
216     (_HURD_THREADVAR_MIG_REPLY, (void *) thread_state->basic.SP);
217
218   if (sigthread && _hurdsig_catch_fault (SIGSEGV))
219     {
220       assert (_hurdsig_fault_sigcode == (long int) portloc);
221       /* Faulted trying to read the stack.  */
222       return NULL;
223     }
224
225   /* Fault now if this pointer is bogus.  */
226   *(volatile mach_port_t *) portloc = *portloc;
227
228   if (sigthread)
229     _hurdsig_end_catch_fault ();
230
231   return portloc;
232 }
233 \f
234 #include "intr-msg.h"
235
236 /* SS->thread is suspended.
237
238    Abort any interruptible RPC operation the thread is doing.
239
240    This uses only the constant member SS->thread and the unlocked, atomically
241    set member SS->intr_port, so no locking is needed.
242
243    If successfully sent an interrupt_operation and therefore the thread should
244    wait for its pending RPC to return (possibly EINTR) before taking the
245    incoming signal, returns the reply port to be received on.  Otherwise
246    returns MACH_PORT_NULL.
247
248    SIGNO is used to find the applicable SA_RESTART bit.  If SIGNO is zero,
249    the RPC fails with EINTR instead of restarting (thread_cancel).
250
251    *STATE_CHANGE is set nonzero if STATE->basic was modified and should
252    be applied back to the thread if it might ever run again, else zero.  */
253
254 mach_port_t
255 _hurdsig_abort_rpcs (struct hurd_sigstate *ss, int signo, int sigthread,
256                      struct machine_thread_all_state *state, int *state_change,
257                      void (*reply) (void))
258 {
259   extern const void _hurd_intr_rpc_msg_in_trap;
260   mach_port_t rcv_port = MACH_PORT_NULL;
261   mach_port_t intr_port;
262
263   *state_change = 0;
264
265   intr_port = ss->intr_port;
266   if (intr_port == MACH_PORT_NULL)
267     /* No interruption needs done.  */
268     return MACH_PORT_NULL;
269
270   /* Abort the thread's kernel context, so any pending message send or
271      receive completes immediately or aborts.  */
272   abort_thread (ss, state, reply);
273
274   if (state->basic.PC < (natural_t) &_hurd_intr_rpc_msg_in_trap)
275     {
276       /* The thread is about to do the RPC, but hasn't yet entered
277          mach_msg.  Mutate the thread's state so it knows not to try
278          the RPC.  */
279       INTR_MSG_BACK_OUT (&state->basic);
280       MACHINE_THREAD_STATE_SET_PC (&state->basic,
281                                    &_hurd_intr_rpc_msg_in_trap);
282       state->basic.SYSRETURN = MACH_SEND_INTERRUPTED;
283       *state_change = 1;
284     }
285   else if (state->basic.PC == (natural_t) &_hurd_intr_rpc_msg_in_trap &&
286            /* The thread was blocked in the system call.  After thread_abort,
287               the return value register indicates what state the RPC was in
288               when interrupted.  */
289            state->basic.SYSRETURN == MACH_RCV_INTERRUPTED)
290       {
291         /* The RPC request message was sent and the thread was waiting for
292            the reply message; now the message receive has been aborted, so
293            the mach_msg call will return MACH_RCV_INTERRUPTED.  We must tell
294            the server to interrupt the pending operation.  The thread must
295            wait for the reply message before running the signal handler (to
296            guarantee that the operation has finished being interrupted), so
297            our nonzero return tells the trampoline code to finish the message
298            receive operation before running the handler.  */
299
300         mach_port_t *reply = interrupted_reply_port_location (state,
301                                                               sigthread);
302         error_t err = __interrupt_operation (intr_port);
303
304         if (err)
305           {
306             if (reply)
307               {
308                 /* The interrupt didn't work.
309                    Destroy the receive right the thread is blocked on.  */
310                 __mach_port_destroy (__mach_task_self (), *reply);
311                 *reply = MACH_PORT_NULL;
312               }
313
314             /* The system call return value register now contains
315                MACH_RCV_INTERRUPTED; when mach_msg resumes, it will retry the
316                call.  Since we have just destroyed the receive right, the
317                retry will fail with MACH_RCV_INVALID_NAME.  Instead, just
318                change the return value here to EINTR so mach_msg will not
319                retry and the EINTR error code will propagate up.  */
320             state->basic.SYSRETURN = EINTR;
321             *state_change = 1;
322           }
323         else if (reply)
324           rcv_port = *reply;
325
326         /* All threads whose RPCs were interrupted by the interrupt_operation
327            call above will retry their RPCs unless we clear SS->intr_port.
328            So we clear it for the thread taking a signal when SA_RESTART is
329            clear, so that its call returns EINTR.  */
330         if (! signo || !(ss->actions[signo].sa_flags & SA_RESTART))
331           ss->intr_port = MACH_PORT_NULL;
332       }
333
334   return rcv_port;
335 }
336
337
338 /* Abort the RPCs being run by all threads but this one;
339    all other threads should be suspended.  If LIVE is nonzero, those
340    threads may run again, so they should be adjusted as necessary to be
341    happy when resumed.  STATE is clobbered as a scratch area; its initial
342    contents are ignored, and its contents on return are not useful.  */
343
344 static void
345 abort_all_rpcs (int signo, struct machine_thread_all_state *state, int live)
346 {
347   /* We can just loop over the sigstates.  Any thread doing something
348      interruptible must have one.  We needn't bother locking because all
349      other threads are stopped.  */
350
351   struct hurd_sigstate *ss;
352   size_t nthreads;
353   mach_port_t *reply_ports;
354
355   /* First loop over the sigstates to count them.
356      We need to know how big a vector we will need for REPLY_PORTS.  */
357   nthreads = 0;
358   for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
359     ++nthreads;
360
361   reply_ports = alloca (nthreads * sizeof *reply_ports);
362
363   nthreads = 0;
364   for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
365     if (ss->thread == _hurd_msgport_thread)
366       reply_ports[nthreads++] = MACH_PORT_NULL;
367     else
368       {
369         int state_changed;
370         state->set = 0;         /* Reset scratch area.  */
371
372         /* Abort any operation in progress with interrupt_operation.
373            Record the reply port the thread is waiting on.
374            We will wait for all the replies below.  */
375         reply_ports[nthreads++] = _hurdsig_abort_rpcs (ss, signo, 1,
376                                                        state, &state_changed,
377                                                        NULL);
378         if (state_changed && live)
379           /* Aborting the RPC needed to change this thread's state,
380              and it might ever run again.  So write back its state.  */
381           __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
382                               (natural_t *) &state->basic,
383                               MACHINE_THREAD_STATE_COUNT);
384       }
385
386   /* Wait for replies from all the successfully interrupted RPCs.  */
387   while (nthreads-- > 0)
388     if (reply_ports[nthreads] != MACH_PORT_NULL)
389       {
390         error_t err;
391         mach_msg_header_t head;
392         err = __mach_msg (&head, MACH_RCV_MSG|MACH_RCV_TIMEOUT, 0, sizeof head,
393                           reply_ports[nthreads],
394                           _hurd_interrupted_rpc_timeout, MACH_PORT_NULL);
395         switch (err)
396           {
397           case MACH_RCV_TIMED_OUT:
398           case MACH_RCV_TOO_LARGE:
399             break;
400
401           default:
402             assert_perror (err);
403           }
404       }
405 }
406
407
408 struct hurd_signal_preempt *_hurd_signal_preempt[NSIG];
409 struct mutex _hurd_signal_preempt_lock;
410
411 /* Mask of stop signals.  */
412 #define STOPSIGS (sigmask (SIGTTIN) | sigmask (SIGTTOU) | \
413                   sigmask (SIGSTOP) | sigmask (SIGTSTP))
414
415 /* Deliver a signal.  SS is not locked.  */
416 void
417 _hurd_internal_post_signal (struct hurd_sigstate *ss,
418                             int signo, long int sigcode, int sigerror,
419                             mach_port_t reply_port,
420                             mach_msg_type_name_t reply_port_type,
421                             int untraced)
422 {
423   error_t err;
424   struct machine_thread_all_state thread_state;
425   enum { stop, ignore, core, term, handle } act;
426   sighandler_t handler;
427   struct hurd_signal_preempt *pe;
428   sighandler_t (*preempt) (thread_t, int, long int, int) = NULL;
429   sigset_t pending;
430   int ss_suspended;
431
432   /* Reply to this sig_post message.  */
433   __typeof (__msg_sig_post_reply) *reply_rpc
434     = (untraced ? __msg_sig_post_untraced_reply : __msg_sig_post_reply);
435   void reply (void)
436     {
437       error_t err;
438       if (reply_port == MACH_PORT_NULL)
439         return;
440       err = (*reply_rpc) (reply_port, reply_port_type, 0);
441       reply_port = MACH_PORT_NULL;
442       if (err != MACH_SEND_INVALID_DEST) /* Ignore dead reply port.  */
443         assert_perror (err);
444     }
445
446   /* Mark the signal as pending.  */
447   void mark_pending (void)
448     {
449       __sigaddset (&ss->pending, signo);
450       /* Save the code to be given to the handler when SIGNO is
451          unblocked.  */
452       ss->pending_data[signo].code = sigcode;
453       ss->pending_data[signo].error = sigerror;
454     }
455
456   /* Suspend the process with SIGNO.  */
457   void suspend (void)
458     {
459       /* Stop all other threads and mark ourselves stopped.  */
460       __USEPORT (PROC,
461                  ({
462                    /* Hold the siglock while stopping other threads to be
463                       sure it is not held by another thread afterwards.  */
464                    __mutex_lock (&_hurd_siglock);
465                    __proc_dostop (port, _hurd_msgport_thread);
466                    __mutex_unlock (&_hurd_siglock);
467                    abort_all_rpcs (signo, &thread_state, 1);
468                    reply ();
469                    __proc_mark_stop (port, signo);
470                  }));
471       _hurd_stopped = 1;
472     }
473   /* Resume the process after a suspension.  */
474   void resume (void)
475     {
476       /* Resume the process from being stopped.  */
477       thread_t *threads;
478       mach_msg_type_number_t nthreads, i;
479       error_t err;
480
481       if (! _hurd_stopped)
482         return;
483
484       /* Tell the proc server we are continuing.  */
485       __USEPORT (PROC, __proc_mark_cont (port));
486       /* Fetch ports to all our threads and resume them.  */
487       err = __task_threads (__mach_task_self (), &threads, &nthreads);
488       assert_perror (err);
489       for (i = 0; i < nthreads; ++i)
490         {
491           if (threads[i] != _hurd_msgport_thread &&
492               (act != handle || threads[i] != ss->thread))
493             {
494               err = __thread_resume (threads[i]);
495               assert_perror (err);
496             }
497           err = __mach_port_deallocate (__mach_task_self (),
498                                         threads[i]);
499           assert_perror (err);
500         }
501       __vm_deallocate (__mach_task_self (),
502                        (vm_address_t) threads,
503                        nthreads * sizeof *threads);
504       _hurd_stopped = 0;
505       /* The thread that will run the handler is already suspended.  */
506       ss_suspended = 1;
507     }
508
509   if (signo == 0)
510     {
511       if (untraced)
512         /* This is PTRACE_CONTINUE.  */
513         resume ();
514
515       /* This call is just to check for pending signals.  */
516       __spin_lock (&ss->lock);
517       goto check_pending_signals;
518     }
519
520  post_signal:
521
522   thread_state.set = 0;         /* We know nothing.  */
523
524   /* Check for a preempted signal.  Preempted signals
525      can arrive during critical sections.  */
526   __mutex_lock (&_hurd_signal_preempt_lock);
527   for (pe = _hurd_signal_preempt[signo]; pe != NULL; pe = pe->next)
528     if (pe->handler && sigcode >= pe->first && sigcode <= pe->last)
529       {
530         preempt = pe->handler;
531         break;
532       }
533   __mutex_unlock (&_hurd_signal_preempt_lock);
534
535   handler = SIG_DFL;
536   if (preempt)
537     /* Let the preempting handler examine the thread.
538        If it returns SIG_DFL, we run the normal handler;
539        otherwise we use the handler it returns.  */
540     handler = (*preempt) (ss->thread, signo, sigcode, sigerror);
541
542   ss_suspended = 0;
543
544   if (handler != SIG_DFL)
545     /* Run the preemption-provided handler.  */
546     act = handle;
547   else
548     {
549       /* No preemption.  Do normal handling.  */
550
551       __spin_lock (&ss->lock);
552
553       if (!untraced && (_hurd_exec_flags & EXEC_TRACED))
554         {
555           /* We are being traced.  Stop to tell the debugger of the signal.  */
556           if (_hurd_stopped)
557             /* Already stopped.  Mark the signal as pending;
558                when resumed, we will notice it and stop again.  */
559             mark_pending ();
560           else
561             suspend ();
562           __spin_unlock (&ss->lock);
563           reply ();
564           return;
565         }
566
567       handler = ss->actions[signo].sa_handler;
568
569       if (handler == SIG_DFL)
570         /* Figure out the default action for this signal.  */
571         switch (signo)
572           {
573           case 0:
574             /* A sig_post msg with SIGNO==0 is sent to
575                tell us to check for pending signals.  */
576             act = ignore;
577             break;
578
579           case SIGTTIN:
580           case SIGTTOU:
581           case SIGSTOP:
582           case SIGTSTP:
583             act = stop;
584             break;
585
586           case SIGCONT:
587           case SIGIO:
588           case SIGURG:
589           case SIGCHLD:
590           case SIGWINCH:
591             act = ignore;
592             break;
593
594           case SIGQUIT:
595           case SIGILL:
596           case SIGTRAP:
597           case SIGIOT:
598           case SIGEMT:
599           case SIGFPE:
600           case SIGBUS:
601           case SIGSEGV:
602           case SIGSYS:
603             act = core;
604             break;
605
606           case SIGINFO:
607             if (_hurd_pgrp == _hurd_pid)
608               {
609                 /* We are the process group leader.  Since there is no
610                    user-specified handler for SIGINFO, we use a default one
611                    which prints something interesting.  We use the normal
612                    handler mechanism instead of just doing it here to avoid
613                    the signal thread faulting or blocking in this
614                    potentially hairy operation.  */
615                 act = handle;
616                 handler = _hurd_siginfo_handler;
617               }
618             else
619               act = ignore;
620             break;
621
622           default:
623             act = term;
624             break;
625           }
626       else if (handler == SIG_IGN)
627         act = ignore;
628       else
629         act = handle;
630
631       if (__sigmask (signo) & STOPSIGS)
632         /* Stop signals clear a pending SIGCONT even if they
633            are handled or ignored (but not if preempted).  */
634         ss->pending &= ~sigmask (SIGCONT);
635       else
636         {
637           if (signo == SIGCONT)
638             /* Even if handled or ignored (but not preempted), SIGCONT clears
639                stop signals and resumes the process.  */
640             ss->pending &= ~STOPSIGS;
641
642           if (_hurd_stopped && act != stop && (untraced || signo == SIGCONT))
643             resume ();
644         }
645     }
646
647   if (_hurd_orphaned && act == stop &&
648       (__sigmask (signo) & (__sigmask (SIGTTIN) | __sigmask (SIGTTOU) |
649                             __sigmask (SIGTSTP))))
650     {
651       /* If we would ordinarily stop for a job control signal, but we are
652          orphaned so noone would ever notice and continue us again, we just
653          quietly die, alone and in the dark.  */
654       sigcode = signo;
655       signo = SIGKILL;
656       act = term;
657     }
658
659   /* Handle receipt of a blocked signal, or any signal while stopped.  */
660   if (__sigismember (&ss->blocked, signo) ||
661       (signo != SIGKILL && _hurd_stopped))
662     {
663       mark_pending ();
664       act = ignore;
665     }
666
667   /* Perform the chosen action for the signal.  */
668   switch (act)
669     {
670     case stop:
671       if (_hurd_stopped)
672         {
673           /* We are already stopped, but receiving an untraced stop
674              signal.  Instead of resuming and suspending again, just
675              notify the proc server of the new stop signal.  */
676           error_t err = __USEPORT (PROC, __proc_mark_stop (port, signo));
677           assert_perror (err);
678         }
679       else
680         /* Suspend the process.  */
681         suspend ();
682       break;
683
684     case ignore:
685       /* Nobody cares about this signal.  */
686       break;
687
688     sigbomb:
689       /* We got a fault setting up the stack frame for the handler.
690          Nothing to do but die; BSD gets SIGILL in this case.  */
691       sigcode = signo;  /* XXX ? */
692       signo = SIGILL;
693       act = core;
694       /* FALLTHROUGH */
695
696     case term:                  /* Time to die.  */
697     case core:                  /* And leave a rotting corpse.  */
698       /* Have the proc server stop all other threads in our task.  */
699       err = __USEPORT (PROC, __proc_dostop (port, _hurd_msgport_thread));
700       assert_perror (err);
701       /* No more user instructions will be executed.
702          The signal can now be considered delivered.  */
703       reply ();
704       /* Abort all server operations now in progress.  */
705       abort_all_rpcs (signo, &thread_state, 0);
706
707       {
708         int status = W_EXITCODE (0, signo);
709         /* Do a core dump if desired.  Only set the wait status bit saying we
710            in fact dumped core if the operation was actually successful.  */
711         if (act == core && write_corefile (signo, sigcode, sigerror))
712           status |= WCOREFLAG;
713         /* Tell proc how we died and then stick the saber in the gut.  */
714         _hurd_exit (status);
715         /* NOTREACHED */
716       }
717
718     case handle:
719       /* Call a handler for this signal.  */
720       {
721         struct sigcontext *scp, ocontext;
722         int wait_for_reply, state_changed;
723
724         /* Stop the thread and abort its pending RPC operations.  */
725         if (! ss_suspended)
726           {
727             err = __thread_suspend (ss->thread);
728             assert_perror (err);
729           }
730
731         /* Abort the thread's kernel context, so any pending message send
732            or receive completes immediately or aborts.  If an interruptible
733            RPC is in progress, abort_rpcs will do this.  But we must always
734            do it before fetching the thread's state, because
735            thread_get_state is never kosher before thread_abort.  */
736         abort_thread (ss, &thread_state, NULL);
737
738         if (ss->context)
739           {
740             /* We have a previous sigcontext that sigreturn was about
741                to restore when another signal arrived.  */
742
743             mach_port_t *loc;
744
745             if (_hurdsig_catch_fault (SIGSEGV))
746               {
747                 assert (_hurdsig_fault_sigcode >= (long int) ss->context &&
748                         _hurdsig_fault_sigcode < (long int) (ss->context + 1));
749                 /* We faulted reading the thread's stack.  Forget that
750                    context and pretend it wasn't there.  It almost
751                    certainly crash if this handler returns, but that's it's
752                    problem.  */
753                 ss->context = NULL;
754               }
755             else
756               {
757                 /* Copy the context from the thread's stack before
758                    we start diddling the stack to set up the handler.  */
759                 ocontext = *ss->context;
760                 ss->context = &ocontext;
761               }
762             _hurdsig_end_catch_fault ();
763
764             if (! machine_get_basic_state (ss->thread, &thread_state))
765               goto sigbomb;
766             loc = interrupted_reply_port_location (&thread_state, 1);
767             if (loc && *loc != MACH_PORT_NULL)
768               /* This is the reply port for the context which called
769                  sigreturn.  Since we are abandoning that context entirely
770                  and restoring SS->context instead, destroy this port.  */
771               __mach_port_destroy (__mach_task_self (), *loc);
772
773             /* The thread was in sigreturn, not in any interruptible RPC.  */
774             wait_for_reply = 0;
775
776             assert (! ss->critical_section);
777           }
778         else
779           {
780             wait_for_reply
781               = (_hurdsig_abort_rpcs (ss, signo, 1,
782                                       &thread_state, &state_changed,
783                                       &reply)
784                  != MACH_PORT_NULL);
785
786             if (ss->critical_section)
787               {
788                 /* The thread is in a critical section.  Mark the signal as
789                    pending.  When it finishes the critical section, it will
790                    check for pending signals.  */
791                 mark_pending ();
792                 assert (! state_changed);
793                 __thread_resume (ss->thread);
794                 break;
795               }
796           }
797
798         /* Call the machine-dependent function to set the thread up
799            to run the signal handler, and preserve its old context.  */
800         scp = _hurd_setup_sighandler (ss, handler,
801                                       signo, sigcode,
802                                       wait_for_reply, &thread_state);
803         if (scp == NULL)
804           goto sigbomb;
805
806         /* Set the machine-independent parts of the signal context.  */
807
808         {
809           /* Fetch the thread variable for the MiG reply port,
810              and set it to MACH_PORT_NULL.  */
811           mach_port_t *loc = interrupted_reply_port_location (&thread_state,
812                                                               1);
813           if (loc)
814             {
815               scp->sc_reply_port = *loc;
816               *loc = MACH_PORT_NULL;
817             }
818           else
819             scp->sc_reply_port = MACH_PORT_NULL;
820
821           /* Save the intr_port in use by the interrupted code,
822              and clear the cell before running the trampoline.  */
823           scp->sc_intr_port = ss->intr_port;
824           ss->intr_port = MACH_PORT_NULL;
825
826           if (ss->context)
827             {
828               /* After the handler runs we will restore to the state in
829                  SS->context, not the state of the thread now.  So restore
830                  that context's reply port and intr port.  */
831
832               scp->sc_reply_port = ss->context->sc_reply_port;
833               scp->sc_intr_port = ss->context->sc_intr_port;
834
835               ss->context = NULL;
836             }
837         }
838
839         /* Backdoor extra argument to signal handler.  */
840         scp->sc_error = sigerror;
841
842         /* Block SIGNO and requested signals while running the handler.  */
843         scp->sc_mask = ss->blocked;
844         ss->blocked |= __sigmask (signo) | ss->actions[signo].sa_mask;
845
846         /* Start the thread running the handler (or possibly waiting for an
847            RPC reply before running the handler).  */
848         err = __thread_set_state (ss->thread, MACHINE_THREAD_STATE_FLAVOR,
849                                   (natural_t *) &thread_state.basic,
850                                   MACHINE_THREAD_STATE_COUNT);
851         assert_perror (err);
852         err = __thread_resume (ss->thread);
853         assert_perror (err);
854         thread_state.set = 0;   /* Everything we know is now wrong.  */
855         break;
856       }
857     }
858
859   /* The signal has either been ignored or is now being handled.  We can
860      consider it delivered and reply to the killer.  */
861   reply ();
862
863   /* We get here unless the signal was fatal.  We still hold SS->lock.
864      Check for pending signals, and loop to post them.  */
865   {
866     /* Return nonzero if SS has any signals pending we should worry about.
867        We don't worry about any pending signals if we are stopped, nor if
868        SS is in a critical section.  We are guaranteed to get a sig_post
869        message before any of them become deliverable: either the SIGCONT
870        signal, or a sig_post with SIGNO==0 as an explicit poll when the
871        thread finishes its critical section.  */
872     inline int signals_pending (void)
873       {
874         if (_hurd_stopped || ss->critical_section)
875           return 0;
876         return pending = ss->pending & ~ss->blocked;
877       }
878
879   check_pending_signals:
880     untraced = 0;
881
882     if (signals_pending ())
883       {
884       pending:
885         for (signo = 1; signo < NSIG; ++signo)
886           if (__sigismember (&pending, signo))
887             {
888               __sigdelset (&ss->pending, signo);
889               sigcode = ss->pending_data[signo].code;
890               sigerror = ss->pending_data[signo].error;
891               __spin_unlock (&ss->lock);
892               goto post_signal;
893             }
894       }
895
896     /* No pending signals left undelivered for this thread.
897        If we were sent signal 0, we need to check for pending
898        signals for all threads.  */
899     if (signo == 0)
900       {
901         __spin_unlock (&ss->lock);
902         __mutex_lock (&_hurd_siglock);
903         for (ss = _hurd_sigstates; ss != NULL; ss = ss->next)
904           {
905             __spin_lock (&ss->lock);
906             if (signals_pending ())
907               goto pending;
908             __spin_unlock (&ss->lock);
909           }
910         __mutex_unlock (&_hurd_siglock);
911       }
912     else
913       {
914         /* No more signals pending; SS->lock is still locked.
915            Wake up any sigsuspend call that is blocking SS->thread.  */
916         if (ss->suspended != MACH_PORT_NULL)
917           {
918             /* There is a sigsuspend waiting.  Tell it to wake up.  */
919             error_t err;
920             mach_msg_header_t msg;
921             err = __mach_port_insert_right (__mach_task_self (),
922                                             ss->suspended, ss->suspended,
923                                             MACH_MSG_TYPE_MAKE_SEND);
924             assert_perror (err);
925             msg.msgh_bits = MACH_MSGH_BITS (MACH_MSG_TYPE_MOVE_SEND, 0);
926             msg.msgh_remote_port = ss->suspended;
927             msg.msgh_local_port = MACH_PORT_NULL;
928             /* These values do not matter.  */
929             msg.msgh_id = 8675309; /* Jenny, Jenny.  */
930             msg.msgh_seqno = 17; /* Random.  */
931             ss->suspended = MACH_PORT_NULL;
932             err = __mach_msg (&msg, MACH_SEND_MSG, sizeof msg, 0,
933                               MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
934                               MACH_PORT_NULL);
935             assert_perror (err);
936           }
937         __spin_unlock (&ss->lock);
938       }
939   }
940
941   /* All pending signals delivered to all threads.
942      Now we can send the reply message even for signal 0.  */
943   reply ();
944 }
945 \f
946 /* Decide whether REFPORT enables the sender to send us a SIGNO signal.
947    Returns zero if so, otherwise the error code to return to the sender.  */
948
949 static error_t
950 signal_allowed (int signo, mach_port_t refport)
951 {
952   if (signo < 0 || signo >= NSIG)
953     return EINVAL;
954
955   if (refport == __mach_task_self ())
956     /* Can send any signal.  */
957     goto win;
958
959   /* Avoid needing to check for this below.  */
960   if (refport == MACH_PORT_NULL)
961     return EPERM;
962
963   switch (signo)
964     {
965     case SIGINT:
966     case SIGQUIT:
967     case SIGTSTP:
968     case SIGHUP:
969     case SIGINFO:
970     case SIGTTIN:
971     case SIGTTOU:
972       /* Job control signals can be sent by the controlling terminal.  */
973       if (__USEPORT (CTTYID, port == refport))
974         goto win;
975       break;
976
977     case SIGCONT:
978       {
979         /* A continue signal can be sent by anyone in the session.  */
980         mach_port_t sessport;
981         if (! __USEPORT (PROC, __proc_getsidport (port, &sessport)))
982           {
983             __mach_port_deallocate (__mach_task_self (), sessport);
984             if (refport == sessport)
985               goto win;
986           }
987       }
988       break;
989
990     case SIGIO:
991     case SIGURG:
992       {
993         /* Any io object a file descriptor refers to might send us
994            one of these signals using its async ID port for REFPORT.
995
996            This is pretty wide open; it is not unlikely that some random
997            process can at least open for reading something we have open,
998            get its async ID port, and send us a spurious SIGIO or SIGURG
999            signal.  But BSD is actually wider open than that!--you can set
1000            the owner of an io object to any process or process group
1001            whatsoever and send them gratuitous signals.
1002
1003            Someday we could implement some reasonable scheme for
1004            authorizing SIGIO and SIGURG signals properly.  */
1005
1006         int d;
1007         __mutex_lock (&_hurd_dtable_lock);
1008         for (d = 0; (unsigned int) d < (unsigned int) _hurd_dtablesize; ++d)
1009           {
1010             struct hurd_userlink ulink;
1011             io_t port;
1012             mach_port_t asyncid;
1013             if (_hurd_dtable[d] == NULL)
1014               continue;
1015             port = _hurd_port_get (&_hurd_dtable[d]->port, &ulink);
1016             if (! __io_get_icky_async_id (port, &asyncid))
1017               {
1018                 if (refport == asyncid)
1019                   /* Break out of the loop on the next iteration.  */
1020                   d = -1;
1021                 __mach_port_deallocate (__mach_task_self (), asyncid);
1022               }
1023             _hurd_port_free (&_hurd_dtable[d]->port, &ulink, port);
1024           }
1025         /* If we found a lucky winner, we've set D to -1 in the loop.  */
1026         if (d < 0)
1027           goto win;
1028       }
1029     }
1030
1031   /* If this signal is legit, we have done `goto win' by now.
1032      When we return the error, mig deallocates REFPORT.  */
1033   return EPERM;
1034
1035  win:
1036   /* Deallocate the REFPORT send right; we are done with it.  */
1037   __mach_port_deallocate (__mach_task_self (), refport);
1038
1039   return 0;
1040 }
1041
1042 /* Implement the sig_post RPC from <hurd/msg.defs>;
1043    sent when someone wants us to get a signal.  */
1044 kern_return_t
1045 _S_msg_sig_post (mach_port_t me,
1046                  mach_port_t reply_port, mach_msg_type_name_t reply_port_type,
1047                  int signo,
1048                  mach_port_t refport)
1049 {
1050   error_t err;
1051
1052   if (err = signal_allowed (signo, refport))
1053     return err;
1054
1055   /* Post the signal to the designated signal-receiving thread.  This will
1056      reply when the signal can be considered delivered.  */
1057   _hurd_internal_post_signal (_hurd_thread_sigstate (_hurd_sigthread),
1058                               signo, 0, 0, reply_port, reply_port_type,
1059                               0); /* Stop if traced.  */
1060
1061   return MIG_NO_REPLY;          /* Already replied.  */
1062 }
1063
1064 /* Implement the sig_post_untraced RPC from <hurd/msg.defs>;
1065    sent when the debugger wants us to really get a signal
1066    even if we are traced.  */
1067 kern_return_t
1068 _S_msg_sig_post_untraced (mach_port_t me,
1069                           mach_port_t reply_port,
1070                           mach_msg_type_name_t reply_port_type,
1071                           int signo,
1072                           mach_port_t refport)
1073 {
1074   error_t err;
1075
1076   if (err = signal_allowed (signo, refport))
1077     return err;
1078
1079   /* Post the signal to the designated signal-receiving thread.  This will
1080      reply when the signal can be considered delivered.  */
1081   _hurd_internal_post_signal (_hurd_thread_sigstate (_hurd_sigthread),
1082                               signo, 0, 0, reply_port, reply_port_type,
1083                               1); /* Untraced flag. */
1084
1085   return MIG_NO_REPLY;          /* Already replied.  */
1086 }
1087 \f
1088 extern void __mig_init (void *);
1089
1090 #include <mach/task_special_ports.h>
1091
1092 /* Initialize the message port and _hurd_sigthread and start the signal
1093    thread.  */
1094
1095 void
1096 _hurdsig_init (void)
1097 {
1098   error_t err;
1099   vm_size_t stacksize;
1100
1101   __mutex_init (&_hurd_siglock);
1102
1103   err = __mach_port_allocate (__mach_task_self (),
1104                               MACH_PORT_RIGHT_RECEIVE,
1105                               &_hurd_msgport);
1106   assert_perror (err);
1107
1108   /* Make a send right to the signal port.  */
1109   err = __mach_port_insert_right (__mach_task_self (),
1110                                   _hurd_msgport,
1111                                   _hurd_msgport,
1112                                   MACH_MSG_TYPE_MAKE_SEND);
1113   assert_perror (err);
1114
1115   /* Set the default thread to receive task-global signals
1116      to this one, the main (first) user thread.  */
1117   _hurd_sigthread = __mach_thread_self ();
1118
1119   /* Start the signal thread listening on the message port.  */
1120
1121   err = __thread_create (__mach_task_self (), &_hurd_msgport_thread);
1122   assert_perror (err);
1123
1124   stacksize = __vm_page_size * 4; /* Small stack for signal thread.  */
1125   err = __mach_setup_thread (__mach_task_self (), _hurd_msgport_thread,
1126                              _hurd_msgport_receive,
1127                              (vm_address_t *) &__hurd_sigthread_stack_base,
1128                              &stacksize);
1129   assert_perror (err);
1130
1131   __hurd_sigthread_stack_end = __hurd_sigthread_stack_base + stacksize;
1132   __hurd_sigthread_variables =
1133     malloc (__hurd_threadvar_max * sizeof (unsigned long int));
1134   if (__hurd_sigthread_variables == NULL)
1135     __libc_fatal ("hurd: Can't allocate thread variables for signal thread\n");
1136
1137   /* Reinitialize the MiG support routines so they will use a per-thread
1138      variable for the cached reply port.  */
1139   __mig_init ((void *) __hurd_sigthread_stack_base);
1140
1141   err = __thread_resume (_hurd_msgport_thread);
1142   assert_perror (err);
1143
1144   /* Receive exceptions on the signal port.  */
1145   __task_set_special_port (__mach_task_self (),
1146                            TASK_EXCEPTION_PORT, _hurd_msgport);
1147 }
1148 \f                               /* XXXX */
1149 /* Reauthenticate with the proc server.  */
1150
1151 static void
1152 reauth_proc (mach_port_t new)
1153 {
1154   mach_port_t ref, ignore;
1155
1156   ref = __mach_reply_port ();
1157   if (! HURD_PORT_USE (&_hurd_ports[INIT_PORT_PROC],
1158                        __proc_reauthenticate (port, ref,
1159                                               MACH_MSG_TYPE_MAKE_SEND) ||
1160                        __auth_user_authenticate (new, port, ref,
1161                                                  MACH_MSG_TYPE_MAKE_SEND,
1162                                                  &ignore))
1163       && ignore != MACH_PORT_NULL)
1164     __mach_port_deallocate (__mach_task_self (), ignore);
1165   __mach_port_destroy (__mach_task_self (), ref);
1166
1167   (void) &reauth_proc;          /* Silence compiler warning.  */
1168 }
1169 text_set_element (_hurd_reauth_hook, reauth_proc);
1170 \f
1171 /* Like `getenv', but safe for the signal thread to run.
1172    If the environment is trashed, this will just return NULL.  */
1173
1174 const char *
1175 _hurdsig_getenv (const char *variable)
1176 {
1177   if (_hurdsig_catch_fault (SIGSEGV))
1178     /* We bombed in getenv.  */
1179     return NULL;
1180   else
1181     {
1182       const char *value = getenv (variable);
1183       /* Fault now if VALUE is a bogus string.  */
1184       (void) strlen (value);
1185       _hurdsig_end_catch_fault ();
1186       return value;
1187     }
1188 }