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