gdb/darwin-nat.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Darwin support for GDB, the GNU debugger.
  2.    Copyright (C) 2008-2015 Free Software Foundation, Inc.

  3.    Contributed by AdaCore.

  4.    This file is part of GDB.

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

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

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

  15. #include "defs.h"
  16. #include "top.h"
  17. #include "inferior.h"
  18. #include "target.h"
  19. #include "symfile.h"
  20. #include "symtab.h"
  21. #include "objfiles.h"
  22. #include "gdb.h"
  23. #include "gdbcmd.h"
  24. #include "gdbcore.h"
  25. #include "gdbthread.h"
  26. #include "regcache.h"
  27. #include "event-top.h"
  28. #include "inf-loop.h"
  29. #include <sys/stat.h>
  30. #include "inf-child.h"
  31. #include "value.h"
  32. #include "arch-utils.h"
  33. #include "bfd.h"
  34. #include "bfd/mach-o.h"

  35. #include <sys/ptrace.h>
  36. #include <sys/signal.h>
  37. #include <machine/setjmp.h>
  38. #include <sys/types.h>
  39. #include <unistd.h>
  40. #include <signal.h>
  41. #include <ctype.h>
  42. #include <sys/sysctl.h>
  43. #include <sys/proc.h>
  44. #include <libproc.h>
  45. #include <sys/syscall.h>
  46. #include <spawn.h>

  47. #include <mach/mach_error.h>
  48. #include <mach/mach_vm.h>
  49. #include <mach/mach_init.h>
  50. #include <mach/vm_map.h>
  51. #include <mach/task.h>
  52. #include <mach/mach_port.h>
  53. #include <mach/thread_act.h>
  54. #include <mach/port.h>

  55. #include "darwin-nat.h"
  56. #include "common/filestuff.h"

  57. /* Quick overview.
  58.    Darwin kernel is Mach + BSD derived kernel.  Note that they share the
  59.    same memory space and are linked together (ie there is no micro-kernel).

  60.    Although ptrace(2) is available on Darwin, it is not complete.  We have
  61.    to use Mach calls to read and write memory and to modify registers.  We
  62.    also use Mach to get inferior faults.  As we cannot use select(2) or
  63.    signals with Mach port (the Mach communication channel), signals are
  64.    reported to gdb as an exception.  Furthermore we detect death of the
  65.    inferior through a Mach notification message.  This way we only wait
  66.    on Mach ports.

  67.    Some Mach documentation is available for Apple xnu source package or
  68.    from the web.  */


  69. #define PTRACE(CMD, PID, ADDR, SIG) \
  70. darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))

  71. static void darwin_stop (struct target_ops *self, ptid_t);

  72. static void darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
  73.                               enum gdb_signal signal);
  74. static void darwin_resume (ptid_t ptid, int step,
  75.                            enum gdb_signal signal);

  76. static ptid_t darwin_wait_to (struct target_ops *ops, ptid_t ptid,
  77.                               struct target_waitstatus *status, int options);
  78. static ptid_t darwin_wait (ptid_t ptid, struct target_waitstatus *status);

  79. static void darwin_mourn_inferior (struct target_ops *ops);

  80. static void darwin_kill_inferior (struct target_ops *ops);

  81. static void darwin_ptrace_me (void);

  82. static void darwin_ptrace_him (int pid);

  83. static void darwin_create_inferior (struct target_ops *ops, char *exec_file,
  84.                                     char *allargs, char **env, int from_tty);

  85. static void darwin_files_info (struct target_ops *ops);

  86. static char *darwin_pid_to_str (struct target_ops *ops, ptid_t tpid);

  87. static int darwin_thread_alive (struct target_ops *ops, ptid_t tpid);

  88. static void darwin_encode_reply (mig_reply_error_t *reply,
  89.                                  mach_msg_header_t *hdr, integer_t code);

  90. /* Target operations for Darwin.  */
  91. static struct target_ops *darwin_ops;

  92. /* Task identifier of gdb.  */
  93. static task_t gdb_task;

  94. /* A copy of mach_host_self ().  */
  95. mach_port_t darwin_host_self;

  96. /* Exception port.  */
  97. mach_port_t darwin_ex_port;

  98. /* Port set, to wait for answer on all ports.  */
  99. mach_port_t darwin_port_set;

  100. /* Page size.  */
  101. static vm_size_t mach_page_size;

  102. /* If Set, catch all mach exceptions (before they are converted to signals
  103.    by the kernel).  */
  104. static int enable_mach_exceptions;

  105. /* Inferior that should report a fake stop event.  */
  106. static struct inferior *darwin_inf_fake_stop;

  107. #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
  108. #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)

  109. /* This controls output of inferior debugging.  */
  110. static unsigned int darwin_debug_flag = 0;

  111. /* Create a __TEXT __info_plist section in the executable so that gdb could
  112.    be signed.  This is required to get an authorization for task_for_pid.

  113.    Once gdb is built, you must codesign it with any system-trusted signing
  114.    authority.  See taskgated(8) for details.  */
  115. static const unsigned char info_plist[]
  116. __attribute__ ((section ("__TEXT,__info_plist"),used)) =
  117.   "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  118.   "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
  119.   " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
  120.   "<plist version=\"1.0\">\n"
  121.   "<dict>\n"
  122.   "  <key>CFBundleIdentifier</key>\n"
  123.   "  <string>org.gnu.gdb</string>\n"
  124.   "  <key>CFBundleName</key>\n"
  125.   "  <string>gdb</string>\n"
  126.   "  <key>CFBundleVersion</key>\n"
  127.   "  <string>1.0</string>\n"
  128.   "  <key>SecTaskAccess</key>\n"
  129.   "  <array>\n"
  130.   "    <string>allowed</string>\n"
  131.   "    <string>debug</string>\n"
  132.   "  </array>\n"
  133.   "</dict>\n"
  134.   "</plist>\n";

  135. static void
  136. inferior_debug (int level, const char *fmt, ...)
  137. {
  138.   va_list ap;

  139.   if (darwin_debug_flag < level)
  140.     return;

  141.   va_start (ap, fmt);
  142.   printf_unfiltered (_("[%d inferior]: "), getpid ());
  143.   vprintf_unfiltered (fmt, ap);
  144.   va_end (ap);
  145. }

  146. void
  147. mach_check_error (kern_return_t ret, const char *file,
  148.                   unsigned int line, const char *func)
  149. {
  150.   if (ret == KERN_SUCCESS)
  151.     return;
  152.   if (func == NULL)
  153.     func = _("[UNKNOWN]");

  154.   warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)"),
  155.            file, line, func, mach_error_string (ret), (unsigned long) ret);
  156. }

  157. static const char *
  158. unparse_exception_type (unsigned int i)
  159. {
  160.   static char unknown_exception_buf[32];

  161.   switch (i)
  162.     {
  163.     case EXC_BAD_ACCESS:
  164.       return "EXC_BAD_ACCESS";
  165.     case EXC_BAD_INSTRUCTION:
  166.       return "EXC_BAD_INSTRUCTION";
  167.     case EXC_ARITHMETIC:
  168.       return "EXC_ARITHMETIC";
  169.     case EXC_EMULATION:
  170.       return "EXC_EMULATION";
  171.     case EXC_SOFTWARE:
  172.       return "EXC_SOFTWARE";
  173.     case EXC_BREAKPOINT:
  174.       return "EXC_BREAKPOINT";
  175.     case EXC_SYSCALL:
  176.       return "EXC_SYSCALL";
  177.     case EXC_MACH_SYSCALL:
  178.       return "EXC_MACH_SYSCALL";
  179.     case EXC_RPC_ALERT:
  180.       return "EXC_RPC_ALERT";
  181.     case EXC_CRASH:
  182.       return "EXC_CRASH";
  183.     default:
  184.       snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
  185.       return unknown_exception_buf;
  186.     }
  187. }

  188. /* Set errno to zero, and then call ptrace with the given arguments.
  189.    If inferior debugging traces are on, then also print a debug
  190.    trace.

  191.    The returned value is the same as the value returned by ptrace,
  192.    except in the case where that value is -1 but errno is zero.
  193.    This case is documented to be a non-error situation, so we
  194.    return zero in that case. */

  195. static int
  196. darwin_ptrace (const char *name,
  197.                int request, int pid, PTRACE_TYPE_ARG3 arg3, int arg4)
  198. {
  199.   int ret;

  200.   errno = 0;
  201.   ret = ptrace (request, pid, (caddr_t) arg3, arg4);
  202.   if (ret == -1 && errno == 0)
  203.     ret = 0;

  204.   inferior_debug (4, _("ptrace (%s, %d, 0x%x, %d): %d (%s)\n"),
  205.                   name, pid, arg3, arg4, ret,
  206.                   (ret != 0) ? safe_strerror (errno) : _("no error"));
  207.   return ret;
  208. }

  209. static int
  210. cmp_thread_t (const void *l, const void *r)
  211. {
  212.   thread_t tl = *(const thread_t *)l;
  213.   thread_t tr = *(const thread_t *)r;
  214.   return (int)(tl - tr);
  215. }

  216. static void
  217. darwin_check_new_threads (struct inferior *inf)
  218. {
  219.   kern_return_t kret;
  220.   unsigned int i;
  221.   thread_array_t thread_list;
  222.   unsigned int new_nbr;
  223.   unsigned int old_nbr;
  224.   unsigned int new_ix, old_ix;
  225.   darwin_inferior *darwin_inf = inf->private;
  226.   VEC (darwin_thread_t) *thread_vec;

  227.   /* Get list of threads.  */
  228.   kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
  229.   MACH_CHECK_ERROR (kret);
  230.   if (kret != KERN_SUCCESS)
  231.     return;

  232.   /* Sort the list.  */
  233.   if (new_nbr > 1)
  234.     qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);

  235.   if (darwin_inf->threads)
  236.     old_nbr = VEC_length (darwin_thread_t, darwin_inf->threads);
  237.   else
  238.     old_nbr = 0;

  239.   /* Quick check for no changes.  */
  240.   if (old_nbr == new_nbr)
  241.     {
  242.       for (i = 0; i < new_nbr; i++)
  243.         if (thread_list[i]
  244.             != VEC_index (darwin_thread_t, darwin_inf->threads, i)->gdb_port)
  245.           break;
  246.       if (i == new_nbr)
  247.         {
  248.           /* Deallocate ports.  */
  249.           for (i = 0; i < new_nbr; i++)
  250.             {
  251.               kret = mach_port_deallocate (mach_task_self (), thread_list[i]);
  252.               MACH_CHECK_ERROR (kret);
  253.             }

  254.           /* Deallocate the buffer.  */
  255.           kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
  256.                                 new_nbr * sizeof (int));
  257.           MACH_CHECK_ERROR (kret);

  258.           return;
  259.         }
  260.     }

  261.   thread_vec = VEC_alloc (darwin_thread_t, new_nbr);

  262.   for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
  263.     {
  264.       thread_t new_id = (new_ix < new_nbr) ?
  265.         thread_list[new_ix] : THREAD_NULL;
  266.       darwin_thread_t *old = (old_ix < old_nbr) ?
  267.         VEC_index (darwin_thread_t, darwin_inf->threads, old_ix) : NULL;
  268.       thread_t old_id = old ? old->gdb_port : THREAD_NULL;

  269.       inferior_debug
  270.         (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:0x%x old_id:0x%x\n"),
  271.          new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);

  272.       if (old_id == new_id)
  273.         {
  274.           /* Thread still exist.  */
  275.           VEC_safe_push (darwin_thread_t, thread_vec, old);
  276.           new_ix++;
  277.           old_ix++;

  278.           /* Deallocate the port.  */
  279.           kret = mach_port_deallocate (gdb_task, new_id);
  280.           MACH_CHECK_ERROR (kret);

  281.           continue;
  282.         }
  283.       if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
  284.         {
  285.           /* Ignore dead ports.
  286.              In some weird cases, we might get dead ports.  They should
  287.              correspond to dead thread so they could safely be ignored.  */
  288.           new_ix++;
  289.           continue;
  290.         }
  291.       if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
  292.         {
  293.           /* A thread was created.  */
  294.           struct thread_info *tp;
  295.           struct private_thread_info *pti;

  296.           pti = XCNEW (struct private_thread_info);
  297.           pti->gdb_port = new_id;
  298.           pti->msg_state = DARWIN_RUNNING;

  299.           /* Add a new thread unless this is the first one ever met.  */
  300.           if (!(old_nbr == 0 && new_ix == 0))
  301.             tp = add_thread_with_info (ptid_build (inf->pid, 0, new_id), pti);
  302.           else
  303.             {
  304.               tp = find_thread_ptid (ptid_build (inf->pid, 0, 0));
  305.               gdb_assert (tp);
  306.               tp->private = pti;
  307.             }
  308.           VEC_safe_push (darwin_thread_t, thread_vec, pti);
  309.           new_ix++;
  310.           continue;
  311.         }
  312.       if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
  313.         {
  314.           /* A thread was removed.  */
  315.           delete_thread (ptid_build (inf->pid, 0, old_id));
  316.           kret = mach_port_deallocate (gdb_task, old_id);
  317.           MACH_CHECK_ERROR (kret);
  318.           old_ix++;
  319.           continue;
  320.         }
  321.       gdb_assert_not_reached ("unexpected thread case");
  322.     }

  323.   if (darwin_inf->threads)
  324.     VEC_free (darwin_thread_t, darwin_inf->threads);
  325.   darwin_inf->threads = thread_vec;

  326.   /* Deallocate the buffer.  */
  327.   kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
  328.                         new_nbr * sizeof (int));
  329.   MACH_CHECK_ERROR (kret);
  330. }

  331. static int
  332. find_inferior_task_it (struct inferior *inf, void *port_ptr)
  333. {
  334.   return inf->private->task == *(task_t*)port_ptr;
  335. }

  336. static int
  337. find_inferior_notify_it (struct inferior *inf, void *port_ptr)
  338. {
  339.   return inf->private->notify_port == *(task_t*)port_ptr;
  340. }

  341. /* Return an inferior by task port.  */
  342. static struct inferior *
  343. darwin_find_inferior_by_task (task_t port)
  344. {
  345.   return iterate_over_inferiors (&find_inferior_task_it, &port);
  346. }

  347. /* Return an inferior by notification port.  */
  348. static struct inferior *
  349. darwin_find_inferior_by_notify (mach_port_t port)
  350. {
  351.   return iterate_over_inferiors (&find_inferior_notify_it, &port);
  352. }

  353. /* Return a thread by port.  */
  354. static darwin_thread_t *
  355. darwin_find_thread (struct inferior *inf, thread_t thread)
  356. {
  357.   darwin_thread_t *t;
  358.   int k;

  359.   for (k = 0;
  360.        VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
  361.        k++)
  362.     if (t->gdb_port == thread)
  363.       return t;
  364.   return NULL;
  365. }

  366. /* Suspend (ie stop) an inferior at Mach level.  */

  367. static void
  368. darwin_suspend_inferior (struct inferior *inf)
  369. {
  370.   if (!inf->private->suspended)
  371.     {
  372.       kern_return_t kret;

  373.       kret = task_suspend (inf->private->task);
  374.       MACH_CHECK_ERROR (kret);

  375.       inf->private->suspended = 1;
  376.     }
  377. }

  378. /* Resume an inferior at Mach level.  */

  379. static void
  380. darwin_resume_inferior (struct inferior *inf)
  381. {
  382.   if (inf->private->suspended)
  383.     {
  384.       kern_return_t kret;

  385.       kret = task_resume (inf->private->task);
  386.       MACH_CHECK_ERROR (kret);

  387.       inf->private->suspended = 0;
  388.     }
  389. }

  390. /* Iterator functions.  */

  391. static int
  392. darwin_suspend_inferior_it (struct inferior *inf, void *arg)
  393. {
  394.   darwin_suspend_inferior (inf);
  395.   darwin_check_new_threads (inf);
  396.   return 0;
  397. }

  398. static int
  399. darwin_resume_inferior_it (struct inferior *inf, void *arg)
  400. {
  401.   darwin_resume_inferior (inf);
  402.   return 0;
  403. }

  404. static void
  405. darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
  406. {
  407.   printf_unfiltered (_("message header:\n"));
  408.   printf_unfiltered (_(" bits: 0x%x\n"), hdr->msgh_bits);
  409.   printf_unfiltered (_(" size: 0x%x\n"), hdr->msgh_size);
  410.   printf_unfiltered (_(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
  411.   printf_unfiltered (_(" local-port: 0x%x\n"), hdr->msgh_local_port);
  412.   printf_unfiltered (_(" reserved: 0x%x\n"), hdr->msgh_reserved);
  413.   printf_unfiltered (_(" id: 0x%x\n"), hdr->msgh_id);

  414.   if (disp_body)
  415.     {
  416.       const unsigned char *data;
  417.       const unsigned int *ldata;
  418.       int size;
  419.       int i;

  420.       data = (unsigned char *)(hdr + 1);
  421.       size = hdr->msgh_size - sizeof (mach_msg_header_t);

  422.       if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
  423.         {
  424.           mach_msg_body_t *bod = (mach_msg_body_t*)data;
  425.           mach_msg_port_descriptor_t *desc =
  426.             (mach_msg_port_descriptor_t *)(bod + 1);
  427.           int k;
  428.           NDR_record_t *ndr;
  429.           printf_unfiltered (_("body: descriptor_count=%u\n"),
  430.                              bod->msgh_descriptor_count);
  431.           data += sizeof (mach_msg_body_t);
  432.           size -= sizeof (mach_msg_body_t);
  433.           for (k = 0; k < bod->msgh_descriptor_count; k++)
  434.             switch (desc[k].type)
  435.               {
  436.               case MACH_MSG_PORT_DESCRIPTOR:
  437.                 printf_unfiltered
  438.                   (_(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
  439.                    k, desc[k].type, desc[k].name, desc[k].disposition);
  440.                 break;
  441.               default:
  442.                 printf_unfiltered (_(" descr %d: type=%u\n"),
  443.                                    k, desc[k].type);
  444.                 break;
  445.               }
  446.           data += bod->msgh_descriptor_count
  447.             * sizeof (mach_msg_port_descriptor_t);
  448.           size -= bod->msgh_descriptor_count
  449.             * sizeof (mach_msg_port_descriptor_t);
  450.           ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
  451.           printf_unfiltered
  452.             (_("NDR: mig=%02x if=%02x encod=%02x "
  453.                "int=%02x char=%02x float=%02x\n"),
  454.              ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
  455.              ndr->int_rep, ndr->char_rep, ndr->float_rep);
  456.           data += sizeof (NDR_record_t);
  457.           size -= sizeof (NDR_record_t);
  458.         }

  459.       printf_unfiltered (_(data:"));
  460.       ldata = (const unsigned int *)data;
  461.       for (i = 0; i < size / sizeof (unsigned int); i++)
  462.         printf_unfiltered (" %08x", ldata[i]);
  463.       printf_unfiltered (_("\n"));
  464.     }
  465. }

  466. static int
  467. darwin_decode_exception_message (mach_msg_header_t *hdr,
  468.                                  struct inferior **pinf,
  469.                                  darwin_thread_t **pthread)
  470. {
  471.   mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
  472.   mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
  473.   NDR_record_t *ndr;
  474.   integer_t *data;
  475.   struct inferior *inf;
  476.   darwin_thread_t *thread;
  477.   task_t task_port;
  478.   thread_t thread_port;
  479.   kern_return_t kret;
  480.   int i;

  481.   /* Check message destination.  */
  482.   if (hdr->msgh_local_port != darwin_ex_port)
  483.     return -1;

  484.   /* Check message header.  */
  485.   if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
  486.     return -1;

  487.   /* Check descriptors.  */
  488.   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
  489.                         + sizeof (*ndr) + 2 * sizeof (integer_t))
  490.       || bod->msgh_descriptor_count != 2
  491.       || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
  492.       || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
  493.       || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
  494.       || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
  495.     return -1;

  496.   /* Check data representation.  */
  497.   ndr = (NDR_record_t *)(desc + 2);
  498.   if (ndr->mig_vers != NDR_PROTOCOL_2_0
  499.       || ndr->if_vers != NDR_PROTOCOL_2_0
  500.       || ndr->mig_encoding != NDR_record.mig_encoding
  501.       || ndr->int_rep != NDR_record.int_rep
  502.       || ndr->char_rep != NDR_record.char_rep
  503.       || ndr->float_rep != NDR_record.float_rep)
  504.     return -1;

  505.   /* Ok, the hard work.  */
  506.   data = (integer_t *)(ndr + 1);

  507.   task_port = desc[1].name;
  508.   thread_port = desc[0].name;

  509.   /* We got new rights to the task, get rid of it.  Do not get rid of thread
  510.      right, as we will need it to find the thread.  */
  511.   kret = mach_port_deallocate (mach_task_self (), task_port);
  512.   MACH_CHECK_ERROR (kret);

  513.   /* Find process by port.  */
  514.   inf = darwin_find_inferior_by_task (task_port);
  515.   *pinf = inf;
  516.   if (inf == NULL)
  517.     {
  518.       /* Not a known inferior.  This could happen if the child fork, as
  519.          the created process will inherit its exception port.
  520.          FIXME: should the exception port be restored ?  */
  521.       kern_return_t kret;
  522.       mig_reply_error_t reply;

  523.       /* Free thread port (we don't know it).  */
  524.       kret = mach_port_deallocate (mach_task_self (), thread_port);
  525.       MACH_CHECK_ERROR (kret);

  526.       darwin_encode_reply (&reply, hdr, KERN_SUCCESS);

  527.       kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
  528.                        reply.Head.msgh_size, 0,
  529.                        MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
  530.                        MACH_PORT_NULL);
  531.       MACH_CHECK_ERROR (kret);

  532.       return 0;
  533.     }

  534.   /* Find thread by port.  */
  535.   /* Check for new threads.  Do it early so that the port in the exception
  536.      message can be deallocated.  */
  537.   darwin_check_new_threads (inf);

  538.   /* Free the thread port (as gdb knows the thread, it has already has a right
  539.      for it, so this just decrement a reference counter).  */
  540.   kret = mach_port_deallocate (mach_task_self (), thread_port);
  541.   MACH_CHECK_ERROR (kret);

  542.   thread = darwin_find_thread (inf, thread_port);
  543.   if (thread == NULL)
  544.     return -1;
  545.   *pthread = thread;

  546.   /* The thread should be running.  However we have observed cases where a
  547.      thread got a SIGTTIN message after being stopped.  */
  548.   gdb_assert (thread->msg_state != DARWIN_MESSAGE);

  549.   /* Finish decoding.  */
  550.   thread->event.header = *hdr;
  551.   thread->event.thread_port = thread_port;
  552.   thread->event.task_port = task_port;
  553.   thread->event.ex_type = data[0];
  554.   thread->event.data_count = data[1];

  555.   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
  556.                         + sizeof (*ndr) + 2 * sizeof (integer_t)
  557.                         + data[1] * sizeof (integer_t)))
  558.       return -1;
  559.   for (i = 0; i < data[1]; i++)
  560.     thread->event.ex_data[i] = data[2 + i];

  561.   thread->msg_state = DARWIN_MESSAGE;

  562.   return 0;
  563. }

  564. static void
  565. darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
  566.                      integer_t code)
  567. {
  568.   mach_msg_header_t *rh = &reply->Head;

  569.   rh->msgh_bits = MACH_MSGH_BITS (MACH_MSGH_BITS_REMOTE (hdr->msgh_bits), 0);
  570.   rh->msgh_remote_port = hdr->msgh_remote_port;
  571.   rh->msgh_size = (mach_msg_size_t) sizeof (mig_reply_error_t);
  572.   rh->msgh_local_port = MACH_PORT_NULL;
  573.   rh->msgh_id = hdr->msgh_id + 100;

  574.   reply->NDR = NDR_record;
  575.   reply->RetCode = code;
  576. }

  577. static void
  578. darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
  579. {
  580.   kern_return_t kret;
  581.   mig_reply_error_t reply;

  582.   darwin_encode_reply (&reply, &thread->event.header, KERN_SUCCESS);

  583.   kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
  584.                    reply.Head.msgh_size, 0,
  585.                    MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
  586.                    MACH_PORT_NULL);
  587.   MACH_CHECK_ERROR (kret);

  588.   inf->private->pending_messages--;
  589. }

  590. static void
  591. darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
  592.                       int step, int nsignal)
  593. {
  594.   kern_return_t kret;
  595.   int res;

  596.   inferior_debug
  597.     (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
  598.      thread->msg_state, thread->gdb_port, step, nsignal);

  599.   switch (thread->msg_state)
  600.     {
  601.     case DARWIN_MESSAGE:
  602.       if (thread->event.ex_type == EXC_SOFTWARE
  603.           && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
  604.         {
  605.           /* Either deliver a new signal or cancel the signal received.  */
  606.           res = PTRACE (PT_THUPDATE, inf->pid,
  607.                         (void *)(uintptr_t)thread->gdb_port, nsignal);
  608.           if (res < 0)
  609.             inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
  610.         }
  611.       else if (nsignal)
  612.         {
  613.           /* Note: ptrace is allowed only if the process is stopped.
  614.              Directly send the signal to the thread.  */
  615.           res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
  616.           inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
  617.                           thread->gdb_port, nsignal, res);
  618.           thread->signaled = 1;
  619.         }

  620.       /* Set or reset single step.  */
  621.       if (step != thread->single_step)
  622.         {
  623.           inferior_debug (4, _("darwin_set_sstep (thread=0x%x, enable=%d)\n"),
  624.                           thread->gdb_port, step);
  625.           darwin_set_sstep (thread->gdb_port, step);
  626.           thread->single_step = step;
  627.         }

  628.       darwin_send_reply (inf, thread);
  629.       thread->msg_state = DARWIN_RUNNING;
  630.       break;

  631.     case DARWIN_RUNNING:
  632.       break;

  633.     case DARWIN_STOPPED:
  634.       kret = thread_resume (thread->gdb_port);
  635.       MACH_CHECK_ERROR (kret);

  636.       thread->msg_state = DARWIN_RUNNING;
  637.       break;
  638.     }
  639. }

  640. /* Resume all threads of the inferior.  */

  641. static void
  642. darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
  643. {
  644.   darwin_thread_t *thread;
  645.   int k;

  646.   for (k = 0;
  647.        VEC_iterate (darwin_thread_t, inf->private->threads, k, thread);
  648.        k++)
  649.     darwin_resume_thread (inf, thread, step, nsignal);
  650. }

  651. struct resume_inferior_threads_param
  652. {
  653.   int step;
  654.   int nsignal;
  655. };

  656. static int
  657. darwin_resume_inferior_threads_it (struct inferior *inf, void *param)
  658. {
  659.   int step = ((struct resume_inferior_threads_param *)param)->step;
  660.   int nsignal = ((struct resume_inferior_threads_param *)param)->nsignal;

  661.   darwin_resume_inferior_threads (inf, step, nsignal);

  662.   return 0;
  663. }

  664. /* Suspend all threads of INF.  */

  665. static void
  666. darwin_suspend_inferior_threads (struct inferior *inf)
  667. {
  668.   darwin_thread_t *thread;
  669.   kern_return_t kret;
  670.   int k;

  671.   for (k = 0;
  672.        VEC_iterate (darwin_thread_t, inf->private->threads, k, thread);
  673.        k++)
  674.     switch (thread->msg_state)
  675.       {
  676.       case DARWIN_STOPPED:
  677.       case DARWIN_MESSAGE:
  678.         break;
  679.       case DARWIN_RUNNING:
  680.         kret = thread_suspend (thread->gdb_port);
  681.         MACH_CHECK_ERROR (kret);
  682.         thread->msg_state = DARWIN_STOPPED;
  683.         break;
  684.       }
  685. }

  686. static void
  687. darwin_resume (ptid_t ptid, int step, enum gdb_signal signal)
  688. {
  689.   struct target_waitstatus status;
  690.   int pid;

  691.   kern_return_t kret;
  692.   int res;
  693.   int nsignal;
  694.   struct inferior *inf;

  695.   inferior_debug
  696.     (2, _("darwin_resume: pid=%d, tid=0x%x, step=%d, signal=%d\n"),
  697.      ptid_get_pid (ptid), ptid_get_tid (ptid), step, signal);

  698.   if (signal == GDB_SIGNAL_0)
  699.     nsignal = 0;
  700.   else
  701.     nsignal = gdb_signal_to_host (signal);

  702.   /* Don't try to single step all threads.  */
  703.   if (step)
  704.     ptid = inferior_ptid;

  705.   /* minus_one_ptid is RESUME_ALL.  */
  706.   if (ptid_equal (ptid, minus_one_ptid))
  707.     {
  708.       struct resume_inferior_threads_param param;

  709.       param.nsignal = nsignal;
  710.       param.step = step;

  711.       /* Resume threads.  */
  712.       iterate_over_inferiors (darwin_resume_inferior_threads_it, &param);
  713.       /* Resume tasks.  */
  714.       iterate_over_inferiors (darwin_resume_inferior_it, NULL);
  715.     }
  716.   else
  717.     {
  718.       struct inferior *inf = find_inferior_ptid (ptid);
  719.       long tid = ptid_get_tid (ptid);

  720.       /* Stop the inferior (should be useless).  */
  721.       darwin_suspend_inferior (inf);

  722.       if (tid == 0)
  723.         darwin_resume_inferior_threads (inf, step, nsignal);
  724.       else
  725.         {
  726.           darwin_thread_t *thread;

  727.           /* Suspend threads of the task.  */
  728.           darwin_suspend_inferior_threads (inf);

  729.           /* Resume the selected thread.  */
  730.           thread = darwin_find_thread (inf, tid);
  731.           gdb_assert (thread);
  732.           darwin_resume_thread (inf, thread, step, nsignal);
  733.         }

  734.       /* Resume the task.  */
  735.       darwin_resume_inferior (inf);
  736.     }
  737. }

  738. static void
  739. darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
  740.                   enum gdb_signal signal)
  741. {
  742.   return darwin_resume (ptid, step, signal);
  743. }

  744. static ptid_t
  745. darwin_decode_message (mach_msg_header_t *hdr,
  746.                        darwin_thread_t **pthread,
  747.                        struct inferior **pinf,
  748.                        struct target_waitstatus *status)
  749. {
  750.   darwin_thread_t *thread;
  751.   struct inferior *inf;

  752.   /* Exception message.  2401 == 0x961 is exc.  */
  753.   if (hdr->msgh_id == 2401)
  754.     {
  755.       int res;

  756.       /* Decode message.  */
  757.       res = darwin_decode_exception_message (hdr, &inf, &thread);

  758.       if (res < 0)
  759.         {
  760.           /* Should not happen...  */
  761.           printf_unfiltered
  762.             (_("darwin_wait: ill-formatted message (id=0x%x)\n"), hdr->msgh_id);
  763.           /* FIXME: send a failure reply?  */
  764.           status->kind = TARGET_WAITKIND_IGNORE;
  765.           return minus_one_ptid;
  766.         }
  767.       if (inf == NULL)
  768.         {
  769.           status->kind = TARGET_WAITKIND_IGNORE;
  770.           return minus_one_ptid;
  771.         }
  772.       *pinf = inf;
  773.       *pthread = thread;
  774.       inf->private->pending_messages++;

  775.       status->kind = TARGET_WAITKIND_STOPPED;
  776.       thread->msg_state = DARWIN_MESSAGE;

  777.       inferior_debug (4, _("darwin_wait: thread=0x%x, got %s\n"),
  778.                       thread->gdb_port,
  779.                       unparse_exception_type (thread->event.ex_type));

  780.       switch (thread->event.ex_type)
  781.         {
  782.         case EXC_BAD_ACCESS:
  783.           status->value.sig = GDB_EXC_BAD_ACCESS;
  784.           break;
  785.         case EXC_BAD_INSTRUCTION:
  786.           status->value.sig = GDB_EXC_BAD_INSTRUCTION;
  787.           break;
  788.         case EXC_ARITHMETIC:
  789.           status->value.sig = GDB_EXC_ARITHMETIC;
  790.           break;
  791.         case EXC_EMULATION:
  792.           status->value.sig = GDB_EXC_EMULATION;
  793.           break;
  794.         case EXC_SOFTWARE:
  795.           if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
  796.             {
  797.               status->value.sig =
  798.                 gdb_signal_from_host (thread->event.ex_data[1]);
  799.               inferior_debug (5, _("  (signal %d: %s)\n"),
  800.                               thread->event.ex_data[1],
  801.                               gdb_signal_to_name (status->value.sig));

  802.               /* If the thread is stopped because it has received a signal
  803.                  that gdb has just sent, continue.  */
  804.               if (thread->signaled)
  805.                 {
  806.                   thread->signaled = 0;
  807.                   darwin_send_reply (inf, thread);
  808.                   thread->msg_state = DARWIN_RUNNING;
  809.                   status->kind = TARGET_WAITKIND_IGNORE;
  810.                 }
  811.             }
  812.           else
  813.             status->value.sig = GDB_EXC_SOFTWARE;
  814.           break;
  815.         case EXC_BREAKPOINT:
  816.           /* Many internal GDB routines expect breakpoints to be reported
  817.              as GDB_SIGNAL_TRAP, and will report GDB_EXC_BREAKPOINT
  818.              as a spurious signal.  */
  819.           status->value.sig = GDB_SIGNAL_TRAP;
  820.           break;
  821.         default:
  822.           status->value.sig = GDB_SIGNAL_UNKNOWN;
  823.           break;
  824.         }

  825.       return ptid_build (inf->pid, 0, thread->gdb_port);
  826.     }
  827.   else if (hdr->msgh_id == 0x48)
  828.     {
  829.       /* MACH_NOTIFY_DEAD_NAME: notification for exit.  */
  830.       *pinf = NULL;
  831.       *pthread = NULL;

  832.       inf = darwin_find_inferior_by_notify (hdr->msgh_local_port);
  833.       if (inf != NULL)
  834.         {
  835.           if (!inf->private->no_ptrace)
  836.             {
  837.               pid_t res;
  838.               int wstatus;

  839.               res = wait4 (inf->pid, &wstatus, 0, NULL);
  840.               if (res < 0 || res != inf->pid)
  841.                 {
  842.                   printf_unfiltered (_("wait4: res=%d: %s\n"),
  843.                                      res, safe_strerror (errno));
  844.                   status->kind = TARGET_WAITKIND_IGNORE;
  845.                   return minus_one_ptid;
  846.                 }
  847.               if (WIFEXITED (wstatus))
  848.                 {
  849.                   status->kind = TARGET_WAITKIND_EXITED;
  850.                   status->value.integer = WEXITSTATUS (wstatus);
  851.                 }
  852.               else
  853.                 {
  854.                   status->kind = TARGET_WAITKIND_SIGNALLED;
  855.                   status->value.sig = WTERMSIG (wstatus);
  856.                 }

  857.               inferior_debug (4, _("darwin_wait: pid=%d exit, status=0x%x\n"),
  858.                               res, wstatus);

  859.               /* Looks necessary on Leopard and harmless...  */
  860.               wait4 (inf->pid, &wstatus, 0, NULL);

  861.               return ptid_build (inf->pid, 0, 0);
  862.             }
  863.           else
  864.             {
  865.               inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
  866.               status->kind = TARGET_WAITKIND_EXITED;
  867.               status->value.integer = 0; /* Don't know.  */
  868.               return ptid_build (inf->pid, 0, 0);
  869.             }
  870.         }
  871.     }

  872.   /* Unknown message.  */
  873.   warning (_("darwin: got unknown message, id: 0x%x"), hdr->msgh_id);
  874.   status->kind = TARGET_WAITKIND_IGNORE;
  875.   return minus_one_ptid;
  876. }

  877. static int
  878. cancel_breakpoint (ptid_t ptid)
  879. {
  880.   /* Arrange for a breakpoint to be hit again later.  We will handle
  881.      the current event, eventually we will resume this thread, and this
  882.      breakpoint will trap again.

  883.      If we do not do this, then we run the risk that the user will
  884.      delete or disable the breakpoint, but the thread will have already
  885.      tripped on it.  */

  886.   struct regcache *regcache = get_thread_regcache (ptid);
  887.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  888.   CORE_ADDR pc;

  889.   pc = regcache_read_pc (regcache) - target_decr_pc_after_break (gdbarch);
  890.   if (breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
  891.     {
  892.       inferior_debug (4, "cancel_breakpoint for thread 0x%x\n",
  893.                       ptid_get_tid (ptid));

  894.       /* Back up the PC if necessary.  */
  895.       if (target_decr_pc_after_break (gdbarch))
  896.         regcache_write_pc (regcache, pc);

  897.       return 1;
  898.     }
  899.   return 0;
  900. }

  901. static ptid_t
  902. darwin_wait (ptid_t ptid, struct target_waitstatus *status)
  903. {
  904.   kern_return_t kret;
  905.   union
  906.   {
  907.     mach_msg_header_t hdr;
  908.     char data[0x100];
  909.   } msgin;
  910.   mach_msg_header_t *hdr = &msgin.hdr;
  911.   ptid_t res;
  912.   darwin_thread_t *thread;
  913.   struct inferior *inf;

  914.   inferior_debug
  915.     (2, _("darwin_wait: waiting for a message pid=%d thread=%lx\n"),
  916.      ptid_get_pid (ptid), ptid_get_tid (ptid));

  917.   /* Handle fake stop events at first.  */
  918.   if (darwin_inf_fake_stop != NULL)
  919.     {
  920.       inf = darwin_inf_fake_stop;
  921.       darwin_inf_fake_stop = NULL;

  922.       status->kind = TARGET_WAITKIND_STOPPED;
  923.       status->value.sig = GDB_SIGNAL_TRAP;
  924.       thread = VEC_index (darwin_thread_t, inf->private->threads, 0);
  925.       thread->msg_state = DARWIN_STOPPED;
  926.       return ptid_build (inf->pid, 0, thread->gdb_port);
  927.     }

  928.   do
  929.     {
  930.       /* set_sigint_trap (); */

  931.       /* Wait for a message.  */
  932.       kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
  933.                        sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);

  934.       /* clear_sigint_trap (); */

  935.       if (kret == MACH_RCV_INTERRUPTED)
  936.         {
  937.           status->kind = TARGET_WAITKIND_IGNORE;
  938.           return minus_one_ptid;
  939.         }

  940.       if (kret != MACH_MSG_SUCCESS)
  941.         {
  942.           inferior_debug (5, _("mach_msg: ret=0x%x\n"), kret);
  943.           status->kind = TARGET_WAITKIND_SPURIOUS;
  944.           return minus_one_ptid;
  945.         }

  946.       /* Debug: display message.  */
  947.       if (darwin_debug_flag > 10)
  948.         darwin_dump_message (hdr, darwin_debug_flag > 11);

  949.       res = darwin_decode_message (hdr, &thread, &inf, status);
  950.       if (ptid_equal (res, minus_one_ptid))
  951.         continue;

  952.       /* Early return in case an inferior has exited.  */
  953.       if (inf == NULL)
  954.         return res;
  955.     }
  956.   while (status->kind == TARGET_WAITKIND_IGNORE);

  957.   /* Stop all tasks.  */
  958.   iterate_over_inferiors (darwin_suspend_inferior_it, NULL);

  959.   /* Read pending messages.  */
  960.   while (1)
  961.     {
  962.       struct target_waitstatus status2;
  963.       ptid_t ptid2;

  964.       kret = mach_msg (&msgin.hdr,
  965.                        MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
  966.                        sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);

  967.       if (kret == MACH_RCV_TIMED_OUT)
  968.         break;
  969.       if (kret != MACH_MSG_SUCCESS)
  970.         {
  971.           inferior_debug
  972.             (5, _("darwin_wait: mach_msg(pending) ret=0x%x\n"), kret);
  973.           break;
  974.         }

  975.       /* Debug: display message.  */
  976.       if (darwin_debug_flag > 10)
  977.         darwin_dump_message (hdr, darwin_debug_flag > 11);

  978.       ptid2 = darwin_decode_message (hdr, &thread, &inf, &status2);

  979.       if (inf != NULL && thread != NULL
  980.           && thread->event.ex_type == EXC_BREAKPOINT)
  981.         {
  982.           if (thread->single_step
  983.               || cancel_breakpoint (ptid_build (inf->pid, 0, thread->gdb_port)))
  984.             {
  985.               gdb_assert (thread->msg_state == DARWIN_MESSAGE);
  986.               darwin_send_reply (inf, thread);
  987.               thread->msg_state = DARWIN_RUNNING;
  988.             }
  989.           else
  990.             inferior_debug
  991.               (3, _("darwin_wait: thread 0x%x hit a non-gdb breakpoint\n"),
  992.                thread->gdb_port);
  993.         }
  994.       else
  995.         inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
  996.     }
  997.   return res;
  998. }

  999. static ptid_t
  1000. darwin_wait_to (struct target_ops *ops,
  1001.                 ptid_t ptid, struct target_waitstatus *status, int options)
  1002. {
  1003.   return darwin_wait (ptid, status);
  1004. }

  1005. static void
  1006. darwin_stop (struct target_ops *self, ptid_t t)
  1007. {
  1008.   struct inferior *inf = current_inferior ();

  1009.   /* FIXME: handle in no_ptrace mode.  */
  1010.   gdb_assert (!inf->private->no_ptrace);
  1011.   kill (inf->pid, SIGINT);
  1012. }

  1013. static void
  1014. darwin_mourn_inferior (struct target_ops *ops)
  1015. {
  1016.   struct inferior *inf = current_inferior ();
  1017.   kern_return_t kret;
  1018.   mach_port_t prev;
  1019.   int i;

  1020.   /* Deallocate threads.  */
  1021.   if (inf->private->threads)
  1022.     {
  1023.       int k;
  1024.       darwin_thread_t *t;
  1025.       for (k = 0;
  1026.            VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
  1027.            k++)
  1028.         {
  1029.           kret = mach_port_deallocate (gdb_task, t->gdb_port);
  1030.           MACH_CHECK_ERROR (kret);
  1031.         }
  1032.       VEC_free (darwin_thread_t, inf->private->threads);
  1033.       inf->private->threads = NULL;
  1034.     }

  1035.   kret = mach_port_move_member (gdb_task,
  1036.                                 inf->private->notify_port, MACH_PORT_NULL);
  1037.   MACH_CHECK_ERROR (kret);

  1038.   kret = mach_port_request_notification (gdb_task, inf->private->task,
  1039.                                          MACH_NOTIFY_DEAD_NAME, 0,
  1040.                                          MACH_PORT_NULL,
  1041.                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
  1042.                                          &prev);
  1043.   /* This can fail if the task is dead.  */
  1044.   inferior_debug (4, "task=0x%x, prev=0x%x, notify_port=0x%x\n",
  1045.                   inf->private->task, prev, inf->private->notify_port);

  1046.   if (kret == KERN_SUCCESS)
  1047.     {
  1048.       kret = mach_port_deallocate (gdb_task, prev);
  1049.       MACH_CHECK_ERROR (kret);
  1050.     }

  1051.   kret = mach_port_destroy (gdb_task, inf->private->notify_port);
  1052.   MACH_CHECK_ERROR (kret);


  1053.   /* Deallocate saved exception ports.  */
  1054.   for (i = 0; i < inf->private->exception_info.count; i++)
  1055.     {
  1056.       kret = mach_port_deallocate
  1057.         (gdb_task, inf->private->exception_info.ports[i]);
  1058.       MACH_CHECK_ERROR (kret);
  1059.     }
  1060.   inf->private->exception_info.count = 0;

  1061.   kret = mach_port_deallocate (gdb_task, inf->private->task);
  1062.   MACH_CHECK_ERROR (kret);

  1063.   xfree (inf->private);
  1064.   inf->private = NULL;

  1065.   inf_child_mourn_inferior (ops);
  1066. }

  1067. static void
  1068. darwin_reply_to_all_pending_messages (struct inferior *inf)
  1069. {
  1070.   int k;
  1071.   darwin_thread_t *t;

  1072.   for (k = 0;
  1073.        VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
  1074.        k++)
  1075.     {
  1076.       if (t->msg_state == DARWIN_MESSAGE)
  1077.         darwin_resume_thread (inf, t, 0, 0);
  1078.     }
  1079. }

  1080. static void
  1081. darwin_stop_inferior (struct inferior *inf)
  1082. {
  1083.   struct target_waitstatus wstatus;
  1084.   ptid_t ptid;
  1085.   kern_return_t kret;
  1086.   int status;
  1087.   int res;

  1088.   gdb_assert (inf != NULL);

  1089.   darwin_suspend_inferior (inf);

  1090.   darwin_reply_to_all_pending_messages (inf);

  1091.   if (inf->private->no_ptrace)
  1092.     return;

  1093.   res = kill (inf->pid, SIGSTOP);
  1094.   if (res != 0)
  1095.     warning (_("cannot kill: %s"), safe_strerror (errno));

  1096.   /* Wait until the process is really stopped.  */
  1097.   while (1)
  1098.     {
  1099.       ptid = darwin_wait (inferior_ptid, &wstatus);
  1100.       if (wstatus.kind == TARGET_WAITKIND_STOPPED
  1101.           && wstatus.value.sig == GDB_SIGNAL_STOP)
  1102.         break;
  1103.     }
  1104. }

  1105. static kern_return_t
  1106. darwin_save_exception_ports (darwin_inferior *inf)
  1107. {
  1108.   kern_return_t kret;

  1109.   inf->exception_info.count =
  1110.     sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);

  1111.   kret = task_get_exception_ports
  1112.     (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
  1113.      &inf->exception_info.count, inf->exception_info.ports,
  1114.      inf->exception_info.behaviors, inf->exception_info.flavors);
  1115.   return kret;
  1116. }

  1117. static kern_return_t
  1118. darwin_restore_exception_ports (darwin_inferior *inf)
  1119. {
  1120.   int i;
  1121.   kern_return_t kret;

  1122.   for (i = 0; i < inf->exception_info.count; i++)
  1123.     {
  1124.       kret = task_set_exception_ports
  1125.         (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
  1126.          inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
  1127.       if (kret != KERN_SUCCESS)
  1128.         return kret;
  1129.     }

  1130.   return KERN_SUCCESS;
  1131. }

  1132. static void
  1133. darwin_kill_inferior (struct target_ops *ops)
  1134. {
  1135.   struct inferior *inf = current_inferior ();
  1136.   struct target_waitstatus wstatus;
  1137.   ptid_t ptid;
  1138.   kern_return_t kret;
  1139.   int status;
  1140.   int res;

  1141.   if (ptid_equal (inferior_ptid, null_ptid))
  1142.     return;

  1143.   gdb_assert (inf != NULL);

  1144.   kret = darwin_restore_exception_ports (inf->private);
  1145.   MACH_CHECK_ERROR (kret);

  1146.   darwin_reply_to_all_pending_messages (inf);

  1147.   res = kill (inf->pid, 9);

  1148.   if (res == 0)
  1149.     {
  1150.       darwin_resume_inferior (inf);

  1151.       ptid = darwin_wait (inferior_ptid, &wstatus);
  1152.     }
  1153.   else if (errno != ESRCH)
  1154.     warning (_("Failed to kill inferior: kill (%d, 9) returned [%s]"),
  1155.              inf->pid, safe_strerror (errno));

  1156.   target_mourn_inferior ();
  1157. }

  1158. static void
  1159. darwin_attach_pid (struct inferior *inf)
  1160. {
  1161.   kern_return_t kret;
  1162.   mach_port_t prev_port;
  1163.   int traps_expected;
  1164.   mach_port_t prev_not;
  1165.   exception_mask_t mask;

  1166.   inf->private = XCNEW (darwin_inferior);

  1167.   kret = task_for_pid (gdb_task, inf->pid, &inf->private->task);
  1168.   if (kret != KERN_SUCCESS)
  1169.     {
  1170.       int status;

  1171.       if (!inf->attach_flag)
  1172.         {
  1173.           kill (inf->pid, 9);
  1174.           waitpid (inf->pid, &status, 0);
  1175.         }

  1176.       error (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
  1177.                " (please check gdb is codesigned - see taskgated(8))"),
  1178.              inf->pid, mach_error_string (kret), (unsigned long) kret);
  1179.     }

  1180.   inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
  1181.                   inf->private->task, inf->pid);

  1182.   if (darwin_ex_port == MACH_PORT_NULL)
  1183.     {
  1184.       /* Create a port to get exceptions.  */
  1185.       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
  1186.                                  &darwin_ex_port);
  1187.       if (kret != KERN_SUCCESS)
  1188.         error (_("Unable to create exception port, mach_port_allocate "
  1189.                  "returned: %d"),
  1190.                kret);

  1191.       kret = mach_port_insert_right (gdb_task, darwin_ex_port, darwin_ex_port,
  1192.                                      MACH_MSG_TYPE_MAKE_SEND);
  1193.       if (kret != KERN_SUCCESS)
  1194.         error (_("Unable to create exception port, mach_port_insert_right "
  1195.                  "returned: %d"),
  1196.                kret);

  1197.       /* Create a port set and put ex_port in it.  */
  1198.       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
  1199.                                  &darwin_port_set);
  1200.       if (kret != KERN_SUCCESS)
  1201.         error (_("Unable to create port set, mach_port_allocate "
  1202.                  "returned: %d"),
  1203.                kret);

  1204.       kret = mach_port_move_member (gdb_task, darwin_ex_port, darwin_port_set);
  1205.       if (kret != KERN_SUCCESS)
  1206.         error (_("Unable to move exception port into new port set, "
  1207.                  "mach_port_move_member\n"
  1208.                  "returned: %d"),
  1209.                kret);
  1210.     }

  1211.   /* Create a port to be notified when the child task terminates.  */
  1212.   kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
  1213.                              &inf->private->notify_port);
  1214.   if (kret != KERN_SUCCESS)
  1215.     error (_("Unable to create notification port, mach_port_allocate "
  1216.              "returned: %d"),
  1217.            kret);

  1218.   kret = mach_port_move_member (gdb_task,
  1219.                                 inf->private->notify_port, darwin_port_set);
  1220.   if (kret != KERN_SUCCESS)
  1221.     error (_("Unable to move notification port into new port set, "
  1222.              "mach_port_move_member\n"
  1223.              "returned: %d"),
  1224.            kret);

  1225.   kret = mach_port_request_notification (gdb_task, inf->private->task,
  1226.                                          MACH_NOTIFY_DEAD_NAME, 0,
  1227.                                          inf->private->notify_port,
  1228.                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
  1229.                                          &prev_not);
  1230.   if (kret != KERN_SUCCESS)
  1231.     error (_("Termination notification request failed, "
  1232.              "mach_port_request_notification\n"
  1233.              "returned: %d"),
  1234.            kret);
  1235.   if (prev_not != MACH_PORT_NULL)
  1236.     {
  1237.       /* This is unexpected, as there should not be any previously
  1238.          registered notification request.  But this is not a fatal
  1239.          issue, so just emit a warning.  */
  1240.       warning (_("\
  1241. A task termination request was registered before the debugger registered\n\
  1242. its own.  This is unexpected, but should otherwise not have any actual\n\
  1243. impact on the debugging session."));
  1244.     }

  1245.   kret = darwin_save_exception_ports (inf->private);
  1246.   if (kret != KERN_SUCCESS)
  1247.     error (_("Unable to save exception ports, task_get_exception_ports"
  1248.              "returned: %d"),
  1249.            kret);

  1250.   /* Set exception port.  */
  1251.   if (enable_mach_exceptions)
  1252.     mask = EXC_MASK_ALL;
  1253.   else
  1254.     mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
  1255.   kret = task_set_exception_ports (inf->private->task, mask, darwin_ex_port,
  1256.                                    EXCEPTION_DEFAULT, THREAD_STATE_NONE);
  1257.   if (kret != KERN_SUCCESS)
  1258.     error (_("Unable to set exception ports, task_set_exception_ports"
  1259.              "returned: %d"),
  1260.            kret);

  1261.   if (!target_is_pushed (darwin_ops))
  1262.     push_target (darwin_ops);
  1263. }

  1264. static void
  1265. darwin_init_thread_list (struct inferior *inf)
  1266. {
  1267.   darwin_thread_t *thread;
  1268.   ptid_t new_ptid;

  1269.   darwin_check_new_threads (inf);

  1270.   gdb_assert (inf->private->threads
  1271.               && VEC_length (darwin_thread_t, inf->private->threads) > 0);
  1272.   thread = VEC_index (darwin_thread_t, inf->private->threads, 0);

  1273.   /* Note: fork_inferior automatically add a thead but it uses a wrong ptid.
  1274.      Fix up.  */
  1275.   new_ptid = ptid_build (inf->pid, 0, thread->gdb_port);
  1276.   thread_change_ptid (inferior_ptid, new_ptid);
  1277.   inferior_ptid = new_ptid;
  1278. }

  1279. /* The child must synchronize with gdb: gdb must set the exception port
  1280.    before the child call PTRACE_SIGEXC.  We use a pipe to achieve this.
  1281.    FIXME: is there a lighter way ?  */
  1282. static int ptrace_fds[2];

  1283. static void
  1284. darwin_ptrace_me (void)
  1285. {
  1286.   int res;
  1287.   char c;

  1288.   /* Close write end point.  */
  1289.   close (ptrace_fds[1]);

  1290.   /* Wait until gdb is ready.  */
  1291.   res = read (ptrace_fds[0], &c, 1);
  1292.   if (res != 0)
  1293.     error (_("unable to read from pipe, read returned: %d"), res);
  1294.   close (ptrace_fds[0]);

  1295.   /* Get rid of privileges.  */
  1296.   setegid (getgid ());

  1297.   /* Set TRACEME.  */
  1298.   PTRACE (PT_TRACE_ME, 0, 0, 0);

  1299.   /* Redirect signals to exception port.  */
  1300.   PTRACE (PT_SIGEXC, 0, 0, 0);
  1301. }

  1302. /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2).  */
  1303. static void
  1304. darwin_pre_ptrace (void)
  1305. {
  1306.   if (pipe (ptrace_fds) != 0)
  1307.     {
  1308.       ptrace_fds[0] = -1;
  1309.       ptrace_fds[1] = -1;
  1310.       error (_("unable to create a pipe: %s"), safe_strerror (errno));
  1311.     }

  1312.   mark_fd_no_cloexec (ptrace_fds[0]);
  1313.   mark_fd_no_cloexec (ptrace_fds[1]);
  1314. }

  1315. static void
  1316. darwin_ptrace_him (int pid)
  1317. {
  1318.   task_t itask;
  1319.   kern_return_t kret;
  1320.   mach_port_t prev_port;
  1321.   int traps_expected;
  1322.   struct inferior *inf = current_inferior ();

  1323.   darwin_attach_pid (inf);

  1324.   /* Let's the child run.  */
  1325.   close (ptrace_fds[0]);
  1326.   close (ptrace_fds[1]);

  1327.   unmark_fd_no_cloexec (ptrace_fds[0]);
  1328.   unmark_fd_no_cloexec (ptrace_fds[1]);

  1329.   darwin_init_thread_list (inf);

  1330.   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
  1331. }

  1332. static void
  1333. darwin_execvp (const char *file, char * const argv[], char * const env[])
  1334. {
  1335.   posix_spawnattr_t attr;
  1336.   short ps_flags = 0;
  1337.   int res;

  1338.   res = posix_spawnattr_init (&attr);
  1339.   if (res != 0)
  1340.     {
  1341.       fprintf_unfiltered
  1342.         (gdb_stderr, "Cannot initialize attribute for posix_spawn\n");
  1343.       return;
  1344.     }

  1345.   /* Do like execve: replace the image.  */
  1346.   ps_flags = POSIX_SPAWN_SETEXEC;

  1347.   /* Disable ASLR.  The constant doesn't look to be available outside the
  1348.      kernel include files.  */
  1349. #ifndef _POSIX_SPAWN_DISABLE_ASLR
  1350. #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
  1351. #endif
  1352.   ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
  1353.   res = posix_spawnattr_setflags (&attr, ps_flags);
  1354.   if (res != 0)
  1355.     {
  1356.       fprintf_unfiltered (gdb_stderr, "Cannot set posix_spawn flags\n");
  1357.       return;
  1358.     }

  1359.   posix_spawnp (NULL, argv[0], NULL, &attr, argv, env);
  1360. }

  1361. static void
  1362. darwin_create_inferior (struct target_ops *ops, char *exec_file,
  1363.                         char *allargs, char **env, int from_tty)
  1364. {
  1365.   /* Do the hard work.  */
  1366.   fork_inferior (exec_file, allargs, env, darwin_ptrace_me, darwin_ptrace_him,
  1367.                  darwin_pre_ptrace, NULL, darwin_execvp);

  1368.   /* Return now in case of error.  */
  1369.   if (ptid_equal (inferior_ptid, null_ptid))
  1370.     return;
  1371. }


  1372. /* Set things up such that the next call to darwin_wait will immediately
  1373.    return a fake stop event for inferior INF.

  1374.    This assumes that the inferior's thread list has been initialized,
  1375.    as it will suspend the inferior's first thread.  */

  1376. static void
  1377. darwin_setup_fake_stop_event (struct inferior *inf)
  1378. {
  1379.   darwin_thread_t *thread;
  1380.   kern_return_t kret;

  1381.   gdb_assert (darwin_inf_fake_stop == NULL);
  1382.   darwin_inf_fake_stop = inf;

  1383.   /* When detecting a fake pending stop event, darwin_wait returns
  1384.      an event saying that the first thread is in a DARWIN_STOPPED
  1385.      state.  To make that accurate, we need to suspend that thread
  1386.      as well.  Otherwise, we'll try resuming it when resuming the
  1387.      inferior, and get a warning because the thread's suspend count
  1388.      is already zero, making the resume request useless.  */
  1389.   thread = VEC_index (darwin_thread_t, inf->private->threads, 0);
  1390.   kret = thread_suspend (thread->gdb_port);
  1391.   MACH_CHECK_ERROR (kret);
  1392. }

  1393. /* Attach to process PID, then initialize for debugging it
  1394.    and wait for the trace-trap that results from attaching.  */
  1395. static void
  1396. darwin_attach (struct target_ops *ops, const char *args, int from_tty)
  1397. {
  1398.   pid_t pid;
  1399.   pid_t pid2;
  1400.   int wstatus;
  1401.   int res;
  1402.   struct inferior *inf;
  1403.   kern_return_t kret;

  1404.   pid = parse_pid_to_attach (args);

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

  1407.   if (from_tty)
  1408.     {
  1409.       char *exec_file = get_exec_file (0);

  1410.       if (exec_file)
  1411.         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
  1412.                            target_pid_to_str (pid_to_ptid (pid)));
  1413.       else
  1414.         printf_unfiltered (_("Attaching to %s\n"),
  1415.                            target_pid_to_str (pid_to_ptid (pid)));

  1416.       gdb_flush (gdb_stdout);
  1417.     }

  1418.   if (pid == 0 || kill (pid, 0) < 0)
  1419.     error (_("Can't attach to process %d: %s (%d)"),
  1420.            pid, safe_strerror (errno), errno);

  1421.   inferior_ptid = pid_to_ptid (pid);
  1422.   inf = current_inferior ();
  1423.   inferior_appeared (inf, pid);
  1424.   inf->attach_flag = 1;

  1425.   /* Always add a main thread.  */
  1426.   add_thread_silent (inferior_ptid);

  1427.   darwin_attach_pid (inf);

  1428.   darwin_suspend_inferior (inf);

  1429.   darwin_init_thread_list (inf);

  1430.   darwin_check_osabi (inf->private, ptid_get_tid (inferior_ptid));

  1431.   darwin_setup_fake_stop_event (inf);

  1432.   inf->private->no_ptrace = 1;
  1433. }

  1434. /* Take a program previously attached to and detaches it.
  1435.    The program resumes execution and will no longer stop
  1436.    on signals, etc.  We'd better not have left any breakpoints
  1437.    in the program or it'll die when it hits one.  For this
  1438.    to work, it may be necessary for the process to have been
  1439.    previously attached.  It *might* work if the program was
  1440.    started via fork.  */
  1441. static void
  1442. darwin_detach (struct target_ops *ops, const char *args, int from_tty)
  1443. {
  1444.   pid_t pid = ptid_get_pid (inferior_ptid);
  1445.   struct inferior *inf = current_inferior ();
  1446.   kern_return_t kret;
  1447.   int res;

  1448.   /* Display message.  */
  1449.   if (from_tty)
  1450.     {
  1451.       char *exec_file = get_exec_file (0);
  1452.       if (exec_file == 0)
  1453.         exec_file = "";
  1454.       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
  1455.                          target_pid_to_str (pid_to_ptid (pid)));
  1456.       gdb_flush (gdb_stdout);
  1457.     }

  1458.   /* If ptrace() is in use, stop the process.  */
  1459.   if (!inf->private->no_ptrace)
  1460.     darwin_stop_inferior (inf);

  1461.   kret = darwin_restore_exception_ports (inf->private);
  1462.   MACH_CHECK_ERROR (kret);

  1463.   if (!inf->private->no_ptrace)
  1464.     {
  1465.       res = PTRACE (PT_DETACH, inf->pid, 0, 0);
  1466.       if (res != 0)
  1467.         printf_unfiltered (_("Unable to detach from process-id %d: %s (%d)"),
  1468.                            inf->pid, safe_strerror (errno), errno);
  1469.     }

  1470.   darwin_reply_to_all_pending_messages (inf);

  1471.   /* When using ptrace, we have just performed a PT_DETACH, which
  1472.      resumes the inferior.  On the other hand, when we are not using
  1473.      ptrace, we need to resume its execution ourselves.  */
  1474.   if (inf->private->no_ptrace)
  1475.     darwin_resume_inferior (inf);

  1476.   darwin_mourn_inferior (ops);
  1477. }

  1478. static void
  1479. darwin_files_info (struct target_ops *ops)
  1480. {
  1481. }

  1482. static char *
  1483. darwin_pid_to_str (struct target_ops *ops, ptid_t ptid)
  1484. {
  1485.   static char buf[80];
  1486.   long tid = ptid_get_tid (ptid);

  1487.   if (tid != 0)
  1488.     {
  1489.       snprintf (buf, sizeof (buf), _("Thread 0x%lx of process %u"),
  1490.                 tid, ptid_get_pid (ptid));
  1491.       return buf;
  1492.     }

  1493.   return normal_pid_to_str (ptid);
  1494. }

  1495. static int
  1496. darwin_thread_alive (struct target_ops *ops, ptid_t ptid)
  1497. {
  1498.   return 1;
  1499. }

  1500. /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
  1501.    copy it to RDADDR in gdb's address space.
  1502.    If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
  1503.    to ADDR in inferior task's address space.
  1504.    Return 0 on failure; number of bytes read / writen otherwise.  */
  1505. static int
  1506. darwin_read_write_inferior (task_t task, CORE_ADDR addr,
  1507.                             gdb_byte *rdaddr, const gdb_byte *wraddr,
  1508.                             ULONGEST length)
  1509. {
  1510.   kern_return_t kret;
  1511.   mach_vm_address_t offset = addr & (mach_page_size - 1);
  1512.   mach_vm_address_t low_address = (mach_vm_address_t) (addr - offset);
  1513.   mach_vm_size_t aligned_length = (mach_vm_size_t) PAGE_ROUND (offset + length);
  1514.   pointer_t copied;
  1515.   mach_msg_type_number_t copy_count;
  1516.   mach_vm_size_t remaining_length;
  1517.   mach_vm_address_t region_address;
  1518.   mach_vm_size_t region_length;

  1519.   inferior_debug (8, _("darwin_read_write_inferior(task=0x%x, %s, len=%s)\n"),
  1520.                   task, core_addr_to_string (addr), pulongest (length));

  1521.   /* Get memory from inferior with page aligned addresses.  */
  1522.   kret = mach_vm_read (task, low_address, aligned_length,
  1523.                       &copied, &copy_count);
  1524.   if (kret != KERN_SUCCESS)
  1525.     {
  1526.       inferior_debug
  1527.         (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
  1528.          core_addr_to_string (addr), mach_error_string (kret));
  1529.       return 0;
  1530.     }

  1531.   if (rdaddr != NULL)
  1532.     memcpy (rdaddr, (char *)copied + offset, length);

  1533.   if (wraddr == NULL)
  1534.     goto out;

  1535.   memcpy ((char *)copied + offset, wraddr, length);

  1536.   /* Do writes atomically.
  1537.      First check for holes and unwritable memory.  */
  1538.   for (region_address = low_address, remaining_length = aligned_length;
  1539.        region_address < low_address + aligned_length;
  1540.        region_address += region_length, remaining_length -= region_length)
  1541.     {
  1542.       vm_region_submap_short_info_data_64_t info;
  1543.       mach_vm_address_t region_start = region_address;
  1544.       mach_msg_type_number_t count;
  1545.       natural_t region_depth;

  1546.       region_depth = 100000;
  1547.       count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
  1548.       kret = mach_vm_region_recurse
  1549.         (task, &region_start, &region_length, &region_depth,
  1550.          (vm_region_recurse_info_t) &info, &count);

  1551.       if (kret != KERN_SUCCESS)
  1552.         {
  1553.           inferior_debug (1, _("darwin_read_write_inferior: "
  1554.                                "mach_vm_region_recurse failed at %s: %s\n"),
  1555.                           core_addr_to_string (region_address),
  1556.                           mach_error_string (kret));
  1557.           goto out;
  1558.         }

  1559.       inferior_debug
  1560.         (9, _("darwin_read_write_inferior: "
  1561.               "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
  1562.          core_addr_to_string (region_address),
  1563.          core_addr_to_string (region_start),
  1564.          core_addr_to_string (region_length));

  1565.       /* Check for holes in memory.  */
  1566.       if (region_start > region_address)
  1567.         {
  1568.           warning (_("No memory at %s (vs %s+0x%x).  Nothing written"),
  1569.                    core_addr_to_string (region_address),
  1570.                    core_addr_to_string (region_start),
  1571.                    (unsigned)region_length);
  1572.           length = 0;
  1573.           goto out;
  1574.         }

  1575.       /* Adjust the length.  */
  1576.       region_length -= (region_address - region_start);

  1577.       if (!(info.max_protection & VM_PROT_WRITE))
  1578.         {
  1579.           kret = mach_vm_protect
  1580.             (task, region_address, region_length,
  1581.              TRUE, info.max_protection | VM_PROT_WRITE | VM_PROT_COPY);
  1582.           if (kret != KERN_SUCCESS)
  1583.             {
  1584.               warning (_("darwin_read_write_inf: "
  1585.                          "mach_vm_protect max failed at %s: %s"),
  1586.                        core_addr_to_string (region_address),
  1587.                        mach_error_string (kret));
  1588.               length = 0;
  1589.               goto out;
  1590.             }
  1591.         }

  1592.       if (!(info.protection & VM_PROT_WRITE))
  1593.         {
  1594.           kret = mach_vm_protect (task, region_address, region_length,
  1595.                                  FALSE, info.protection | VM_PROT_WRITE);
  1596.           if (kret != KERN_SUCCESS)
  1597.             {
  1598.               warning (_("darwin_read_write_inf: "
  1599.                          "mach_vm_protect failed at %s (len=0x%lx): %s"),
  1600.                        core_addr_to_string (region_address),
  1601.                        (unsigned long)region_length, mach_error_string (kret));
  1602.               length = 0;
  1603.               goto out;
  1604.             }
  1605.         }
  1606.     }

  1607.   kret = mach_vm_write (task, low_address, copied, aligned_length);

  1608.   if (kret != KERN_SUCCESS)
  1609.     {
  1610.       warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
  1611.                mach_error_string (kret));
  1612.       length = 0;
  1613.     }
  1614. out:
  1615.   mach_vm_deallocate (mach_task_self (), copied, copy_count);
  1616.   return length;
  1617. }

  1618. /* Read LENGTH bytes at offset ADDR of task_dyld_info for TASK, and copy them
  1619.    to RDADDR.
  1620.    Return 0 on failure; number of bytes read / written otherwise.  */

  1621. #ifdef TASK_DYLD_INFO_COUNT
  1622. /* This is not available in Darwin 9.  */
  1623. static enum target_xfer_status
  1624. darwin_read_dyld_info (task_t task, CORE_ADDR addr, gdb_byte *rdaddr,
  1625.                        ULONGEST length, ULONGEST *xfered_len)
  1626. {
  1627.   struct task_dyld_info task_dyld_info;
  1628.   mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
  1629.   int sz = TASK_DYLD_INFO_COUNT * sizeof (natural_t);
  1630.   kern_return_t kret;

  1631.   if (addr >= sz)
  1632.     return TARGET_XFER_EOF;

  1633.   kret = task_info (task, TASK_DYLD_INFO, (task_info_t) &task_dyld_info, &count);
  1634.   MACH_CHECK_ERROR (kret);
  1635.   if (kret != KERN_SUCCESS)
  1636.     return TARGET_XFER_E_IO;
  1637.   /* Truncate.  */
  1638.   if (addr + length > sz)
  1639.     length = sz - addr;
  1640.   memcpy (rdaddr, (char *)&task_dyld_info + addr, length);
  1641.   *xfered_len = (ULONGEST) length;
  1642.   return TARGET_XFER_OK;
  1643. }
  1644. #endif



  1645. static enum target_xfer_status
  1646. darwin_xfer_partial (struct target_ops *ops,
  1647.                      enum target_object object, const char *annex,
  1648.                      gdb_byte *readbuf, const gdb_byte *writebuf,
  1649.                      ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
  1650. {
  1651.   struct inferior *inf = current_inferior ();

  1652.   inferior_debug
  1653.     (8, _("darwin_xfer_partial(%s, %s, rbuf=%s, wbuf=%s) pid=%u\n"),
  1654.      core_addr_to_string (offset), pulongest (len),
  1655.      host_address_to_string (readbuf), host_address_to_string (writebuf),
  1656.      inf->pid);

  1657.   switch (object)
  1658.     {
  1659.     case TARGET_OBJECT_MEMORY:
  1660.       {
  1661.         int l = darwin_read_write_inferior (inf->private->task, offset,
  1662.                                             readbuf, writebuf, len);

  1663.         if (l == 0)
  1664.           return TARGET_XFER_EOF;
  1665.         else
  1666.           {
  1667.             gdb_assert (l > 0);
  1668.             *xfered_len = (ULONGEST) l;
  1669.             return TARGET_XFER_OK;
  1670.           }
  1671.       }
  1672. #ifdef TASK_DYLD_INFO_COUNT
  1673.     case TARGET_OBJECT_DARWIN_DYLD_INFO:
  1674.       if (writebuf != NULL || readbuf == NULL)
  1675.         {
  1676.           /* Support only read.  */
  1677.           return TARGET_XFER_E_IO;
  1678.         }
  1679.       return darwin_read_dyld_info (inf->private->task, offset, readbuf, len,
  1680.                                     xfered_len);
  1681. #endif
  1682.     default:
  1683.       return TARGET_XFER_E_IO;
  1684.     }

  1685. }

  1686. static void
  1687. set_enable_mach_exceptions (char *args, int from_tty,
  1688.                             struct cmd_list_element *c)
  1689. {
  1690.   if (!ptid_equal (inferior_ptid, null_ptid))
  1691.     {
  1692.       struct inferior *inf = current_inferior ();
  1693.       exception_mask_t mask;
  1694.       kern_return_t kret;

  1695.       if (enable_mach_exceptions)
  1696.         mask = EXC_MASK_ALL;
  1697.       else
  1698.         {
  1699.           darwin_restore_exception_ports (inf->private);
  1700.           mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
  1701.         }
  1702.       kret = task_set_exception_ports (inf->private->task, mask, darwin_ex_port,
  1703.                                        EXCEPTION_DEFAULT, THREAD_STATE_NONE);
  1704.       MACH_CHECK_ERROR (kret);
  1705.     }
  1706. }

  1707. static char *
  1708. darwin_pid_to_exec_file (struct target_ops *self, int pid)
  1709. {
  1710.   static char path[PATH_MAX];
  1711.   int res;

  1712.   res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, PATH_MAX);
  1713.   if (res >= 0)
  1714.     return path;
  1715.   else
  1716.     return NULL;
  1717. }

  1718. static ptid_t
  1719. darwin_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
  1720. {
  1721.   int i;
  1722.   darwin_thread_t *t;
  1723.   int k;
  1724.   struct inferior *inf = current_inferior ();
  1725.   kern_return_t kret;
  1726.   mach_port_name_array_t names;
  1727.   mach_msg_type_number_t names_count;
  1728.   mach_port_type_array_t types;
  1729.   mach_msg_type_number_t types_count;
  1730.   long res = 0;

  1731.   /* First linear search.  */
  1732.   for (k = 0;
  1733.        VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
  1734.        k++)
  1735.     if (t->inf_port == lwp)
  1736.       return ptid_build (ptid_get_pid (inferior_ptid), 0, t->gdb_port);

  1737.   /* Maybe the port was never extract.  Do it now.  */

  1738.   /* First get inferior port names.  */
  1739.   kret = mach_port_names (inf->private->task, &names, &names_count, &types,
  1740.                           &types_count);
  1741.   MACH_CHECK_ERROR (kret);
  1742.   if (kret != KERN_SUCCESS)
  1743.     return null_ptid;

  1744.   /* For each name, copy the right in the gdb space and then compare with
  1745.      our view of the inferior threads.  We don't forget to deallocate the
  1746.      right.  */
  1747.   for (i = 0; i < names_count; i++)
  1748.     {
  1749.       mach_port_t local_name;
  1750.       mach_msg_type_name_t local_type;

  1751.       /* We just need to know the corresponding name in gdb name space.
  1752.          So extract and deallocate the right.  */
  1753.       kret = mach_port_extract_right (inf->private->task, names[i],
  1754.                                       MACH_MSG_TYPE_COPY_SEND,
  1755.                                       &local_name, &local_type);
  1756.       if (kret != KERN_SUCCESS)
  1757.         continue;
  1758.       mach_port_deallocate (gdb_task, local_name);

  1759.       for (k = 0;
  1760.            VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
  1761.            k++)
  1762.         if (t->gdb_port == local_name)
  1763.           {
  1764.             t->inf_port = names[i];
  1765.             if (names[i] == lwp)
  1766.               res = t->gdb_port;
  1767.           }
  1768.     }

  1769.   vm_deallocate (gdb_task, (vm_address_t) names,
  1770.                  names_count * sizeof (mach_port_t));

  1771.   if (res)
  1772.     return ptid_build (ptid_get_pid (inferior_ptid), 0, res);
  1773.   else
  1774.     return null_ptid;
  1775. }

  1776. static int
  1777. darwin_supports_multi_process (struct target_ops *self)
  1778. {
  1779.   return 1;
  1780. }

  1781. /* -Wmissing-prototypes */
  1782. extern initialize_file_ftype _initialize_darwin_inferior;

  1783. void
  1784. _initialize_darwin_inferior (void)
  1785. {
  1786.   kern_return_t kret;

  1787.   gdb_task = mach_task_self ();
  1788.   darwin_host_self = mach_host_self ();

  1789.   /* Read page size.  */
  1790.   kret = host_page_size (darwin_host_self, &mach_page_size);
  1791.   if (kret != KERN_SUCCESS)
  1792.     {
  1793.       mach_page_size = 0x1000;
  1794.       MACH_CHECK_ERROR (kret);
  1795.     }

  1796.   darwin_ops = inf_child_target ();

  1797.   darwin_ops->to_create_inferior = darwin_create_inferior;
  1798.   darwin_ops->to_attach = darwin_attach;
  1799.   darwin_ops->to_attach_no_wait = 0;
  1800.   darwin_ops->to_detach = darwin_detach;
  1801.   darwin_ops->to_files_info = darwin_files_info;
  1802.   darwin_ops->to_wait = darwin_wait_to;
  1803.   darwin_ops->to_mourn_inferior = darwin_mourn_inferior;
  1804.   darwin_ops->to_kill = darwin_kill_inferior;
  1805.   darwin_ops->to_stop = darwin_stop;
  1806.   darwin_ops->to_resume = darwin_resume_to;
  1807.   darwin_ops->to_thread_alive = darwin_thread_alive;
  1808.   darwin_ops->to_pid_to_str = darwin_pid_to_str;
  1809.   darwin_ops->to_pid_to_exec_file = darwin_pid_to_exec_file;
  1810.   darwin_ops->to_load = NULL;
  1811.   darwin_ops->to_xfer_partial = darwin_xfer_partial;
  1812.   darwin_ops->to_supports_multi_process = darwin_supports_multi_process;
  1813.   darwin_ops->to_get_ada_task_ptid = darwin_get_ada_task_ptid;

  1814.   darwin_complete_target (darwin_ops);

  1815.   add_target (darwin_ops);

  1816.   inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"), mach_task_self (),
  1817.                   getpid ());

  1818.   add_setshow_zuinteger_cmd ("darwin", class_obscure,
  1819.                              &darwin_debug_flag, _("\
  1820. Set if printing inferior communication debugging statements."), _("\
  1821. Show if printing inferior communication debugging statements."), NULL,
  1822.                              NULL, NULL,
  1823.                              &setdebuglist, &showdebuglist);

  1824.   add_setshow_boolean_cmd ("mach-exceptions", class_support,
  1825.                            &enable_mach_exceptions, _("\
  1826. Set if mach exceptions are caught."), _("\
  1827. Show if mach exceptions are caught."), _("\
  1828. When this mode is on, all low level exceptions are reported before being\n\
  1829. reported by the kernel."),
  1830.                            &set_enable_mach_exceptions, NULL,
  1831.                            &setlist, &showlist);
  1832. }