Mon Apr 28 21:25:32 1997 Michael Snyder <msnyder@cleaver.cygnus.com>
[platform/upstream/binutils.git] / gdb / gnu-nat.c
1 /* Interface GDB to the GNU Hurd
2    Copyright (C) 1992, 1995, 1996 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    Written by Miles Bader <miles@gnu.ai.mit.edu>
7
8    Some code and ideas from m3-nat.c by Jukka Virtanen <jtv@hut.fi>
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 */
24
25 #include <stdio.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <assert.h>
29 #include <setjmp.h>
30 #include <limits.h>
31 #include <sys/ptrace.h>
32
33 /* We include this because we don't need the access macros and they conflict
34    with gdb's definitions (ick).  This is very non standard!  */
35 #include <waitflags.h>
36
37 #include <mach.h>
38 #include <mach/message.h>
39 #include <mach/notify.h>
40 #include <mach_error.h>
41 #include <mach/exception.h>
42 #include <mach/vm_attributes.h>
43
44 #include <hurd/process.h>
45 #include <hurd/process_request.h>
46 #include <hurd/msg.h>
47 #include <hurd/msg_request.h>
48 #include <hurd/signal.h>
49 #include <hurd/interrupt.h>
50 #include <hurd/sigpreempt.h>
51
52 #include <portinfo.h>
53
54 #include "defs.h"
55 #include "inferior.h"
56 #include "symtab.h"
57 #include "value.h"
58 #include "language.h"
59 #include "target.h"
60 #include "wait.h"
61 #include "gdbcmd.h"
62 #include "gdbcore.h"
63
64 #include "gnu-nat.h"
65
66 #include "exc_request_S.h"
67 #include "notify_S.h"
68 #include "process_reply_S.h"
69 #include "msg_reply_S.h"
70
71 #include "exc_request_U.h"
72 #include "msg_U.h"
73
74 static process_t proc_server = MACH_PORT_NULL;
75
76 /* If we've sent a proc_wait_request to the proc server, the pid of the
77    process we asked about.  We can only ever have one outstanding.  */
78 int proc_wait_pid = 0;
79
80 /* The number of wait requests we've sent, and expect replies from.  */
81 int proc_waits_pending = 0;
82
83 int gnu_debug_flag = 0;
84
85 /* Forward decls */
86
87 extern struct target_ops gnu_ops;
88 extern char *strerror();
89
90 int inf_update_procs (struct inf *inf);
91 static struct inf *make_inf ();
92 static void inf_clear_wait (struct inf *inf);
93 static void inf_cleanup (struct inf *inf);
94 static void inf_startup (struct inf *inf, int pid, task_t task);
95 static int inf_update_suspends (struct inf *inf);
96 static void inf_set_task (struct inf *inf, task_t port);
97 static void inf_validate_procs (struct inf *inf);
98 static void inf_steal_exc_ports (struct inf *inf);
99 static void inf_restore_exc_ports (struct inf *inf);
100 static struct proc *inf_tid_to_proc (struct inf *inf, int tid);
101 static inline void inf_set_threads_resume_sc (struct inf *inf, 
102                                               struct proc *run_thread, 
103                                               int run_others);
104 static inline int inf_set_threads_resume_sc_for_signal_thread (struct inf *inf);
105 static inline void inf_suspend (struct inf *inf);
106 static inline void inf_resume (struct inf *inf);
107 static void inf_set_step_thread (struct inf *inf, struct proc *proc);
108 static void inf_detach (struct inf *inf);
109 static void inf_attach (struct inf *inf, int pid);
110 static void inf_signal (struct inf *inf, enum target_signal sig);
111
112 #define inf_debug(_inf, msg, args...) \
113   do { struct inf *__inf = (_inf); \
114        debug ("{inf %d %p}: " msg, __inf->pid, __inf , ##args); } while (0)
115
116 void proc_abort (struct proc *proc, int force);
117 thread_state_t proc_get_state (struct proc *proc, int force);
118 static struct proc *make_proc (struct inf *inf, mach_port_t port, int tid);
119 static struct proc *_proc_free (struct proc *proc);
120 static int proc_update_sc (struct proc *proc);
121 static error_t proc_get_exception_port (struct proc *proc, mach_port_t *port);
122 static error_t proc_set_exception_port (struct proc *proc, mach_port_t port);
123 static mach_port_t _proc_get_exc_port (struct proc *proc);
124 static void proc_steal_exc_port (struct proc *proc, mach_port_t exc_port);
125 static void proc_restore_exc_port (struct proc *proc);
126 static int proc_trace (struct proc *proc, int set);
127 char *proc_string (struct proc *proc);
128
129 /* Evaluate RPC_EXPR in a scope with the variables MSGPORT and REFPORT bound
130    to INF's msg port and task port respectively.  If it has no msg port,
131    EIEIO is returned.  INF must refer to a running process!  */
132 #define INF_MSGPORT_RPC(inf, rpc_expr) \
133   HURD_MSGPORT_RPC (proc_getmsgport (proc_server, inf->pid, &msgport), \
134                     (refport = inf->task->port, 0), 0, \
135                     msgport ? (rpc_expr) : EIEIO)
136
137 /* Like INF_MSGPORT_RPC, but will also resume the signal thread to ensure
138    there's someone around to deal with the RPC (and resuspend things
139    afterwards).  This effects INF's threads' resume_sc count.  */
140 #define INF_RESUME_MSGPORT_RPC(inf, rpc_expr) \
141   (inf_set_threads_resume_sc_for_signal_thread (inf) \
142    ? ({ error_t __e; \
143         inf_resume (inf); \
144         __e = INF_MSGPORT_RPC (inf, rpc_expr); \
145         inf_suspend (inf); \
146         __e; }) \
147    : EIEIO)
148
149 #define MIG_SERVER_DIED EMIG_SERVER_DIED /* XXX */
150 \f
151 /* The state passed by an exception message.  */
152 struct exc_state
153 {
154   int exception;                /* The exception code */
155   int code, subcode;
156   mach_port_t handler;          /* The real exception port to handle this. */
157   mach_port_t reply;            /* The reply port from the exception call. */
158 };
159
160 /* The results of the last wait an inf did. */
161 struct inf_wait
162 {
163   struct target_waitstatus status; /* The status returned to gdb.  */
164   struct exc_state exc;         /* The exception that caused us to return. */
165   struct proc *thread;          /* The thread in question.  */
166   int suppress;                 /* Something trivial happened.  */
167 };
168
169 /* The state of an inferior.  */
170 struct inf
171 {
172   /* Fields describing the current inferior.  */
173
174   struct proc *task;            /* The mach task.   */
175   struct proc *threads;         /* A linked list of all threads in TASK.  */
176
177   /* True if THREADS needn't be validated by querying the task.  We assume that
178      we and the task in question are the only ones frobbing the thread list,
179      so as long as we don't let any code run, we don't have to worry about
180      THREADS changing.  */
181   int threads_up_to_date;
182
183   pid_t pid;                    /* The real system PID. */
184
185   struct inf_wait wait;         /* What to return from target_wait.  */
186
187   /* One thread proc in INF may be in `single-stepping mode'.  This is it.  */
188   struct proc *step_thread;
189
190   /* The thread we think is the signal thread.  */
191   struct proc *signal_thread;
192
193   mach_port_t event_port;       /* Where we receive various msgs.  */
194
195   /* True if we think at least one thread in the inferior could currently be
196      running.  */
197   int running : 1;
198
199   /* True if the process has stopped (in the proc server sense).  Note that
200      since a proc server `stop' leaves the signal thread running, the inf can
201      be RUNNING && STOPPED...  */
202   int stopped : 1;
203
204   /* True if the inferior is traced.  */
205   int traced : 1;
206
207   /* True if we shouldn't try waiting for the inferior, usually because we
208      can't for some reason.  */
209   int no_wait : 1;
210
211   /* When starting a new inferior, we don't try to validate threads until all
212      the proper execs have been done.  This is a count of how many execs we
213      expect to happen.  */
214   unsigned pending_execs;
215
216   /* Fields describing global state */
217
218   /* The task suspend count used when gdb has control.  This is normally 1 to
219      make things easier for us, but sometimes (like when attaching to vital
220      system servers) it may be desirable to let the task continue to run
221      (pausing individual threads as necessary).  */
222   int pause_sc;
223
224   /* The task suspend count left when detaching from a task.  */
225   int detach_sc;
226
227   /* The initial values used for the run_sc and pause_sc of newly discovered
228      threads -- see the definition of those fields in struct proc.  */
229   int default_thread_run_sc;
230   int default_thread_pause_sc;
231   int default_thread_detach_sc;
232
233   /* True if the process should be traced when started/attached.  Newly
234      started processes *must* be traced at first to exec them properly, but
235      if this is false, tracing is turned off as soon it has done so.  */
236   int want_signals;
237
238   /* True if exceptions from the inferior process should be trapped.  This
239      must be on to use breakpoints.  */
240   int want_exceptions;
241 };
242
243
244 int __proc_pid (struct proc *proc)
245 {
246   return proc->inf->pid;
247 }
248 \f
249 /* Update PROC's real suspend count to match it's desired one.  Returns true
250    if we think PROC is now in a runnable state.  */
251 static int
252 proc_update_sc (struct proc *proc)
253 {
254   int running;
255   int err =  0;
256   int delta = proc->sc - proc->cur_sc;
257
258   if (delta)
259     proc_debug (proc, "sc: %d --> %d", proc->cur_sc, proc->sc);
260
261   if (proc->sc == 0 && proc->state_changed)
262     /* Since PROC may start running, we must write back any state changes. */
263     {
264       assert (proc_is_thread (proc));
265       proc_debug (proc, "storing back changed thread state");
266       err = thread_set_state (proc->port, THREAD_STATE_FLAVOR,
267                               (thread_state_t)&proc->state, THREAD_STATE_SIZE);
268       if (! err)
269         proc->state_changed = 0;
270     }
271
272   if (delta > 0)
273     while (delta-- > 0 && !err)
274       if (proc_is_task (proc))
275         err = task_suspend (proc->port);
276       else
277         err = thread_suspend (proc->port);
278   else
279     while (delta++ < 0 && !err)
280       if (proc_is_task (proc))
281         err = task_resume (proc->port);
282       else
283         err = thread_resume (proc->port);
284
285   if (! err)
286     proc->cur_sc = proc->sc;
287
288   /* If we got an error, then the task/thread has disappeared.  */
289   running = !err && proc->sc == 0;
290
291   proc_debug (proc, "is %s", err ? "dead" : running ? "running" : "suspended");
292   if (err)
293     proc_debug (proc, "err = %s", strerror (err));
294
295   if (running)
296     {
297       proc->aborted = 0;
298       proc->state_valid = proc->state_changed = 0;
299       proc->fetched_regs = 0;
300     }
301
302   return running;
303 }
304 \f
305 /* Thread_abort is called on PROC if needed.  PROC must be a thread proc.
306    If PROC is deemed `precious', then nothing is done unless FORCE is true.
307    In particular, a thread is precious if it's running (in which case forcing
308    it includes suspending it first), or if it has an exception pending.  */
309 void
310 proc_abort (struct proc *proc, int force)
311 {
312   assert (proc_is_thread (proc));
313
314   if (! proc->aborted)
315     {
316       struct inf *inf = proc->inf;
317       int running = (proc->cur_sc == 0 && inf->task->cur_sc == 0);
318
319       if (running && force)
320         {
321           proc->sc = 1;
322           inf_update_suspends (proc->inf);
323           running = 0;
324           warning ("Stopped %s.", proc_string (proc));
325         }
326       else if (proc == inf->wait.thread && inf->wait.exc.reply && !force)
327         /* An exception is pending on PROC, which don't mess with.  */
328         running = 1;
329
330       if (! running)
331         /* We only abort the thread if it's not actually running.  */
332         {
333           thread_abort (proc->port);
334           proc_debug (proc, "aborted");
335           proc->aborted = 1;
336         }
337       else
338         proc_debug (proc, "not aborting");
339     }
340 }
341
342 /* Make sure that the state field in PROC is up to date, and return a pointer
343    to it, or 0 if something is wrong.  If WILL_MODIFY is true, makes sure
344    that the thread is stopped and aborted first, and sets the state_changed
345    field in PROC to true.  */
346 thread_state_t
347 proc_get_state (struct proc *proc, int will_modify)
348 {
349   int was_aborted = proc->aborted;
350
351   proc_debug (proc, "updating state info%s",
352               will_modify ? " (with intention to modify)" : "");
353
354   proc_abort (proc, will_modify);
355
356   if (! was_aborted && proc->aborted)
357     /* PROC's state may have changed since we last fetched it.  */
358     proc->state_valid = 0;
359
360   if (! proc->state_valid)
361     {
362       mach_msg_type_number_t state_size = THREAD_STATE_SIZE;
363       error_t err =
364         thread_get_state (proc->port, THREAD_STATE_FLAVOR,
365                           (thread_state_t)&proc->state, &state_size);
366       proc_debug (proc, "getting thread state");
367       proc->state_valid = !err;
368     }
369
370   if (proc->state_valid)
371     {
372       if (will_modify)
373         proc->state_changed = 1;
374       return (thread_state_t)&proc->state;
375     }
376   else
377     return 0;
378 }
379 \f
380 /* Set PORT to PROC's exception port.  */
381 static error_t
382 proc_get_exception_port (struct proc *proc, mach_port_t *port)
383 {
384   if (proc_is_task (proc))
385     return task_get_exception_port (proc->port, port);
386   else
387     return thread_get_exception_port (proc->port, port);
388 }
389
390 /* Set PROC's exception port to PORT.  */
391 static error_t
392 proc_set_exception_port (struct proc *proc, mach_port_t port)
393 {
394   proc_debug (proc, "setting exception port: %d", port);
395   if (proc_is_task (proc))
396     return task_set_exception_port (proc->port, port);
397   else
398     return thread_set_exception_port (proc->port, port);
399 }
400
401 /* Get PROC's exception port, cleaning up a bit if proc has died.  */
402 static mach_port_t
403 _proc_get_exc_port (struct proc *proc)
404 {
405   mach_port_t exc_port;
406   error_t err = proc_get_exception_port (proc, &exc_port);
407
408   if (err)
409     /* PROC must be dead.  */
410     {
411       if (proc->exc_port)
412         mach_port_deallocate (mach_task_self (), proc->exc_port);
413       proc->exc_port = MACH_PORT_NULL;
414       if (proc->saved_exc_port)
415         mach_port_deallocate (mach_task_self (), proc->saved_exc_port);
416       proc->saved_exc_port = MACH_PORT_NULL;
417     }
418
419   return exc_port;
420 }
421
422 /* Replace PROC's exception port with EXC_PORT, unless it's already been
423    done.  Stash away any existing exception port so we can restore it later. */
424 static void
425 proc_steal_exc_port (struct proc *proc, mach_port_t exc_port)
426 {
427   mach_port_t cur_exc_port = _proc_get_exc_port (proc);
428
429   if (cur_exc_port)
430     {
431       error_t err;
432
433       proc_debug (proc, "inserting exception port: %d", exc_port);
434
435       if (cur_exc_port != exc_port)
436         /* Put in our exception port.  */
437         err = proc_set_exception_port (proc, exc_port);
438
439       if (err || cur_exc_port == proc->exc_port)
440         /* We previously set the exception port, and it's still set.  So we
441            just keep the old saved port which is what the proc set.  */
442         {
443           if (cur_exc_port)
444             mach_port_deallocate (mach_task_self (), cur_exc_port);
445         }
446       else
447         /* Keep a copy of PROC's old exception port so it can be restored. */
448         {
449           if (proc->saved_exc_port)
450             mach_port_deallocate (mach_task_self (), proc->saved_exc_port);
451           proc->saved_exc_port = cur_exc_port;
452         }
453
454       proc_debug (proc, "saved exception port: %d", proc->saved_exc_port);
455
456       if (!err)
457         proc->exc_port = exc_port;
458       else
459         warning ("Error setting exception port for %s: %s",
460                  proc_string (proc), strerror (err));
461     }
462 }
463
464 /* If we previously replaced PROC's exception port, put back what we
465    found there at the time, unless *our* exception port has since been
466    overwritten, in which case who knows what's going on.  */
467 static void
468 proc_restore_exc_port (struct proc *proc)
469 {
470   mach_port_t cur_exc_port = _proc_get_exc_port (proc);
471
472   if (cur_exc_port)
473     {
474       error_t err = 0;
475
476       proc_debug (proc, "restoring real exception port");
477
478       if (proc->exc_port == cur_exc_port)
479         /* Our's is still there.  */
480         err = proc_set_exception_port (proc, proc->saved_exc_port);
481
482       if (proc->saved_exc_port)
483         mach_port_deallocate (mach_task_self (), proc->saved_exc_port);
484       proc->saved_exc_port = MACH_PORT_NULL;
485
486       if (!err)
487         proc->exc_port = MACH_PORT_NULL;
488       else
489         warning ("Error setting exception port for %s: %s",
490                  proc_string (proc), strerror (err));
491     }
492 }
493 \f
494 /* Turns hardware tracing in PROC on or off when SET is true or false,
495    respectively.  Returns true on success.  */
496 static int
497 proc_trace (struct proc *proc, int set)
498 {
499   thread_state_t state = proc_get_state (proc, 1);
500
501   if (! state)
502     return 0;                   /* the thread must be dead.  */
503
504   proc_debug (proc, "tracing %s", set ? "on" : "off");
505   
506   if (set)
507     {
508       /* XXX We don't get the exception unless the thread has its own
509          exception port???? */
510       if (proc->exc_port == MACH_PORT_NULL)
511         proc_steal_exc_port (proc, proc->inf->event_port);
512       THREAD_STATE_SET_TRACED (state);
513     }
514   else
515     THREAD_STATE_CLEAR_TRACED (state);
516
517   return 1;
518 }
519 \f
520 /* A variable from which to assign new TIDs.  */
521 static int next_thread_id = 1;
522
523 /* Returns a new proc structure with the given fields.  Also adds a
524    notification for PORT becoming dead to be sent to INF's notify port.  */
525 struct proc *
526 make_proc (struct inf *inf, mach_port_t port, int tid)
527 {
528   error_t err;
529   mach_port_t prev_port = MACH_PORT_NULL;
530   struct proc *proc = malloc (sizeof (struct proc));
531
532   proc->port = port;
533   proc->tid = tid;
534   proc->inf = inf;
535   proc->next = 0;
536   proc->saved_exc_port = MACH_PORT_NULL;
537   proc->exc_port = MACH_PORT_NULL;
538
539   proc->sc = 0;
540   proc->cur_sc = 0;
541
542   /* Note that these are all the values for threads; the task simply uses the
543      corresponding field in INF directly.  */
544   proc->run_sc = inf->default_thread_run_sc;
545   proc->pause_sc = inf->default_thread_pause_sc;
546   proc->detach_sc = inf->default_thread_detach_sc;
547   proc->resume_sc = proc->run_sc;
548
549   proc->aborted = 0;
550   proc->dead = 0;
551   proc->state_valid = 0;
552   proc->state_changed = 0;
553
554   proc_debug (proc, "is new");
555
556   /* Get notified when things die.  */
557   err =
558     mach_port_request_notification (mach_task_self(), port,
559                                     MACH_NOTIFY_DEAD_NAME, 1,
560                                     inf->event_port,
561                                     MACH_MSG_TYPE_MAKE_SEND_ONCE,
562                                     &prev_port);
563   if (err)
564     warning ("Couldn't request notification for port %d: %s",
565              port, strerror (err));
566   else
567     {
568       proc_debug (proc, "notifications to: %d", inf->event_port);
569       if (prev_port != MACH_PORT_NULL)
570         mach_port_deallocate (mach_task_self (), prev_port);
571     }
572
573   if (inf->want_exceptions)
574     if (proc_is_task (proc))
575       /* Make the task exception port point to us.  */
576       proc_steal_exc_port (proc, inf->event_port);
577     else
578       /* Just clear thread exception ports -- they default to the task one.  */
579       proc_steal_exc_port (proc, MACH_PORT_NULL);
580
581   return proc;
582 }
583
584 /* Frees PROC and any resources it uses, and returns the value of PROC's 
585    next field.  */
586 static struct proc *
587 _proc_free (struct proc *proc)
588 {
589   struct inf *inf = proc->inf;
590   struct proc *next = proc->next;
591
592   proc_debug (proc, "freeing...");
593
594   if (proc == inf->step_thread)
595     /* Turn off single stepping.  */
596     inf_set_step_thread (inf, 0);
597   if (proc == inf->wait.thread)
598     inf_clear_wait (inf);
599   if (proc == inf->signal_thread)
600     inf->signal_thread = 0;
601
602   if (proc->port != MACH_PORT_NULL)
603     {
604       if (proc->exc_port != MACH_PORT_NULL)
605         /* Restore the original exception port.  */
606         proc_restore_exc_port (proc);
607       if (proc->cur_sc != 0)
608         /* Resume the thread/task.  */
609         {
610           proc->sc = 0;
611           proc_update_sc (proc);
612         }
613       mach_port_deallocate (mach_task_self (), proc->port);
614     }
615
616   free (proc);
617   return next;
618 }
619 \f
620 struct inf *make_inf ()
621 {
622   struct inf *inf = malloc (sizeof (struct inf));
623
624   if (!inf)
625     return 0;
626
627   inf->task = 0;
628   inf->threads = 0;
629   inf->threads_up_to_date = 0;
630   inf->pid = 0;
631   inf->wait.status.kind = TARGET_WAITKIND_SPURIOUS;
632   inf->wait.thread = 0;
633   inf->wait.exc.handler = MACH_PORT_NULL;
634   inf->wait.exc.reply = MACH_PORT_NULL;
635   inf->step_thread = 0;
636   inf->signal_thread = 0;
637   inf->event_port = MACH_PORT_NULL;
638   inf->stopped = 0;
639   inf->running = 0;
640   inf->traced = 0;
641   inf->no_wait = 0;
642   inf->pending_execs = 0;
643   inf->pause_sc = 1;
644   inf->detach_sc = 0;
645   inf->default_thread_run_sc = 0;
646   inf->default_thread_pause_sc = 0;
647   inf->default_thread_detach_sc = 0;
648   inf->want_signals = 1;        /* By default */
649   inf->want_exceptions = 1;     /* By default */
650
651   return inf;
652 }
653
654 /* clear INF's target wait status.  */
655 static void
656 inf_clear_wait (struct inf *inf)
657 {
658   inf_debug (inf, "clearing wait");
659   inf->wait.status.kind = TARGET_WAITKIND_SPURIOUS;
660   inf->wait.thread = 0;
661   inf->wait.suppress = 0;
662   if (inf->wait.exc.handler != MACH_PORT_NULL)
663     {
664       mach_port_deallocate (mach_task_self (), inf->wait.exc.handler);
665       inf->wait.exc.handler = MACH_PORT_NULL;
666     }
667   if (inf->wait.exc.reply != MACH_PORT_NULL)
668     {
669       mach_port_deallocate (mach_task_self (), inf->wait.exc.reply);
670       inf->wait.exc.reply = MACH_PORT_NULL;
671     }
672 }
673 \f
674 static void
675 inf_cleanup (struct inf *inf)
676 {
677   inf_debug (inf, "cleanup");
678
679   inf_clear_wait (inf);
680
681   inf_set_task (inf, MACH_PORT_NULL);
682   inf->pid = 0;
683   inf->traced = 0;
684   inf->no_wait = 0;
685   inf->stopped = 0;
686   inf->running = 0;
687   inf->pending_execs = 0;
688
689   if (inf->event_port)
690     {
691       mach_port_destroy (mach_task_self (), inf->event_port);
692       inf->event_port = MACH_PORT_NULL;
693     }
694 }
695
696 static void
697 inf_startup (struct inf *inf, int pid, task_t task)
698 {
699   error_t err;
700
701   inf_debug (inf, "startup: pid = %d, task = %d", pid, task);
702
703   inf_cleanup (inf);
704
705   /* Make the port on which we receive all events.  */
706   err = mach_port_allocate (mach_task_self (),
707                             MACH_PORT_RIGHT_RECEIVE, &inf->event_port);
708   if (err)
709     error ("Error allocating event port: %s", strerror (err));
710
711   /* Make a send right for it, so we can easily copy it for other people.  */
712   mach_port_insert_right (mach_task_self (), inf->event_port,
713                           inf->event_port, MACH_MSG_TYPE_MAKE_SEND);
714
715   if (inf->pause_sc)
716     task_suspend (task);
717
718   inf_set_task (inf, task); 
719
720   if (inf->task)
721     {
722       inf->pid = pid;
723       if (inf->pause_sc)
724         inf->task->sc = inf->task->cur_sc = 1; /* Reflect task_suspend above */
725     }
726 }
727 \f
728 /* close current process, if any, and attach INF to process PORT */
729 static void 
730 inf_set_task (struct inf *inf, mach_port_t port)
731 {
732   struct proc *task = inf->task;
733
734   inf_debug (inf, "setting task: %d", port);
735
736   if (task && task->port != port)
737     {
738       inf->task = 0;
739       inf_validate_procs (inf); /* Trash all the threads. */
740       _proc_free (task);        /* And the task. */
741     }
742
743   if (port != MACH_PORT_NULL)
744     {
745       inf->task = make_proc (inf, port, PROC_TID_TASK);
746       inf->threads_up_to_date = 0;
747     }
748 }
749 \f
750 /* Validates INF's stopped field from the actual proc server state.  */
751 static void
752 inf_validate_stopped (struct inf *inf)
753 {
754   char *noise;
755   mach_msg_type_number_t noise_len = 0;
756   struct procinfo *pi;
757   mach_msg_type_number_t pi_len = 0;
758   int info_flags = 0;
759   error_t err =
760     proc_getprocinfo (proc_server, inf->pid, &info_flags,
761                       (procinfo_t *)&pi, &pi_len, &noise, &noise_len);
762
763   if (! err)
764     {
765       inf->stopped = !!(pi->state & PI_STOPPED);
766       vm_deallocate (mach_task_self (), (vm_address_t)pi, pi_len);
767       if (noise_len > 0)
768         vm_deallocate (mach_task_self (), (vm_address_t)noise, noise_len);
769     }
770 }
771
772 /* Validates INF's task suspend count.  If it's higher than we expect, verify
773    with the user before `stealing' the extra count.  */
774 static void
775 inf_validate_task_sc (struct inf *inf)
776 {
777   struct task_basic_info info;
778   mach_msg_type_number_t info_len = TASK_BASIC_INFO_COUNT;
779   error_t err =
780     task_info (inf->task->port, TASK_BASIC_INFO, (task_info_t)&info, &info_len);
781
782   if (err)
783     inf->task->dead = 1;        /* oh well */
784   else if (inf->task->cur_sc < info.suspend_count)
785     {
786       int abort;
787
788       target_terminal_ours ();  /* Allow I/O.  */
789       abort =
790         !query ("Pid %d has an additional task suspend count of %d; clear it? ",
791                 inf->pid, info.suspend_count - inf->task->cur_sc);
792       target_terminal_inferior (); /* Give it back to the child.  */
793
794       if (abort)
795         error ("Additional task suspend count left untouched.");
796
797       inf->task->cur_sc = info.suspend_count;
798     }
799 }
800
801 /* Turns tracing for INF on or off, depending on ON, unless it already is.
802    If INF is running, the resume_sc count of INF's threads will be modified,
803    and the signal thread will briefly be run to change the trace state.  */
804 static void
805 inf_set_traced (struct inf *inf, int on)
806 {
807   if (on != inf->traced)
808     if (inf->task && !inf->task->dead)
809       /* Make it take effect immediately.  */
810       {
811         sigset_t mask = on ? ~(sigset_t)0 : 0;
812         error_t err =
813           INF_RESUME_MSGPORT_RPC (inf, msg_set_init_int (msgport, refport,
814                                                          INIT_TRACEMASK, mask));
815         if (err == EIEIO)
816           {
817             if (on)
818               warning ("Can't modify tracing state for pid %d: No signal thread",
819                        inf->pid);
820             inf->traced = on;
821           }
822         else if (err)
823           warning ("Can't modify tracing state for pid %d: %s",
824                    inf->pid, strerror (err));
825         else
826           inf->traced = on;
827       }
828     else
829       inf->traced = on;
830 }
831 \f
832 /* Makes all the real suspend count deltas of all the procs in INF match the
833    desired values.  Careful to always do thread/task suspend counts in the
834    safe order.  Returns true if at least one thread is thought to be running.*/
835 static int
836 inf_update_suspends (struct inf *inf)
837 {
838   struct proc *task = inf->task;
839   /* We don't have to update INF->threads even though we're iterating over it
840      because we'll change a thread only if it already has an existing proc
841      entry.  */
842
843   inf_debug (inf, "updating suspend counts");
844
845   if (task)
846     {
847       struct proc *thread;
848       int task_running = (task->sc == 0), thread_running = 0;
849
850       if (task->sc > task->cur_sc)
851         /* The task is becoming _more_ suspended; do before any threads.  */
852         task_running = proc_update_sc (task);
853
854       if (inf->pending_execs)
855         /* When we're waiting for an exec, things may be happening behind our
856            back, so be conservative.  */
857         thread_running = 1;
858
859       /* Do all the thread suspend counts.  */
860       for (thread = inf->threads; thread; thread = thread->next)
861         thread_running |= proc_update_sc (thread);
862
863       if (task->sc != task->cur_sc)
864         /* We didn't do the task first, because we wanted to wait for the
865            threads; do it now.  */
866         task_running = proc_update_sc (task);
867
868       inf_debug (inf, "%srunning...",
869                  (thread_running && task_running) ? "" : "not ");
870
871       inf->running = thread_running && task_running;
872
873       /* Once any thread has executed some code, we can't depend on the
874          threads list any more.  */
875       if (inf->running)
876         inf->threads_up_to_date = 0;
877
878       return inf->running;
879     }
880
881   return 0;
882 }
883 \f
884 /* Converts a GDB pid to a struct proc.  */
885 struct proc *
886 inf_tid_to_thread (struct inf *inf, int tid)
887 {
888   struct proc *thread = inf->threads;
889   if (tid == inf->pid)  /* main thread */
890     return thread;
891   while (thread)
892     if (thread->tid == tid)
893       return thread;
894     else
895       thread = thread->next;
896   return 0;
897 }
898
899 /* Converts a thread port to a struct proc.  */
900 static struct proc *
901 inf_port_to_thread (struct inf *inf, mach_port_t port)
902 {
903   struct proc *thread = inf->threads;
904   while (thread)
905     if (thread->port == port)
906       return thread;
907     else
908       thread = thread->next;
909   return 0;
910 }
911 \f
912 /* Make INF's list of threads be consistent with reality of TASK.  */
913 static void
914 inf_validate_procs (struct inf *inf)
915 {
916   int i;
917   thread_array_t threads;
918   unsigned num_threads;
919   struct proc *task = inf->task;
920
921   /* If no threads are currently running, this function will guarantee that
922      things are up to date.  The exception is if there are zero threads --
923      then it is almost certainly in an odd state, and probably some outside
924      agent will create threads.  */
925   inf->threads_up_to_date = inf->threads ? !inf->running : 0;
926
927   if (task)
928     {
929       error_t err = task_threads (task->port, &threads, &num_threads);
930       inf_debug (inf, "fetching threads");
931       if (err)
932         /* TASK must be dead.  */
933         {
934           task->dead = 1;
935           task = 0;
936         }
937     }
938
939   if (!task)
940     {
941       num_threads = 0;
942       inf_debug (inf, "no task");
943     }
944
945   {
946     unsigned search_start = 0;  /* Make things normally linear.  */
947     /* Which thread in PROCS corresponds to each task thread, & the task.  */
948     struct proc *matched[num_threads + 1];
949     /* The last thread in INF->threads, so we can add to the end.  */
950     struct proc *last = 0;
951     /* The current thread we're considering. */
952     struct proc *thread = inf->threads;
953
954     bzero (matched, sizeof (matched));
955
956     while (thread)
957       {
958         unsigned left;
959
960         for (i = search_start, left = num_threads; left; i++, left--)
961           {
962             if (i >= num_threads)
963               i -= num_threads; /* I wrapped around.  */
964             if (thread->port == threads[i])
965               /* We already know about this thread.  */
966               {
967                 matched[i] = thread;
968                 last = thread;
969                 thread = thread->next;
970                 search_start++;
971                 break;
972               }
973           }
974
975         if (! left)
976           {
977             proc_debug (thread, "died!");
978             thread->port = MACH_PORT_NULL;
979             thread = _proc_free (thread); /* THREAD is dead.  */
980             (last ? last->next : inf->threads) = thread;
981           }
982       }
983
984     for (i = 0; i < num_threads; i++)
985       if (matched[i])
986         /* Throw away the duplicate send right.  */
987         mach_port_deallocate (mach_task_self (), threads[i]);
988       else
989         /* THREADS[I] is a thread we don't know about yet!  */
990         {
991 #if 0
992           thread = make_proc (inf, threads[i], next_thread_id++);
993 #else
994           thread = make_proc (inf, threads[i], threads[i]);
995 #endif
996           (last ? last->next : inf->threads) = thread;
997           last = thread;
998           proc_debug (thread, "new thread: %d", threads[i]);
999 #if 1 /* try leaving this out, see what happens */
1000           add_thread (thread->tid); /* Tell GDB's generic thread code.  */
1001 #if 0   /* seems to cause kernel exceptions??? */
1002           target_terminal_ours_for_output ();   /* allow debugger I/O */
1003           printf_filtered ("[gnu-nat: New %s]\n", 
1004                            target_pid_to_str (thread->tid));
1005           target_terminal_inferior ();  /* give it back */
1006 #endif
1007 #endif
1008         }
1009
1010     vm_deallocate(mach_task_self(),
1011                   (vm_address_t)threads, (num_threads * sizeof(thread_t)));
1012   }
1013 }
1014 \f
1015 /* Makes sure that INF's thread list is synced with the actual process.  */
1016 inline int
1017 inf_update_procs (struct inf *inf)
1018 {
1019   if (! inf->task)
1020     return 0;
1021   if (! inf->threads_up_to_date)
1022     inf_validate_procs (inf);
1023   return !!inf->task;
1024 }
1025
1026 /* Sets the resume_sc of each thread in inf.  That of RUN_THREAD is set to 0,
1027    and others are set to their run_sc if RUN_OTHERS is true, and otherwise
1028    their pause_sc.  */
1029 static inline void 
1030 inf_set_threads_resume_sc (struct inf *inf,
1031                            struct proc *run_thread, int run_others)
1032 {
1033   struct proc *thread;
1034   inf_update_procs (inf);
1035   for (thread = inf->threads; thread; thread = thread->next)
1036     if (thread == run_thread)
1037       thread->resume_sc = 0;
1038     else if (run_others)
1039       thread->resume_sc = thread->run_sc;
1040     else
1041       thread->resume_sc = thread->pause_sc;
1042 }
1043 \f
1044 /* Cause INF to continue execution immediately; individual threads may still
1045    be suspended (but their suspend counts will be updated).  */
1046 static inline void
1047 inf_resume (struct inf *inf)
1048 {
1049   struct proc *thread;
1050
1051   inf_update_procs (inf);
1052
1053   for (thread = inf->threads; thread; thread = thread->next)
1054     thread->sc = thread->resume_sc;
1055
1056   if (inf->task)
1057     {
1058       if (! inf->pending_execs)
1059         /* Try to make sure our task count is correct -- in the case where
1060            we're waiting for an exec though, things are too volatile, so just
1061            assume things will be reasonable (which they usually will be).  */
1062         inf_validate_task_sc (inf);
1063       inf->task->sc = 0;
1064     }
1065
1066   inf_update_suspends (inf);
1067 }
1068
1069 /* Cause INF to stop execution immediately; individual threads may still
1070    be running.  */
1071 static inline void
1072 inf_suspend (struct inf *inf)
1073 {
1074   struct proc *thread;
1075
1076   inf_update_procs (inf);
1077
1078   for (thread = inf->threads; thread; thread = thread->next)
1079     thread->sc = thread->pause_sc;
1080
1081   if (inf->task)
1082     inf->task->sc = inf->pause_sc;
1083
1084   inf_update_suspends (inf);
1085 }
1086 \f
1087 /* INF has one thread PROC that is in single-stepping mode.  This function
1088    changes it to be PROC, changing any old step_thread to be a normal one.  A
1089    PROC of 0 clears any existing value.  */
1090 static void
1091 inf_set_step_thread (struct inf *inf, struct proc *thread)
1092 {
1093   assert (!thread || proc_is_thread (thread));
1094
1095   if (thread)
1096     inf_debug (inf, "setting step thread: %d/%d", inf->pid, thread->tid);
1097   else
1098     inf_debug (inf, "clearing step thread");
1099
1100   if (inf->step_thread != thread)
1101     {
1102       if (inf->step_thread && inf->step_thread->port != MACH_PORT_NULL)
1103         if (! proc_trace (inf->step_thread, 0))
1104           return;
1105       if (thread && proc_trace (thread, 1))
1106         inf->step_thread = thread;
1107       else
1108         inf->step_thread = 0;
1109     }
1110 }
1111 \f
1112 /* Set up the thread resume_sc's so that only the signal thread is running
1113    (plus whatever other thread are set to always run).  Returns true if we
1114    did so, or false if we can't find a signal thread.  */
1115 static inline int
1116 inf_set_threads_resume_sc_for_signal_thread (struct inf *inf)
1117 {
1118   if (inf->signal_thread)
1119     {
1120       inf_set_threads_resume_sc (inf, inf->signal_thread, 0);
1121       return 1;
1122     }
1123   else
1124     return 0;
1125 }
1126
1127 static void
1128 inf_update_signal_thread (struct inf *inf)
1129 {
1130   /* XXX for now we assume that if there's a msgport, the 2nd thread is
1131      the signal thread.  */
1132   inf->signal_thread = inf->threads ? inf->threads->next : 0;
1133 }
1134 \f
1135 /* Detachs from INF's inferior task, letting it run once again...  */
1136 static void
1137 inf_detach (struct inf *inf)
1138 {
1139   struct proc *task = inf->task;
1140
1141   inf_debug (inf, "detaching...");
1142
1143   inf_clear_wait (inf);
1144   inf_set_step_thread (inf, 0);
1145
1146   if (task)
1147     {
1148       struct proc *thread;
1149
1150       inf_set_traced (inf, 0);
1151       if (inf->stopped)
1152         inf_signal (inf, TARGET_SIGNAL_0);
1153
1154       proc_restore_exc_port (task);
1155       task->sc = inf->detach_sc;
1156
1157       for (thread = inf->threads; thread; thread = thread->next)
1158         {
1159           proc_restore_exc_port (thread);
1160           thread->sc = thread->detach_sc;
1161         }
1162
1163       inf_update_suspends (inf);
1164     }
1165
1166   inf_cleanup (inf);
1167 }
1168
1169 /* Attaches INF to the process with process id PID, returning it in a suspended
1170    state suitable for debugging.  */
1171 static void
1172 inf_attach (struct inf *inf, int pid)
1173 {
1174   error_t err;
1175   task_t task;
1176
1177   inf_debug (inf, "attaching: %d", pid);
1178
1179   err = proc_pid2task (proc_server, pid, &task);
1180   if (err)
1181     error ("Error getting task for pid %d: %s", pid, strerror (err));
1182
1183   if (inf->pid)
1184     inf_detach (inf);
1185
1186   inf_startup (inf, pid, task);
1187 }
1188 \f
1189 /* Makes sure that we've got our exception ports entrenched in the process. */
1190 void inf_steal_exc_ports (struct inf *inf)
1191 {
1192   struct proc *thread;
1193
1194   inf_debug (inf, "stealing exception ports");
1195
1196   inf_set_step_thread (inf, 0); /* The step thread is special. */
1197
1198   proc_steal_exc_port (inf->task, inf->event_port);
1199   for (thread = inf->threads; thread; thread = thread->next)
1200     proc_steal_exc_port (thread, MACH_PORT_NULL);
1201 }
1202
1203 /* Makes sure the process has its own exception ports.  */
1204 void inf_restore_exc_ports (struct inf *inf)
1205 {
1206   struct proc *thread;
1207
1208   inf_debug (inf, "restoring exception ports");
1209
1210   inf_set_step_thread (inf, 0); /* The step thread is special. */
1211
1212   proc_restore_exc_port (inf->task);
1213   for (thread = inf->threads; thread; thread = thread->next)
1214     proc_restore_exc_port (thread);
1215 }
1216 \f
1217 /* Deliver signal SIG to INF.  If INF is stopped, delivering a signal, even
1218    signal 0, will continue it.  INF is assumed to be in a paused state, and
1219    the resume_sc's of INF's threads may be affected.  */
1220 static void
1221 inf_signal (struct inf *inf, enum target_signal sig)
1222 {
1223   error_t err = 0;
1224   int host_sig = target_signal_to_host (sig);
1225
1226 #define NAME target_signal_to_name (sig)
1227
1228   if (host_sig >= _NSIG)
1229     /* A mach exception.  Exceptions are encoded in the signal space by
1230        putting them after _NSIG; this assumes they're positive (and not
1231        extremely large)!  */
1232     {
1233       struct inf_wait *w = &inf->wait;
1234       if (w->status.kind == TARGET_WAITKIND_STOPPED
1235           && w->status.value.sig == sig
1236           && w->thread && !w->thread->aborted)
1237         /* We're passing through the last exception we received.  This is
1238            kind of bogus, because exceptions are per-thread whereas gdb
1239            treats signals as per-process.  We just forward the exception to
1240            the correct handler, even it's not for the same thread as TID --
1241            i.e., we pretend it's global.  */
1242         {
1243           struct exc_state *e = &w->exc;
1244           inf_debug (inf, "passing through exception:"
1245                      " task = %d, thread = %d, exc = %d"
1246                      ", code = %d, subcode = %d",
1247                      w->thread->port, inf->task->port,
1248                      e->exception, e->code, e->subcode);
1249           err =
1250             exception_raise_request (e->handler,
1251                                      e->reply, MACH_MSG_TYPE_MOVE_SEND_ONCE,
1252                                      w->thread->port, inf->task->port,
1253                                      e->exception, e->code, e->subcode);
1254         }
1255       else
1256         error ("Can't forward spontaneous exception (%s).", NAME);
1257     }
1258   else
1259     /* A Unix signal.  */
1260     if (inf->stopped)
1261       /* The process is stopped and expecting a signal.  Just send off a
1262          request and let it get handled when we resume everything.  */
1263       {
1264         inf_debug (inf, "sending %s to stopped process", NAME);
1265         err =
1266           INF_MSGPORT_RPC (inf,
1267                            msg_sig_post_untraced_request (msgport,
1268                                                           inf->event_port,
1269                                                           MACH_MSG_TYPE_MAKE_SEND_ONCE,
1270                                                           host_sig, 0,
1271                                                           refport));
1272         if (! err)
1273           /* Posting an untraced signal automatically continues it.
1274              We clear this here rather than when we get the reply
1275              because we'd rather assume it's not stopped when it
1276              actually is, than the reverse.  */
1277           inf->stopped = 0;
1278       }
1279     else
1280       /* It's not expecting it.  We have to let just the signal thread
1281          run, and wait for it to get into a reasonable state before we
1282          can continue the rest of the process.  When we finally resume the
1283          process the signal we request will be the very first thing that
1284          happens. */
1285       {
1286         inf_debug (inf, "sending %s to unstopped process (so resuming signal thread)", NAME);
1287         err = 
1288           INF_RESUME_MSGPORT_RPC (inf, msg_sig_post_untraced (msgport,
1289                                                               host_sig, 0, refport));
1290       }
1291
1292   if (err == EIEIO)
1293     /* Can't do too much... */
1294     warning ("Can't deliver signal %s: No signal thread.", NAME);
1295   else if (err)
1296     warning ("Delivering signal %s: %s", NAME, strerror (err));
1297
1298 #undef NAME
1299 }
1300 \f
1301 /* The inferior used for all gdb target ops.  */
1302 struct inf *current_inferior = 0;
1303
1304 /* The inferior being waited for by gnu_wait.  Since GDB is decidely not
1305    multi-threaded, we don't bother to lock this.  */
1306 struct inf *waiting_inf;
1307
1308 /* Wait for something to happen in the inferior, returning what in STATUS. */
1309 static int
1310 gnu_wait (int tid, struct target_waitstatus *status)
1311 {
1312   struct msg {
1313     mach_msg_header_t hdr;
1314     mach_msg_type_t type;
1315     int data[8000];
1316   } msg;
1317   error_t err;
1318   struct proc *thread;
1319   struct inf *inf = current_inferior;
1320
1321   assert (inf->task);
1322
1323   if (!inf->threads && !inf->pending_execs)
1324     /* No threads!  Assume that maybe some outside agency is frobbing our
1325        task, and really look for new threads.  If we can't find any, just tell
1326        the user to try again later.  */
1327     {
1328       inf_validate_procs (inf);
1329       if (!inf->threads && !inf->task->dead)
1330         error ("There are no threads; try again later.");
1331     }
1332
1333   waiting_inf = inf;
1334
1335   inf_debug (inf, "waiting for: %d", tid);
1336
1337  rewait:
1338   if (proc_wait_pid != inf->pid && !inf->no_wait)
1339     /* Always get information on events from the proc server.  */
1340     {
1341       inf_debug (inf, "requesting wait on pid %d", inf->pid);
1342
1343       if (proc_wait_pid)
1344         /* The proc server is single-threaded, and only allows a single
1345            outstanding wait request, so we have to cancel the previous one. */
1346         {
1347           inf_debug (inf, "cancelling previous wait on pid %d", proc_wait_pid);
1348           interrupt_operation (proc_server, 0);
1349         }
1350
1351       err =
1352         proc_wait_request (proc_server, inf->event_port, inf->pid, WUNTRACED);
1353       if (err)
1354         warning ("wait request failed: %s", strerror (err));
1355       else
1356         {
1357           inf_debug (inf, "waits pending: %d", proc_waits_pending);
1358           proc_wait_pid = inf->pid;
1359           /* Even if proc_waits_pending was > 0 before, we still won't get
1360              any other replies, because it was either from a different INF,
1361              or a different process attached to INF -- and the event port,
1362              which is the wait reply port, changes when you switch processes.*/
1363           proc_waits_pending = 1;
1364         }
1365     }
1366
1367   inf_clear_wait (inf);
1368
1369   /* What can happen? (1) Dead name notification; (2) Exceptions arrive;
1370      (3) wait reply from the proc server.  */
1371
1372   inf_debug (inf, "waiting for an event...");
1373   err = mach_msg (&msg.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT,
1374                   0, sizeof (struct msg), inf->event_port,
1375                   MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
1376
1377   /* Re-suspend the task.  */
1378   inf_suspend (inf);
1379
1380   if (err == EMACH_RCV_INTERRUPTED)
1381     inf_debug (inf, "interrupted");
1382   else if (err)
1383     error ("Couldn't wait for an event: %s", strerror (err));
1384   else
1385     {
1386       struct {
1387         mach_msg_header_t hdr;
1388         mach_msg_type_t err_type;
1389         kern_return_t err;
1390         char noise[200];
1391       } reply;
1392
1393       inf_debug (inf, "event: msgid = %d", msg.hdr.msgh_id);
1394
1395       /* Handle what we got.  */
1396       if (! notify_server (&msg.hdr, &reply.hdr)
1397           && ! exc_server (&msg.hdr, &reply.hdr)
1398           && ! process_reply_server (&msg.hdr, &reply.hdr)
1399           && ! msg_reply_server (&msg.hdr, &reply.hdr))
1400         /* Whatever it is, it's something strange.  */
1401         error ("Got a strange event, msg id = %d.", msg.hdr.msgh_id);
1402
1403       if (reply.err)
1404         error ("Handling event, msgid = %d: %s",
1405                msg.hdr.msgh_id, strerror (reply.err));
1406     }
1407
1408   if (inf->pending_execs)
1409     /* We're waiting for the inferior to finish execing.  */
1410     {
1411       struct inf_wait *w = &inf->wait;
1412       enum target_waitkind kind = w->status.kind;
1413
1414       if (kind == TARGET_WAITKIND_SPURIOUS)
1415         /* Since gdb is actually counting the number of times the inferior
1416            stops, expecting one stop per exec, we only return major events
1417            while execing.  */
1418         {
1419           w->suppress = 1;
1420           inf_debug (inf, "pending_execs = %d, ignoring minor event",
1421                      inf->pending_execs);
1422         }
1423       else if (kind == TARGET_WAITKIND_STOPPED
1424                && w->status.value.sig == TARGET_SIGNAL_TRAP)
1425         /* Ah hah!  A SIGTRAP from the inferior while starting up probably
1426            means we've succesfully completed an exec!  */
1427         {
1428 #if 0   /* do we need this? */
1429           if (--inf->pending_execs == 0)
1430             /* We're done!  */
1431             {
1432               prune_threads (1);        /* Get rid of the old shell threads */
1433               renumber_threads (0); /* Give our threads reasonable names. */
1434             }
1435 #endif
1436           inf_debug (inf, "pending exec completed, pending_execs => %d",
1437                      inf->pending_execs);
1438         }
1439     }
1440
1441   if (inf->wait.suppress)
1442     /* Some totally spurious event happened that we don't consider
1443        worth returning to gdb.  Just keep waiting.  */
1444     {
1445       inf_debug (inf, "suppressing return, rewaiting...");
1446       inf_resume (inf);
1447       goto rewait;
1448     }
1449
1450   /* Pass back out our results.  */
1451   bcopy (&inf->wait.status, status, sizeof (*status));
1452
1453   thread = inf->wait.thread;
1454   if (thread)
1455     tid = thread->tid;
1456   else
1457     thread = inf_tid_to_thread (inf, tid);
1458
1459   if (!thread || thread->port == MACH_PORT_NULL)
1460     /* TID is dead; try and find a new thread.  */
1461     if (inf_update_procs (inf) && inf->threads)
1462       tid = inf->threads->tid;  /* The first available thread.  */
1463     else
1464       tid = inferior_pid; /* let wait_for_inferior handle exit case */
1465
1466   if (thread && tid >= 0 && status->kind != TARGET_WAITKIND_SPURIOUS
1467       && inf->pause_sc == 0 && thread->pause_sc == 0)
1468     /* If something actually happened to THREAD, make sure we suspend it.  */
1469     {
1470       thread->sc = 1;
1471       inf_update_suspends (inf);
1472     }      
1473
1474   inf_debug (inf, "returning tid = %d, status = %s (%d)", tid,
1475              status->kind == TARGET_WAITKIND_EXITED ? "EXITED"
1476              : status->kind == TARGET_WAITKIND_STOPPED ? "STOPPED"
1477              : status->kind == TARGET_WAITKIND_SIGNALLED ? "SIGNALLED"
1478              : status->kind == TARGET_WAITKIND_LOADED ? "LOADED"
1479              : status->kind == TARGET_WAITKIND_SPURIOUS ? "SPURIOUS"
1480              : "?",
1481              status->value.integer);
1482
1483   return tid;
1484 }
1485 \f
1486 /* The rpc handler called by exc_server.  */
1487 error_t
1488 S_exception_raise_request (mach_port_t port, mach_port_t reply_port,
1489                            thread_t thread_port, task_t task_port,
1490                            int exception, int code, int subcode)
1491 {
1492   struct inf *inf = waiting_inf;
1493   struct proc *thread = inf_port_to_thread (inf, thread_port);
1494
1495   inf_debug (waiting_inf,
1496              "thread = %d, task = %d, exc = %d, code = %d, subcode = %d",
1497              thread_port, task_port, exception, code);
1498
1499   if (!thread)
1500     /* We don't know about thread?  */
1501     {
1502       inf_update_procs (inf);
1503       thread = inf_port_to_thread (inf, thread_port);
1504       if (!thread)
1505         /* Give up, the generating thread is gone.  */
1506         return 0;
1507     }
1508
1509   mach_port_deallocate (mach_task_self (), thread_port);
1510   mach_port_deallocate (mach_task_self (), task_port);
1511
1512   if (! thread->aborted)
1513     /* THREAD hasn't been aborted since this exception happened (abortion
1514        clears any exception state), so it must be real.  */
1515     {
1516       /* Store away the details; this will destroy any previous info.  */
1517       inf->wait.thread = thread;
1518
1519       inf->wait.status.kind = TARGET_WAITKIND_STOPPED;
1520
1521       if (exception == EXC_BREAKPOINT)
1522         /* GDB likes to get SIGTRAP for breakpoints.  */
1523         {
1524           inf->wait.status.value.sig = TARGET_SIGNAL_TRAP;
1525           mach_port_deallocate (mach_task_self (), reply_port);
1526         }
1527       else
1528         /* Record the exception so that we can forward it later.  */
1529         {
1530           if (thread->exc_port == port)
1531             {
1532               inf_debug (waiting_inf, "Handler is thread exeption port <%d>",
1533                          thread->saved_exc_port);
1534               inf->wait.exc.handler = thread->saved_exc_port;
1535             }
1536           else
1537             {
1538               inf_debug (waiting_inf, "Handler is task exeption port <%d>",
1539                          inf->task->saved_exc_port);
1540               inf->wait.exc.handler = inf->task->saved_exc_port;
1541               assert (inf->task->exc_port == port);
1542             }
1543           if (inf->wait.exc.handler != MACH_PORT_NULL)
1544             /* Add a reference to the exception handler. */
1545             mach_port_mod_refs (mach_task_self (),
1546                                 inf->wait.exc.handler, MACH_PORT_RIGHT_SEND,
1547                                 1);
1548
1549           inf->wait.exc.exception = exception;
1550           inf->wait.exc.code = code;
1551           inf->wait.exc.subcode = subcode;
1552           inf->wait.exc.reply = reply_port;
1553
1554           /* Exceptions are encoded in the signal space by putting them after
1555              _NSIG; this assumes they're positive (and not extremely large)! */
1556           inf->wait.status.value.sig =
1557             target_signal_from_host (_NSIG + exception);
1558         }
1559     }
1560   else
1561     /* A supppressed exception, which ignore.  */
1562     {
1563       inf->wait.suppress = 1;
1564       mach_port_deallocate (mach_task_self (), reply_port);
1565     }
1566
1567   return 0;
1568 }
1569 \f
1570 /* Fill in INF's wait field after a task has died without giving us more
1571    detailed information.  */
1572 static void
1573 inf_task_died_status (struct inf *inf)
1574 {
1575   warning ("Pid %d died with unknown exit status, using SIGKILL.", inf->pid);
1576   inf->wait.status.kind = TARGET_WAITKIND_SIGNALLED;
1577   inf->wait.status.value.sig = TARGET_SIGNAL_KILL;
1578 }
1579
1580 /* Notify server routines.  The only real one is dead name notification.  */
1581 error_t
1582 do_mach_notify_dead_name (mach_port_t notify, mach_port_t dead_port)
1583 {
1584   struct inf *inf = waiting_inf;
1585
1586   inf_debug (waiting_inf, "port = %d", dead_port);
1587
1588   if (inf->task && inf->task->port == dead_port)
1589     {
1590       proc_debug (inf->task, "is dead");
1591       inf->task->port = MACH_PORT_NULL;
1592       if (proc_wait_pid == inf->pid)
1593         /* We have a wait outstanding on the process, which will return more
1594            detailed information, so delay until we get that.  */
1595         inf->wait.suppress = 1;
1596       else
1597         /* We never waited for the process (maybe it wasn't a child), so just
1598            pretend it got a SIGKILL.  */
1599         inf_task_died_status (inf);
1600     }
1601   else
1602     {
1603       struct proc *thread = inf_port_to_thread (inf, dead_port);
1604       if (thread)
1605         {
1606           proc_debug (thread, "is dead");
1607           thread->port = MACH_PORT_NULL;
1608         }
1609     }
1610
1611   mach_port_deallocate (mach_task_self (), dead_port);
1612   inf->threads_up_to_date = 0; /* Just in case */
1613
1614   return 0;
1615 }
1616 \f
1617 static error_t
1618 ill_rpc (char *fun)
1619 {
1620   warning ("illegal rpc: %s", fun);
1621   return 0;
1622 }
1623
1624 error_t
1625 do_mach_notify_no_senders (mach_port_t notify, mach_port_mscount_t count)
1626 {
1627   return ill_rpc (__FUNCTION__);
1628 }
1629
1630 error_t
1631 do_mach_notify_port_deleted (mach_port_t notify, mach_port_t name)
1632 {
1633   return ill_rpc (__FUNCTION__);
1634 }
1635
1636 error_t
1637 do_mach_notify_msg_accepted (mach_port_t notify, mach_port_t name)
1638 {
1639   return ill_rpc (__FUNCTION__);
1640 }
1641
1642 error_t
1643 do_mach_notify_port_destroyed (mach_port_t notify, mach_port_t name)
1644 {
1645   return ill_rpc (__FUNCTION__);
1646 }
1647
1648 error_t
1649 do_mach_notify_send_once (mach_port_t notify)
1650 {
1651   return ill_rpc (__FUNCTION__);
1652 }
1653 \f
1654 /* Process_reply server routines.  We only use process_wait_reply.  */
1655
1656 error_t
1657 S_proc_wait_reply (mach_port_t reply, error_t err,
1658                    int status, int sigcode, rusage_t rusage, pid_t pid)
1659 {
1660   struct inf *inf = waiting_inf;
1661
1662   inf_debug (inf, "err = %s, pid = %d, status = 0x%x, sigcode = %d",
1663              err ? strerror (err) : "0", pid, status, sigcode);
1664
1665   if (err && proc_wait_pid && (!inf->task || !inf->task->port))
1666     /* Ack.  The task has died, but the task-died notification code didn't
1667        tell anyone because it thought a more detailed reply from the
1668        procserver was forthcoming.  However, we now learn that won't
1669        happen...  So we have to act like the task just died, and this time,
1670        tell the world.  */
1671     inf_task_died_status (inf);
1672
1673   if (--proc_waits_pending == 0)
1674     /* PROC_WAIT_PID represents the most recent wait.  We will always get
1675        replies in order because the proc server is single threaded.  */
1676     proc_wait_pid = 0;
1677
1678   inf_debug (inf, "waits pending now: %d", proc_waits_pending);
1679
1680   if (err)
1681     {
1682       if (err != EINTR)
1683         {
1684           warning ("Can't wait for pid %d: %s", inf->pid, strerror (err));
1685           inf->no_wait = 1;
1686
1687           /* Since we can't see the inferior's signals, don't trap them.  */
1688           inf_set_traced (inf, 0);
1689         }
1690     }
1691   else if (pid == inf->pid)
1692     {
1693       store_waitstatus (&inf->wait.status, status);
1694       if (inf->wait.status.kind == TARGET_WAITKIND_STOPPED)
1695         /* The process has sent us a signal, and stopped itself in a sane
1696            state pending our actions.  */
1697         {
1698           inf_debug (inf, "process has stopped itself");
1699           inf->stopped = 1;
1700         }
1701     }
1702   else
1703     inf->wait.suppress = 1;     /* Something odd happened.  Ignore.  */
1704
1705   return 0;
1706 }
1707
1708 error_t
1709 S_proc_setmsgport_reply (mach_port_t reply, error_t err,
1710                          mach_port_t old_msg_port)
1711 {
1712   return ill_rpc (__FUNCTION__);
1713 }
1714
1715 error_t
1716 S_proc_getmsgport_reply (mach_port_t reply, error_t err, mach_port_t msg_port)
1717 {
1718   return ill_rpc (__FUNCTION__);
1719 }
1720 \f
1721 /* Msg_reply server routines.  We only use msg_sig_post_untraced_reply.  */
1722
1723 error_t
1724 S_msg_sig_post_untraced_reply (mach_port_t reply, error_t err)
1725 {
1726   struct inf *inf = waiting_inf;
1727
1728   if (err == EBUSY)
1729     /* EBUSY is what we get when the crash server has grabbed control of the
1730        process and doesn't like what signal we tried to send it.  Just act
1731        like the process stopped (using a signal of 0 should mean that the
1732        *next* time the user continues, it will pass signal 0, which the crash
1733        server should like).  */
1734     {
1735       inf->wait.status.kind = TARGET_WAITKIND_STOPPED;
1736       inf->wait.status.value.sig = TARGET_SIGNAL_0;
1737     }
1738   else if (err)
1739     warning ("Signal delivery failed: %s", strerror (err));
1740
1741   if (err)
1742     /* We only get this reply when we've posted a signal to a process which we
1743        thought was stopped, and which we expected to continue after the signal.
1744        Given that the signal has failed for some reason, it's reasonable to
1745        assume it's still stopped.  */
1746     inf->stopped = 1;
1747   else
1748     inf->wait.suppress = 1;
1749
1750   return 0;
1751 }
1752
1753 error_t
1754 S_msg_sig_post_reply (mach_port_t reply, error_t err)
1755 {
1756   return ill_rpc (__FUNCTION__);
1757 }
1758 \f
1759 /* Returns the number of messages queued for the receive right PORT.  */
1760 static mach_port_msgcount_t
1761 port_msgs_queued (mach_port_t port)
1762 {
1763   struct mach_port_status status;
1764   error_t err =
1765     mach_port_get_receive_status (mach_task_self (), port, &status);
1766
1767   if (err)
1768     return 0;
1769   else
1770     return status.mps_msgcount;
1771 }
1772 \f
1773 /* Resume execution of the inferior process.
1774
1775    If STEP is nonzero, single-step it.
1776    If SIGNAL is nonzero, give it that signal.
1777
1778    TID  STEP:
1779    -1   true   Single step the current thread allowing other threads to run.
1780    -1   false  Continue the current thread allowing other threads to run.
1781    X    true   Single step the given thread, don't allow any others to run.
1782    X    false  Continue the given thread, do not allow any others to run.
1783    (Where X, of course, is anything except -1)
1784
1785    Note that a resume may not `take' if there are pending exceptions/&c
1786    still unprocessed from the last resume we did (any given resume may result
1787    in multiple events returned by wait).
1788 */
1789 static void
1790 gnu_resume (int tid, int step, enum target_signal sig)
1791 {
1792   struct proc *step_thread = 0;
1793   struct inf *inf = current_inferior;
1794
1795   inf_debug (inf, "tid = %d, step = %d, sig = %d", tid, step, sig);
1796
1797   if (sig != TARGET_SIGNAL_0 || inf->stopped)
1798     inf_signal (inf, sig);
1799   else if (inf->wait.exc.reply != MACH_PORT_NULL)
1800     /* We received an exception to which we have chosen not to forward, so
1801        abort the faulting thread, which will perhaps retake it.  */
1802     {
1803       proc_abort (inf->wait.thread, 1);
1804       warning ("Aborting %s with unforwarded exception %s.",
1805                proc_string (inf->wait.thread),
1806                target_signal_to_name (inf->wait.status.value.sig));
1807     }
1808
1809   if (port_msgs_queued (inf->event_port))
1810     /* If there are still messages in our event queue, don't bother resuming
1811        the process, as we're just going to stop it right away anyway. */
1812     return;
1813
1814   inf_update_procs (inf);
1815
1816   if (tid < 0)
1817     /* Allow all threads to run, except perhaps single-stepping one.  */
1818     {
1819       inf_debug (inf, "running all threads; tid = %d", inferior_pid);
1820       tid = inferior_pid;       /* What to step. */
1821       inf_set_threads_resume_sc (inf, 0, 1);
1822     }
1823   else
1824     /* Just allow a single thread to run.  */
1825     {
1826       struct proc *thread = inf_tid_to_thread (inf, tid);
1827       if (! thread)
1828         error ("Can't run single thread id %d: no such thread!");
1829       inf_debug (inf, "running one thread: %d/%d", inf->pid, thread->tid);
1830       inf_set_threads_resume_sc (inf, thread, 0);
1831     }
1832
1833   if (step)
1834     {
1835       step_thread = inf_tid_to_thread (inf, tid);
1836       if (! step_thread)
1837         warning ("Can't step thread id %d: no such thread.", tid);
1838       else
1839         inf_debug (inf, "stepping thread: %d/%d", inf->pid, step_thread->tid);
1840     }
1841   if (step_thread != inf->step_thread)
1842     inf_set_step_thread (inf, step_thread);
1843
1844   inf_debug (inf, "here we go...");
1845   inf_resume (inf);
1846 }
1847 \f
1848 static void
1849 gnu_kill_inferior ()
1850 {
1851   struct proc *task = current_inferior->task;
1852   if (task)
1853     {
1854       proc_debug (task, "terminating...");
1855       task_terminate (task->port);
1856       inf_set_task (current_inferior, MACH_PORT_NULL);
1857     }
1858   target_mourn_inferior ();
1859 }
1860
1861 /* Clean up after the inferior dies.  */
1862
1863 static void
1864 gnu_mourn_inferior ()
1865 {
1866   inf_debug (current_inferior, "rip");
1867   inf_detach (current_inferior);
1868   unpush_target (&gnu_ops);
1869   generic_mourn_inferior ();
1870 }
1871 \f
1872 /* Fork an inferior process, and start debugging it.  */
1873
1874 /* Set INFERIOR_PID to the first thread available in the child, if any.  */
1875 static int
1876 inf_pick_first_thread ()
1877 {
1878   if (current_inferior->task && current_inferior->threads)
1879     /* The first thread.  */
1880     return current_inferior->threads->tid;
1881   else
1882     /* What may be the next thread.  */
1883     return next_thread_id;
1884 }
1885
1886 static struct inf *
1887 cur_inf ()
1888 {
1889   if (! current_inferior)
1890     current_inferior = make_inf ();
1891   return current_inferior;
1892 }
1893
1894 static void
1895 gnu_create_inferior (exec_file, allargs, env)
1896      char *exec_file;
1897      char *allargs;
1898      char **env;
1899 {
1900   struct inf *inf = cur_inf ();
1901
1902   void trace_me ()
1903     {
1904       /* We're in the child; make this process stop as soon as it execs.  */
1905       inf_debug (inf, "tracing self");
1906       if (ptrace (PTRACE_TRACEME) != 0)
1907         error ("ptrace (PTRACE_TRACEME) failed!");
1908     }
1909   int attach_to_child (int pid)
1910     {
1911       /* Attach to the now stopped child, which is actually a shell...  */
1912       inf_debug (inf, "attaching to child: %d", pid);
1913
1914       inf_attach (inf, pid);
1915
1916       attach_flag = 0;
1917       push_target (&gnu_ops);
1918
1919       inf->pending_execs = 2;
1920       inf->traced = 1;
1921
1922       /* Now let the child run again, knowing that it will stop immediately
1923          because of the ptrace. */
1924       inf_resume (inf);
1925       inferior_pid = inf_pick_first_thread ();
1926
1927       startup_inferior (inf->pending_execs);
1928
1929       return inferior_pid;
1930     }
1931
1932   inf_debug (inf, "creating inferior");
1933
1934   fork_inferior (exec_file, allargs, env, trace_me, attach_to_child, NULL);
1935
1936   inf_update_signal_thread (inf);
1937   inf_set_traced (inf, inf->want_signals);
1938
1939   /* Execing the process will have trashed our exception ports; steal them
1940      back (or make sure they're restored if the user wants that).  */
1941   if (inf->want_exceptions)
1942     inf_steal_exc_ports (inf);
1943   else
1944     inf_restore_exc_ports (inf);
1945
1946   /* Here we go!  */
1947   proceed ((CORE_ADDR) -1, 0, 0);
1948 }
1949
1950 /* Mark our target-struct as eligible for stray "run" and "attach"
1951    commands.  */
1952 static int
1953 gnu_can_run ()
1954 {
1955   return 1;
1956 }
1957 \f
1958 #ifdef ATTACH_DETACH
1959
1960 /* Attach to process PID, then initialize for debugging it
1961    and wait for the trace-trap that results from attaching.  */
1962 static void
1963 gnu_attach (args, from_tty)
1964      char *args;
1965      int from_tty;
1966 {
1967   int pid;
1968   char *exec_file;
1969   struct inf *inf = cur_inf ();
1970
1971   if (!args)
1972     error_no_arg ("PID to attach");
1973
1974   pid = atoi (args);
1975
1976   if (pid == getpid())          /* Trying to masturbate? */
1977     error ("I refuse to debug myself!");
1978
1979   if (from_tty)
1980     {
1981       exec_file = (char *) get_exec_file (0);
1982
1983       if (exec_file)
1984         printf_unfiltered ("Attaching to program `%s', pid %d\n",
1985                            exec_file, pid);
1986       else
1987         printf_unfiltered ("Attaching to pid %d\n", pid);
1988
1989       gdb_flush (gdb_stdout);
1990     }
1991
1992   inf_debug (inf, "attaching to pid: %d", pid);
1993
1994   inf_attach (inf, pid);
1995   inf_update_procs (inf);
1996
1997   inferior_pid = inf_pick_first_thread ();
1998
1999   attach_flag = 1;
2000   push_target (&gnu_ops);
2001
2002   inf_update_signal_thread (inf);
2003   inf_set_traced (inf, inf->want_signals);
2004
2005   /* If the process was stopped before we attached, make it continue the next
2006      time the user does a continue.  */
2007   inf_validate_stopped (inf);
2008
2009 #if 0 /* Do we need this?  Actually I can see where it 
2010          might be helpful here, but it's just cosmetic.
2011          Let's come back to it later.  XXX Fix me. */
2012   renumber_threads (0);         /* Give our threads reasonable names. */
2013 #endif
2014 }
2015 \f
2016 /* Take a program previously attached to and detaches it.
2017    The program resumes execution and will no longer stop
2018    on signals, etc.  We'd better not have left any breakpoints
2019    in the program or it'll die when it hits one.  For this
2020    to work, it may be necessary for the process to have been
2021    previously attached.  It *might* work if the program was
2022    started via fork.  */
2023 static void
2024 gnu_detach (args, from_tty)
2025      char *args;
2026      int from_tty;
2027 {
2028   if (from_tty)
2029     {
2030       char *exec_file = get_exec_file (0);
2031       if (exec_file)
2032         printf_unfiltered ("Detaching from program `%s' pid %d\n",
2033                            exec_file, current_inferior->pid);
2034       else
2035         printf_unfiltered ("Detaching from pid %d\n", current_inferior->pid);
2036       gdb_flush (gdb_stdout);
2037     }
2038   
2039   inf_detach (current_inferior);
2040
2041   inferior_pid = 0;
2042
2043   unpush_target (&gnu_ops);             /* Pop out of handling an inferior */
2044 }
2045 #endif /* ATTACH_DETACH */
2046
2047 static void
2048 gnu_terminal_init_inferior ()
2049 {
2050   assert (current_inferior);
2051   terminal_init_inferior_with_pgrp (current_inferior->pid);
2052 }
2053
2054 /* Get ready to modify the registers array.  On machines which store
2055    individual registers, this doesn't need to do anything.  On machines
2056    which store all the registers in one fell swoop, this makes sure
2057    that registers contains all the registers from the program being
2058    debugged.  */
2059
2060 static void
2061 gnu_prepare_to_store ()
2062 {
2063 #ifdef CHILD_PREPARE_TO_STORE
2064   CHILD_PREPARE_TO_STORE ();
2065 #endif
2066 }
2067
2068 static void
2069 gnu_open (arg, from_tty)
2070      char *arg;
2071      int from_tty;
2072 {
2073   error ("Use the \"run\" command to start a Unix child process.");
2074 }
2075
2076 static void
2077 gnu_stop ()
2078 {
2079   error ("to_stop target function not implemented");
2080 }
2081
2082 static int
2083 gnu_thread_alive (int tid)
2084 {
2085   inf_update_procs (current_inferior);
2086   return !!inf_tid_to_thread (current_inferior, tid);
2087 }
2088 \f
2089 /*
2090  * Read inferior task's LEN bytes from ADDR and copy it to MYADDR
2091  * in gdb's address space.
2092  *
2093  * Return 0 on failure; number of bytes read otherwise.
2094  */
2095 int
2096 gnu_read_inferior (task, addr, myaddr, length)
2097      task_t task;
2098      CORE_ADDR addr;
2099      char *myaddr;
2100      int length;
2101 {
2102   error_t err;
2103   vm_address_t low_address = (vm_address_t) trunc_page (addr);
2104   vm_size_t aligned_length =
2105     (vm_size_t) round_page (addr+length) - low_address;
2106   pointer_t    copied;
2107   int          copy_count;
2108
2109   /* Get memory from inferior with page aligned addresses */
2110   err = vm_read (task, low_address, aligned_length, &copied, &copy_count);
2111   if (err)
2112     return 0;
2113
2114   err = hurd_safe_copyin (myaddr, (void*)addr - low_address + copied, length);
2115   if (err)
2116     {
2117       warning ("Read from inferior faulted: %s", strerror (err));
2118       length = 0;
2119     }
2120
2121   err = vm_deallocate (mach_task_self (), copied, copy_count);
2122   if (err)
2123     warning ("gnu_read_inferior vm_deallocate failed: %s", strerror (err));
2124
2125   return length;
2126 }
2127
2128 #define CHK_GOTO_OUT(str,ret) \
2129   do if (ret != KERN_SUCCESS) { errstr = #str; goto out; } while(0)
2130
2131 struct vm_region_list {
2132   struct vm_region_list *next;
2133   vm_prot_t     protection;
2134   vm_address_t  start;
2135   vm_size_t     length;
2136 };
2137
2138 struct obstack  region_obstack;
2139
2140 /*
2141  * Write gdb's LEN bytes from MYADDR and copy it to ADDR
2142  * in inferior task's address space.
2143  */
2144 int
2145 gnu_write_inferior (task, addr, myaddr, length)
2146      task_t task;
2147      CORE_ADDR addr;
2148      char *myaddr;
2149      int length;
2150 {
2151   error_t err = 0;
2152   vm_address_t low_address       = (vm_address_t) trunc_page (addr);
2153   vm_size_t    aligned_length = 
2154                         (vm_size_t) round_page (addr+length) - low_address;
2155   pointer_t    copied;
2156   int          copy_count;
2157   int          deallocate = 0;
2158
2159   char         *errstr = "Bug in gnu_write_inferior";
2160
2161   struct vm_region_list *region_element;
2162   struct vm_region_list *region_head = (struct vm_region_list *)NULL;
2163
2164   /* Get memory from inferior with page aligned addresses */
2165   err = vm_read (task,
2166                  low_address,
2167                  aligned_length,
2168                  &copied,
2169                  &copy_count);
2170   CHK_GOTO_OUT ("gnu_write_inferior vm_read failed", err);
2171
2172   deallocate++;
2173
2174   err = hurd_safe_copyout ((void*)addr - low_address + copied, myaddr, length);
2175   CHK_GOTO_OUT ("Write to inferior faulted", err);
2176
2177   obstack_init (&region_obstack);
2178
2179   /* Do writes atomically.
2180    * First check for holes and unwritable memory.
2181    */
2182   {
2183     vm_size_t    remaining_length  = aligned_length;
2184     vm_address_t region_address    = low_address;
2185
2186     struct vm_region_list *scan;
2187
2188     while(region_address < low_address + aligned_length)
2189       {
2190         vm_prot_t protection;
2191         vm_prot_t max_protection;
2192         vm_inherit_t inheritance;
2193         boolean_t shared;
2194         mach_port_t object_name;
2195         vm_offset_t offset;
2196         vm_size_t   region_length = remaining_length;
2197         vm_address_t old_address  = region_address;
2198     
2199         err = vm_region (task,
2200                          &region_address,
2201                          &region_length,
2202                          &protection,
2203                          &max_protection,
2204                          &inheritance,
2205                          &shared,
2206                          &object_name,
2207                          &offset);
2208         CHK_GOTO_OUT ("vm_region failed", err);
2209
2210         /* Check for holes in memory */
2211         if (old_address != region_address)
2212           {
2213             warning ("No memory at 0x%x. Nothing written",
2214                      old_address);
2215             err = KERN_SUCCESS;
2216             length = 0;
2217             goto out;
2218           }
2219
2220         if (!(max_protection & VM_PROT_WRITE))
2221           {
2222             warning ("Memory at address 0x%x is unwritable. Nothing written",
2223                      old_address);
2224             err = KERN_SUCCESS;
2225             length = 0;
2226             goto out;
2227           }
2228
2229         /* Chain the regions for later use */
2230         region_element = 
2231           (struct vm_region_list *)
2232             obstack_alloc (&region_obstack, sizeof (struct vm_region_list));
2233     
2234         region_element->protection = protection;
2235         region_element->start      = region_address;
2236         region_element->length     = region_length;
2237
2238         /* Chain the regions along with protections */
2239         region_element->next = region_head;
2240         region_head          = region_element;
2241         
2242         region_address += region_length;
2243         remaining_length = remaining_length - region_length;
2244       }
2245
2246     /* If things fail after this, we give up.
2247      * Somebody is messing up inferior_task's mappings.
2248      */
2249     
2250     /* Enable writes to the chained vm regions */
2251     for (scan = region_head; scan; scan = scan->next)
2252       {
2253         boolean_t protection_changed = FALSE;
2254         
2255         if (!(scan->protection & VM_PROT_WRITE))
2256           {
2257             err = vm_protect (task,
2258                               scan->start,
2259                               scan->length,
2260                               FALSE,
2261                               scan->protection | VM_PROT_WRITE);
2262             CHK_GOTO_OUT ("vm_protect: enable write failed", err);
2263           }
2264       }
2265
2266     err = vm_write (task,
2267                     low_address,
2268                     copied,
2269                     aligned_length);
2270     CHK_GOTO_OUT ("vm_write failed", err);
2271         
2272     /* Set up the original region protections, if they were changed */
2273     for (scan = region_head; scan; scan = scan->next)
2274       {
2275         boolean_t protection_changed = FALSE;
2276         
2277         if (!(scan->protection & VM_PROT_WRITE))
2278           {
2279             err = vm_protect (task,
2280                               scan->start,
2281                               scan->length,
2282                               FALSE,
2283                               scan->protection);
2284             CHK_GOTO_OUT ("vm_protect: enable write failed", err);
2285           }
2286       }
2287   }
2288
2289  out:
2290   if (deallocate)
2291     {
2292       obstack_free (&region_obstack, 0);
2293       
2294       (void) vm_deallocate (mach_task_self (),
2295                             copied,
2296                             copy_count);
2297     }
2298
2299   if (err != KERN_SUCCESS)
2300     {
2301       warning ("%s: %s", errstr, mach_error_string (err));
2302       return 0;
2303     }
2304
2305   return length;
2306 }
2307 \f
2308 /* Return 0 on failure, number of bytes handled otherwise.  */
2309 static int
2310 gnu_xfer_memory (memaddr, myaddr, len, write, target)
2311      CORE_ADDR memaddr;
2312      char *myaddr;
2313      int len;
2314      int write;
2315      struct target_ops *target; /* IGNORED */
2316 {
2317   int result;
2318   task_t task =
2319     current_inferior
2320       ? (current_inferior->task ? current_inferior->task->port : 0)
2321       : 0;
2322
2323   if (task == MACH_PORT_NULL)
2324     return 0;
2325   else
2326     {
2327       inf_debug (current_inferior, "%s %p[%d] %s %p",
2328                  write ? "writing" : "reading", memaddr, len,
2329                  write ? "<--" : "-->", myaddr);
2330       if (write)
2331         return gnu_write_inferior (task, memaddr, myaddr, len);
2332       else
2333         return gnu_read_inferior  (task, memaddr, myaddr, len);
2334     }
2335 }
2336 \f
2337 extern void gnu_store_registers (int regno);
2338 extern void gnu_fetch_registers (int regno);
2339
2340 struct target_ops gnu_ops = {
2341   "GNU",                        /* to_shortname */
2342   "GNU Hurd process",           /* to_longname */
2343   "GNU Hurd process",           /* to_doc */
2344   gnu_open,                     /* to_open */
2345   0,                            /* to_close */
2346   gnu_attach,                   /* to_attach */
2347   gnu_detach,                   /* to_detach */
2348   gnu_resume,                   /* to_resume */
2349   gnu_wait,                     /* to_wait */
2350   gnu_fetch_registers,          /* to_fetch_registers */
2351   gnu_store_registers,          /* to_store_registers */
2352   gnu_prepare_to_store,         /* to_prepare_to_store */
2353   gnu_xfer_memory,              /* to_xfer_memory */
2354   0,                            /* to_files_info */
2355   memory_insert_breakpoint,     /* to_insert_breakpoint */
2356   memory_remove_breakpoint,     /* to_remove_breakpoint */
2357   gnu_terminal_init_inferior,   /* to_terminal_init */
2358   terminal_inferior,            /* to_terminal_inferior */
2359   terminal_ours_for_output,     /* to_terminal_ours_for_output */
2360   terminal_ours,                /* to_terminal_ours */
2361   child_terminal_info,          /* to_terminal_info */
2362   gnu_kill_inferior,            /* to_kill */
2363   0,                            /* to_load */
2364   0,                            /* to_lookup_symbol */
2365
2366   gnu_create_inferior,          /* to_create_inferior */
2367   gnu_mourn_inferior,           /* to_mourn_inferior */
2368   gnu_can_run,                  /* to_can_run */
2369   0,                            /* to_notice_signals */
2370   gnu_thread_alive,             /* to_thread_alive */
2371   gnu_stop,                     /* to_stop */
2372   process_stratum,              /* to_stratum */
2373   0,                            /* to_next */
2374   1,                            /* to_has_all_memory */
2375   1,                            /* to_has_memory */
2376   1,                            /* to_has_stack */
2377   1,                            /* to_has_registers */
2378   1,                            /* to_has_execution */
2379   0,                            /* sections */
2380   0,                            /* sections_end */
2381   OPS_MAGIC                     /* to_magic */
2382 };
2383 \f
2384 /* Return printable description of proc.  */
2385 char *proc_string (struct proc *proc)
2386 {
2387   static char tid_str[80];
2388   if (proc_is_task (proc))
2389     sprintf (tid_str, "process %d", proc->inf->pid);
2390   else
2391     sprintf (tid_str, "thread %d.%d",
2392              proc->inf->pid,
2393 #if 0
2394              pid_to_thread_id (proc->tid)
2395 #else
2396              proc->tid
2397 #endif
2398 );
2399   return tid_str;
2400 }
2401
2402 char *
2403 gnu_target_pid_to_str (int tid)
2404 {
2405   struct inf *inf = current_inferior;
2406   struct proc *thread = inf_tid_to_thread (inf, tid);
2407
2408   if (thread)
2409     return proc_string (thread);
2410   else
2411     {
2412       static char tid_str[80];
2413       sprintf (tid_str, "bogus thread id %d", tid);
2414       return tid_str;
2415     }
2416 }
2417 \f
2418 /* User task commands.  */
2419
2420 struct cmd_list_element *set_task_cmd_list = 0;
2421 struct cmd_list_element *show_task_cmd_list = 0;
2422 /* User thread commands.  */
2423
2424 /* Commands with a prefix of `set/show thread'.  */
2425 extern struct cmd_list_element *thread_cmd_list;
2426 struct cmd_list_element *set_thread_cmd_list = NULL;
2427 struct cmd_list_element *show_thread_cmd_list = NULL;
2428
2429 /* Commands with a prefix of `set/show thread default'.  */
2430 struct cmd_list_element *set_thread_default_cmd_list = NULL;
2431 struct cmd_list_element *show_thread_default_cmd_list = NULL;
2432
2433 static void
2434 set_thread_cmd (char *args, int from_tty)
2435 {
2436   printf_unfiltered ("\"set thread\" must be followed by the name of a thread
2437 property, or \"default\".\n");
2438 }
2439
2440 static void
2441 show_thread_cmd (char *args, int from_tty)
2442 {
2443   printf_unfiltered ("\"show thread\" must be followed by the name of a thread property, or \"default\".\n");
2444 }
2445
2446 static void
2447 set_thread_default_cmd (char *args, int from_tty)
2448 {
2449   printf_unfiltered ("\"set thread default\" must be followed by the name of a thread property.\n");
2450 }
2451
2452 static void
2453 show_thread_default_cmd (char *args, int from_tty)
2454 {
2455   printf_unfiltered ("\"show thread default\" must be followed by the name of a thread property.\n");
2456 }
2457
2458 static int
2459 parse_int_arg (char *args, char *cmd_prefix)
2460 {
2461   if (args)
2462     {
2463       char *arg_end;
2464       int val = strtoul (args, &arg_end, 10);
2465       if (*args && *arg_end == '\0')
2466         return val;
2467     }
2468   error ("Illegal argument for \"%s\" command, should be an integer.", cmd_prefix);
2469 }
2470
2471 static int
2472 _parse_bool_arg (char *args, char *t_val, char *f_val, char *cmd_prefix)
2473 {
2474   if (!args || strcmp (args, t_val) == 0)
2475     return 1;
2476   else if (strcmp (args, f_val) == 0)
2477     return 0;
2478   else
2479     error ("Illegal argument for \"%s\" command, should be \"%s\" or \"%s\".",
2480            cmd_prefix, t_val, f_val);
2481 }
2482
2483 #define parse_bool_arg(args, cmd_prefix) \
2484   _parse_bool_arg (args, "on", "off", cmd_prefix)
2485
2486 static void
2487 check_empty (char *args, char *cmd_prefix)
2488 {
2489   if (args)
2490     error ("Garbage after \"%s\" command: `%s'", cmd_prefix, args);
2491 }
2492
2493 /* Returns the alive thread named by INFERIOR_PID, or signals an error.  */
2494 static struct proc *
2495 cur_thread ()
2496 {
2497   struct inf *inf = cur_inf ();
2498   struct proc *thread = inf_tid_to_thread (inf, inferior_pid);
2499   if (!thread)
2500     error ("No current thread.");
2501   return thread;
2502 }
2503
2504 /* Returns the current inferior, but signals an error if it has no task.  */
2505 static struct inf *
2506 active_inf ()
2507 {
2508   struct inf *inf = cur_inf ();
2509   if (! inf->task)
2510     error ("No current process.");
2511   return inf;
2512 }
2513 \f
2514 static void
2515 set_task_pause_cmd (char *args, int from_tty)
2516 {
2517   struct inf *inf = cur_inf ();
2518   int old_sc = inf->pause_sc;
2519
2520   inf->pause_sc = parse_bool_arg (args, "set task pause");
2521
2522   if (old_sc == 0 && inf->pause_sc != 0)
2523     /* If the task is currently unsuspended, immediately suspend it,
2524        otherwise wait until the next time it gets control.  */
2525     inf_suspend (inf);
2526 }
2527
2528 static void
2529 show_task_pause_cmd (char *args, int from_tty)
2530 {
2531   struct inf *inf = cur_inf ();
2532   check_empty (args, "show task pause");
2533   printf_unfiltered ("The inferior task %s suspended while gdb has control.\n",
2534                      inf->task
2535                      ? (inf->pause_sc == 0 ? "isn't" : "is")
2536                      : (inf->pause_sc == 0 ? "won't be" : "will be"));
2537 }
2538
2539 static void
2540 set_task_detach_sc_cmd (char *args, int from_tty)
2541 {
2542   cur_inf ()->detach_sc = parse_int_arg (args, "set task detach-suspend-count");
2543 }
2544
2545 static void
2546 show_task_detach_sc_cmd (char *args, int from_tty)
2547 {
2548   check_empty (args, "show task detach-suspend-count");
2549   printf_unfiltered ("The inferior task will be left with a suspend count of %d when detaching.\n",
2550                      cur_inf ()->detach_sc);
2551 }
2552 \f
2553 static void
2554 set_thread_default_pause_cmd (char *args, int from_tty)
2555 {
2556   struct inf *inf = cur_inf ();
2557   inf->default_thread_pause_sc =
2558     parse_bool_arg (args, "set thread default pause") ? 0 : 1;
2559 }
2560
2561 static void
2562 show_thread_default_pause_cmd (char *args, int from_tty)
2563 {
2564   struct inf *inf = cur_inf ();
2565   int sc = inf->default_thread_pause_sc;
2566   check_empty (args, "show thread default pause");
2567   printf_unfiltered ("New threads %s suspended while gdb has control%s.\n",
2568                      sc ? "are" : "aren't",
2569                      !sc && inf->pause_sc ? " (but the task is)" : "");
2570 }
2571
2572 static void
2573 set_thread_default_run_cmd (char *args, int from_tty)
2574 {
2575   struct inf *inf = cur_inf ();
2576   inf->default_thread_run_sc =
2577     parse_bool_arg (args, "set thread default run") ? 0 : 1;
2578 }
2579
2580 static void
2581 show_thread_default_run_cmd (char *args, int from_tty)
2582 {
2583   struct inf *inf = cur_inf ();
2584   check_empty (args, "show thread default run");
2585   printf_unfiltered ("New threads %s allowed to run.\n",
2586                      inf->default_thread_run_sc == 0 ? "are" : "aren't");
2587 }
2588
2589 static void
2590 set_thread_default_detach_sc_cmd (char *args, int from_tty)
2591 {
2592   cur_inf ()->default_thread_detach_sc =
2593     parse_int_arg (args, "set thread default detach-suspend-count");
2594 }
2595
2596 static void
2597 show_thread_default_detach_sc_cmd (char *args, int from_tty)
2598 {
2599   check_empty (args, "show thread default detach-suspend-count");
2600   printf_unfiltered ("New threads will get a detach-suspend-count of %d.\n",
2601                      cur_inf ()->default_thread_detach_sc);
2602 }
2603 \f
2604 /* Steal a send right called NAME in the inferior task, and make it PROC's
2605    saved exception port.  */
2606 static void
2607 steal_exc_port (struct proc *proc, mach_port_t name)
2608 {
2609   error_t err;
2610   mach_port_t port;
2611   mach_msg_type_name_t port_type;
2612
2613   if (!proc || !proc->inf->task)
2614     error ("No inferior task.");
2615
2616   err = mach_port_extract_right (proc->inf->task->port,
2617                                  name, MACH_MSG_TYPE_COPY_SEND,
2618                                  &port, &port_type);
2619   if (err)
2620     error ("Couldn't extract send right %d from inferior: %s",
2621            name, strerror (err));
2622
2623   if (proc->saved_exc_port)
2624     /* Get rid of our reference to the old one.  */
2625     mach_port_deallocate (mach_task_self (), proc->saved_exc_port);
2626
2627   proc->saved_exc_port = port;
2628
2629   if (! proc->exc_port)
2630     /* If PROC is a thread, we may not have set its exception port before.
2631        We can't use proc_steal_exc_port because it also sets saved_exc_port. */
2632     {
2633        proc->exc_port = proc->inf->event_port;
2634        err = proc_set_exception_port (proc, proc->exc_port);
2635        error ("Can't set exception port for %s: %s",
2636               proc_string (proc), strerror (err));
2637     }
2638 }
2639 \f
2640 static void
2641 set_task_exc_port_cmd (char *args, int from_tty)
2642 {
2643   struct inf *inf = cur_inf ();
2644   if (!args)
2645     error ("No argument to \"set task exception-port\" command.");
2646   steal_exc_port (inf->task, parse_and_eval_address (args));
2647 }
2648
2649 static void 
2650 set_stopped_cmd (char *args, int from_tty)
2651 {
2652   cur_inf ()->stopped = _parse_bool_arg (args, "yes", "no", "set stopped");
2653 }
2654
2655 static void
2656 show_stopped_cmd (char *args, int from_tty)
2657 {
2658   struct inf *inf = active_inf ();
2659   check_empty (args, "show stopped");
2660   printf_unfiltered ("The inferior process %s stopped.\n",
2661                      inf->stopped ? "is" : "isn't");
2662 }
2663
2664 static void 
2665 set_sig_thread_cmd (char *args, int from_tty)
2666 {
2667   int tid;
2668   struct inf *inf = cur_inf ();
2669
2670   if (!args || (! isdigit (*args) && strcmp (args, "none") != 0))
2671     error ("Illegal argument to \"set signal-thread\" command.\n"
2672            "Should be an integer thread ID, or `none'.");
2673
2674   if (strcmp (args, "none") == 0)
2675     inf->signal_thread = 0;
2676   else
2677     {
2678       int tid = thread_id_to_pid (atoi (args));
2679       if (tid < 0)
2680         error ("Thread ID %s not known.  Use the \"info threads\" command to\n"
2681                "see the IDs of currently known threads.", args);
2682       inf->signal_thread = inf_tid_to_thread (inf, tid);
2683     }
2684 }
2685
2686 static void
2687 show_sig_thread_cmd (char *args, int from_tty)
2688 {
2689   struct inf *inf = active_inf ();
2690   check_empty (args, "show signal-thread");
2691   if (inf->signal_thread)
2692     printf_unfiltered ("The signal thread is %s.\n",
2693                        proc_string (inf->signal_thread));
2694   else
2695     printf_unfiltered ("There is no signal thread.\n");
2696 }
2697 \f
2698 static void 
2699 set_signals_cmd (char *args, int from_tty)
2700 {
2701   int trace;
2702   struct inf *inf = cur_inf ();
2703
2704   inf->want_signals = parse_bool_arg (args, "set signals");
2705
2706   if (inf->task && inf->want_signals != inf->traced)
2707     /* Make this take effect immediately in a running process.  */
2708     inf_set_traced (inf, inf->want_signals);
2709 }
2710
2711 static void
2712 show_signals_cmd (char *args, int from_tty)
2713 {
2714   struct inf *inf = cur_inf ();
2715   check_empty (args, "show signals");
2716   printf_unfiltered ("The inferior process's signals %s intercepted.\n",
2717                      inf->task
2718                      ? (inf->traced ? "are" : "aren't")
2719                      : (inf->want_signals ? "will be" : "won't be"));
2720 }
2721
2722 static void 
2723 set_exceptions_cmd (char *args, int from_tty)
2724 {
2725   struct inf *inf = cur_inf ();
2726   int val = parse_bool_arg (args, "set exceptions");
2727
2728   if (inf->task && inf->want_exceptions != val)
2729     /* Make this take effect immediately in a running process.  */
2730     /* XXX */;
2731
2732   inf->want_exceptions = val;
2733 }
2734
2735 static void
2736 show_exceptions_cmd (char *args, int from_tty)
2737 {
2738   struct inf *inf = cur_inf ();
2739   check_empty (args, "show exceptions");
2740   printf_unfiltered ("Exceptions in the inferior %s trapped.\n",
2741                      inf->task
2742                      ? (inf->want_exceptions ? "are" : "aren't")
2743                      : (inf->want_exceptions ? "will be" : "won't be"));
2744 }
2745 \f
2746 static void
2747 set_task_cmd (char *args, int from_tty)
2748 {
2749   printf_unfiltered ("\"set task\" must be followed by the name of a task property.\n");
2750 }
2751
2752 static void
2753 show_task_cmd (char *args, int from_tty)
2754 {
2755   struct inf *inf = cur_inf ();
2756
2757   check_empty (args, "show task");
2758
2759   show_signals_cmd (0, from_tty);
2760   show_exceptions_cmd (0, from_tty);
2761   show_task_pause_cmd (0, from_tty);
2762
2763   if (inf->pause_sc == 0)
2764     show_thread_default_pause_cmd (0, from_tty);
2765   show_thread_default_run_cmd (0, from_tty);
2766
2767   if (inf->task)
2768     {
2769       show_stopped_cmd (0, from_tty);
2770       show_sig_thread_cmd (0, from_tty);
2771     }
2772
2773   if (inf->detach_sc != 0)
2774     show_task_detach_sc_cmd (0, from_tty);
2775   if (inf->default_thread_detach_sc != 0)
2776     show_thread_default_detach_sc_cmd (0, from_tty);
2777 }
2778 \f
2779 static void
2780 set_noninvasive_cmd (char *args, int from_tty)
2781 {
2782   /* Invert the sense of the arg for each component.  */
2783   char *inv_args = parse_bool_arg (args, "set noninvasive") ? "off" : "on";
2784
2785   set_task_pause_cmd (inv_args, from_tty);
2786   set_signals_cmd (inv_args, from_tty);
2787   set_exceptions_cmd (inv_args, from_tty);
2788 }
2789 \f
2790 static void
2791 info_port_rights (char *args, mach_port_type_t only)
2792 {
2793   struct inf *inf = active_inf ();
2794   value_ptr vmark = value_mark ();
2795
2796   if (args)
2797     /* Explicit list of port rights.  */
2798     {
2799       while (*args)
2800         {
2801           value_ptr val = parse_to_comma_and_eval (&args);
2802           long right = value_as_long (val);
2803           error_t err =
2804             print_port_info (right, 0, inf->task->port, PORTINFO_DETAILS,
2805                              stdout);
2806           if (err)
2807             error ("%ld: %s.", right, strerror (err));
2808         }
2809     }
2810   else
2811     /* Print all of them.  */
2812     {
2813       error_t err =
2814         print_task_ports_info (inf->task->port, only, PORTINFO_DETAILS,
2815                                stdout);
2816       if (err)
2817         error ("%s.", strerror (err));
2818     }
2819
2820   value_free_to_mark (vmark);
2821 }
2822
2823 static void
2824 info_send_rights_cmd (char *args, int from_tty)
2825 {
2826   info_port_rights (args, MACH_PORT_TYPE_SEND);
2827 }
2828 static void
2829 info_recv_rights_cmd (char *args, int from_tty)
2830 {
2831   info_port_rights (args, MACH_PORT_TYPE_RECEIVE);
2832 }
2833 static void
2834 info_port_sets_cmd (char *args, int from_tty)
2835 {
2836   info_port_rights (args, MACH_PORT_TYPE_PORT_SET);
2837 }
2838 static void
2839 info_dead_names_cmd (char *args, int from_tty)
2840 {
2841   info_port_rights (args, MACH_PORT_TYPE_DEAD_NAME);
2842 }
2843 static void
2844 info_port_rights_cmd (char *args, int from_tty)
2845 {
2846   info_port_rights (args, ~0);
2847 }
2848 \f
2849 static void add_task_commands ()
2850 {
2851   add_cmd ("pause", class_run, set_thread_default_pause_cmd,
2852            "Set whether the new threads are suspended while gdb has control.\n"
2853            "This property normally has no effect because the whole task is\n"
2854            "suspended, however, that may be disabled with \"set task pause off\".\n"
2855            "The default value is \"off\".",
2856            &set_thread_default_cmd_list);
2857   add_cmd ("pause", no_class, show_thread_default_pause_cmd,
2858            "Show whether new threads are suspended while gdb has control.",
2859            &show_thread_default_cmd_list);
2860   add_cmd ("run", class_run, set_thread_default_run_cmd,
2861            "Set whether new threads are allowed to run (once gdb has noticed them).",
2862            &set_thread_default_cmd_list);
2863   add_cmd ("run", no_class, show_thread_default_run_cmd,
2864            "Show whether new threads are allowed to run (once gdb has noticed
2865 them).",
2866            &show_thread_default_cmd_list);
2867   add_cmd ("detach-suspend-count", class_run, set_thread_default_detach_sc_cmd,
2868            "Set the default detach-suspend-count value for new threads.",
2869            &set_thread_default_cmd_list);
2870   add_cmd ("detach-suspend-count", no_class, show_thread_default_detach_sc_cmd,
2871            "Show the default detach-suspend-count value for new threads.",
2872            &show_thread_default_cmd_list);
2873
2874   add_cmd ("signals", class_run, set_signals_cmd,
2875            "Set whether the inferior process's signals will be intercepted.\n"
2876            "Mach exceptions (such as breakpoint traps) are not affected.",
2877            &setlist);
2878   add_alias_cmd ("sigs", "signals", class_run, 1, &setlist);
2879   add_cmd ("signals", no_class, show_signals_cmd,
2880            "Show whether the inferior process's signals will be intercepted.",
2881            &showlist);
2882   add_alias_cmd ("sigs", "signals", no_class, 1, &showlist);
2883
2884   add_cmd ("signal-thread", class_run, set_sig_thread_cmd,
2885            "Set the thread that gdb thinks is the libc signal thread.\n"
2886            "This thread is run when delivering a signal to a non-stopped process.",
2887            &setlist);
2888   add_alias_cmd ("sigthread", "signal-thread", class_run, 1, &setlist);
2889   add_cmd ("signal-thread", no_class, show_sig_thread_cmd,
2890            "Set the thread that gdb thinks is the libc signal thread.",
2891            &showlist);
2892   add_alias_cmd ("sigthread", "signal-thread", no_class, 1, &showlist);
2893
2894   add_cmd ("stopped", class_run, set_stopped_cmd,
2895            "Set whether gdb thinks the inferior process is stopped as with SIGSTOP.\n"
2896            "Stopped process will be continued by sending them a signal.",
2897            &setlist);
2898   add_cmd ("stopped", no_class, show_signals_cmd,
2899            "Show whether gdb thinks the inferior process is stopped as with SIGSTOP.",
2900            &showlist);
2901
2902   add_cmd ("exceptions", class_run, set_exceptions_cmd,
2903            "Set whether exceptions in the inferior process will be trapped.\n"
2904            "When exceptions are turned off, neither breakpoints nor single-stepping\n"
2905            "will work.",
2906            &setlist);
2907   /* Allow `set exc' despite conflict with `set exception-port'.  */
2908   add_alias_cmd ("exc", "exceptions", class_run, 1, &setlist);
2909   add_cmd ("exceptions", no_class, show_exceptions_cmd,
2910            "Show whether exceptions in the inferior process will be trapped.",
2911            &showlist);
2912
2913   add_prefix_cmd ("task", no_class, set_task_cmd,
2914                   "Command prefix for setting task attributes.",
2915                   &set_task_cmd_list, "set task ", 0, &setlist);
2916   add_prefix_cmd ("task", no_class, show_task_cmd,
2917                   "Command prefix for showing task attributes.",
2918                   &show_task_cmd_list, "show task ", 0, &showlist);
2919
2920   add_cmd ("pause", class_run, set_task_pause_cmd,
2921            "Set whether the task is suspended while gdb has control.\n"
2922            "A value of \"on\" takes effect immediately, otherwise nothing\n"
2923            "happens until the next time the program is continued.\n"
2924            "When setting this to \"off\", \"set thread default pause on\"\n"
2925            "can be used to pause individual threads by default instead.",
2926            &set_task_cmd_list);
2927   add_cmd ("pause", no_class, show_task_pause_cmd,
2928            "Show whether the task is suspended while gdb has control.",
2929            &show_task_cmd_list);
2930   add_cmd ("detach-suspend-count", class_run, set_task_detach_sc_cmd,
2931            "Set the suspend count will leave on the thread when detaching.",
2932            &set_task_cmd_list);
2933   add_cmd ("detach-suspend-count", no_class, show_task_detach_sc_cmd,
2934            "Show the suspend count will leave on the thread when detaching.",
2935            &show_task_cmd_list);
2936
2937   add_cmd ("exception-port", no_class, set_task_exc_port_cmd,
2938            "Set the task exception port to which we forward exceptions.\n"
2939            "The argument should be the value of the send right in the task.",
2940            &set_task_cmd_list);
2941   add_alias_cmd ("excp", "exception-port", no_class, 1, &set_task_cmd_list);
2942   add_alias_cmd ("exc-port", "exception-port", no_class, 1, &set_task_cmd_list);
2943
2944   /* A convenient way of turning on all options require to noninvasively
2945      debug running tasks.  */
2946   add_cmd ("noninvasive", no_class, set_noninvasive_cmd,
2947            "Set task options so that we interfere as little as possible.\n"
2948            "This is the same as setting `task pause', `exceptions', and"
2949            "`signals' to the opposite value.",
2950            &setlist);
2951
2952   /* Commands to show information about the task's ports.  */
2953   add_cmd ("send-rights", class_info, info_send_rights_cmd,
2954            "Show information about the task's send rights",
2955            &infolist);
2956   add_cmd ("receive-rights", class_info, info_recv_rights_cmd,
2957            "Show information about the task's receive rights",
2958            &infolist);
2959   add_cmd ("port-rights", class_info, info_send_rights_cmd,
2960            "Show information about the task's port rights",
2961            &infolist);
2962   add_cmd ("port-sets", class_info, info_port_sets_cmd,
2963            "Show information about the task's port sets",
2964            &infolist);
2965   add_cmd ("dead-names", class_info, info_dead_names_cmd,
2966            "Show information about the task's dead names",
2967            &infolist);
2968   add_info_alias ("ports", "port-rights", 1);
2969   add_info_alias ("port", "port-rights", 1);
2970   add_info_alias ("psets", "port-sets", 1);
2971 }
2972 \f
2973
2974 static void
2975 set_thread_pause_cmd (char *args, int from_tty)
2976 {
2977   struct proc *thread = cur_thread ();
2978   int old_sc = thread->pause_sc;
2979   thread->pause_sc = parse_bool_arg (args, "set thread pause");
2980   if (old_sc == 0 && thread->pause_sc != 0 && thread->inf->pause_sc == 0)
2981     /* If the task is currently unsuspended, immediately suspend it,
2982        otherwise wait until the next time it gets control.  */
2983     inf_suspend (thread->inf);
2984 }
2985
2986 static void
2987 show_thread_pause_cmd (char *args, int from_tty)
2988 {
2989   struct proc *thread = cur_thread ();
2990   int sc = thread->pause_sc;
2991   check_empty (args, "show task pause");
2992   printf_unfiltered ("Thread %s %s suspended while gdb has control%s.\n",
2993                      proc_string (thread),
2994                      sc ? "is" : "isn't",
2995                      !sc && thread->inf->pause_sc ? " (but the task is)" : "");
2996 }
2997
2998 static void
2999 set_thread_run_cmd (char *args, int from_tty)
3000 {
3001   struct proc *thread = cur_thread ();
3002   thread->run_sc = parse_bool_arg (args, "set thread run") ? 0 : 1;
3003 }
3004
3005 static void
3006 show_thread_run_cmd (char *args, int from_tty)
3007 {
3008   struct proc *thread = cur_thread ();
3009   check_empty (args, "show thread run");
3010   printf_unfiltered ("Thread %s %s allowed to run.",
3011                      proc_string (thread),
3012                      thread->run_sc == 0 ? "is" : "isn't");
3013 }
3014
3015 static void
3016 set_thread_detach_sc_cmd (char *args, int from_tty)
3017 {
3018   cur_thread ()->detach_sc = parse_int_arg (args, "set thread detach-suspend-count");
3019 }
3020
3021 static void
3022 show_thread_detach_sc_cmd (char *args, int from_tty)
3023 {
3024   struct proc *thread = cur_thread ();
3025   check_empty (args, "show thread detach-suspend-count");
3026   printf_unfiltered ("Thread %s will be left with a suspend count of %d when detaching.\n",
3027                      proc_string (thread),
3028                      thread->detach_sc);
3029 }
3030
3031 static void
3032 set_thread_exc_port_cmd (char *args, int from_tty)
3033 {
3034   struct proc *thread = cur_thread ();
3035   if (!args)
3036     error ("No argument to \"set thread exception-port\" command.");
3037   steal_exc_port (thread, parse_and_eval_address (args));
3038 }
3039
3040 #if 0
3041 static void
3042 show_thread_cmd (char *args, int from_tty)
3043 {
3044   struct proc *thread = cur_thread ();
3045   check_empty (args, "show thread");
3046   show_thread_run_cmd (0, from_tty);
3047   show_thread_pause_cmd (0, from_tty);
3048   if (thread->detach_sc != 0)
3049     show_thread_detach_sc_cmd (0, from_tty);
3050 }
3051 #endif
3052
3053 static void
3054 thread_takeover_sc_cmd (char *args, int from_tty)
3055 {
3056   struct proc *thread = cur_thread ();
3057   thread_basic_info_data_t _info;
3058   thread_basic_info_t info = &_info;
3059   mach_msg_type_number_t info_len = THREAD_BASIC_INFO_COUNT;
3060   error_t err =
3061     thread_info (thread->port, THREAD_BASIC_INFO, (int *)&info, &info_len);
3062   if (err)
3063     error ("%s.", strerror (err));
3064   thread->sc = info->suspend_count;
3065   if (from_tty)
3066     printf_unfiltered ("Suspend count was %d.\n", thread->sc);
3067   if (info != &_info)
3068     vm_deallocate (mach_task_self (), (vm_address_t)info, info_len * sizeof (int));
3069 }
3070
3071 add_thread_commands ()
3072 {
3073   add_prefix_cmd ("thread", no_class, set_thread_cmd,
3074                   "Command prefix for setting thread properties.",
3075                   &set_thread_cmd_list, "set thread ", 0, &setlist);
3076   add_prefix_cmd ("default", no_class, show_thread_cmd,
3077                   "Command prefix for setting default thread properties.",
3078                   &set_thread_default_cmd_list, "set thread default ", 0,
3079                   &set_thread_cmd_list);
3080   add_prefix_cmd ("thread", no_class, set_thread_default_cmd,
3081                   "Command prefix for showing thread properties.",
3082                   &show_thread_cmd_list, "show thread ", 0, &showlist);
3083   add_prefix_cmd ("default", no_class, show_thread_default_cmd,
3084                   "Command prefix for showing default thread properties.",
3085                   &show_thread_default_cmd_list, "show thread default ", 0,
3086                   &show_thread_cmd_list);
3087
3088   add_cmd ("pause", class_run, set_thread_pause_cmd,
3089            "Set whether the current thread is suspended while gdb has control.\n"
3090            "A value of \"on\" takes effect immediately, otherwise nothing\n"
3091            "happens until the next time the program is continued.  This\n"
3092            "property normally has no effect because the whole task is suspended,\n"
3093            "however, that may be disabled with \"set task pause off\".\n"
3094            "The default value is \"off\".",
3095            &set_thread_cmd_list);
3096   add_cmd ("pause", no_class, show_thread_pause_cmd,
3097            "Show whether the current thread is suspended while gdb has control.",
3098            &show_thread_cmd_list);
3099
3100   add_cmd ("run", class_run, set_thread_run_cmd,
3101            "Set whether the current thread is allowed to run.",
3102            &set_thread_cmd_list);
3103   add_cmd ("run", no_class, show_thread_run_cmd,
3104            "Show whether the current thread is allowed to run.",
3105            &show_thread_cmd_list);
3106
3107   add_cmd ("detach-suspend-count", class_run, set_thread_detach_sc_cmd,
3108            "Set the suspend count will leave on the thread when detaching.\n"
3109            "Note that this is relative to suspend count when gdb noticed the thread;\n"
3110            "use the `thread takeover-suspend-count' to force it to an absolute value.",
3111            &set_thread_cmd_list);
3112   add_cmd ("detach-suspend-count", no_class, show_thread_detach_sc_cmd,
3113            "Show the suspend count will leave on the thread when detaching."
3114            "Note that this is relative to suspend count when gdb noticed the thread;\n"
3115            "use the `thread takeover-suspend-count' to force it to an absolute value.",
3116            &show_thread_cmd_list);
3117
3118   add_cmd ("exception-port", no_class, set_thread_exc_port_cmd,
3119            "Set the exception port to which we forward exceptions for the\n"
3120            "current thread, overriding the task exception port.\n"
3121            "The argument should be the value of the send right in the task.",
3122            &set_thread_cmd_list);
3123   add_alias_cmd ("excp", "exception-port", no_class, 1, &set_thread_cmd_list);
3124   add_alias_cmd ("exc-port", "exception-port", no_class, 1, &set_thread_cmd_list);
3125
3126   add_cmd ("takeover-suspend-count", no_class, thread_takeover_sc_cmd,
3127            "Force the threads absolute suspend-count to be gdb's.\n"
3128            "Prior to giving this command, gdb's thread suspend-counts are relative to\n"
3129            "the thread's initial suspend-count when gdb notices the threads.",
3130            &thread_cmd_list);
3131 }
3132 \f
3133 void
3134 _initialize_gnu_nat ()
3135 {
3136   proc_server = getproc ();
3137
3138   add_target (&gnu_ops);
3139
3140   add_task_commands ();
3141   add_thread_commands ();
3142
3143 #if MAINTENANCE_CMDS
3144   add_set_cmd ("gnu-debug", class_maintenance,
3145                var_boolean, (char *)&gnu_debug_flag,
3146                "Set debugging output for the gnu backend.", &maintenancelist);
3147 #endif
3148 }
3149 \f
3150 #ifdef  FLUSH_INFERIOR_CACHE
3151
3152 /* When over-writing code on some machines the I-Cache must be flushed
3153    explicitly, because it is not kept coherent by the lazy hardware.
3154    This definitely includes breakpoints, for instance, or else we
3155    end up looping in mysterious Bpt traps */
3156
3157 void
3158 flush_inferior_icache(pc, amount)
3159      CORE_ADDR pc;
3160 {
3161   vm_machine_attribute_val_t flush = MATTR_VAL_ICACHE_FLUSH;
3162   error_t   ret;
3163   
3164   ret = vm_machine_attribute (current_inferior->task->port,
3165                               pc,
3166                               amount,
3167                               MATTR_CACHE,
3168                               &flush);
3169   if (ret != KERN_SUCCESS)
3170     warning ("Error flushing inferior's cache : %s", strerror (ret));
3171 }
3172 #endif  FLUSH_INFERIOR_CACHE