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