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