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