gdb/gnu-nat.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Interface GDB to the GNU Hurd.
  2.    Copyright (C) 1992-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    Written by Miles Bader <miles@gnu.ai.mit.edu>

  5.    Some code and ideas from m3-nat.c by Jukka Virtanen <jtv@hut.fi>

  6.    This program is free software; you can redistribute it and/or modify
  7.    it under the terms of the GNU General Public License as published by
  8.    the Free Software Foundation; either version 3 of the License, or
  9.    (at your option) any later version.

  10.    This program is distributed in the hope that it will be useful,
  11.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13.    GNU General Public License for more details.

  14.    You should have received a copy of the GNU General Public License
  15.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  16. #include "defs.h"

  17. #include <ctype.h>
  18. #include <limits.h>
  19. #include <setjmp.h>
  20. #include <signal.h>
  21. #include <sys/ptrace.h>

  22. #include <mach.h>
  23. #include <mach_error.h>
  24. #include <mach/exception.h>
  25. #include <mach/message.h>
  26. #include <mach/notify.h>
  27. #include <mach/vm_attributes.h>

  28. #include <hurd.h>
  29. #include <hurd/interrupt.h>
  30. #include <hurd/msg.h>
  31. #include <hurd/msg_request.h>
  32. #include <hurd/process.h>
  33. /* Defined in <hurd/process.h>, but we need forward declarations from
  34.    <hurd/process_request.h> as well.  */
  35. #undef _process_user_
  36. #include <hurd/process_request.h>
  37. #include <hurd/signal.h>
  38. #include <hurd/sigpreempt.h>

  39. #include <portinfo.h>

  40. #include "inferior.h"
  41. #include "symtab.h"
  42. #include "value.h"
  43. #include "language.h"
  44. #include "target.h"
  45. #include "gdb_wait.h"
  46. #include "gdbcmd.h"
  47. #include "gdbcore.h"
  48. #include "gdbthread.h"
  49. #include "gdb_obstack.h"

  50. #include "gnu-nat.h"
  51. #include "inf-child.h"

  52. #include "exc_request_S.h"
  53. #include "notify_S.h"
  54. #include "process_reply_S.h"
  55. #include "msg_reply_S.h"
  56. #include "exc_request_U.h"
  57. #include "msg_U.h"

  58. static process_t proc_server = MACH_PORT_NULL;

  59. /* If we've sent a proc_wait_request to the proc server, the pid of the
  60.    process we asked about.  We can only ever have one outstanding.  */
  61. int proc_wait_pid = 0;

  62. /* The number of wait requests we've sent, and expect replies from.  */
  63. int proc_waits_pending = 0;

  64. int gnu_debug_flag = 0;

  65. /* Forward decls */

  66. static struct inf *make_inf ();
  67. void inf_clear_wait (struct inf *inf);
  68. void inf_cleanup (struct inf *inf);
  69. void inf_startup (struct inf *inf, int pid);
  70. int inf_update_suspends (struct inf *inf);
  71. void inf_set_pid (struct inf *inf, pid_t pid);
  72. void inf_validate_procs (struct inf *inf);
  73. void inf_steal_exc_ports (struct inf *inf);
  74. void inf_restore_exc_ports (struct inf *inf);
  75. void inf_set_threads_resume_sc (struct inf *inf,
  76.                                 struct proc *run_thread,
  77.                                 int run_others);
  78. int inf_set_threads_resume_sc_for_signal_thread (struct inf *inf);
  79. void inf_suspend (struct inf *inf);
  80. void inf_resume (struct inf *inf);
  81. void inf_set_step_thread (struct inf *inf, struct proc *proc);
  82. void inf_detach (struct inf *inf);
  83. void inf_attach (struct inf *inf, int pid);
  84. void inf_signal (struct inf *inf, enum gdb_signal sig);
  85. void inf_continue (struct inf *inf);

  86. #define inf_debug(_inf, msg, args...) \
  87.   do { struct inf *__inf = (_inf); \
  88.        debug ("{inf %d %s}: " msg, __inf->pid, \
  89.        host_address_to_string (__inf) , ##args); } while (0)

  90. void proc_abort (struct proc *proc, int force);
  91. struct proc *make_proc (struct inf *inf, mach_port_t port, int tid);
  92. struct proc *_proc_free (struct proc *proc);
  93. int proc_update_sc (struct proc *proc);
  94. error_t proc_get_exception_port (struct proc *proc, mach_port_t * port);
  95. error_t proc_set_exception_port (struct proc *proc, mach_port_t port);
  96. static mach_port_t _proc_get_exc_port (struct proc *proc);
  97. void proc_steal_exc_port (struct proc *proc, mach_port_t exc_port);
  98. void proc_restore_exc_port (struct proc *proc);
  99. int proc_trace (struct proc *proc, int set);

  100. /* Evaluate RPC_EXPR in a scope with the variables MSGPORT and REFPORT bound
  101.    to INF's msg port and task port respectively.  If it has no msg port,
  102.    EIEIO is returned.  INF must refer to a running process!  */
  103. #define INF_MSGPORT_RPC(inf, rpc_expr) \
  104.   HURD_MSGPORT_RPC (proc_getmsgport (proc_server, inf->pid, &msgport), \
  105.                     (refport = inf->task->port, 0), 0, \
  106.                     msgport ? (rpc_expr) : EIEIO)

  107. /* Like INF_MSGPORT_RPC, but will also resume the signal thread to ensure
  108.    there's someone around to deal with the RPC (and resuspend things
  109.    afterwards).  This effects INF's threads' resume_sc count.  */
  110. #define INF_RESUME_MSGPORT_RPC(inf, rpc_expr) \
  111.   (inf_set_threads_resume_sc_for_signal_thread (inf) \
  112.    ? ({ error_t __e; \
  113.         inf_resume (inf); \
  114.         __e = INF_MSGPORT_RPC (inf, rpc_expr); \
  115.         inf_suspend (inf); \
  116.         __e; }) \
  117.    : EIEIO)


  118. /* The state passed by an exception message.  */
  119. struct exc_state
  120.   {
  121.     int exception;                /* The exception code.  */
  122.     int code, subcode;
  123.     mach_port_t handler;        /* The real exception port to handle this.  */
  124.     mach_port_t reply;                /* The reply port from the exception call.  */
  125.   };

  126. /* The results of the last wait an inf did.  */
  127. struct inf_wait
  128.   {
  129.     struct target_waitstatus status;        /* The status returned to gdb.  */
  130.     struct exc_state exc;        /* The exception that caused us to return.  */
  131.     struct proc *thread;        /* The thread in question.  */
  132.     int suppress;                /* Something trivial happened.  */
  133.   };

  134. /* The state of an inferior.  */
  135. struct inf
  136.   {
  137.     /* Fields describing the current inferior.  */

  138.     struct proc *task;                /* The mach task.   */
  139.     struct proc *threads;        /* A linked list of all threads in TASK.  */

  140.     /* True if THREADS needn't be validated by querying the task.  We
  141.        assume that we and the task in question are the only ones
  142.        frobbing the thread list, so as long as we don't let any code
  143.        run, we don't have to worry about THREADS changing.  */
  144.     int threads_up_to_date;

  145.     pid_t pid;                        /* The real system PID.  */

  146.     struct inf_wait wait;        /* What to return from target_wait.  */

  147.     /* One thread proc in INF may be in `single-stepping mode'.  This
  148.        is it.  */
  149.     struct proc *step_thread;

  150.     /* The thread we think is the signal thread.  */
  151.     struct proc *signal_thread;

  152.     mach_port_t event_port;        /* Where we receive various msgs.  */

  153.     /* True if we think at least one thread in the inferior could currently be
  154.        running.  */
  155.     unsigned int running:1;

  156.     /* True if the process has stopped (in the proc server sense).  Note that
  157.        since a proc server `stop' leaves the signal thread running, the inf can
  158.        be RUNNING && STOPPED...  */
  159.     unsigned int stopped:1;

  160.     /* True if the inferior has no message port.  */
  161.     unsigned int nomsg:1;

  162.     /* True if the inferior is traced.  */
  163.     unsigned int traced:1;

  164.     /* True if we shouldn't try waiting for the inferior, usually because we
  165.        can't for some reason.  */
  166.     unsigned int no_wait:1;

  167.     /* When starting a new inferior, we don't try to validate threads until all
  168.        the proper execs have been done, which this flag states we still
  169.        expect to happen.  */
  170.     unsigned int pending_execs:1;

  171.     /* Fields describing global state.  */

  172.     /* The task suspend count used when gdb has control.  This is normally 1 to
  173.        make things easier for us, but sometimes (like when attaching to vital
  174.        system servers) it may be desirable to let the task continue to run
  175.        (pausing individual threads as necessary).  */
  176.     int pause_sc;

  177.     /* The task suspend count left when detaching from a task.  */
  178.     int detach_sc;

  179.     /* The initial values used for the run_sc and pause_sc of newly discovered
  180.        threads -- see the definition of those fields in struct proc.  */
  181.     int default_thread_run_sc;
  182.     int default_thread_pause_sc;
  183.     int default_thread_detach_sc;

  184.     /* True if the process should be traced when started/attached.  Newly
  185.        started processes *must* be traced at first to exec them properly, but
  186.        if this is false, tracing is turned off as soon it has done so.  */
  187.     int want_signals;

  188.     /* True if exceptions from the inferior process should be trapped.  This
  189.        must be on to use breakpoints.  */
  190.     int want_exceptions;
  191.   };


  192. int
  193. __proc_pid (struct proc *proc)
  194. {
  195.   return proc->inf->pid;
  196. }


  197. /* Update PROC's real suspend count to match it's desired one.  Returns true
  198.    if we think PROC is now in a runnable state.  */
  199. int
  200. proc_update_sc (struct proc *proc)
  201. {
  202.   int running;
  203.   int err = 0;
  204.   int delta = proc->sc - proc->cur_sc;

  205.   if (delta)
  206.     proc_debug (proc, "sc: %d --> %d", proc->cur_sc, proc->sc);

  207.   if (proc->sc == 0 && proc->state_changed)
  208.     /* Since PROC may start running, we must write back any state changes.  */
  209.     {
  210.       gdb_assert (proc_is_thread (proc));
  211.       proc_debug (proc, "storing back changed thread state");
  212.       err = thread_set_state (proc->port, THREAD_STATE_FLAVOR,
  213.                          (thread_state_t) &proc->state, THREAD_STATE_SIZE);
  214.       if (!err)
  215.         proc->state_changed = 0;
  216.     }

  217.   if (delta > 0)
  218.     {
  219.       while (delta-- > 0 && !err)
  220.         {
  221.           if (proc_is_task (proc))
  222.             err = task_suspend (proc->port);
  223.           else
  224.             err = thread_suspend (proc->port);
  225.         }
  226.     }
  227.   else
  228.     {
  229.       while (delta++ < 0 && !err)
  230.         {
  231.           if (proc_is_task (proc))
  232.             err = task_resume (proc->port);
  233.           else
  234.             err = thread_resume (proc->port);
  235.         }
  236.     }
  237.   if (!err)
  238.     proc->cur_sc = proc->sc;

  239.   /* If we got an error, then the task/thread has disappeared.  */
  240.   running = !err && proc->sc == 0;

  241.   proc_debug (proc, "is %s", err ? "dead" : running ? "running" : "suspended");
  242.   if (err)
  243.     proc_debug (proc, "err = %s", safe_strerror (err));

  244.   if (running)
  245.     {
  246.       proc->aborted = 0;
  247.       proc->state_valid = proc->state_changed = 0;
  248.       proc->fetched_regs = 0;
  249.     }

  250.   return running;
  251. }


  252. /* Thread_abort is called on PROC if needed.  PROC must be a thread proc.
  253.    If PROC is deemed `precious', then nothing is done unless FORCE is true.
  254.    In particular, a thread is precious if it's running (in which case forcing
  255.    it includes suspending it first), or if it has an exception pending.  */
  256. void
  257. proc_abort (struct proc *proc, int force)
  258. {
  259.   gdb_assert (proc_is_thread (proc));

  260.   if (!proc->aborted)
  261.     {
  262.       struct inf *inf = proc->inf;
  263.       int running = (proc->cur_sc == 0 && inf->task->cur_sc == 0);

  264.       if (running && force)
  265.         {
  266.           proc->sc = 1;
  267.           inf_update_suspends (proc->inf);
  268.           running = 0;
  269.           warning (_("Stopped %s."), proc_string (proc));
  270.         }
  271.       else if (proc == inf->wait.thread && inf->wait.exc.reply && !force)
  272.         /* An exception is pending on PROC, which don't mess with.  */
  273.         running = 1;

  274.       if (!running)
  275.         /* We only abort the thread if it's not actually running.  */
  276.         {
  277.           thread_abort (proc->port);
  278.           proc_debug (proc, "aborted");
  279.           proc->aborted = 1;
  280.         }
  281.       else
  282.         proc_debug (proc, "not aborting");
  283.     }
  284. }

  285. /* Make sure that the state field in PROC is up to date, and return a pointer
  286.    to it, or 0 if something is wrong.  If WILL_MODIFY is true, makes sure
  287.    that the thread is stopped and aborted first, and sets the state_changed
  288.    field in PROC to true.  */
  289. thread_state_t
  290. proc_get_state (struct proc *proc, int will_modify)
  291. {
  292.   int was_aborted = proc->aborted;

  293.   proc_debug (proc, "updating state info%s",
  294.               will_modify ? " (with intention to modify)" : "");

  295.   proc_abort (proc, will_modify);

  296.   if (!was_aborted && proc->aborted)
  297.     /* PROC's state may have changed since we last fetched it.  */
  298.     proc->state_valid = 0;

  299.   if (!proc->state_valid)
  300.     {
  301.       mach_msg_type_number_t state_size = THREAD_STATE_SIZE;
  302.       error_t err =
  303.         thread_get_state (proc->port, THREAD_STATE_FLAVOR,
  304.                           (thread_state_t) &proc->state, &state_size);

  305.       proc_debug (proc, "getting thread state");
  306.       proc->state_valid = !err;
  307.     }

  308.   if (proc->state_valid)
  309.     {
  310.       if (will_modify)
  311.         proc->state_changed = 1;
  312.       return (thread_state_t) &proc->state;
  313.     }
  314.   else
  315.     return 0;
  316. }


  317. /* Set PORT to PROC's exception port.  */
  318. error_t
  319. proc_get_exception_port (struct proc * proc, mach_port_t * port)
  320. {
  321.   if (proc_is_task (proc))
  322.     return task_get_exception_port (proc->port, port);
  323.   else
  324.     return thread_get_exception_port (proc->port, port);
  325. }

  326. /* Set PROC's exception port to PORT.  */
  327. error_t
  328. proc_set_exception_port (struct proc * proc, mach_port_t port)
  329. {
  330.   proc_debug (proc, "setting exception port: %lu", port);
  331.   if (proc_is_task (proc))
  332.     return task_set_exception_port (proc->port, port);
  333.   else
  334.     return thread_set_exception_port (proc->port, port);
  335. }

  336. /* Get PROC's exception port, cleaning up a bit if proc has died.  */
  337. static mach_port_t
  338. _proc_get_exc_port (struct proc *proc)
  339. {
  340.   mach_port_t exc_port;
  341.   error_t err = proc_get_exception_port (proc, &exc_port);

  342.   if (err)
  343.     /* PROC must be dead.  */
  344.     {
  345.       if (proc->exc_port)
  346.         mach_port_deallocate (mach_task_self (), proc->exc_port);
  347.       proc->exc_port = MACH_PORT_NULL;
  348.       if (proc->saved_exc_port)
  349.         mach_port_deallocate (mach_task_self (), proc->saved_exc_port);
  350.       proc->saved_exc_port = MACH_PORT_NULL;
  351.     }

  352.   return exc_port;
  353. }

  354. /* Replace PROC's exception port with EXC_PORT, unless it's already
  355.    been done.  Stash away any existing exception port so we can
  356.    restore it later.  */
  357. void
  358. proc_steal_exc_port (struct proc *proc, mach_port_t exc_port)
  359. {
  360.   mach_port_t cur_exc_port = _proc_get_exc_port (proc);

  361.   if (cur_exc_port)
  362.     {
  363.       error_t err = 0;

  364.       proc_debug (proc, "inserting exception port: %lu", exc_port);

  365.       if (cur_exc_port != exc_port)
  366.         /* Put in our exception port.  */
  367.         err = proc_set_exception_port (proc, exc_port);

  368.       if (err || cur_exc_port == proc->exc_port)
  369.         /* We previously set the exception port, and it's still set.  So we
  370.            just keep the old saved port which is what the proc set.  */
  371.         {
  372.           if (cur_exc_port)
  373.             mach_port_deallocate (mach_task_self (), cur_exc_port);
  374.         }
  375.       else
  376.         /* Keep a copy of PROC's old exception port so it can be restored.  */
  377.         {
  378.           if (proc->saved_exc_port)
  379.             mach_port_deallocate (mach_task_self (), proc->saved_exc_port);
  380.           proc->saved_exc_port = cur_exc_port;
  381.         }

  382.       proc_debug (proc, "saved exception port: %lu", proc->saved_exc_port);

  383.       if (!err)
  384.         proc->exc_port = exc_port;
  385.       else
  386.         warning (_("Error setting exception port for %s: %s"),
  387.                  proc_string (proc), safe_strerror (err));
  388.     }
  389. }

  390. /* If we previously replaced PROC's exception port, put back what we
  391.    found there at the time, unless *our* exception port has since been
  392.    overwritten, in which case who knows what's going on.  */
  393. void
  394. proc_restore_exc_port (struct proc *proc)
  395. {
  396.   mach_port_t cur_exc_port = _proc_get_exc_port (proc);

  397.   if (cur_exc_port)
  398.     {
  399.       error_t err = 0;

  400.       proc_debug (proc, "restoring real exception port");

  401.       if (proc->exc_port == cur_exc_port)
  402.         /* Our's is still there.  */
  403.         err = proc_set_exception_port (proc, proc->saved_exc_port);

  404.       if (proc->saved_exc_port)
  405.         mach_port_deallocate (mach_task_self (), proc->saved_exc_port);
  406.       proc->saved_exc_port = MACH_PORT_NULL;

  407.       if (!err)
  408.         proc->exc_port = MACH_PORT_NULL;
  409.       else
  410.         warning (_("Error setting exception port for %s: %s"),
  411.                  proc_string (proc), safe_strerror (err));
  412.     }
  413. }


  414. /* Turns hardware tracing in PROC on or off when SET is true or false,
  415.    respectively.  Returns true on success.  */
  416. int
  417. proc_trace (struct proc *proc, int set)
  418. {
  419.   thread_state_t state = proc_get_state (proc, 1);

  420.   if (!state)
  421.     return 0;                        /* The thread must be dead.  */

  422.   proc_debug (proc, "tracing %s", set ? "on" : "off");

  423.   if (set)
  424.     {
  425.       /* XXX We don't get the exception unless the thread has its own
  426.          exception port????  */
  427.       if (proc->exc_port == MACH_PORT_NULL)
  428.         proc_steal_exc_port (proc, proc->inf->event_port);
  429.       THREAD_STATE_SET_TRACED (state);
  430.     }
  431.   else
  432.     THREAD_STATE_CLEAR_TRACED (state);

  433.   return 1;
  434. }


  435. /* A variable from which to assign new TIDs.  */
  436. static int next_thread_id = 1;

  437. /* Returns a new proc structure with the given fields.  Also adds a
  438.    notification for PORT becoming dead to be sent to INF's notify port.  */
  439. struct proc *
  440. make_proc (struct inf *inf, mach_port_t port, int tid)
  441. {
  442.   error_t err;
  443.   mach_port_t prev_port = MACH_PORT_NULL;
  444.   struct proc *proc = xmalloc (sizeof (struct proc));

  445.   proc->port = port;
  446.   proc->tid = tid;
  447.   proc->inf = inf;
  448.   proc->next = 0;
  449.   proc->saved_exc_port = MACH_PORT_NULL;
  450.   proc->exc_port = MACH_PORT_NULL;

  451.   proc->sc = 0;
  452.   proc->cur_sc = 0;

  453.   /* Note that these are all the values for threads; the task simply uses the
  454.      corresponding field in INF directly.  */
  455.   proc->run_sc = inf->default_thread_run_sc;
  456.   proc->pause_sc = inf->default_thread_pause_sc;
  457.   proc->detach_sc = inf->default_thread_detach_sc;
  458.   proc->resume_sc = proc->run_sc;

  459.   proc->aborted = 0;
  460.   proc->dead = 0;
  461.   proc->state_valid = 0;
  462.   proc->state_changed = 0;

  463.   proc_debug (proc, "is new");

  464.   /* Get notified when things die.  */
  465.   err =
  466.     mach_port_request_notification (mach_task_self (), port,
  467.                                     MACH_NOTIFY_DEAD_NAME, 1,
  468.                                     inf->event_port,
  469.                                     MACH_MSG_TYPE_MAKE_SEND_ONCE,
  470.                                     &prev_port);
  471.   if (err)
  472.     warning (_("Couldn't request notification for port %lu: %s"),
  473.              port, safe_strerror (err));
  474.   else
  475.     {
  476.       proc_debug (proc, "notifications to: %lu", inf->event_port);
  477.       if (prev_port != MACH_PORT_NULL)
  478.         mach_port_deallocate (mach_task_self (), prev_port);
  479.     }

  480.   if (inf->want_exceptions)
  481.     {
  482.       if (proc_is_task (proc))
  483.         /* Make the task exception port point to us.  */
  484.         proc_steal_exc_port (proc, inf->event_port);
  485.       else
  486.         /* Just clear thread exception ports -- they default to the
  487.            task one.  */
  488.         proc_steal_exc_port (proc, MACH_PORT_NULL);
  489.     }

  490.   return proc;
  491. }

  492. /* Frees PROC and any resources it uses, and returns the value of PROC's
  493.    next field.  */
  494. struct proc *
  495. _proc_free (struct proc *proc)
  496. {
  497.   struct inf *inf = proc->inf;
  498.   struct proc *next = proc->next;

  499.   proc_debug (proc, "freeing...");

  500.   if (proc == inf->step_thread)
  501.     /* Turn off single stepping.  */
  502.     inf_set_step_thread (inf, 0);
  503.   if (proc == inf->wait.thread)
  504.     inf_clear_wait (inf);
  505.   if (proc == inf->signal_thread)
  506.     inf->signal_thread = 0;

  507.   if (proc->port != MACH_PORT_NULL)
  508.     {
  509.       if (proc->exc_port != MACH_PORT_NULL)
  510.         /* Restore the original exception port.  */
  511.         proc_restore_exc_port (proc);
  512.       if (proc->cur_sc != 0)
  513.         /* Resume the thread/task.  */
  514.         {
  515.           proc->sc = 0;
  516.           proc_update_sc (proc);
  517.         }
  518.       mach_port_deallocate (mach_task_self (), proc->port);
  519.     }

  520.   xfree (proc);
  521.   return next;
  522. }


  523. static struct inf *
  524. make_inf (void)
  525. {
  526.   struct inf *inf = xmalloc (sizeof (struct inf));

  527.   inf->task = 0;
  528.   inf->threads = 0;
  529.   inf->threads_up_to_date = 0;
  530.   inf->pid = 0;
  531.   inf->wait.status.kind = TARGET_WAITKIND_SPURIOUS;
  532.   inf->wait.thread = 0;
  533.   inf->wait.exc.handler = MACH_PORT_NULL;
  534.   inf->wait.exc.reply = MACH_PORT_NULL;
  535.   inf->step_thread = 0;
  536.   inf->signal_thread = 0;
  537.   inf->event_port = MACH_PORT_NULL;
  538.   inf->running = 0;
  539.   inf->stopped = 0;
  540.   inf->nomsg = 1;
  541.   inf->traced = 0;
  542.   inf->no_wait = 0;
  543.   inf->pending_execs = 0;
  544.   inf->pause_sc = 1;
  545.   inf->detach_sc = 0;
  546.   inf->default_thread_run_sc = 0;
  547.   inf->default_thread_pause_sc = 0;
  548.   inf->default_thread_detach_sc = 0;
  549.   inf->want_signals = 1;        /* By default */
  550.   inf->want_exceptions = 1;        /* By default */

  551.   return inf;
  552. }

  553. /* Clear INF's target wait status.  */
  554. void
  555. inf_clear_wait (struct inf *inf)
  556. {
  557.   inf_debug (inf, "clearing wait");
  558.   inf->wait.status.kind = TARGET_WAITKIND_SPURIOUS;
  559.   inf->wait.thread = 0;
  560.   inf->wait.suppress = 0;
  561.   if (inf->wait.exc.handler != MACH_PORT_NULL)
  562.     {
  563.       mach_port_deallocate (mach_task_self (), inf->wait.exc.handler);
  564.       inf->wait.exc.handler = MACH_PORT_NULL;
  565.     }
  566.   if (inf->wait.exc.reply != MACH_PORT_NULL)
  567.     {
  568.       mach_port_deallocate (mach_task_self (), inf->wait.exc.reply);
  569.       inf->wait.exc.reply = MACH_PORT_NULL;
  570.     }
  571. }


  572. void
  573. inf_cleanup (struct inf *inf)
  574. {
  575.   inf_debug (inf, "cleanup");

  576.   inf_clear_wait (inf);

  577.   inf_set_pid (inf, -1);
  578.   inf->pid = 0;
  579.   inf->running = 0;
  580.   inf->stopped = 0;
  581.   inf->nomsg = 1;
  582.   inf->traced = 0;
  583.   inf->no_wait = 0;
  584.   inf->pending_execs = 0;

  585.   if (inf->event_port)
  586.     {
  587.       mach_port_destroy (mach_task_self (), inf->event_port);
  588.       inf->event_port = MACH_PORT_NULL;
  589.     }
  590. }

  591. void
  592. inf_startup (struct inf *inf, int pid)
  593. {
  594.   error_t err;

  595.   inf_debug (inf, "startup: pid = %d", pid);

  596.   inf_cleanup (inf);

  597.   /* Make the port on which we receive all events.  */
  598.   err = mach_port_allocate (mach_task_self (),
  599.                             MACH_PORT_RIGHT_RECEIVE, &inf->event_port);
  600.   if (err)
  601.     error (_("Error allocating event port: %s"), safe_strerror (err));

  602.   /* Make a send right for it, so we can easily copy it for other people.  */
  603.   mach_port_insert_right (mach_task_self (), inf->event_port,
  604.                           inf->event_port, MACH_MSG_TYPE_MAKE_SEND);
  605.   inf_set_pid (inf, pid);
  606. }


  607. /* Close current process, if any, and attach INF to process PORT.  */
  608. void
  609. inf_set_pid (struct inf *inf, pid_t pid)
  610. {
  611.   task_t task_port;
  612.   struct proc *task = inf->task;

  613.   inf_debug (inf, "setting pid: %d", pid);

  614.   if (pid < 0)
  615.     task_port = MACH_PORT_NULL;
  616.   else
  617.     {
  618.       error_t err = proc_pid2task (proc_server, pid, &task_port);

  619.       if (err)
  620.         error (_("Error getting task for pid %d: %s"),
  621.                pid, safe_strerror (err));
  622.     }

  623.   inf_debug (inf, "setting task: %lu", task_port);

  624.   if (inf->pause_sc)
  625.     task_suspend (task_port);

  626.   if (task && task->port != task_port)
  627.     {
  628.       inf->task = 0;
  629.       inf_validate_procs (inf);        /* Trash all the threads.  */
  630.       _proc_free (task);        /* And the task.  */
  631.     }

  632.   if (task_port != MACH_PORT_NULL)
  633.     {
  634.       inf->task = make_proc (inf, task_port, PROC_TID_TASK);
  635.       inf->threads_up_to_date = 0;
  636.     }

  637.   if (inf->task)
  638.     {
  639.       inf->pid = pid;
  640.       if (inf->pause_sc)
  641.         /* Reflect task_suspend above.  */
  642.         inf->task->sc = inf->task->cur_sc = 1;
  643.     }
  644.   else
  645.     inf->pid = -1;
  646. }


  647. /* Validates INF's stopped, nomsg and traced field from the actual
  648.    proc server state.  Note that the traced field is only updated from
  649.    the proc server state if we do not have a message port.  If we do
  650.    have a message port we'd better look at the tracemask itself.  */
  651. static void
  652. inf_validate_procinfo (struct inf *inf)
  653. {
  654.   char *noise;
  655.   mach_msg_type_number_t noise_len = 0;
  656.   struct procinfo *pi;
  657.   mach_msg_type_number_t pi_len = 0;
  658.   int info_flags = 0;
  659.   error_t err =
  660.     proc_getprocinfo (proc_server, inf->pid, &info_flags,
  661.                       (procinfo_t *) &pi, &pi_len, &noise, &noise_len);

  662.   if (!err)
  663.     {
  664.       inf->stopped = !!(pi->state & PI_STOPPED);
  665.       inf->nomsg = !!(pi->state & PI_NOMSG);
  666.       if (inf->nomsg)
  667.         inf->traced = !!(pi->state & PI_TRACED);
  668.       vm_deallocate (mach_task_self (), (vm_address_t) pi,
  669.                      pi_len * sizeof (*(procinfo_t) 0));
  670.       if (noise_len > 0)
  671.         vm_deallocate (mach_task_self (), (vm_address_t) noise, noise_len);
  672.     }
  673. }

  674. /* Validates INF's task suspend count.  If it's higher than we expect,
  675.    verify with the user before `stealing' the extra count.  */
  676. static void
  677. inf_validate_task_sc (struct inf *inf)
  678. {
  679.   char *noise;
  680.   mach_msg_type_number_t noise_len = 0;
  681.   struct procinfo *pi;
  682.   mach_msg_type_number_t pi_len = 0;
  683.   int info_flags = PI_FETCH_TASKINFO;
  684.   int suspend_count = -1;
  685.   error_t err;

  686. retry:
  687.   err = proc_getprocinfo (proc_server, inf->pid, &info_flags,
  688.                           (procinfo_t *) &pi, &pi_len, &noise, &noise_len);
  689.   if (err)
  690.     {
  691.       inf->task->dead = 1; /* oh well */
  692.       return;
  693.     }

  694.   if (inf->task->cur_sc < pi->taskinfo.suspend_count && suspend_count == -1)
  695.     {
  696.       /* The proc server might have suspended the task while stopping
  697.          it.  This happens when the task is handling a traced signal.
  698.          Refetch the suspend count.  The proc server should be
  699.          finished stopping the task by now.  */
  700.       suspend_count = pi->taskinfo.suspend_count;
  701.       goto retry;
  702.     }

  703.   suspend_count = pi->taskinfo.suspend_count;

  704.   vm_deallocate (mach_task_self (), (vm_address_t) pi,
  705.                  pi_len * sizeof (*(procinfo_t) 0));
  706.   if (noise_len > 0)
  707.     vm_deallocate (mach_task_self (), (vm_address_t) noise, noise_len);

  708.   if (inf->task->cur_sc < suspend_count)
  709.     {
  710.       int abort;

  711.       target_terminal_ours ();        /* Allow I/O.  */
  712.       abort = !query (_("Pid %d has an additional task suspend count of %d;"
  713.                       " clear it? "), inf->pid,
  714.                       suspend_count - inf->task->cur_sc);
  715.       target_terminal_inferior ();        /* Give it back to the child.  */

  716.       if (abort)
  717.         error (_("Additional task suspend count left untouched."));

  718.       inf->task->cur_sc = suspend_count;
  719.     }
  720. }

  721. /* Turns tracing for INF on or off, depending on ON, unless it already
  722.    is.  If INF is running, the resume_sc count of INF's threads will
  723.    be modified, and the signal thread will briefly be run to change
  724.    the trace state.  */
  725. static void
  726. inf_set_traced (struct inf *inf, int on)
  727. {
  728.   if (on == inf->traced)
  729.     return;

  730.   if (inf->task && !inf->task->dead)
  731.     /* Make it take effect immediately.  */
  732.     {
  733.       sigset_t mask = on ? ~(sigset_t) 0 : 0;
  734.       error_t err =
  735.         INF_RESUME_MSGPORT_RPC (inf, msg_set_init_int (msgport, refport,
  736.                                                        INIT_TRACEMASK, mask));

  737.       if (err == EIEIO)
  738.         {
  739.           if (on)
  740.             warning (_("Can't modify tracing state for pid %d: %s"),
  741.                      inf->pid, "No signal thread");
  742.           inf->traced = on;
  743.         }
  744.       else if (err)
  745.         warning (_("Can't modify tracing state for pid %d: %s"),
  746.                  inf->pid, safe_strerror (err));
  747.       else
  748.         inf->traced = on;
  749.     }
  750.   else
  751.     inf->traced = on;
  752. }


  753. /* Makes all the real suspend count deltas of all the procs in INF
  754.    match the desired values.  Careful to always do thread/task suspend
  755.    counts in the safe order.  Returns true if at least one thread is
  756.    thought to be running.  */
  757. int
  758. inf_update_suspends (struct inf *inf)
  759. {
  760.   struct proc *task = inf->task;

  761.   /* We don't have to update INF->threads even though we're iterating over it
  762.      because we'll change a thread only if it already has an existing proc
  763.      entry.  */
  764.   inf_debug (inf, "updating suspend counts");

  765.   if (task)
  766.     {
  767.       struct proc *thread;
  768.       int task_running = (task->sc == 0), thread_running = 0;

  769.       if (task->sc > task->cur_sc)
  770.         /* The task is becoming _more_ suspended; do before any threads.  */
  771.         task_running = proc_update_sc (task);

  772.       if (inf->pending_execs)
  773.         /* When we're waiting for an exec, things may be happening behind our
  774.            back, so be conservative.  */
  775.         thread_running = 1;

  776.       /* Do all the thread suspend counts.  */
  777.       for (thread = inf->threads; thread; thread = thread->next)
  778.         thread_running |= proc_update_sc (thread);

  779.       if (task->sc != task->cur_sc)
  780.         /* We didn't do the task first, because we wanted to wait for the
  781.            threads; do it now.  */
  782.         task_running = proc_update_sc (task);

  783.       inf_debug (inf, "%srunning...",
  784.                  (thread_running && task_running) ? "" : "not ");

  785.       inf->running = thread_running && task_running;

  786.       /* Once any thread has executed some code, we can't depend on the
  787.          threads list any more.  */
  788.       if (inf->running)
  789.         inf->threads_up_to_date = 0;

  790.       return inf->running;
  791.     }

  792.   return 0;
  793. }


  794. /* Converts a GDB pid to a struct proc.  */
  795. struct proc *
  796. inf_tid_to_thread (struct inf *inf, int tid)
  797. {
  798.   struct proc *thread = inf->threads;

  799.   while (thread)
  800.     if (thread->tid == tid)
  801.       return thread;
  802.     else
  803.       thread = thread->next;
  804.   return 0;
  805. }

  806. /* Converts a thread port to a struct proc.  */
  807. static struct proc *
  808. inf_port_to_thread (struct inf *inf, mach_port_t port)
  809. {
  810.   struct proc *thread = inf->threads;

  811.   while (thread)
  812.     if (thread->port == port)
  813.       return thread;
  814.     else
  815.       thread = thread->next;
  816.   return 0;
  817. }

  818. /* See gnu-nat.h.  */

  819. void
  820. inf_threads (struct inf *inf, inf_threads_ftype *f, void *arg)
  821. {
  822.   struct proc *thread;

  823.   for (thread = inf->threads; thread; thread = thread->next)
  824.     f (thread, arg);
  825. }


  826. /* Make INF's list of threads be consistent with reality of TASK.  */
  827. void
  828. inf_validate_procs (struct inf *inf)
  829. {
  830.   thread_array_t threads;
  831.   mach_msg_type_number_t num_threads, i;
  832.   struct proc *task = inf->task;

  833.   /* If no threads are currently running, this function will guarantee that
  834.      things are up to date.  The exception is if there are zero threads --
  835.      then it is almost certainly in an odd state, and probably some outside
  836.      agent will create threads.  */
  837.   inf->threads_up_to_date = inf->threads ? !inf->running : 0;

  838.   if (task)
  839.     {
  840.       error_t err = task_threads (task->port, &threads, &num_threads);

  841.       inf_debug (inf, "fetching threads");
  842.       if (err)
  843.         /* TASK must be dead.  */
  844.         {
  845.           task->dead = 1;
  846.           task = 0;
  847.         }
  848.     }

  849.   if (!task)
  850.     {
  851.       num_threads = 0;
  852.       inf_debug (inf, "no task");
  853.     }

  854.   {
  855.     /* Make things normally linear.  */
  856.     mach_msg_type_number_t search_start = 0;
  857.     /* Which thread in PROCS corresponds to each task thread, & the task.  */
  858.     struct proc *matched[num_threads + 1];
  859.     /* The last thread in INF->threads, so we can add to the end.  */
  860.     struct proc *last = 0;
  861.     /* The current thread we're considering.  */
  862.     struct proc *thread = inf->threads;

  863.     memset (matched, 0, sizeof (matched));

  864.     while (thread)
  865.       {
  866.         mach_msg_type_number_t left;

  867.         for (i = search_start, left = num_threads; left; i++, left--)
  868.           {
  869.             if (i >= num_threads)
  870.               i -= num_threads;        /* I wrapped around.  */
  871.             if (thread->port == threads[i])
  872.               /* We already know about this thread.  */
  873.               {
  874.                 matched[i] = thread;
  875.                 last = thread;
  876.                 thread = thread->next;
  877.                 search_start++;
  878.                 break;
  879.               }
  880.           }

  881.         if (!left)
  882.           {
  883.             proc_debug (thread, "died!");
  884.             thread->port = MACH_PORT_NULL;
  885.             thread = _proc_free (thread);        /* THREAD is dead.  */
  886.             if (last)
  887.               last->next = thread;
  888.             else
  889.               inf->threads = thread;
  890.           }
  891.       }

  892.     for (i = 0; i < num_threads; i++)
  893.       {
  894.         if (matched[i])
  895.           /* Throw away the duplicate send right.  */
  896.           mach_port_deallocate (mach_task_self (), threads[i]);
  897.         else
  898.           /* THREADS[I] is a thread we don't know about yet!  */
  899.           {
  900.             ptid_t ptid;

  901.             thread = make_proc (inf, threads[i], next_thread_id++);
  902.             if (last)
  903.               last->next = thread;
  904.             else
  905.               inf->threads = thread;
  906.             last = thread;
  907.             proc_debug (thread, "new thread: %lu", threads[i]);

  908.             ptid = ptid_build (inf->pid, thread->tid, 0);

  909.             /* Tell GDB's generic thread code.  */

  910.             if (ptid_equal (inferior_ptid, pid_to_ptid (inf->pid)))
  911.               /* This is the first time we're hearing about thread
  912.                  ids, after a fork-child.  */
  913.               thread_change_ptid (inferior_ptid, ptid);
  914.             else if (inf->pending_execs != 0)
  915.               /* This is a shell thread.  */
  916.               add_thread_silent (ptid);
  917.             else
  918.               add_thread (ptid);
  919.           }
  920.       }

  921.     vm_deallocate (mach_task_self (),
  922.                    (vm_address_t) threads, (num_threads * sizeof (thread_t)));
  923.   }
  924. }


  925. /* Makes sure that INF's thread list is synced with the actual process.  */
  926. int
  927. inf_update_procs (struct inf *inf)
  928. {
  929.   if (!inf->task)
  930.     return 0;
  931.   if (!inf->threads_up_to_date)
  932.     inf_validate_procs (inf);
  933.   return !!inf->task;
  934. }

  935. /* Sets the resume_sc of each thread in inf.  That of RUN_THREAD is set to 0,
  936.    and others are set to their run_sc if RUN_OTHERS is true, and otherwise
  937.    their pause_sc.  */
  938. void
  939. inf_set_threads_resume_sc (struct inf *inf,
  940.                            struct proc *run_thread, int run_others)
  941. {
  942.   struct proc *thread;

  943.   inf_update_procs (inf);
  944.   for (thread = inf->threads; thread; thread = thread->next)
  945.     if (thread == run_thread)
  946.       thread->resume_sc = 0;
  947.     else if (run_others)
  948.       thread->resume_sc = thread->run_sc;
  949.     else
  950.       thread->resume_sc = thread->pause_sc;
  951. }


  952. /* Cause INF to continue execution immediately; individual threads may still
  953.    be suspended (but their suspend counts will be updated).  */
  954. void
  955. inf_resume (struct inf *inf)
  956. {
  957.   struct proc *thread;

  958.   inf_update_procs (inf);

  959.   for (thread = inf->threads; thread; thread = thread->next)
  960.     thread->sc = thread->resume_sc;

  961.   if (inf->task)
  962.     {
  963.       if (!inf->pending_execs)
  964.         /* Try to make sure our task count is correct -- in the case where
  965.            we're waiting for an exec though, things are too volatile, so just
  966.            assume things will be reasonable (which they usually will be).  */
  967.         inf_validate_task_sc (inf);
  968.       inf->task->sc = 0;
  969.     }

  970.   inf_update_suspends (inf);
  971. }

  972. /* Cause INF to stop execution immediately; individual threads may still
  973.    be running.  */
  974. void
  975. inf_suspend (struct inf *inf)
  976. {
  977.   struct proc *thread;

  978.   inf_update_procs (inf);

  979.   for (thread = inf->threads; thread; thread = thread->next)
  980.     thread->sc = thread->pause_sc;

  981.   if (inf->task)
  982.     inf->task->sc = inf->pause_sc;

  983.   inf_update_suspends (inf);
  984. }


  985. /* INF has one thread PROC that is in single-stepping mode.  This
  986.    function changes it to be PROC, changing any old step_thread to be
  987.    a normal oneA PROC of 0 clears any existing value.  */
  988. void
  989. inf_set_step_thread (struct inf *inf, struct proc *thread)
  990. {
  991.   gdb_assert (!thread || proc_is_thread (thread));

  992.   if (thread)
  993.     inf_debug (inf, "setting step thread: %d/%d", inf->pid, thread->tid);
  994.   else
  995.     inf_debug (inf, "clearing step thread");

  996.   if (inf->step_thread != thread)
  997.     {
  998.       if (inf->step_thread && inf->step_thread->port != MACH_PORT_NULL)
  999.         if (!proc_trace (inf->step_thread, 0))
  1000.           return;
  1001.       if (thread && proc_trace (thread, 1))
  1002.         inf->step_thread = thread;
  1003.       else
  1004.         inf->step_thread = 0;
  1005.     }
  1006. }


  1007. /* Set up the thread resume_sc's so that only the signal thread is running
  1008.    (plus whatever other thread are set to always run).  Returns true if we
  1009.    did so, or false if we can't find a signal thread.  */
  1010. int
  1011. inf_set_threads_resume_sc_for_signal_thread (struct inf *inf)
  1012. {
  1013.   if (inf->signal_thread)
  1014.     {
  1015.       inf_set_threads_resume_sc (inf, inf->signal_thread, 0);
  1016.       return 1;
  1017.     }
  1018.   else
  1019.     return 0;
  1020. }

  1021. static void
  1022. inf_update_signal_thread (struct inf *inf)
  1023. {
  1024.   /* XXX for now we assume that if there's a msgport, the 2nd thread is
  1025.      the signal thread.  */
  1026.   inf->signal_thread = inf->threads ? inf->threads->next : 0;
  1027. }


  1028. /* Detachs from INF's inferior task, letting it run once again...  */
  1029. void
  1030. inf_detach (struct inf *inf)
  1031. {
  1032.   struct proc *task = inf->task;

  1033.   inf_debug (inf, "detaching...");

  1034.   inf_clear_wait (inf);
  1035.   inf_set_step_thread (inf, 0);

  1036.   if (task)
  1037.     {
  1038.       struct proc *thread;

  1039.       inf_validate_procinfo (inf);

  1040.       inf_set_traced (inf, 0);
  1041.       if (inf->stopped)
  1042.         {
  1043.           if (inf->nomsg)
  1044.             inf_continue (inf);
  1045.           else
  1046.             inf_signal (inf, GDB_SIGNAL_0);
  1047.         }

  1048.       proc_restore_exc_port (task);
  1049.       task->sc = inf->detach_sc;

  1050.       for (thread = inf->threads; thread; thread = thread->next)
  1051.         {
  1052.           proc_restore_exc_port (thread);
  1053.           thread->sc = thread->detach_sc;
  1054.         }

  1055.       inf_update_suspends (inf);
  1056.     }

  1057.   inf_cleanup (inf);
  1058. }

  1059. /* Attaches INF to the process with process id PID, returning it in a
  1060.    suspended state suitable for debugging.  */
  1061. void
  1062. inf_attach (struct inf *inf, int pid)
  1063. {
  1064.   inf_debug (inf, "attaching: %d", pid);

  1065.   if (inf->pid)
  1066.     inf_detach (inf);

  1067.   inf_startup (inf, pid);
  1068. }


  1069. /* Makes sure that we've got our exception ports entrenched in the process.  */
  1070. void
  1071. inf_steal_exc_ports (struct inf *inf)
  1072. {
  1073.   struct proc *thread;

  1074.   inf_debug (inf, "stealing exception ports");

  1075.   inf_set_step_thread (inf, 0);        /* The step thread is special.  */

  1076.   proc_steal_exc_port (inf->task, inf->event_port);
  1077.   for (thread = inf->threads; thread; thread = thread->next)
  1078.     proc_steal_exc_port (thread, MACH_PORT_NULL);
  1079. }

  1080. /* Makes sure the process has its own exception ports.  */
  1081. void
  1082. inf_restore_exc_ports (struct inf *inf)
  1083. {
  1084.   struct proc *thread;

  1085.   inf_debug (inf, "restoring exception ports");

  1086.   inf_set_step_thread (inf, 0);        /* The step thread is special.  */

  1087.   proc_restore_exc_port (inf->task);
  1088.   for (thread = inf->threads; thread; thread = thread->next)
  1089.     proc_restore_exc_port (thread);
  1090. }


  1091. /* Deliver signal SIG to INF.  If INF is stopped, delivering a signal, even
  1092.    signal 0, will continue it.  INF is assumed to be in a paused state, and
  1093.    the resume_sc's of INF's threads may be affected.  */
  1094. void
  1095. inf_signal (struct inf *inf, enum gdb_signal sig)
  1096. {
  1097.   error_t err = 0;
  1098.   int host_sig = gdb_signal_to_host (sig);

  1099. #define NAME gdb_signal_to_name (sig)

  1100.   if (host_sig >= _NSIG)
  1101.     /* A mach exception.  Exceptions are encoded in the signal space by
  1102.        putting them after _NSIG; this assumes they're positive (and not
  1103.        extremely large)!  */
  1104.     {
  1105.       struct inf_wait *w = &inf->wait;

  1106.       if (w->status.kind == TARGET_WAITKIND_STOPPED
  1107.           && w->status.value.sig == sig
  1108.           && w->thread && !w->thread->aborted)
  1109.         /* We're passing through the last exception we received.  This is
  1110.            kind of bogus, because exceptions are per-thread whereas gdb
  1111.            treats signals as per-process.  We just forward the exception to
  1112.            the correct handler, even it's not for the same thread as TID --
  1113.            i.e., we pretend it's global.  */
  1114.         {
  1115.           struct exc_state *e = &w->exc;

  1116.           inf_debug (inf, "passing through exception:"
  1117.                      " task = %lu, thread = %lu, exc = %d"
  1118.                      ", code = %d, subcode = %d",
  1119.                      w->thread->port, inf->task->port,
  1120.                      e->exception, e->code, e->subcode);
  1121.           err =
  1122.             exception_raise_request (e->handler,
  1123.                                      e->reply, MACH_MSG_TYPE_MOVE_SEND_ONCE,
  1124.                                      w->thread->port, inf->task->port,
  1125.                                      e->exception, e->code, e->subcode);
  1126.         }
  1127.       else
  1128.         error (_("Can't forward spontaneous exception (%s)."), NAME);
  1129.     }
  1130.   else
  1131.     /* A Unix signal.  */
  1132.   if (inf->stopped)
  1133.     /* The process is stopped and expecting a signal.  Just send off a
  1134.        request and let it get handled when we resume everything.  */
  1135.     {
  1136.       inf_debug (inf, "sending %s to stopped process", NAME);
  1137.       err =
  1138.         INF_MSGPORT_RPC (inf,
  1139.                          msg_sig_post_untraced_request (msgport,
  1140.                                                         inf->event_port,
  1141.                                                MACH_MSG_TYPE_MAKE_SEND_ONCE,
  1142.                                                         host_sig, 0,
  1143.                                                         refport));
  1144.       if (!err)
  1145.         /* Posting an untraced signal automatically continues it.
  1146.            We clear this here rather than when we get the reply
  1147.            because we'd rather assume it's not stopped when it
  1148.            actually is, than the reverse.  */
  1149.         inf->stopped = 0;
  1150.     }
  1151.   else
  1152.     /* It's not expecting it.  We have to let just the signal thread
  1153.        run, and wait for it to get into a reasonable state before we
  1154.        can continue the rest of the process.  When we finally resume the
  1155.        process the signal we request will be the very first thing that
  1156.        happens.  */
  1157.     {
  1158.       inf_debug (inf, "sending %s to unstopped process"
  1159.                  " (so resuming signal thread)", NAME);
  1160.       err =
  1161.         INF_RESUME_MSGPORT_RPC (inf,
  1162.                                 msg_sig_post_untraced (msgport, host_sig,
  1163.                                                        0, refport));
  1164.     }

  1165.   if (err == EIEIO)
  1166.     /* Can't do too much...  */
  1167.     warning (_("Can't deliver signal %s: No signal thread."), NAME);
  1168.   else if (err)
  1169.     warning (_("Delivering signal %s: %s"), NAME, safe_strerror (err));

  1170. #undef NAME
  1171. }


  1172. /* Continue INF without delivering a signal.  This is meant to be used
  1173.    when INF does not have a message port.  */
  1174. void
  1175. inf_continue (struct inf *inf)
  1176. {
  1177.   process_t proc;
  1178.   error_t err = proc_pid2proc (proc_server, inf->pid, &proc);

  1179.   if (!err)
  1180.     {
  1181.       inf_debug (inf, "continuing process");

  1182.       err = proc_mark_cont (proc);
  1183.       if (!err)
  1184.         {
  1185.           struct proc *thread;

  1186.           for (thread = inf->threads; thread; thread = thread->next)
  1187.             thread_resume (thread->port);

  1188.           inf->stopped = 0;
  1189.         }
  1190.     }

  1191.   if (err)
  1192.     warning (_("Can't continue process: %s"), safe_strerror (err));
  1193. }


  1194. /* The inferior used for all gdb target ops.  */
  1195. struct inf *gnu_current_inf = 0;

  1196. /* The inferior being waited for by gnu_wait.  Since GDB is decidely not
  1197.    multi-threaded, we don't bother to lock this.  */
  1198. struct inf *waiting_inf;

  1199. /* Wait for something to happen in the inferior, returning what in STATUS.  */
  1200. static ptid_t
  1201. gnu_wait (struct target_ops *ops,
  1202.           ptid_t ptid, struct target_waitstatus *status, int options)
  1203. {
  1204.   struct msg
  1205.     {
  1206.       mach_msg_header_t hdr;
  1207.       mach_msg_type_t type;
  1208.       int data[8000];
  1209.     } msg;
  1210.   error_t err;
  1211.   struct proc *thread;
  1212.   struct inf *inf = gnu_current_inf;

  1213.   extern int exc_server (mach_msg_header_t *, mach_msg_header_t *);
  1214.   extern int msg_reply_server (mach_msg_header_t *, mach_msg_header_t *);
  1215.   extern int notify_server (mach_msg_header_t *, mach_msg_header_t *);
  1216.   extern int process_reply_server (mach_msg_header_t *, mach_msg_header_t *);

  1217.   gdb_assert (inf->task);

  1218.   if (!inf->threads && !inf->pending_execs)
  1219.     /* No threads!  Assume that maybe some outside agency is frobbing our
  1220.        task, and really look for new threads.  If we can't find any, just tell
  1221.        the user to try again later.  */
  1222.     {
  1223.       inf_validate_procs (inf);
  1224.       if (!inf->threads && !inf->task->dead)
  1225.         error (_("There are no threads; try again later."));
  1226.     }

  1227.   waiting_inf = inf;

  1228.   inf_debug (inf, "waiting for: %s", target_pid_to_str (ptid));

  1229. rewait:
  1230.   if (proc_wait_pid != inf->pid && !inf->no_wait)
  1231.     /* Always get information on events from the proc server.  */
  1232.     {
  1233.       inf_debug (inf, "requesting wait on pid %d", inf->pid);

  1234.       if (proc_wait_pid)
  1235.         /* The proc server is single-threaded, and only allows a single
  1236.            outstanding wait request, so we have to cancel the previous one.  */
  1237.         {
  1238.           inf_debug (inf, "cancelling previous wait on pid %d", proc_wait_pid);
  1239.           interrupt_operation (proc_server, 0);
  1240.         }

  1241.       err =
  1242.         proc_wait_request (proc_server, inf->event_port, inf->pid, WUNTRACED);
  1243.       if (err)
  1244.         warning (_("wait request failed: %s"), safe_strerror (err));
  1245.       else
  1246.         {
  1247.           inf_debug (inf, "waits pending: %d", proc_waits_pending);
  1248.           proc_wait_pid = inf->pid;
  1249.           /* Even if proc_waits_pending was > 0 before, we still won't
  1250.              get any other replies, because it was either from a
  1251.              different INF, or a different process attached to INF --
  1252.              and the event port, which is the wait reply port, changes
  1253.              when you switch processes.  */
  1254.           proc_waits_pending = 1;
  1255.         }
  1256.     }

  1257.   inf_clear_wait (inf);

  1258.   /* What can happen? (1) Dead name notification; (2) Exceptions arrive;
  1259.      (3) wait reply from the proc server.  */

  1260.   inf_debug (inf, "waiting for an event...");
  1261.   err = mach_msg (&msg.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT,
  1262.                   0, sizeof (struct msg), inf->event_port,
  1263.                   MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);

  1264.   /* Re-suspend the task.  */
  1265.   inf_suspend (inf);

  1266.   if (!inf->task && inf->pending_execs)
  1267.     /* When doing an exec, it's possible that the old task wasn't reused
  1268.        (e.g., setuid execs).  So if the task seems to have disappeared,
  1269.        attempt to refetch it, as the pid should still be the same.  */
  1270.     inf_set_pid (inf, inf->pid);

  1271.   if (err == EMACH_RCV_INTERRUPTED)
  1272.     inf_debug (inf, "interrupted");
  1273.   else if (err)
  1274.     error (_("Couldn't wait for an event: %s"), safe_strerror (err));
  1275.   else
  1276.     {
  1277.       struct
  1278.         {
  1279.           mach_msg_header_t hdr;
  1280.           mach_msg_type_t err_type;
  1281.           kern_return_t err;
  1282.           char noise[200];
  1283.         }
  1284.       reply;

  1285.       inf_debug (inf, "event: msgid = %d", msg.hdr.msgh_id);

  1286.       /* Handle what we got.  */
  1287.       if (!notify_server (&msg.hdr, &reply.hdr)
  1288.           && !exc_server (&msg.hdr, &reply.hdr)
  1289.           && !process_reply_server (&msg.hdr, &reply.hdr)
  1290.           && !msg_reply_server (&msg.hdr, &reply.hdr))
  1291.         /* Whatever it is, it's something strange.  */
  1292.         error (_("Got a strange event, msg id = %d."), msg.hdr.msgh_id);

  1293.       if (reply.err)
  1294.         error (_("Handling event, msgid = %d: %s"),
  1295.                msg.hdr.msgh_id, safe_strerror (reply.err));
  1296.     }

  1297.   if (inf->pending_execs)
  1298.     /* We're waiting for the inferior to finish execing.  */
  1299.     {
  1300.       struct inf_wait *w = &inf->wait;
  1301.       enum target_waitkind kind = w->status.kind;

  1302.       if (kind == TARGET_WAITKIND_SPURIOUS)
  1303.         /* Since gdb is actually counting the number of times the inferior
  1304.            stops, expecting one stop per exec, we only return major events
  1305.            while execing.  */
  1306.         {
  1307.           w->suppress = 1;
  1308.           inf_debug (inf, "pending_execs, ignoring minor event");
  1309.         }
  1310.       else if (kind == TARGET_WAITKIND_STOPPED
  1311.                && w->status.value.sig == GDB_SIGNAL_TRAP)
  1312.         /* Ah hah!  A SIGTRAP from the inferior while starting up probably
  1313.            means we've succesfully completed an exec!  */
  1314.         {
  1315.           inf_debug (inf, "one pending exec completed");
  1316.         }
  1317.       else if (kind == TARGET_WAITKIND_STOPPED)
  1318.         /* It's possible that this signal is because of a crashed process
  1319.            being handled by the hurd crash server; in this case, the process
  1320.            will have an extra task suspend, which we need to know about.
  1321.            Since the code in inf_resume that normally checks for this is
  1322.            disabled while INF->pending_execs, we do the check here instead.  */
  1323.         inf_validate_task_sc (inf);
  1324.     }

  1325.   if (inf->wait.suppress)
  1326.     /* Some totally spurious event happened that we don't consider
  1327.        worth returning to gdb.  Just keep waiting.  */
  1328.     {
  1329.       inf_debug (inf, "suppressing return, rewaiting...");
  1330.       inf_resume (inf);
  1331.       goto rewait;
  1332.     }

  1333.   /* Pass back out our results.  */
  1334.   memcpy (status, &inf->wait.status, sizeof (*status));

  1335.   thread = inf->wait.thread;
  1336.   if (thread)
  1337.     ptid = ptid_build (inf->pid, thread->tid, 0);
  1338.   else if (ptid_equal (ptid, minus_one_ptid))
  1339.     thread = inf_tid_to_thread (inf, -1);
  1340.   else
  1341.     thread = inf_tid_to_thread (inf, ptid_get_lwp (ptid));

  1342.   if (!thread || thread->port == MACH_PORT_NULL)
  1343.     {
  1344.       /* TID is dead; try and find a new thread.  */
  1345.       if (inf_update_procs (inf) && inf->threads)
  1346.         ptid = ptid_build (inf->pid, inf->threads->tid, 0); /* The first
  1347.                                                                available
  1348.                                                                thread.  */
  1349.       else
  1350.         ptid = inferior_ptid;        /* let wait_for_inferior handle exit case */
  1351.     }

  1352.   if (thread
  1353.       && !ptid_equal (ptid, minus_one_ptid)
  1354.       && status->kind != TARGET_WAITKIND_SPURIOUS
  1355.       && inf->pause_sc == 0 && thread->pause_sc == 0)
  1356.     /* If something actually happened to THREAD, make sure we
  1357.        suspend it.  */
  1358.     {
  1359.       thread->sc = 1;
  1360.       inf_update_suspends (inf);
  1361.     }

  1362.   inf_debug (inf, "returning ptid = %s, status = %s (%d)",
  1363.              target_pid_to_str (ptid),
  1364.              status->kind == TARGET_WAITKIND_EXITED ? "EXITED"
  1365.              : status->kind == TARGET_WAITKIND_STOPPED ? "STOPPED"
  1366.              : status->kind == TARGET_WAITKIND_SIGNALLED ? "SIGNALLED"
  1367.              : status->kind == TARGET_WAITKIND_LOADED ? "LOADED"
  1368.              : status->kind == TARGET_WAITKIND_SPURIOUS ? "SPURIOUS"
  1369.              : "?",
  1370.              status->value.integer);

  1371.   return ptid;
  1372. }


  1373. /* The rpc handler called by exc_server.  */
  1374. error_t
  1375. S_exception_raise_request (mach_port_t port, mach_port_t reply_port,
  1376.                            thread_t thread_port, task_t task_port,
  1377.                            int exception, int code, int subcode)
  1378. {
  1379.   struct inf *inf = waiting_inf;
  1380.   struct proc *thread = inf_port_to_thread (inf, thread_port);

  1381.   inf_debug (waiting_inf,
  1382.              "thread = %lu, task = %lu, exc = %d, code = %d, subcode = %d",
  1383.              thread_port, task_port, exception, code, subcode);

  1384.   if (!thread)
  1385.     /* We don't know about thread?  */
  1386.     {
  1387.       inf_update_procs (inf);
  1388.       thread = inf_port_to_thread (inf, thread_port);
  1389.       if (!thread)
  1390.         /* Give up, the generating thread is gone.  */
  1391.         return 0;
  1392.     }

  1393.   mach_port_deallocate (mach_task_self (), thread_port);
  1394.   mach_port_deallocate (mach_task_self (), task_port);

  1395.   if (!thread->aborted)
  1396.     /* THREAD hasn't been aborted since this exception happened (abortion
  1397.        clears any exception state), so it must be real.  */
  1398.     {
  1399.       /* Store away the details; this will destroy any previous info.  */
  1400.       inf->wait.thread = thread;

  1401.       inf->wait.status.kind = TARGET_WAITKIND_STOPPED;

  1402.       if (exception == EXC_BREAKPOINT)
  1403.         /* GDB likes to get SIGTRAP for breakpoints.  */
  1404.         {
  1405.           inf->wait.status.value.sig = GDB_SIGNAL_TRAP;
  1406.           mach_port_deallocate (mach_task_self (), reply_port);
  1407.         }
  1408.       else
  1409.         /* Record the exception so that we can forward it later.  */
  1410.         {
  1411.           if (thread->exc_port == port)
  1412.             {
  1413.               inf_debug (waiting_inf, "Handler is thread exception port <%lu>",
  1414.                          thread->saved_exc_port);
  1415.               inf->wait.exc.handler = thread->saved_exc_port;
  1416.             }
  1417.           else
  1418.             {
  1419.               inf_debug (waiting_inf, "Handler is task exception port <%lu>",
  1420.                          inf->task->saved_exc_port);
  1421.               inf->wait.exc.handler = inf->task->saved_exc_port;
  1422.               gdb_assert (inf->task->exc_port == port);
  1423.             }
  1424.           if (inf->wait.exc.handler != MACH_PORT_NULL)
  1425.             /* Add a reference to the exception handler.  */
  1426.             mach_port_mod_refs (mach_task_self (),
  1427.                                 inf->wait.exc.handler, MACH_PORT_RIGHT_SEND,
  1428.                                 1);

  1429.           inf->wait.exc.exception = exception;
  1430.           inf->wait.exc.code = code;
  1431.           inf->wait.exc.subcode = subcode;
  1432.           inf->wait.exc.reply = reply_port;

  1433.           /* Exceptions are encoded in the signal space by putting
  1434.              them after _NSIG; this assumes they're positive (and not
  1435.              extremely large)!  */
  1436.           inf->wait.status.value.sig =
  1437.             gdb_signal_from_host (_NSIG + exception);
  1438.         }
  1439.     }
  1440.   else
  1441.     /* A supppressed exception, which ignore.  */
  1442.     {
  1443.       inf->wait.suppress = 1;
  1444.       mach_port_deallocate (mach_task_self (), reply_port);
  1445.     }

  1446.   return 0;
  1447. }


  1448. /* Fill in INF's wait field after a task has died without giving us more
  1449.    detailed information.  */
  1450. static void
  1451. inf_task_died_status (struct inf *inf)
  1452. {
  1453.   warning (_("Pid %d died with unknown exit status, using SIGKILL."),
  1454.            inf->pid);
  1455.   inf->wait.status.kind = TARGET_WAITKIND_SIGNALLED;
  1456.   inf->wait.status.value.sig = GDB_SIGNAL_KILL;
  1457. }

  1458. /* Notify server routines.  The only real one is dead name notification.  */
  1459. error_t
  1460. do_mach_notify_dead_name (mach_port_t notify, mach_port_t dead_port)
  1461. {
  1462.   struct inf *inf = waiting_inf;

  1463.   inf_debug (waiting_inf, "port = %lu", dead_port);

  1464.   if (inf->task && inf->task->port == dead_port)
  1465.     {
  1466.       proc_debug (inf->task, "is dead");
  1467.       inf->task->port = MACH_PORT_NULL;
  1468.       if (proc_wait_pid == inf->pid)
  1469.         /* We have a wait outstanding on the process, which will return more
  1470.            detailed information, so delay until we get that.  */
  1471.         inf->wait.suppress = 1;
  1472.       else
  1473.         /* We never waited for the process (maybe it wasn't a child), so just
  1474.            pretend it got a SIGKILL.  */
  1475.         inf_task_died_status (inf);
  1476.     }
  1477.   else
  1478.     {
  1479.       struct proc *thread = inf_port_to_thread (inf, dead_port);

  1480.       if (thread)
  1481.         {
  1482.           proc_debug (thread, "is dead");
  1483.           thread->port = MACH_PORT_NULL;
  1484.         }

  1485.       if (inf->task->dead)
  1486.         /* Since the task is dead, its threads are dying with it.  */
  1487.         inf->wait.suppress = 1;
  1488.     }

  1489.   mach_port_deallocate (mach_task_self (), dead_port);
  1490.   inf->threads_up_to_date = 0;        /* Just in case.  */

  1491.   return 0;
  1492. }


  1493. #define ILL_RPC(fun, ...) \
  1494.   extern kern_return_t fun (__VA_ARGS__); \
  1495.   kern_return_t fun (__VA_ARGS__) \
  1496.   { \
  1497.     warning (_("illegal rpc: %s"), #fun); \
  1498.     return 0; \
  1499.   }

  1500. ILL_RPC (do_mach_notify_no_senders,
  1501.          mach_port_t notify, mach_port_mscount_t count)
  1502. ILL_RPC (do_mach_notify_port_deleted,
  1503.          mach_port_t notify, mach_port_t name)
  1504. ILL_RPC (do_mach_notify_msg_accepted,
  1505.          mach_port_t notify, mach_port_t name)
  1506. ILL_RPC (do_mach_notify_port_destroyed,
  1507.          mach_port_t notify, mach_port_t name)
  1508. ILL_RPC (do_mach_notify_send_once,
  1509.          mach_port_t notify)

  1510. /* Process_reply server routines.  We only use process_wait_reply.  */

  1511. error_t
  1512. S_proc_wait_reply (mach_port_t reply, error_t err,
  1513.                    int status, int sigcode, rusage_t rusage, pid_t pid)
  1514. {
  1515.   struct inf *inf = waiting_inf;

  1516.   inf_debug (inf, "err = %s, pid = %d, status = 0x%x, sigcode = %d",
  1517.              err ? safe_strerror (err) : "0", pid, status, sigcode);

  1518.   if (err && proc_wait_pid && (!inf->task || !inf->task->port))
  1519.     /* Ack.  The task has died, but the task-died notification code didn't
  1520.        tell anyone because it thought a more detailed reply from the
  1521.        procserver was forthcoming.  However, we now learn that won't
  1522.        happen...  So we have to act like the task just died, and this time,
  1523.        tell the world.  */
  1524.     inf_task_died_status (inf);

  1525.   if (--proc_waits_pending == 0)
  1526.     /* PROC_WAIT_PID represents the most recent wait.  We will always get
  1527.        replies in order because the proc server is single threaded.  */
  1528.     proc_wait_pid = 0;

  1529.   inf_debug (inf, "waits pending now: %d", proc_waits_pending);

  1530.   if (err)
  1531.     {
  1532.       if (err != EINTR)
  1533.         {
  1534.           warning (_("Can't wait for pid %d: %s"),
  1535.                    inf->pid, safe_strerror (err));
  1536.           inf->no_wait = 1;

  1537.           /* Since we can't see the inferior's signals, don't trap them.  */
  1538.           inf_set_traced (inf, 0);
  1539.         }
  1540.     }
  1541.   else if (pid == inf->pid)
  1542.     {
  1543.       store_waitstatus (&inf->wait.status, status);
  1544.       if (inf->wait.status.kind == TARGET_WAITKIND_STOPPED)
  1545.         /* The process has sent us a signal, and stopped itself in a sane
  1546.            state pending our actions.  */
  1547.         {
  1548.           inf_debug (inf, "process has stopped itself");
  1549.           inf->stopped = 1;
  1550.         }
  1551.     }
  1552.   else
  1553.     inf->wait.suppress = 1;        /* Something odd happened.  Ignore.  */

  1554.   return 0;
  1555. }

  1556. ILL_RPC (S_proc_setmsgport_reply,
  1557.          mach_port_t reply_port, kern_return_t return_code,
  1558.          mach_port_t oldmsgport)
  1559. ILL_RPC (S_proc_getmsgport_reply,
  1560.          mach_port_t reply_port, kern_return_t return_code,
  1561.          mach_port_t msgports)
  1562. ILL_RPC (S_proc_pid2task_reply,
  1563.          mach_port_t reply_port, kern_return_t return_code, mach_port_t task)
  1564. ILL_RPC (S_proc_task2pid_reply,
  1565.          mach_port_t reply_port, kern_return_t return_code, pid_t pid)
  1566. ILL_RPC (S_proc_task2proc_reply,
  1567.          mach_port_t reply_port, kern_return_t return_code, mach_port_t proc)
  1568. ILL_RPC (S_proc_proc2task_reply,
  1569.          mach_port_t reply_port, kern_return_t return_code, mach_port_t task)
  1570. ILL_RPC (S_proc_pid2proc_reply,
  1571.          mach_port_t reply_port, kern_return_t return_code, mach_port_t proc)
  1572. ILL_RPC (S_proc_getprocinfo_reply,
  1573.          mach_port_t reply_port, kern_return_t return_code,
  1574.          int flags, procinfo_t procinfo, mach_msg_type_number_t procinfoCnt,
  1575.          data_t threadwaits, mach_msg_type_number_t threadwaitsCnt)
  1576. ILL_RPC (S_proc_getprocargs_reply,
  1577.          mach_port_t reply_port, kern_return_t return_code,
  1578.          data_t procargs, mach_msg_type_number_t procargsCnt)
  1579. ILL_RPC (S_proc_getprocenv_reply,
  1580.          mach_port_t reply_port, kern_return_t return_code,
  1581.          data_t procenv, mach_msg_type_number_t procenvCnt)
  1582. ILL_RPC (S_proc_getloginid_reply,
  1583.          mach_port_t reply_port, kern_return_t return_code, pid_t login_id)
  1584. ILL_RPC (S_proc_getloginpids_reply,
  1585.          mach_port_t reply_port, kern_return_t return_code,
  1586.          pidarray_t pids, mach_msg_type_number_t pidsCnt)
  1587. ILL_RPC (S_proc_getlogin_reply,
  1588.          mach_port_t reply_port, kern_return_t return_code, string_t logname)
  1589. ILL_RPC (S_proc_getsid_reply,
  1590.          mach_port_t reply_port, kern_return_t return_code, pid_t sid)
  1591. ILL_RPC (S_proc_getsessionpgids_reply,
  1592.          mach_port_t reply_port, kern_return_t return_code,
  1593.          pidarray_t pgidset, mach_msg_type_number_t pgidsetCnt)
  1594. ILL_RPC (S_proc_getsessionpids_reply,
  1595.          mach_port_t reply_port, kern_return_t return_code,
  1596.          pidarray_t pidset, mach_msg_type_number_t pidsetCnt)
  1597. ILL_RPC (S_proc_getsidport_reply,
  1598.          mach_port_t reply_port, kern_return_t return_code,
  1599.          mach_port_t sessport)
  1600. ILL_RPC (S_proc_getpgrp_reply,
  1601.          mach_port_t reply_port, kern_return_t return_code, pid_t pgrp)
  1602. ILL_RPC (S_proc_getpgrppids_reply,
  1603.          mach_port_t reply_port, kern_return_t return_code,
  1604.          pidarray_t pidset, mach_msg_type_number_t pidsetCnt)
  1605. ILL_RPC (S_proc_get_tty_reply,
  1606.          mach_port_t reply_port, kern_return_t return_code, mach_port_t tty)
  1607. ILL_RPC (S_proc_getnports_reply,
  1608.          mach_port_t reply_port, kern_return_t return_code,
  1609.          mach_msg_type_number_t nports)
  1610. ILL_RPC (S_proc_is_important_reply,
  1611.          mach_port_t reply_port, kern_return_t return_code,
  1612.          boolean_t essential)
  1613. ILL_RPC (S_proc_get_code_reply,
  1614.          mach_port_t reply_port, kern_return_t return_code,
  1615.          vm_address_t start_code, vm_address_t end_code)

  1616. /* Msg_reply server routines.  We only use msg_sig_post_untraced_reply.  */

  1617. error_t
  1618. S_msg_sig_post_untraced_reply (mach_port_t reply, error_t err)
  1619. {
  1620.   struct inf *inf = waiting_inf;

  1621.   if (err == EBUSY)
  1622.     /* EBUSY is what we get when the crash server has grabbed control of the
  1623.        process and doesn't like what signal we tried to send it.  Just act
  1624.        like the process stopped (using a signal of 0 should mean that the
  1625.        *next* time the user continues, it will pass signal 0, which the crash
  1626.        server should like).  */
  1627.     {
  1628.       inf->wait.status.kind = TARGET_WAITKIND_STOPPED;
  1629.       inf->wait.status.value.sig = GDB_SIGNAL_0;
  1630.     }
  1631.   else if (err)
  1632.     warning (_("Signal delivery failed: %s"), safe_strerror (err));

  1633.   if (err)
  1634.     /* We only get this reply when we've posted a signal to a process which we
  1635.        thought was stopped, and which we expected to continue after the signal.
  1636.        Given that the signal has failed for some reason, it's reasonable to
  1637.        assume it's still stopped.  */
  1638.     inf->stopped = 1;
  1639.   else
  1640.     inf->wait.suppress = 1;

  1641.   return 0;
  1642. }

  1643. ILL_RPC (S_msg_sig_post_reply,
  1644.          mach_port_t reply, error_t err)

  1645. /* Returns the number of messages queued for the receive right PORT.  */
  1646. static mach_port_msgcount_t
  1647. port_msgs_queued (mach_port_t port)
  1648. {
  1649.   struct mach_port_status status;
  1650.   error_t err =
  1651.     mach_port_get_receive_status (mach_task_self (), port, &status);

  1652.   if (err)
  1653.     return 0;
  1654.   else
  1655.     return status.mps_msgcount;
  1656. }


  1657. /* Resume execution of the inferior process.

  1658.    If STEP is nonzero, single-step it.
  1659.    If SIGNAL is nonzero, give it that signal.

  1660.    TID  STEP:
  1661.    -1   true   Single step the current thread allowing other threads to run.
  1662.    -1   false  Continue the current thread allowing other threads to run.
  1663.    X    true   Single step the given thread, don't allow any others to run.
  1664.    X    false  Continue the given thread, do not allow any others to run.
  1665.    (Where X, of course, is anything except -1)

  1666.    Note that a resume may not `take' if there are pending exceptions/&c
  1667.    still unprocessed from the last resume we did (any given resume may result
  1668.    in multiple events returned by wait).  */

  1669. static void
  1670. gnu_resume (struct target_ops *ops,
  1671.             ptid_t ptid, int step, enum gdb_signal sig)
  1672. {
  1673.   struct proc *step_thread = 0;
  1674.   int resume_all;
  1675.   struct inf *inf = gnu_current_inf;

  1676.   inf_debug (inf, "ptid = %s, step = %d, sig = %d",
  1677.              target_pid_to_str (ptid), step, sig);

  1678.   inf_validate_procinfo (inf);

  1679.   if (sig != GDB_SIGNAL_0 || inf->stopped)
  1680.     {
  1681.       if (sig == GDB_SIGNAL_0 && inf->nomsg)
  1682.         inf_continue (inf);
  1683.       else
  1684.         inf_signal (inf, sig);
  1685.     }
  1686.   else if (inf->wait.exc.reply != MACH_PORT_NULL)
  1687.     /* We received an exception to which we have chosen not to forward, so
  1688.        abort the faulting thread, which will perhaps retake it.  */
  1689.     {
  1690.       proc_abort (inf->wait.thread, 1);
  1691.       warning (_("Aborting %s with unforwarded exception %s."),
  1692.                proc_string (inf->wait.thread),
  1693.                gdb_signal_to_name (inf->wait.status.value.sig));
  1694.     }

  1695.   if (port_msgs_queued (inf->event_port))
  1696.     /* If there are still messages in our event queue, don't bother resuming
  1697.        the process, as we're just going to stop it right away anyway.  */
  1698.     return;

  1699.   inf_update_procs (inf);

  1700.   /* A specific PTID means `step only this process id'.  */
  1701.   resume_all = ptid_equal (ptid, minus_one_ptid);

  1702.   if (resume_all)
  1703.     /* Allow all threads to run, except perhaps single-stepping one.  */
  1704.     {
  1705.       inf_debug (inf, "running all threads; tid = %d",
  1706.                  ptid_get_pid (inferior_ptid));
  1707.       ptid = inferior_ptid;        /* What to step.  */
  1708.       inf_set_threads_resume_sc (inf, 0, 1);
  1709.     }
  1710.   else
  1711.     /* Just allow a single thread to run.  */
  1712.     {
  1713.       struct proc *thread = inf_tid_to_thread (inf, ptid_get_lwp (ptid));

  1714.       if (!thread)
  1715.         error (_("Can't run single thread id %s: no such thread!"),
  1716.                target_pid_to_str (ptid));
  1717.       inf_debug (inf, "running one thread: %s", target_pid_to_str (ptid));
  1718.       inf_set_threads_resume_sc (inf, thread, 0);
  1719.     }

  1720.   if (step)
  1721.     {
  1722.       step_thread = inf_tid_to_thread (inf, ptid_get_lwp (ptid));
  1723.       if (!step_thread)
  1724.         warning (_("Can't step thread id %s: no such thread."),
  1725.                  target_pid_to_str (ptid));
  1726.       else
  1727.         inf_debug (inf, "stepping thread: %s", target_pid_to_str (ptid));
  1728.     }
  1729.   if (step_thread != inf->step_thread)
  1730.     inf_set_step_thread (inf, step_thread);

  1731.   inf_debug (inf, "here we go...");
  1732.   inf_resume (inf);
  1733. }


  1734. static void
  1735. gnu_kill_inferior (struct target_ops *ops)
  1736. {
  1737.   struct proc *task = gnu_current_inf->task;

  1738.   if (task)
  1739.     {
  1740.       proc_debug (task, "terminating...");
  1741.       task_terminate (task->port);
  1742.       inf_set_pid (gnu_current_inf, -1);
  1743.     }
  1744.   target_mourn_inferior ();
  1745. }

  1746. /* Clean up after the inferior dies.  */
  1747. static void
  1748. gnu_mourn_inferior (struct target_ops *ops)
  1749. {
  1750.   inf_debug (gnu_current_inf, "rip");
  1751.   inf_detach (gnu_current_inf);
  1752.   inf_child_mourn_inferior (ops);
  1753. }


  1754. /* Fork an inferior process, and start debugging it.  */

  1755. /* Set INFERIOR_PID to the first thread available in the child, if any.  */
  1756. static int
  1757. inf_pick_first_thread (void)
  1758. {
  1759.   if (gnu_current_inf->task && gnu_current_inf->threads)
  1760.     /* The first thread.  */
  1761.     return gnu_current_inf->threads->tid;
  1762.   else
  1763.     /* What may be the next thread.  */
  1764.     return next_thread_id;
  1765. }

  1766. static struct inf *
  1767. cur_inf (void)
  1768. {
  1769.   if (!gnu_current_inf)
  1770.     gnu_current_inf = make_inf ();
  1771.   return gnu_current_inf;
  1772. }

  1773. static void
  1774. gnu_create_inferior (struct target_ops *ops,
  1775.                      char *exec_file, char *allargs, char **env,
  1776.                      int from_tty)
  1777. {
  1778.   struct inf *inf = cur_inf ();
  1779.   int pid;

  1780.   void trace_me (void)
  1781.   {
  1782.     /* We're in the child; make this process stop as soon as it execs.  */
  1783.     inf_debug (inf, "tracing self");
  1784.     if (ptrace (PTRACE_TRACEME) != 0)
  1785.       error (_("ptrace (PTRACE_TRACEME) failed!"));
  1786.   }

  1787.   inf_debug (inf, "creating inferior");

  1788.   pid = fork_inferior (exec_file, allargs, env, trace_me,
  1789.                        NULL, NULL, NULL, NULL);

  1790.   /* Attach to the now stopped child, which is actually a shell...  */
  1791.   inf_debug (inf, "attaching to child: %d", pid);

  1792.   inf_attach (inf, pid);

  1793.   push_target (ops);

  1794.   inf->pending_execs = 1;
  1795.   inf->nomsg = 1;
  1796.   inf->traced = 1;

  1797.   /* Now let the child run again, knowing that it will stop
  1798.      immediately because of the ptrace.  */
  1799.   inf_resume (inf);

  1800.   /* We now have thread info.  */
  1801.   thread_change_ptid (inferior_ptid,
  1802.                       ptid_build (inf->pid, inf_pick_first_thread (), 0));

  1803.   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
  1804.   inf->pending_execs = 0;

  1805.   inf_validate_procinfo (inf);
  1806.   inf_update_signal_thread (inf);
  1807.   inf_set_traced (inf, inf->want_signals);

  1808.   /* Execing the process will have trashed our exception ports; steal them
  1809.      back (or make sure they're restored if the user wants that).  */
  1810.   if (inf->want_exceptions)
  1811.     inf_steal_exc_ports (inf);
  1812.   else
  1813.     inf_restore_exc_ports (inf);
  1814. }


  1815. /* Attach to process PID, then initialize for debugging it
  1816.    and wait for the trace-trap that results from attaching.  */
  1817. static void
  1818. gnu_attach (struct target_ops *ops, const char *args, int from_tty)
  1819. {
  1820.   int pid;
  1821.   char *exec_file;
  1822.   struct inf *inf = cur_inf ();
  1823.   struct inferior *inferior;

  1824.   pid = parse_pid_to_attach (args);

  1825.   if (pid == getpid ())                /* Trying to masturbate?  */
  1826.     error (_("I refuse to debug myself!"));

  1827.   if (from_tty)
  1828.     {
  1829.       exec_file = (char *) get_exec_file (0);

  1830.       if (exec_file)
  1831.         printf_unfiltered ("Attaching to program `%s', pid %d\n",
  1832.                            exec_file, pid);
  1833.       else
  1834.         printf_unfiltered ("Attaching to pid %d\n", pid);

  1835.       gdb_flush (gdb_stdout);
  1836.     }

  1837.   inf_debug (inf, "attaching to pid: %d", pid);

  1838.   inf_attach (inf, pid);

  1839.   push_target (ops);

  1840.   inferior = current_inferior ();
  1841.   inferior_appeared (inferior, pid);
  1842.   inferior->attach_flag = 1;

  1843.   inf_update_procs (inf);

  1844.   inferior_ptid = ptid_build (pid, inf_pick_first_thread (), 0);

  1845.   /* We have to initialize the terminal settings now, since the code
  1846.      below might try to restore them.  */
  1847.   target_terminal_init ();

  1848.   /* If the process was stopped before we attached, make it continue the next
  1849.      time the user does a continue.  */
  1850.   inf_validate_procinfo (inf);

  1851.   inf_update_signal_thread (inf);
  1852.   inf_set_traced (inf, inf->want_signals);

  1853. #if 0                                /* Do we need this?  */
  1854.   renumber_threads (0);                /* Give our threads reasonable names.  */
  1855. #endif
  1856. }


  1857. /* Take a program previously attached to and detaches it.
  1858.    The program resumes execution and will no longer stop
  1859.    on signals, etc.  We'd better not have left any breakpoints
  1860.    in the program or it'll die when it hits one.  For this
  1861.    to work, it may be necessary for the process to have been
  1862.    previously attached.  It *might* work if the program was
  1863.    started via fork.  */
  1864. static void
  1865. gnu_detach (struct target_ops *ops, const char *args, int from_tty)
  1866. {
  1867.   int pid;

  1868.   if (from_tty)
  1869.     {
  1870.       char *exec_file = get_exec_file (0);

  1871.       if (exec_file)
  1872.         printf_unfiltered ("Detaching from program `%s' pid %d\n",
  1873.                            exec_file, gnu_current_inf->pid);
  1874.       else
  1875.         printf_unfiltered ("Detaching from pid %d\n", gnu_current_inf->pid);
  1876.       gdb_flush (gdb_stdout);
  1877.     }

  1878.   pid = gnu_current_inf->pid;

  1879.   inf_detach (gnu_current_inf);

  1880.   inferior_ptid = null_ptid;
  1881.   detach_inferior (pid);

  1882.   inf_child_maybe_unpush_target (ops);
  1883. }

  1884. static void
  1885. gnu_terminal_init (struct target_ops *self)
  1886. {
  1887.   gdb_assert (gnu_current_inf);
  1888.   child_terminal_init_with_pgrp (gnu_current_inf->pid);
  1889. }

  1890. static void
  1891. gnu_stop (struct target_ops *self, ptid_t ptid)
  1892. {
  1893.   error (_("to_stop target function not implemented"));
  1894. }

  1895. static int
  1896. gnu_thread_alive (struct target_ops *ops, ptid_t ptid)
  1897. {
  1898.   inf_update_procs (gnu_current_inf);
  1899.   return !!inf_tid_to_thread (gnu_current_inf,
  1900.                               ptid_get_lwp (ptid));
  1901. }


  1902. /* Read inferior task's LEN bytes from ADDR and copy it to MYADDR in
  1903.    gdb's address space.  Return 0 on failure; number of bytes read
  1904.    otherwise.  */
  1905. static int
  1906. gnu_read_inferior (task_t task, CORE_ADDR addr, gdb_byte *myaddr, int length)
  1907. {
  1908.   error_t err;
  1909.   vm_address_t low_address = (vm_address_t) trunc_page (addr);
  1910.   vm_size_t aligned_length =
  1911.   (vm_size_t) round_page (addr + length) - low_address;
  1912.   pointer_t copied;
  1913.   mach_msg_type_number_t copy_count;

  1914.   /* Get memory from inferior with page aligned addresses.  */
  1915.   err = vm_read (task, low_address, aligned_length, &copied, &copy_count);
  1916.   if (err)
  1917.     return 0;

  1918.   err = hurd_safe_copyin (myaddr, (void *) (addr - low_address + copied),
  1919.                           length);
  1920.   if (err)
  1921.     {
  1922.       warning (_("Read from inferior faulted: %s"), safe_strerror (err));
  1923.       length = 0;
  1924.     }

  1925.   err = vm_deallocate (mach_task_self (), copied, copy_count);
  1926.   if (err)
  1927.     warning (_("gnu_read_inferior vm_deallocate failed: %s"),
  1928.              safe_strerror (err));

  1929.   return length;
  1930. }

  1931. #define CHK_GOTO_OUT(str,ret) \
  1932.   do if (ret != KERN_SUCCESS) { errstr = #str; goto out; } while(0)

  1933. struct vm_region_list
  1934. {
  1935.   struct vm_region_list *next;
  1936.   vm_prot_t protection;
  1937.   vm_address_t start;
  1938.   vm_size_t length;
  1939. };

  1940. struct obstack region_obstack;

  1941. /* Write gdb's LEN bytes from MYADDR and copy it to ADDR in inferior
  1942.    task's address space.  */
  1943. static int
  1944. gnu_write_inferior (task_t task, CORE_ADDR addr,
  1945.                     const gdb_byte *myaddr, int length)
  1946. {
  1947.   error_t err = 0;
  1948.   vm_address_t low_address = (vm_address_t) trunc_page (addr);
  1949.   vm_size_t aligned_length =
  1950.   (vm_size_t) round_page (addr + length) - low_address;
  1951.   pointer_t copied;
  1952.   mach_msg_type_number_t copy_count;
  1953.   int deallocate = 0;

  1954.   char *errstr = "Bug in gnu_write_inferior";

  1955.   struct vm_region_list *region_element;
  1956.   struct vm_region_list *region_head = (struct vm_region_list *) NULL;

  1957.   /* Get memory from inferior with page aligned addresses.  */
  1958.   err = vm_read (task,
  1959.                  low_address,
  1960.                  aligned_length,
  1961.                  &copied,
  1962.                  &copy_count);
  1963.   CHK_GOTO_OUT ("gnu_write_inferior vm_read failed", err);

  1964.   deallocate++;

  1965.   err = hurd_safe_copyout ((void *) (addr - low_address + copied),
  1966.                            myaddr, length);
  1967.   CHK_GOTO_OUT ("Write to inferior faulted", err);

  1968.   obstack_init (&region_obstack);

  1969.   /* Do writes atomically.
  1970.      First check for holes and unwritable memory.  */
  1971.   {
  1972.     vm_size_t remaining_length = aligned_length;
  1973.     vm_address_t region_address = low_address;

  1974.     struct vm_region_list *scan;

  1975.     while (region_address < low_address + aligned_length)
  1976.       {
  1977.         vm_prot_t protection;
  1978.         vm_prot_t max_protection;
  1979.         vm_inherit_t inheritance;
  1980.         boolean_t shared;
  1981.         mach_port_t object_name;
  1982.         vm_offset_t offset;
  1983.         vm_size_t region_length = remaining_length;
  1984.         vm_address_t old_address = region_address;

  1985.         err = vm_region (task,
  1986.                          &region_address,
  1987.                          &region_length,
  1988.                          &protection,
  1989.                          &max_protection,
  1990.                          &inheritance,
  1991.                          &shared,
  1992.                          &object_name,
  1993.                          &offset);
  1994.         CHK_GOTO_OUT ("vm_region failed", err);

  1995.         /* Check for holes in memory.  */
  1996.         if (old_address != region_address)
  1997.           {
  1998.             warning (_("No memory at 0x%lx. Nothing written"),
  1999.                      old_address);
  2000.             err = KERN_SUCCESS;
  2001.             length = 0;
  2002.             goto out;
  2003.           }

  2004.         if (!(max_protection & VM_PROT_WRITE))
  2005.           {
  2006.             warning (_("Memory at address 0x%lx is unwritable. "
  2007.                        "Nothing written"),
  2008.                      old_address);
  2009.             err = KERN_SUCCESS;
  2010.             length = 0;
  2011.             goto out;
  2012.           }

  2013.         /* Chain the regions for later use.  */
  2014.         region_element =
  2015.           (struct vm_region_list *)
  2016.           obstack_alloc (&region_obstack, sizeof (struct vm_region_list));

  2017.         region_element->protection = protection;
  2018.         region_element->start = region_address;
  2019.         region_element->length = region_length;

  2020.         /* Chain the regions along with protections.  */
  2021.         region_element->next = region_head;
  2022.         region_head = region_element;

  2023.         region_address += region_length;
  2024.         remaining_length = remaining_length - region_length;
  2025.       }

  2026.     /* If things fail after this, we give up.
  2027.        Somebody is messing up inferior_task's mappings.  */

  2028.     /* Enable writes to the chained vm regions.  */
  2029.     for (scan = region_head; scan; scan = scan->next)
  2030.       {
  2031.         if (!(scan->protection & VM_PROT_WRITE))
  2032.           {
  2033.             err = vm_protect (task,
  2034.                               scan->start,
  2035.                               scan->length,
  2036.                               FALSE,
  2037.                               scan->protection | VM_PROT_WRITE);
  2038.             CHK_GOTO_OUT ("vm_protect: enable write failed", err);
  2039.           }
  2040.       }

  2041.     err = vm_write (task,
  2042.                     low_address,
  2043.                     copied,
  2044.                     aligned_length);
  2045.     CHK_GOTO_OUT ("vm_write failed", err);

  2046.     /* Set up the original region protections, if they were changed.  */
  2047.     for (scan = region_head; scan; scan = scan->next)
  2048.       {
  2049.         if (!(scan->protection & VM_PROT_WRITE))
  2050.           {
  2051.             err = vm_protect (task,
  2052.                               scan->start,
  2053.                               scan->length,
  2054.                               FALSE,
  2055.                               scan->protection);
  2056.             CHK_GOTO_OUT ("vm_protect: enable write failed", err);
  2057.           }
  2058.       }
  2059.   }

  2060. out:
  2061.   if (deallocate)
  2062.     {
  2063.       obstack_free (&region_obstack, 0);

  2064.       (void) vm_deallocate (mach_task_self (),
  2065.                             copied,
  2066.                             copy_count);
  2067.     }

  2068.   if (err != KERN_SUCCESS)
  2069.     {
  2070.       warning (_("%s: %s"), errstr, mach_error_string (err));
  2071.       return 0;
  2072.     }

  2073.   return length;
  2074. }



  2075. /* Implement the to_xfer_partial target_ops method for
  2076.    TARGET_OBJECT_MEMORY.  */

  2077. static enum target_xfer_status
  2078. gnu_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
  2079.                  CORE_ADDR memaddr, ULONGEST len, ULONGEST *xfered_len)
  2080. {
  2081.   task_t task = (gnu_current_inf
  2082.                  ? (gnu_current_inf->task
  2083.                     ? gnu_current_inf->task->port : 0)
  2084.                  : 0);
  2085.   int res;

  2086.   if (task == MACH_PORT_NULL)
  2087.     return TARGET_XFER_E_IO;

  2088.   if (writebuf != NULL)
  2089.     {
  2090.       inf_debug (gnu_current_inf, "writing %s[%s] <-- %s",
  2091.                  paddress (target_gdbarch (), memaddr), pulongest (len),
  2092.                  host_address_to_string (writebuf));
  2093.       res = gnu_write_inferior (task, memaddr, writebuf, len);
  2094.     }
  2095.   else
  2096.     {
  2097.       inf_debug (gnu_current_inf, "reading %s[%s] --> %s",
  2098.                  paddress (target_gdbarch (), memaddr), pulongest (len),
  2099.                  host_address_to_string (readbuf));
  2100.       res = gnu_read_inferior (task, memaddr, readbuf, len);
  2101.     }
  2102.   gdb_assert (res >= 0);
  2103.   if (res == 0)
  2104.     return TARGET_XFER_E_IO;
  2105.   else
  2106.     {
  2107.       *xfered_len = (ULONGEST) res;
  2108.       return TARGET_XFER_OK;
  2109.     }
  2110. }

  2111. /* Target to_xfer_partial implementation.  */

  2112. static enum target_xfer_status
  2113. gnu_xfer_partial (struct target_ops *ops, enum target_object object,
  2114.                   const char *annex, gdb_byte *readbuf,
  2115.                   const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  2116.                   ULONGEST *xfered_len)
  2117. {
  2118.   switch (object)
  2119.     {
  2120.     case TARGET_OBJECT_MEMORY:
  2121.       return gnu_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
  2122.     default:
  2123.       return TARGET_XFER_E_IO;
  2124.     }
  2125. }

  2126. /* Call FUNC on each memory region in the task.  */
  2127. static int
  2128. gnu_find_memory_regions (struct target_ops *self,
  2129.                          find_memory_region_ftype func, void *data)
  2130. {
  2131.   error_t err;
  2132.   task_t task;
  2133.   vm_address_t region_address, last_region_address, last_region_end;
  2134.   vm_prot_t last_protection;

  2135.   if (gnu_current_inf == 0 || gnu_current_inf->task == 0)
  2136.     return 0;
  2137.   task = gnu_current_inf->task->port;
  2138.   if (task == MACH_PORT_NULL)
  2139.     return 0;

  2140.   region_address = last_region_address = last_region_end = VM_MIN_ADDRESS;
  2141.   last_protection = VM_PROT_NONE;
  2142.   while (region_address < VM_MAX_ADDRESS)
  2143.     {
  2144.       vm_prot_t protection;
  2145.       vm_prot_t max_protection;
  2146.       vm_inherit_t inheritance;
  2147.       boolean_t shared;
  2148.       mach_port_t object_name;
  2149.       vm_offset_t offset;
  2150.       vm_size_t region_length = VM_MAX_ADDRESS - region_address;
  2151.       vm_address_t old_address = region_address;

  2152.       err = vm_region (task,
  2153.                        &region_address,
  2154.                        &region_length,
  2155.                        &protection,
  2156.                        &max_protection,
  2157.                        &inheritance,
  2158.                        &shared,
  2159.                        &object_name,
  2160.                        &offset);
  2161.       if (err == KERN_NO_SPACE)
  2162.         break;
  2163.       if (err != KERN_SUCCESS)
  2164.         {
  2165.           warning (_("vm_region failed: %s"), mach_error_string (err));
  2166.           return -1;
  2167.         }

  2168.       if (protection == last_protection && region_address == last_region_end)
  2169.         /* This region is contiguous with and indistinguishable from
  2170.            the previous one, so we just extend that one.  */
  2171.         last_region_end = region_address += region_length;
  2172.       else
  2173.         {
  2174.           /* This region is distinct from the last one we saw, so report
  2175.              that previous one.  */
  2176.           if (last_protection != VM_PROT_NONE)
  2177.             (*func) (last_region_address,
  2178.                      last_region_end - last_region_address,
  2179.                      last_protection & VM_PROT_READ,
  2180.                      last_protection & VM_PROT_WRITE,
  2181.                      last_protection & VM_PROT_EXECUTE,
  2182.                      1, /* MODIFIED is unknown, pass it as true.  */
  2183.                      data);
  2184.           last_region_address = region_address;
  2185.           last_region_end = region_address += region_length;
  2186.           last_protection = protection;
  2187.         }
  2188.     }

  2189.   /* Report the final region.  */
  2190.   if (last_region_end > last_region_address && last_protection != VM_PROT_NONE)
  2191.     (*func) (last_region_address, last_region_end - last_region_address,
  2192.              last_protection & VM_PROT_READ,
  2193.              last_protection & VM_PROT_WRITE,
  2194.              last_protection & VM_PROT_EXECUTE,
  2195.              1, /* MODIFIED is unknown, pass it as true.  */
  2196.              data);

  2197.   return 0;
  2198. }


  2199. /* Return printable description of proc.  */
  2200. char *
  2201. proc_string (struct proc *proc)
  2202. {
  2203.   static char tid_str[80];

  2204.   if (proc_is_task (proc))
  2205.     xsnprintf (tid_str, sizeof (tid_str), "process %d", proc->inf->pid);
  2206.   else
  2207.     xsnprintf (tid_str, sizeof (tid_str), "Thread %d.%d",
  2208.                proc->inf->pid, proc->tid);
  2209.   return tid_str;
  2210. }

  2211. static char *
  2212. gnu_pid_to_str (struct target_ops *ops, ptid_t ptid)
  2213. {
  2214.   struct inf *inf = gnu_current_inf;
  2215.   int tid = ptid_get_lwp (ptid);
  2216.   struct proc *thread = inf_tid_to_thread (inf, tid);

  2217.   if (thread)
  2218.     return proc_string (thread);
  2219.   else
  2220.     {
  2221.       static char tid_str[80];

  2222.       xsnprintf (tid_str, sizeof (tid_str), "bogus thread id %d", tid);
  2223.       return tid_str;
  2224.     }
  2225. }


  2226. /* Create a prototype generic GNU/Hurd target.  The client can
  2227.    override it with local methods.  */

  2228. struct target_ops *
  2229. gnu_target (void)
  2230. {
  2231.   struct target_ops *t = inf_child_target ();

  2232.   t->to_attach = gnu_attach;
  2233.   t->to_attach_no_wait = 1;
  2234.   t->to_detach = gnu_detach;
  2235.   t->to_resume = gnu_resume;
  2236.   t->to_wait = gnu_wait;
  2237.   t->to_xfer_partial = gnu_xfer_partial;
  2238.   t->to_find_memory_regions = gnu_find_memory_regions;
  2239.   t->to_terminal_init = gnu_terminal_init;
  2240.   t->to_kill = gnu_kill_inferior;
  2241.   t->to_create_inferior = gnu_create_inferior;
  2242.   t->to_mourn_inferior = gnu_mourn_inferior;
  2243.   t->to_thread_alive = gnu_thread_alive;
  2244.   t->to_pid_to_str = gnu_pid_to_str;
  2245.   t->to_stop = gnu_stop;

  2246.   return t;
  2247. }


  2248. /* User task commands.  */

  2249. static struct cmd_list_element *set_task_cmd_list = 0;
  2250. static struct cmd_list_element *show_task_cmd_list = 0;
  2251. /* User thread commands.  */

  2252. /* Commands with a prefix of `set/show thread'.  */
  2253. extern struct cmd_list_element *thread_cmd_list;
  2254. struct cmd_list_element *set_thread_cmd_list = NULL;
  2255. struct cmd_list_element *show_thread_cmd_list = NULL;

  2256. /* Commands with a prefix of `set/show thread default'.  */
  2257. struct cmd_list_element *set_thread_default_cmd_list = NULL;
  2258. struct cmd_list_element *show_thread_default_cmd_list = NULL;

  2259. static void
  2260. set_thread_cmd (char *args, int from_tty)
  2261. {
  2262.   printf_unfiltered ("\"set thread\" must be followed by the "
  2263.                      "name of a thread property, or \"default\".\n");
  2264. }

  2265. static void
  2266. show_thread_cmd (char *args, int from_tty)
  2267. {
  2268.   printf_unfiltered ("\"show thread\" must be followed by the "
  2269.                      "name of a thread property, or \"default\".\n");
  2270. }

  2271. static void
  2272. set_thread_default_cmd (char *args, int from_tty)
  2273. {
  2274.   printf_unfiltered ("\"set thread default\" must be followed "
  2275.                      "by the name of a thread property.\n");
  2276. }

  2277. static void
  2278. show_thread_default_cmd (char *args, int from_tty)
  2279. {
  2280.   printf_unfiltered ("\"show thread default\" must be followed "
  2281.                      "by the name of a thread property.\n");
  2282. }

  2283. static int
  2284. parse_int_arg (char *args, char *cmd_prefix)
  2285. {
  2286.   if (args)
  2287.     {
  2288.       char *arg_end;
  2289.       int val = strtoul (args, &arg_end, 10);

  2290.       if (*args && *arg_end == '\0')
  2291.         return val;
  2292.     }
  2293.   error (_("Illegal argument for \"%s\" command, should be an integer."),
  2294.          cmd_prefix);
  2295. }

  2296. static int
  2297. _parse_bool_arg (char *args, char *t_val, char *f_val, char *cmd_prefix)
  2298. {
  2299.   if (!args || strcmp (args, t_val) == 0)
  2300.     return 1;
  2301.   else if (strcmp (args, f_val) == 0)
  2302.     return 0;
  2303.   else
  2304.     error (_("Illegal argument for \"%s\" command, "
  2305.              "should be \"%s\" or \"%s\"."),
  2306.            cmd_prefix, t_val, f_val);
  2307. }

  2308. #define parse_bool_arg(args, cmd_prefix) \
  2309.   _parse_bool_arg (args, "on", "off", cmd_prefix)

  2310. static void
  2311. check_empty (char *args, char *cmd_prefix)
  2312. {
  2313.   if (args)
  2314.     error (_("Garbage after \"%s\" command: `%s'"), cmd_prefix, args);
  2315. }

  2316. /* Returns the alive thread named by INFERIOR_PID, or signals an error.  */
  2317. static struct proc *
  2318. cur_thread (void)
  2319. {
  2320.   struct inf *inf = cur_inf ();
  2321.   struct proc *thread = inf_tid_to_thread (inf,
  2322.                                            ptid_get_lwp (inferior_ptid));
  2323.   if (!thread)
  2324.     error (_("No current thread."));
  2325.   return thread;
  2326. }

  2327. /* Returns the current inferior, but signals an error if it has no task.  */
  2328. static struct inf *
  2329. active_inf (void)
  2330. {
  2331.   struct inf *inf = cur_inf ();

  2332.   if (!inf->task)
  2333.     error (_("No current process."));
  2334.   return inf;
  2335. }


  2336. static void
  2337. set_task_pause_cmd (char *args, int from_tty)
  2338. {
  2339.   struct inf *inf = cur_inf ();
  2340.   int old_sc = inf->pause_sc;

  2341.   inf->pause_sc = parse_bool_arg (args, "set task pause");

  2342.   if (old_sc == 0 && inf->pause_sc != 0)
  2343.     /* If the task is currently unsuspended, immediately suspend it,
  2344.        otherwise wait until the next time it gets control.  */
  2345.     inf_suspend (inf);
  2346. }

  2347. static void
  2348. show_task_pause_cmd (char *args, int from_tty)
  2349. {
  2350.   struct inf *inf = cur_inf ();

  2351.   check_empty (args, "show task pause");
  2352.   printf_unfiltered ("The inferior task %s suspended while gdb has control.\n",
  2353.                      inf->task
  2354.                      ? (inf->pause_sc == 0 ? "isn't" : "is")
  2355.                      : (inf->pause_sc == 0 ? "won't be" : "will be"));
  2356. }

  2357. static void
  2358. set_task_detach_sc_cmd (char *args, int from_tty)
  2359. {
  2360.   cur_inf ()->detach_sc = parse_int_arg (args,
  2361.                                          "set task detach-suspend-count");
  2362. }

  2363. static void
  2364. show_task_detach_sc_cmd (char *args, int from_tty)
  2365. {
  2366.   check_empty (args, "show task detach-suspend-count");
  2367.   printf_unfiltered ("The inferior task will be left with a "
  2368.                      "suspend count of %d when detaching.\n",
  2369.                      cur_inf ()->detach_sc);
  2370. }


  2371. static void
  2372. set_thread_default_pause_cmd (char *args, int from_tty)
  2373. {
  2374.   struct inf *inf = cur_inf ();

  2375.   inf->default_thread_pause_sc =
  2376.     parse_bool_arg (args, "set thread default pause") ? 0 : 1;
  2377. }

  2378. static void
  2379. show_thread_default_pause_cmd (char *args, int from_tty)
  2380. {
  2381.   struct inf *inf = cur_inf ();
  2382.   int sc = inf->default_thread_pause_sc;

  2383.   check_empty (args, "show thread default pause");
  2384.   printf_unfiltered ("New threads %s suspended while gdb has control%s.\n",
  2385.                      sc ? "are" : "aren't",
  2386.                      !sc && inf->pause_sc ? " (but the task is)" : "");
  2387. }

  2388. static void
  2389. set_thread_default_run_cmd (char *args, int from_tty)
  2390. {
  2391.   struct inf *inf = cur_inf ();

  2392.   inf->default_thread_run_sc =
  2393.     parse_bool_arg (args, "set thread default run") ? 0 : 1;
  2394. }

  2395. static void
  2396. show_thread_default_run_cmd (char *args, int from_tty)
  2397. {
  2398.   struct inf *inf = cur_inf ();

  2399.   check_empty (args, "show thread default run");
  2400.   printf_unfiltered ("New threads %s allowed to run.\n",
  2401.                      inf->default_thread_run_sc == 0 ? "are" : "aren't");
  2402. }

  2403. static void
  2404. set_thread_default_detach_sc_cmd (char *args, int from_tty)
  2405. {
  2406.   cur_inf ()->default_thread_detach_sc =
  2407.     parse_int_arg (args, "set thread default detach-suspend-count");
  2408. }

  2409. static void
  2410. show_thread_default_detach_sc_cmd (char *args, int from_tty)
  2411. {
  2412.   check_empty (args, "show thread default detach-suspend-count");
  2413.   printf_unfiltered ("New threads will get a detach-suspend-count of %d.\n",
  2414.                      cur_inf ()->default_thread_detach_sc);
  2415. }


  2416. /* Steal a send right called NAME in the inferior task, and make it PROC's
  2417.    saved exception port.  */
  2418. static void
  2419. steal_exc_port (struct proc *proc, mach_port_t name)
  2420. {
  2421.   error_t err;
  2422.   mach_port_t port;
  2423.   mach_msg_type_name_t port_type;

  2424.   if (!proc || !proc->inf->task)
  2425.     error (_("No inferior task."));

  2426.   err = mach_port_extract_right (proc->inf->task->port,
  2427.                                  name, MACH_MSG_TYPE_COPY_SEND,
  2428.                                  &port, &port_type);
  2429.   if (err)
  2430.     error (_("Couldn't extract send right %lu from inferior: %s"),
  2431.            name, safe_strerror (err));

  2432.   if (proc->saved_exc_port)
  2433.     /* Get rid of our reference to the old one.  */
  2434.     mach_port_deallocate (mach_task_self (), proc->saved_exc_port);

  2435.   proc->saved_exc_port = port;

  2436.   if (!proc->exc_port)
  2437.     /* If PROC is a thread, we may not have set its exception port
  2438.        before.  We can't use proc_steal_exc_port because it also sets
  2439.        saved_exc_port.  */
  2440.     {
  2441.       proc->exc_port = proc->inf->event_port;
  2442.       err = proc_set_exception_port (proc, proc->exc_port);
  2443.       error (_("Can't set exception port for %s: %s"),
  2444.              proc_string (proc), safe_strerror (err));
  2445.     }
  2446. }

  2447. static void
  2448. set_task_exc_port_cmd (char *args, int from_tty)
  2449. {
  2450.   struct inf *inf = cur_inf ();

  2451.   if (!args)
  2452.     error (_("No argument to \"set task exception-port\" command."));
  2453.   steal_exc_port (inf->task, parse_and_eval_address (args));
  2454. }

  2455. static void
  2456. set_stopped_cmd (char *args, int from_tty)
  2457. {
  2458.   cur_inf ()->stopped = _parse_bool_arg (args, "yes", "no", "set stopped");
  2459. }

  2460. static void
  2461. show_stopped_cmd (char *args, int from_tty)
  2462. {
  2463.   struct inf *inf = active_inf ();

  2464.   check_empty (args, "show stopped");
  2465.   printf_unfiltered ("The inferior process %s stopped.\n",
  2466.                      inf->stopped ? "is" : "isn't");
  2467. }

  2468. static void
  2469. set_sig_thread_cmd (char *args, int from_tty)
  2470. {
  2471.   struct inf *inf = cur_inf ();

  2472.   if (!args || (!isdigit (*args) && strcmp (args, "none") != 0))
  2473.     error (_("Illegal argument to \"set signal-thread\" command.\n"
  2474.            "Should be an integer thread ID, or `none'."));

  2475.   if (strcmp (args, "none") == 0)
  2476.     inf->signal_thread = 0;
  2477.   else
  2478.     {
  2479.       ptid_t ptid = thread_id_to_pid (atoi (args));

  2480.       if (ptid_equal (ptid, minus_one_ptid))
  2481.         error (_("Thread ID %s not known.  "
  2482.                  "Use the \"info threads\" command to\n"
  2483.                "see the IDs of currently known threads."), args);
  2484.       inf->signal_thread = inf_tid_to_thread (inf, ptid_get_lwp (ptid));
  2485.     }
  2486. }

  2487. static void
  2488. show_sig_thread_cmd (char *args, int from_tty)
  2489. {
  2490.   struct inf *inf = active_inf ();

  2491.   check_empty (args, "show signal-thread");
  2492.   if (inf->signal_thread)
  2493.     printf_unfiltered ("The signal thread is %s.\n",
  2494.                        proc_string (inf->signal_thread));
  2495.   else
  2496.     printf_unfiltered ("There is no signal thread.\n");
  2497. }


  2498. static void
  2499. set_signals_cmd (char *args, int from_tty)
  2500. {
  2501.   struct inf *inf = cur_inf ();

  2502.   inf->want_signals = parse_bool_arg (args, "set signals");

  2503.   if (inf->task && inf->want_signals != inf->traced)
  2504.     /* Make this take effect immediately in a running process.  */
  2505.     inf_set_traced (inf, inf->want_signals);
  2506. }

  2507. static void
  2508. show_signals_cmd (char *args, int from_tty)
  2509. {
  2510.   struct inf *inf = cur_inf ();

  2511.   check_empty (args, "show signals");
  2512.   printf_unfiltered ("The inferior process's signals %s intercepted.\n",
  2513.                      inf->task
  2514.                      ? (inf->traced ? "are" : "aren't")
  2515.                      : (inf->want_signals ? "will be" : "won't be"));
  2516. }

  2517. static void
  2518. set_exceptions_cmd (char *args, int from_tty)
  2519. {
  2520.   struct inf *inf = cur_inf ();
  2521.   int val = parse_bool_arg (args, "set exceptions");

  2522.   /* Make this take effect immediately in a running process.  */
  2523.   /* XXX */ ;

  2524.   inf->want_exceptions = val;
  2525. }

  2526. static void
  2527. show_exceptions_cmd (char *args, int from_tty)
  2528. {
  2529.   struct inf *inf = cur_inf ();

  2530.   check_empty (args, "show exceptions");
  2531.   printf_unfiltered ("Exceptions in the inferior %s trapped.\n",
  2532.                      inf->task
  2533.                      ? (inf->want_exceptions ? "are" : "aren't")
  2534.                      : (inf->want_exceptions ? "will be" : "won't be"));
  2535. }


  2536. static void
  2537. set_task_cmd (char *args, int from_tty)
  2538. {
  2539.   printf_unfiltered ("\"set task\" must be followed by the name"
  2540.                      " of a task property.\n");
  2541. }

  2542. static void
  2543. show_task_cmd (char *args, int from_tty)
  2544. {
  2545.   struct inf *inf = cur_inf ();

  2546.   check_empty (args, "show task");

  2547.   show_signals_cmd (0, from_tty);
  2548.   show_exceptions_cmd (0, from_tty);
  2549.   show_task_pause_cmd (0, from_tty);

  2550.   if (inf->pause_sc == 0)
  2551.     show_thread_default_pause_cmd (0, from_tty);
  2552.   show_thread_default_run_cmd (0, from_tty);

  2553.   if (inf->task)
  2554.     {
  2555.       show_stopped_cmd (0, from_tty);
  2556.       show_sig_thread_cmd (0, from_tty);
  2557.     }

  2558.   if (inf->detach_sc != 0)
  2559.     show_task_detach_sc_cmd (0, from_tty);
  2560.   if (inf->default_thread_detach_sc != 0)
  2561.     show_thread_default_detach_sc_cmd (0, from_tty);
  2562. }


  2563. static void
  2564. set_noninvasive_cmd (char *args, int from_tty)
  2565. {
  2566.   /* Invert the sense of the arg for each component.  */
  2567.   char *inv_args = parse_bool_arg (args, "set noninvasive") ? "off" : "on";

  2568.   set_task_pause_cmd (inv_args, from_tty);
  2569.   set_signals_cmd (inv_args, from_tty);
  2570.   set_exceptions_cmd (inv_args, from_tty);
  2571. }


  2572. static void
  2573. info_port_rights (const char *args, mach_port_type_t only)
  2574. {
  2575.   struct inf *inf = active_inf ();
  2576.   struct value *vmark = value_mark ();

  2577.   if (args)
  2578.     /* Explicit list of port rights.  */
  2579.     {
  2580.       while (*args)
  2581.         {
  2582.           struct value *val = parse_to_comma_and_eval (&args);
  2583.           long right = value_as_long (val);
  2584.           error_t err =
  2585.             print_port_info (right, 0, inf->task->port, PORTINFO_DETAILS,
  2586.                              stdout);

  2587.           if (err)
  2588.             error (_("%ld: %s."), right, safe_strerror (err));
  2589.         }
  2590.     }
  2591.   else
  2592.     /* Print all of them.  */
  2593.     {
  2594.       error_t err =
  2595.         print_task_ports_info (inf->task->port, only, PORTINFO_DETAILS,
  2596.                                stdout);
  2597.       if (err)
  2598.         error (_("%s."), safe_strerror (err));
  2599.     }

  2600.   value_free_to_mark (vmark);
  2601. }

  2602. static void
  2603. info_send_rights_cmd (char *args, int from_tty)
  2604. {
  2605.   info_port_rights (args, MACH_PORT_TYPE_SEND);
  2606. }

  2607. static void
  2608. info_recv_rights_cmd (char *args, int from_tty)
  2609. {
  2610.   info_port_rights (args, MACH_PORT_TYPE_RECEIVE);
  2611. }

  2612. static void
  2613. info_port_sets_cmd (char *args, int from_tty)
  2614. {
  2615.   info_port_rights (args, MACH_PORT_TYPE_PORT_SET);
  2616. }

  2617. static void
  2618. info_dead_names_cmd (char *args, int from_tty)
  2619. {
  2620.   info_port_rights (args, MACH_PORT_TYPE_DEAD_NAME);
  2621. }

  2622. static void
  2623. info_port_rights_cmd (char *args, int from_tty)
  2624. {
  2625.   info_port_rights (args, ~0);
  2626. }


  2627. static void
  2628. add_task_commands (void)
  2629. {
  2630.   add_cmd ("pause", class_run, set_thread_default_pause_cmd, _("\
  2631. Set whether the new threads are suspended while gdb has control.\n\
  2632. This property normally has no effect because the whole task is\n\
  2633. suspended, however, that may be disabled with \"set task pause off\".\n\
  2634. The default value is \"off\"."),
  2635.            &set_thread_default_cmd_list);
  2636.   add_cmd ("pause", no_class, show_thread_default_pause_cmd, _("\
  2637. Show whether new threads are suspended while gdb has control."),
  2638.            &show_thread_default_cmd_list);

  2639.   add_cmd ("run", class_run, set_thread_default_run_cmd, _("\
  2640. Set whether new threads are allowed to run (once gdb has noticed them)."),
  2641.            &set_thread_default_cmd_list);
  2642.   add_cmd ("run", no_class, show_thread_default_run_cmd, _("\
  2643. Show whether new threads are allowed to run (once gdb has noticed them)."),
  2644.            &show_thread_default_cmd_list);

  2645.   add_cmd ("detach-suspend-count", class_run, set_thread_default_detach_sc_cmd,
  2646.            _("Set the default detach-suspend-count value for new threads."),
  2647.            &set_thread_default_cmd_list);
  2648.   add_cmd ("detach-suspend-count", no_class, show_thread_default_detach_sc_cmd,
  2649.            _("Show the default detach-suspend-count value for new threads."),
  2650.            &show_thread_default_cmd_list);

  2651.   add_cmd ("signals", class_run, set_signals_cmd, _("\
  2652. Set whether the inferior process's signals will be intercepted.\n\
  2653. Mach exceptions (such as breakpoint traps) are not affected."),
  2654.            &setlist);
  2655.   add_alias_cmd ("sigs", "signals", class_run, 1, &setlist);
  2656.   add_cmd ("signals", no_class, show_signals_cmd, _("\
  2657. Show whether the inferior process's signals will be intercepted."),
  2658.            &showlist);
  2659.   add_alias_cmd ("sigs", "signals", no_class, 1, &showlist);

  2660.   add_cmd ("signal-thread", class_run, set_sig_thread_cmd, _("\
  2661. Set the thread that gdb thinks is the libc signal thread.\n\
  2662. This thread is run when delivering a signal to a non-stopped process."),
  2663.            &setlist);
  2664.   add_alias_cmd ("sigthread", "signal-thread", class_run, 1, &setlist);
  2665.   add_cmd ("signal-thread", no_class, show_sig_thread_cmd, _("\
  2666. Set the thread that gdb thinks is the libc signal thread."),
  2667.            &showlist);
  2668.   add_alias_cmd ("sigthread", "signal-thread", no_class, 1, &showlist);

  2669.   add_cmd ("stopped", class_run, set_stopped_cmd, _("\
  2670. Set whether gdb thinks the inferior process is stopped as with SIGSTOP.\n\
  2671. Stopped process will be continued by sending them a signal."),
  2672.            &setlist);
  2673.   add_cmd ("stopped", no_class, show_stopped_cmd, _("\
  2674. Show whether gdb thinks the inferior process is stopped as with SIGSTOP."),
  2675.            &showlist);

  2676.   add_cmd ("exceptions", class_run, set_exceptions_cmd, _("\
  2677. Set whether exceptions in the inferior process will be trapped.\n\
  2678. When exceptions are turned off, neither breakpoints nor single-stepping\n\
  2679. will work."),
  2680.            &setlist);
  2681.   /* Allow `set exc' despite conflict with `set exception-port'.  */
  2682.   add_alias_cmd ("exc", "exceptions", class_run, 1, &setlist);
  2683.   add_cmd ("exceptions", no_class, show_exceptions_cmd, _("\
  2684. Show whether exceptions in the inferior process will be trapped."),
  2685.            &showlist);

  2686.   add_prefix_cmd ("task", no_class, set_task_cmd,
  2687.                   _("Command prefix for setting task attributes."),
  2688.                   &set_task_cmd_list, "set task ", 0, &setlist);
  2689.   add_prefix_cmd ("task", no_class, show_task_cmd,
  2690.                   _("Command prefix for showing task attributes."),
  2691.                   &show_task_cmd_list, "show task ", 0, &showlist);

  2692.   add_cmd ("pause", class_run, set_task_pause_cmd, _("\
  2693. Set whether the task is suspended while gdb has control.\n\
  2694. A value of \"on\" takes effect immediately, otherwise nothing happens\n\
  2695. until the next time the program is continued.\n\
  2696. When setting this to \"off\", \"set thread default pause on\" can be\n\
  2697. used to pause individual threads by default instead."),
  2698.            &set_task_cmd_list);
  2699.   add_cmd ("pause", no_class, show_task_pause_cmd,
  2700.            _("Show whether the task is suspended while gdb has control."),
  2701.            &show_task_cmd_list);

  2702.   add_cmd ("detach-suspend-count", class_run, set_task_detach_sc_cmd,
  2703.            _("Set the suspend count will leave on the thread when detaching."),
  2704.            &set_task_cmd_list);
  2705.   add_cmd ("detach-suspend-count", no_class, show_task_detach_sc_cmd,
  2706.            _("Show the suspend count will leave "
  2707.              "on the thread when detaching."),
  2708.            &show_task_cmd_list);

  2709.   add_cmd ("exception-port", no_class, set_task_exc_port_cmd, _("\
  2710. Set the task exception port to which we forward exceptions.\n\
  2711. The argument should be the value of the send right in the task."),
  2712.            &set_task_cmd_list);
  2713.   add_alias_cmd ("excp", "exception-port", no_class, 1, &set_task_cmd_list);
  2714.   add_alias_cmd ("exc-port", "exception-port", no_class, 1,
  2715.                  &set_task_cmd_list);

  2716.   /* A convenient way of turning on all options require to noninvasively
  2717.      debug running tasks.  */
  2718.   add_cmd ("noninvasive", no_class, set_noninvasive_cmd, _("\
  2719. Set task options so that we interfere as little as possible.\n\
  2720. This is the same as setting `task pause', `exceptions', and\n\
  2721. `signals' to the opposite value."),
  2722.            &setlist);

  2723.   /* Commands to show information about the task's ports.  */
  2724.   add_cmd ("send-rights", class_info, info_send_rights_cmd,
  2725.            _("Show information about the task's send rights"),
  2726.            &infolist);
  2727.   add_cmd ("receive-rights", class_info, info_recv_rights_cmd,
  2728.            _("Show information about the task's receive rights"),
  2729.            &infolist);
  2730.   add_cmd ("port-rights", class_info, info_port_rights_cmd,
  2731.            _("Show information about the task's port rights"),
  2732.            &infolist);
  2733.   add_cmd ("port-sets", class_info, info_port_sets_cmd,
  2734.            _("Show information about the task's port sets"),
  2735.            &infolist);
  2736.   add_cmd ("dead-names", class_info, info_dead_names_cmd,
  2737.            _("Show information about the task's dead names"),
  2738.            &infolist);
  2739.   add_info_alias ("ports", "port-rights", 1);
  2740.   add_info_alias ("port", "port-rights", 1);
  2741.   add_info_alias ("psets", "port-sets", 1);
  2742. }


  2743. static void
  2744. set_thread_pause_cmd (char *args, int from_tty)
  2745. {
  2746.   struct proc *thread = cur_thread ();
  2747.   int old_sc = thread->pause_sc;

  2748.   thread->pause_sc = parse_bool_arg (args, "set thread pause");
  2749.   if (old_sc == 0 && thread->pause_sc != 0 && thread->inf->pause_sc == 0)
  2750.     /* If the task is currently unsuspended, immediately suspend it,
  2751.        otherwise wait until the next time it gets control.  */
  2752.     inf_suspend (thread->inf);
  2753. }

  2754. static void
  2755. show_thread_pause_cmd (char *args, int from_tty)
  2756. {
  2757.   struct proc *thread = cur_thread ();
  2758.   int sc = thread->pause_sc;

  2759.   check_empty (args, "show task pause");
  2760.   printf_unfiltered ("Thread %s %s suspended while gdb has control%s.\n",
  2761.                      proc_string (thread),
  2762.                      sc ? "is" : "isn't",
  2763.                      !sc && thread->inf->pause_sc ? " (but the task is)" : "");
  2764. }

  2765. static void
  2766. set_thread_run_cmd (char *args, int from_tty)
  2767. {
  2768.   struct proc *thread = cur_thread ();

  2769.   thread->run_sc = parse_bool_arg (args, "set thread run") ? 0 : 1;
  2770. }

  2771. static void
  2772. show_thread_run_cmd (char *args, int from_tty)
  2773. {
  2774.   struct proc *thread = cur_thread ();

  2775.   check_empty (args, "show thread run");
  2776.   printf_unfiltered ("Thread %s %s allowed to run.",
  2777.                      proc_string (thread),
  2778.                      thread->run_sc == 0 ? "is" : "isn't");
  2779. }

  2780. static void
  2781. set_thread_detach_sc_cmd (char *args, int from_tty)
  2782. {
  2783.   cur_thread ()->detach_sc = parse_int_arg (args,
  2784.                                             "set thread detach-suspend-count");
  2785. }

  2786. static void
  2787. show_thread_detach_sc_cmd (char *args, int from_tty)
  2788. {
  2789.   struct proc *thread = cur_thread ();

  2790.   check_empty (args, "show thread detach-suspend-count");
  2791.   printf_unfiltered ("Thread %s will be left with a suspend count"
  2792.                      " of %d when detaching.\n",
  2793.                      proc_string (thread),
  2794.                      thread->detach_sc);
  2795. }

  2796. static void
  2797. set_thread_exc_port_cmd (char *args, int from_tty)
  2798. {
  2799.   struct proc *thread = cur_thread ();

  2800.   if (!args)
  2801.     error (_("No argument to \"set thread exception-port\" command."));
  2802.   steal_exc_port (thread, parse_and_eval_address (args));
  2803. }

  2804. #if 0
  2805. static void
  2806. show_thread_cmd (char *args, int from_tty)
  2807. {
  2808.   struct proc *thread = cur_thread ();

  2809.   check_empty (args, "show thread");
  2810.   show_thread_run_cmd (0, from_tty);
  2811.   show_thread_pause_cmd (0, from_tty);
  2812.   if (thread->detach_sc != 0)
  2813.     show_thread_detach_sc_cmd (0, from_tty);
  2814. }
  2815. #endif

  2816. static void
  2817. thread_takeover_sc_cmd (char *args, int from_tty)
  2818. {
  2819.   struct proc *thread = cur_thread ();

  2820.   thread_basic_info_data_t _info;
  2821.   thread_basic_info_t info = &_info;
  2822.   mach_msg_type_number_t info_len = THREAD_BASIC_INFO_COUNT;
  2823.   error_t err =
  2824.   thread_info (thread->port, THREAD_BASIC_INFO, (int *) &info, &info_len);
  2825.   if (err)
  2826.     error (("%s."), safe_strerror (err));
  2827.   thread->sc = info->suspend_count;
  2828.   if (from_tty)
  2829.     printf_unfiltered ("Suspend count was %d.\n", thread->sc);
  2830.   if (info != &_info)
  2831.     vm_deallocate (mach_task_self (), (vm_address_t) info,
  2832.                    info_len * sizeof (int));
  2833. }


  2834. static void
  2835. add_thread_commands (void)
  2836. {
  2837.   add_prefix_cmd ("thread", no_class, set_thread_cmd,
  2838.                   _("Command prefix for setting thread properties."),
  2839.                   &set_thread_cmd_list, "set thread ", 0, &setlist);
  2840.   add_prefix_cmd ("default", no_class, show_thread_cmd,
  2841.                   _("Command prefix for setting default thread properties."),
  2842.                   &set_thread_default_cmd_list, "set thread default ", 0,
  2843.                   &set_thread_cmd_list);
  2844.   add_prefix_cmd ("thread", no_class, set_thread_default_cmd,
  2845.                   _("Command prefix for showing thread properties."),
  2846.                   &show_thread_cmd_list, "show thread ", 0, &showlist);
  2847.   add_prefix_cmd ("default", no_class, show_thread_default_cmd,
  2848.                   _("Command prefix for showing default thread properties."),
  2849.                   &show_thread_default_cmd_list, "show thread default ", 0,
  2850.                   &show_thread_cmd_list);

  2851.   add_cmd ("pause", class_run, set_thread_pause_cmd, _("\
  2852. Set whether the current thread is suspended while gdb has control.\n\
  2853. A value of \"on\" takes effect immediately, otherwise nothing happens\n\
  2854. until the next time the program is continued.  This property normally\n\
  2855. has no effect because the whole task is suspended, however, that may\n\
  2856. be disabled with \"set task pause off\".\n\
  2857. The default value is \"off\"."),
  2858.            &set_thread_cmd_list);
  2859.   add_cmd ("pause", no_class, show_thread_pause_cmd, _("\
  2860. Show whether the current thread is suspended while gdb has control."),
  2861.            &show_thread_cmd_list);

  2862.   add_cmd ("run", class_run, set_thread_run_cmd,
  2863.            _("Set whether the current thread is allowed to run."),
  2864.            &set_thread_cmd_list);
  2865.   add_cmd ("run", no_class, show_thread_run_cmd,
  2866.            _("Show whether the current thread is allowed to run."),
  2867.            &show_thread_cmd_list);

  2868.   add_cmd ("detach-suspend-count", class_run, set_thread_detach_sc_cmd, _("\
  2869. Set the suspend count will leave on the thread when detaching.\n\
  2870. Note that this is relative to suspend count when gdb noticed the thread;\n\
  2871. use the `thread takeover-suspend-count' to force it to an absolute value."),
  2872.            &set_thread_cmd_list);
  2873.   add_cmd ("detach-suspend-count", no_class, show_thread_detach_sc_cmd, _("\
  2874. Show the suspend count will leave on the thread when detaching.\n\
  2875. Note that this is relative to suspend count when gdb noticed the thread;\n\
  2876. use the `thread takeover-suspend-count' to force it to an absolute value."),
  2877.            &show_thread_cmd_list);

  2878.   add_cmd ("exception-port", no_class, set_thread_exc_port_cmd, _("\
  2879. Set the thread exception port to which we forward exceptions.\n\
  2880. This overrides the task exception port.\n\
  2881. The argument should be the value of the send right in the task."),
  2882.            &set_thread_cmd_list);
  2883.   add_alias_cmd ("excp", "exception-port", no_class, 1, &set_thread_cmd_list);
  2884.   add_alias_cmd ("exc-port", "exception-port", no_class, 1,
  2885.                  &set_thread_cmd_list);

  2886.   add_cmd ("takeover-suspend-count", no_class, thread_takeover_sc_cmd, _("\
  2887. Force the threads absolute suspend-count to be gdb's.\n\
  2888. Prior to giving this command, gdb's thread suspend-counts are relative\n\
  2889. to the thread's initial suspend-count when gdb notices the threads."),
  2890.            &thread_cmd_list);
  2891. }



  2892. /* -Wmissing-prototypes */
  2893. extern initialize_file_ftype _initialize_gnu_nat;

  2894. void
  2895. _initialize_gnu_nat (void)
  2896. {
  2897.   proc_server = getproc ();

  2898.   add_task_commands ();
  2899.   add_thread_commands ();
  2900.   add_setshow_boolean_cmd ("gnu-nat", class_maintenance,
  2901.                            &gnu_debug_flag,
  2902.                            _("Set debugging output for the gnu backend."),
  2903.                            _("Show debugging output for the gnu backend."),
  2904.                            NULL,
  2905.                            NULL,
  2906.                            NULL,
  2907.                            &setdebuglist,
  2908.                            &showdebuglist);
  2909. }

  2910. #ifdef        FLUSH_INFERIOR_CACHE

  2911. /* When over-writing code on some machines the I-Cache must be flushed
  2912.    explicitly, because it is not kept coherent by the lazy hardware.
  2913.    This definitely includes breakpoints, for instance, or else we
  2914.    end up looping in mysterious Bpt traps.  */

  2915. void
  2916. flush_inferior_icache (CORE_ADDR pc, int amount)
  2917. {
  2918.   vm_machine_attribute_val_t flush = MATTR_VAL_ICACHE_FLUSH;
  2919.   error_t ret;

  2920.   ret = vm_machine_attribute (gnu_current_inf->task->port,
  2921.                               pc,
  2922.                               amount,
  2923.                               MATTR_CACHE,
  2924.                               &flush);
  2925.   if (ret != KERN_SUCCESS)
  2926.     warning (_("Error flushing inferior's cache : %s"), safe_strerror (ret));
  2927. }
  2928. #endif /* FLUSH_INFERIOR_CACHE */