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