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