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