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