Rename common to gdbsupport
[external/binutils.git] / gdb / darwin-nat.c
1 /* Darwin support for GDB, the GNU debugger.
2    Copyright (C) 2008-2019 Free Software Foundation, Inc.
3
4    Contributed by AdaCore.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "top.h"
23 #include "inferior.h"
24 #include "target.h"
25 #include "symfile.h"
26 #include "symtab.h"
27 #include "objfiles.h"
28 #include "gdbcmd.h"
29 #include "gdbcore.h"
30 #include "gdbthread.h"
31 #include "regcache.h"
32 #include "event-top.h"
33 #include "inf-loop.h"
34 #include <sys/stat.h>
35 #include "inf-child.h"
36 #include "value.h"
37 #include "arch-utils.h"
38 #include "bfd.h"
39 #include "bfd/mach-o.h"
40
41 #include <copyfile.h>
42 #include <sys/ptrace.h>
43 #include <sys/signal.h>
44 #include <setjmp.h>
45 #include <sys/types.h>
46 #include <unistd.h>
47 #include <signal.h>
48 #include <ctype.h>
49 #include <sys/sysctl.h>
50 #include <sys/proc.h>
51 #include <libproc.h>
52 #include <sys/syscall.h>
53 #include <spawn.h>
54
55 #include <mach/mach_error.h>
56 #include <mach/mach_vm.h>
57 #include <mach/mach_init.h>
58 #include <mach/vm_map.h>
59 #include <mach/task.h>
60 #include <mach/mach_port.h>
61 #include <mach/thread_act.h>
62 #include <mach/port.h>
63
64 #include "darwin-nat.h"
65 #include "filenames.h"
66 #include "gdbsupport/filestuff.h"
67 #include "gdbsupport/gdb_unlinker.h"
68 #include "gdbsupport/pathstuff.h"
69 #include "gdbsupport/scoped_fd.h"
70 #include "nat/fork-inferior.h"
71
72 /* Quick overview.
73    Darwin kernel is Mach + BSD derived kernel.  Note that they share the
74    same memory space and are linked together (ie there is no micro-kernel).
75
76    Although ptrace(2) is available on Darwin, it is not complete.  We have
77    to use Mach calls to read and write memory and to modify registers.  We
78    also use Mach to get inferior faults.  As we cannot use select(2) or
79    signals with Mach port (the Mach communication channel), signals are
80    reported to gdb as an exception.  Furthermore we detect death of the
81    inferior through a Mach notification message.  This way we only wait
82    on Mach ports.
83
84    Some Mach documentation is available for Apple xnu source package or
85    from the web.  */
86
87
88 #define PTRACE(CMD, PID, ADDR, SIG) \
89  darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))
90
91 static ptid_t darwin_wait (ptid_t ptid, struct target_waitstatus *status);
92
93 static void darwin_ptrace_me (void);
94
95 static void darwin_ptrace_him (int pid);
96
97 static void darwin_encode_reply (mig_reply_error_t *reply,
98                                  mach_msg_header_t *hdr, integer_t code);
99
100 static void darwin_setup_request_notification (struct inferior *inf);
101 static void darwin_deallocate_exception_ports (darwin_inferior *inf);
102 static void darwin_setup_exceptions (struct inferior *inf);
103 static void darwin_deallocate_threads (struct inferior *inf);
104
105 /* Task identifier of gdb.  */
106 static task_t gdb_task;
107
108 /* A copy of mach_host_self ().  */
109 mach_port_t darwin_host_self;
110
111 /* Exception port.  */
112 mach_port_t darwin_ex_port;
113
114 /* Port set, to wait for answer on all ports.  */
115 mach_port_t darwin_port_set;
116
117 /* Page size.  */
118 static vm_size_t mach_page_size;
119
120 /* If Set, catch all mach exceptions (before they are converted to signals
121    by the kernel).  */
122 static int enable_mach_exceptions;
123
124 /* Inferior that should report a fake stop event.  */
125 static struct inferior *darwin_inf_fake_stop;
126
127 /* If non-NULL, the shell we actually invoke.  See maybe_cache_shell
128    for details.  */
129 static const char *copied_shell;
130
131 #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
132 #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
133
134 /* This controls output of inferior debugging.  */
135 static unsigned int darwin_debug_flag = 0;
136
137 /* Create a __TEXT __info_plist section in the executable so that gdb could
138    be signed.  This is required to get an authorization for task_for_pid.
139
140    Once gdb is built, you must codesign it with any system-trusted signing
141    authority.  See taskgated(8) for details.  */
142 static const unsigned char info_plist[]
143 __attribute__ ((section ("__TEXT,__info_plist"),used)) =
144   "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
145   "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
146   " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
147   "<plist version=\"1.0\">\n"
148   "<dict>\n"
149   "  <key>CFBundleIdentifier</key>\n"
150   "  <string>org.gnu.gdb</string>\n"
151   "  <key>CFBundleName</key>\n"
152   "  <string>gdb</string>\n"
153   "  <key>CFBundleVersion</key>\n"
154   "  <string>1.0</string>\n"
155   "  <key>SecTaskAccess</key>\n"
156   "  <array>\n"
157   "    <string>allowed</string>\n"
158   "    <string>debug</string>\n"
159   "  </array>\n"
160   "</dict>\n"
161   "</plist>\n";
162
163 static void inferior_debug (int level, const char *fmt, ...)
164   ATTRIBUTE_PRINTF (2, 3);
165
166 static void
167 inferior_debug (int level, const char *fmt, ...)
168 {
169   va_list ap;
170
171   if (darwin_debug_flag < level)
172     return;
173
174   va_start (ap, fmt);
175   printf_unfiltered (_("[%d inferior]: "), getpid ());
176   vprintf_unfiltered (fmt, ap);
177   va_end (ap);
178 }
179
180 void
181 mach_check_error (kern_return_t ret, const char *file,
182                   unsigned int line, const char *func)
183 {
184   if (ret == KERN_SUCCESS)
185     return;
186   if (func == NULL)
187     func = _("[UNKNOWN]");
188
189   warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)"),
190            file, line, func, mach_error_string (ret), (unsigned long) ret);
191 }
192
193 static const char *
194 unparse_exception_type (unsigned int i)
195 {
196   static char unknown_exception_buf[32];
197
198   switch (i)
199     {
200     case EXC_BAD_ACCESS:
201       return "EXC_BAD_ACCESS";
202     case EXC_BAD_INSTRUCTION:
203       return "EXC_BAD_INSTRUCTION";
204     case EXC_ARITHMETIC:
205       return "EXC_ARITHMETIC";
206     case EXC_EMULATION:
207       return "EXC_EMULATION";
208     case EXC_SOFTWARE:
209       return "EXC_SOFTWARE";
210     case EXC_BREAKPOINT:
211       return "EXC_BREAKPOINT";
212     case EXC_SYSCALL:
213       return "EXC_SYSCALL";
214     case EXC_MACH_SYSCALL:
215       return "EXC_MACH_SYSCALL";
216     case EXC_RPC_ALERT:
217       return "EXC_RPC_ALERT";
218     case EXC_CRASH:
219       return "EXC_CRASH";
220     default:
221       snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
222       return unknown_exception_buf;
223     }
224 }
225
226 /* Set errno to zero, and then call ptrace with the given arguments.
227    If inferior debugging traces are on, then also print a debug
228    trace.
229
230    The returned value is the same as the value returned by ptrace,
231    except in the case where that value is -1 but errno is zero.
232    This case is documented to be a non-error situation, so we
233    return zero in that case. */
234
235 static int
236 darwin_ptrace (const char *name,
237                int request, int pid, caddr_t arg3, int arg4)
238 {
239   int ret;
240
241   errno = 0;
242   ret = ptrace (request, pid, arg3, arg4);
243   if (ret == -1 && errno == 0)
244     ret = 0;
245
246   inferior_debug (4, _("ptrace (%s, %d, 0x%lx, %d): %d (%s)\n"),
247                   name, pid, (unsigned long) arg3, arg4, ret,
248                   (ret != 0) ? safe_strerror (errno) : _("no error"));
249   return ret;
250 }
251
252 static int
253 cmp_thread_t (const void *l, const void *r)
254 {
255   thread_t tl = *(const thread_t *)l;
256   thread_t tr = *(const thread_t *)r;
257   return (int)(tl - tr);
258 }
259
260 static void
261 darwin_check_new_threads (struct inferior *inf)
262 {
263   kern_return_t kret;
264   thread_array_t thread_list;
265   unsigned int new_nbr;
266   unsigned int old_nbr;
267   unsigned int new_ix, old_ix;
268   darwin_inferior *darwin_inf = get_darwin_inferior (inf);
269   std::vector<darwin_thread_t *> new_thread_vec;
270
271   if (darwin_inf == nullptr)
272     return;
273
274   /* Get list of threads.  */
275   kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
276   MACH_CHECK_ERROR (kret);
277   if (kret != KERN_SUCCESS)
278     return;
279
280   /* Sort the list.  */
281   if (new_nbr > 1)
282     qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
283
284   old_nbr = darwin_inf->threads.size ();
285
286   /* Quick check for no changes.  */
287   if (old_nbr == new_nbr)
288     {
289       size_t i;
290
291       for (i = 0; i < new_nbr; i++)
292         if (thread_list[i] != darwin_inf->threads[i]->gdb_port)
293           break;
294       if (i == new_nbr)
295         {
296           /* Deallocate ports.  */
297           for (i = 0; i < new_nbr; i++)
298             {
299               kret = mach_port_deallocate (mach_task_self (), thread_list[i]);
300               MACH_CHECK_ERROR (kret);
301             }
302
303           /* Deallocate the buffer.  */
304           kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
305                                 new_nbr * sizeof (int));
306           MACH_CHECK_ERROR (kret);
307
308           return;
309         }
310     }
311
312   /* Full handling: detect new threads, remove dead threads.  */
313
314   new_thread_vec.reserve (new_nbr);
315
316   for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
317     {
318       thread_t new_id = (new_ix < new_nbr) ? thread_list[new_ix] : THREAD_NULL;
319       darwin_thread_t *old
320         = (old_ix < old_nbr) ? darwin_inf->threads[old_ix] : NULL;
321       thread_t old_id = old != NULL ? old->gdb_port : THREAD_NULL;
322
323       inferior_debug
324         (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:0x%x old_id:0x%x\n"),
325          new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);
326
327       if (old_id == new_id)
328         {
329           /* Thread still exist.  */
330           new_thread_vec.push_back (old);
331           new_ix++;
332           old_ix++;
333
334           /* Deallocate the port.  */
335           kret = mach_port_deallocate (gdb_task, new_id);
336           MACH_CHECK_ERROR (kret);
337
338           continue;
339         }
340       if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
341         {
342           /* Ignore dead ports.
343              In some weird cases, we might get dead ports.  They should
344              correspond to dead thread so they could safely be ignored.  */
345           new_ix++;
346           continue;
347         }
348       if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
349         {
350           /* A thread was created.  */
351           darwin_thread_info *pti = new darwin_thread_info;
352
353           pti->gdb_port = new_id;
354           pti->msg_state = DARWIN_RUNNING;
355
356           /* Add the new thread.  */
357           add_thread_with_info (ptid_t (inf->pid, 0, new_id), pti);
358           new_thread_vec.push_back (pti);
359           new_ix++;
360           continue;
361         }
362       if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
363         {
364           /* A thread was removed.  */
365           struct thread_info *thr
366             = find_thread_ptid (ptid_t (inf->pid, 0, old_id));
367           delete_thread (thr);
368           kret = mach_port_deallocate (gdb_task, old_id);
369           MACH_CHECK_ERROR (kret);
370           old_ix++;
371           continue;
372         }
373       gdb_assert_not_reached ("unexpected thread case");
374     }
375
376   darwin_inf->threads = std::move (new_thread_vec);
377
378   /* Deallocate the buffer.  */
379   kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
380                         new_nbr * sizeof (int));
381   MACH_CHECK_ERROR (kret);
382 }
383
384 static int
385 find_inferior_task_it (struct inferior *inf, void *port_ptr)
386 {
387   darwin_inferior *priv = get_darwin_inferior (inf);
388
389   return priv != nullptr && priv->task == *(task_t *)port_ptr;
390 }
391
392 static int
393 find_inferior_pid_it (struct inferior *inf, void *pid_ptr)
394 {
395   return inf->pid == *(int *)pid_ptr;
396 }
397
398 /* Return an inferior by task port.  */
399 static struct inferior *
400 darwin_find_inferior_by_task (task_t port)
401 {
402   return iterate_over_inferiors (&find_inferior_task_it, &port);
403 }
404
405 /* Return an inferior by pid port.  */
406 static struct inferior *
407 darwin_find_inferior_by_pid (int pid)
408 {
409   return iterate_over_inferiors (&find_inferior_pid_it, &pid);
410 }
411
412 /* Return a thread by port.  */
413 static darwin_thread_t *
414 darwin_find_thread (struct inferior *inf, thread_t thread)
415 {
416   darwin_inferior *priv = get_darwin_inferior (inf);
417
418   if (priv != nullptr)
419     for (darwin_thread_t *t : priv->threads)
420       {
421         if (t->gdb_port == thread)
422           return t;
423       }
424
425   return NULL;
426 }
427
428 /* Suspend (ie stop) an inferior at Mach level.  */
429
430 static void
431 darwin_suspend_inferior (struct inferior *inf)
432 {
433   darwin_inferior *priv = get_darwin_inferior (inf);
434
435   if (priv != nullptr && !priv->suspended)
436     {
437       kern_return_t kret;
438
439       kret = task_suspend (priv->task);
440       MACH_CHECK_ERROR (kret);
441
442       priv->suspended = 1;
443     }
444 }
445
446 /* Resume an inferior at Mach level.  */
447
448 static void
449 darwin_resume_inferior (struct inferior *inf)
450 {
451   darwin_inferior *priv = get_darwin_inferior (inf);
452
453   if (priv != nullptr && priv->suspended)
454     {
455       kern_return_t kret;
456
457       kret = task_resume (priv->task);
458       MACH_CHECK_ERROR (kret);
459
460       priv->suspended = 0;
461     }
462 }
463
464 /* Iterator functions.  */
465
466 static int
467 darwin_suspend_inferior_it (struct inferior *inf, void *arg)
468 {
469   darwin_suspend_inferior (inf);
470   darwin_check_new_threads (inf);
471   return 0;
472 }
473
474 static int
475 darwin_resume_inferior_it (struct inferior *inf, void *arg)
476 {
477   darwin_resume_inferior (inf);
478   return 0;
479 }
480
481 static void
482 darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
483 {
484   printf_unfiltered (_("message header:\n"));
485   printf_unfiltered (_(" bits: 0x%x\n"), hdr->msgh_bits);
486   printf_unfiltered (_(" size: 0x%x\n"), hdr->msgh_size);
487   printf_unfiltered (_(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
488   printf_unfiltered (_(" local-port: 0x%x\n"), hdr->msgh_local_port);
489   printf_unfiltered (_(" reserved: 0x%x\n"), hdr->msgh_reserved);
490   printf_unfiltered (_(" id: 0x%x\n"), hdr->msgh_id);
491
492   if (disp_body)
493     {
494       const unsigned char *data;
495       const unsigned int *ldata;
496       int size;
497       int i;
498
499       data = (unsigned char *)(hdr + 1);
500       size = hdr->msgh_size - sizeof (mach_msg_header_t);
501
502       if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
503         {
504           mach_msg_body_t *bod = (mach_msg_body_t*)data;
505           mach_msg_port_descriptor_t *desc =
506             (mach_msg_port_descriptor_t *)(bod + 1);
507           int k;
508           NDR_record_t *ndr;
509           printf_unfiltered (_("body: descriptor_count=%u\n"),
510                              bod->msgh_descriptor_count);
511           data += sizeof (mach_msg_body_t);
512           size -= sizeof (mach_msg_body_t);
513           for (k = 0; k < bod->msgh_descriptor_count; k++)
514             switch (desc[k].type)
515               {
516               case MACH_MSG_PORT_DESCRIPTOR:
517                 printf_unfiltered
518                   (_(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
519                    k, desc[k].type, desc[k].name, desc[k].disposition);
520                 break;
521               default:
522                 printf_unfiltered (_(" descr %d: type=%u\n"),
523                                    k, desc[k].type);
524                 break;
525               }
526           data += bod->msgh_descriptor_count
527             * sizeof (mach_msg_port_descriptor_t);
528           size -= bod->msgh_descriptor_count
529             * sizeof (mach_msg_port_descriptor_t);
530           ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
531           printf_unfiltered
532             (_("NDR: mig=%02x if=%02x encod=%02x "
533                "int=%02x char=%02x float=%02x\n"),
534              ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
535              ndr->int_rep, ndr->char_rep, ndr->float_rep);
536           data += sizeof (NDR_record_t);
537           size -= sizeof (NDR_record_t);
538         }
539
540       printf_unfiltered (_("  data:"));
541       ldata = (const unsigned int *)data;
542       for (i = 0; i < size / sizeof (unsigned int); i++)
543         printf_unfiltered (" %08x", ldata[i]);
544       printf_unfiltered (_("\n"));
545     }
546 }
547
548 /* Adjust inferior data when a new task was created.  */
549
550 static struct inferior *
551 darwin_find_new_inferior (task_t task_port, thread_t thread_port)
552 {
553   int task_pid;
554   struct inferior *inf;
555   kern_return_t kret;
556   mach_port_t prev;
557
558   /* Find the corresponding pid.  */
559   kret = pid_for_task (task_port, &task_pid);
560   if (kret != KERN_SUCCESS)
561     {
562       MACH_CHECK_ERROR (kret);
563       return NULL;
564     }
565
566   /* Find the inferior for this pid.  */
567   inf = darwin_find_inferior_by_pid (task_pid);
568   if (inf == NULL)
569     return NULL;
570
571   darwin_inferior *priv = get_darwin_inferior (inf);
572
573   /* Deallocate saved exception ports.  */
574   darwin_deallocate_exception_ports (priv);
575
576   /* No need to remove dead_name notification, but still...  */
577   kret = mach_port_request_notification (gdb_task, priv->task,
578                                          MACH_NOTIFY_DEAD_NAME, 0,
579                                          MACH_PORT_NULL,
580                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
581                                          &prev);
582   if (kret != KERN_INVALID_ARGUMENT)
583     MACH_CHECK_ERROR (kret);
584
585   /* Replace old task port.  */
586   kret = mach_port_deallocate (gdb_task, priv->task);
587   MACH_CHECK_ERROR (kret);
588   priv->task = task_port;
589
590   darwin_setup_request_notification (inf);
591   darwin_setup_exceptions (inf);
592
593   return inf;
594 }
595
596 /* Check data representation.  */
597
598 static int
599 darwin_check_message_ndr (NDR_record_t *ndr)
600 {
601   if (ndr->mig_vers != NDR_PROTOCOL_2_0
602       || ndr->if_vers != NDR_PROTOCOL_2_0
603       || ndr->mig_encoding != NDR_record.mig_encoding
604       || ndr->int_rep != NDR_record.int_rep
605       || ndr->char_rep != NDR_record.char_rep
606       || ndr->float_rep != NDR_record.float_rep)
607     return -1;
608   return 0;
609 }
610
611 /* Decode an exception message.  */
612
613 static int
614 darwin_decode_exception_message (mach_msg_header_t *hdr,
615                                  struct inferior **pinf,
616                                  darwin_thread_t **pthread)
617 {
618   mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
619   mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
620   NDR_record_t *ndr;
621   integer_t *data;
622   struct inferior *inf;
623   darwin_thread_t *thread;
624   task_t task_port;
625   thread_t thread_port;
626   kern_return_t kret;
627   int i;
628
629   /* Check message destination.  */
630   if (hdr->msgh_local_port != darwin_ex_port)
631     return -1;
632
633   /* Check message header.  */
634   if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
635     return -1;
636
637   /* Check descriptors.  */
638   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
639                         + sizeof (*ndr) + 2 * sizeof (integer_t))
640       || bod->msgh_descriptor_count != 2
641       || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
642       || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
643       || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
644       || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
645     return -1;
646
647   /* Check data representation.  */
648   ndr = (NDR_record_t *)(desc + 2);
649   if (darwin_check_message_ndr (ndr) != 0)
650     return -1;
651
652   /* Ok, the hard work.  */
653   data = (integer_t *)(ndr + 1);
654
655   task_port = desc[1].name;
656   thread_port = desc[0].name;
657
658   /* Find process by port.  */
659   inf = darwin_find_inferior_by_task (task_port);
660   *pinf = inf;
661
662   if (inf == NULL && data[0] == EXC_SOFTWARE && data[1] == 2
663       && data[2] == EXC_SOFT_SIGNAL && data[3] == SIGTRAP)
664     {
665       /* Not a known inferior, but a sigtrap.  This happens on darwin 16.1.0,
666          as a new Mach task is created when a process exec.  */
667       inf = darwin_find_new_inferior (task_port, thread_port);
668       *pinf = inf;
669
670       if (inf == NULL)
671         {
672           /* Deallocate task_port, unless it was saved.  */
673           kret = mach_port_deallocate (mach_task_self (), task_port);
674           MACH_CHECK_ERROR (kret);
675         }
676     }
677   else
678     {
679       /* We got new rights to the task, get rid of it.  Do not get rid of
680          thread right, as we will need it to find the thread.  */
681       kret = mach_port_deallocate (mach_task_self (), task_port);
682       MACH_CHECK_ERROR (kret);
683     }
684
685   if (inf == NULL)
686     {
687       /* Not a known inferior.  This could happen if the child fork, as
688          the created process will inherit its exception port.
689          FIXME: should the exception port be restored ?  */
690       mig_reply_error_t reply;
691
692       inferior_debug
693         (4, _("darwin_decode_exception_message: unknown task 0x%x\n"),
694          task_port);
695
696       /* Free thread port (we don't know it).  */
697       kret = mach_port_deallocate (mach_task_self (), thread_port);
698       MACH_CHECK_ERROR (kret);
699
700       darwin_encode_reply (&reply, hdr, KERN_SUCCESS);
701
702       kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
703                        reply.Head.msgh_size, 0,
704                        MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
705                        MACH_PORT_NULL);
706       MACH_CHECK_ERROR (kret);
707
708       return 0;
709     }
710
711   /* Find thread by port.  */
712   /* Check for new threads.  Do it early so that the port in the exception
713      message can be deallocated.  */
714   darwin_check_new_threads (inf);
715
716   /* Free the thread port (as gdb knows the thread, it has already has a right
717      for it, so this just decrement a reference counter).  */
718   kret = mach_port_deallocate (mach_task_self (), thread_port);
719   MACH_CHECK_ERROR (kret);
720
721   thread = darwin_find_thread (inf, thread_port);
722   if (thread == NULL)
723     return -1;
724   *pthread = thread;
725
726   /* The thread should be running.  However we have observed cases where a
727      thread got a SIGTTIN message after being stopped.  */
728   gdb_assert (thread->msg_state != DARWIN_MESSAGE);
729
730   /* Finish decoding.  */
731   thread->event.header = *hdr;
732   thread->event.thread_port = thread_port;
733   thread->event.task_port = task_port;
734   thread->event.ex_type = data[0];
735   thread->event.data_count = data[1];
736
737   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
738                         + sizeof (*ndr) + 2 * sizeof (integer_t)
739                         + data[1] * sizeof (integer_t)))
740       return -1;
741   for (i = 0; i < data[1]; i++)
742     thread->event.ex_data[i] = data[2 + i];
743
744   thread->msg_state = DARWIN_MESSAGE;
745
746   return 0;
747 }
748
749 /* Decode dead_name notify message.  */
750
751 static int
752 darwin_decode_notify_message (mach_msg_header_t *hdr, struct inferior **pinf)
753 {
754   NDR_record_t *ndr = (NDR_record_t *)(hdr + 1);
755   integer_t *data = (integer_t *)(ndr + 1);
756   struct inferior *inf;
757   task_t task_port;
758
759   /* Check message header.  */
760   if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
761     return -1;
762
763   /* Check descriptors.  */
764   if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*ndr) + sizeof (integer_t)))
765     return -2;
766
767   /* Check data representation.  */
768   if (darwin_check_message_ndr (ndr) != 0)
769     return -3;
770
771   task_port = data[0];
772
773   /* Find process by port.  */
774   inf = darwin_find_inferior_by_task (task_port);
775   *pinf = inf;
776
777   /* Check message destination.  */
778   if (inf != NULL)
779     {
780       darwin_inferior *priv = get_darwin_inferior (inf);
781       if (hdr->msgh_local_port != priv->notify_port)
782         return -4;
783     }
784
785   return 0;
786 }
787
788 static void
789 darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
790                      integer_t code)
791 {
792   mach_msg_header_t *rh = &reply->Head;
793
794   rh->msgh_bits = MACH_MSGH_BITS (MACH_MSGH_BITS_REMOTE (hdr->msgh_bits), 0);
795   rh->msgh_remote_port = hdr->msgh_remote_port;
796   rh->msgh_size = (mach_msg_size_t) sizeof (mig_reply_error_t);
797   rh->msgh_local_port = MACH_PORT_NULL;
798   rh->msgh_id = hdr->msgh_id + 100;
799
800   reply->NDR = NDR_record;
801   reply->RetCode = code;
802 }
803
804 static void
805 darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
806 {
807   kern_return_t kret;
808   mig_reply_error_t reply;
809   darwin_inferior *priv = get_darwin_inferior (inf);
810
811   darwin_encode_reply (&reply, &thread->event.header, KERN_SUCCESS);
812
813   kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
814                    reply.Head.msgh_size, 0,
815                    MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
816                    MACH_PORT_NULL);
817   MACH_CHECK_ERROR (kret);
818
819   priv->pending_messages--;
820 }
821
822 /* Wrapper around the __pthread_kill syscall.  We use this instead of the
823    pthread_kill function to be able to send a signal to any kind of thread,
824    including GCD threads.  */
825
826 static int
827 darwin_pthread_kill (darwin_thread_t *thread, int nsignal)
828 {
829   DIAGNOSTIC_PUSH;
830   DIAGNOSTIC_IGNORE_DEPRECATED_DECLARATIONS;
831   int res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
832   DIAGNOSTIC_POP;
833   return res;
834 }
835
836 static void
837 darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
838                       int step, int nsignal)
839 {
840   inferior_debug
841     (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
842      thread->msg_state, thread->gdb_port, step, nsignal);
843
844   switch (thread->msg_state)
845     {
846     case DARWIN_MESSAGE:
847       if (thread->event.ex_type == EXC_SOFTWARE
848           && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
849         {
850           /* Either deliver a new signal or cancel the signal received.  */
851           int res = PTRACE (PT_THUPDATE, inf->pid,
852                             (caddr_t) (uintptr_t) thread->gdb_port, nsignal);
853           if (res < 0)
854             inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
855         }
856       else if (nsignal)
857         {
858           /* Note: ptrace is allowed only if the process is stopped.
859              Directly send the signal to the thread.  */
860           int res = darwin_pthread_kill (thread, nsignal);
861           inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
862                           thread->gdb_port, nsignal, res);
863           thread->signaled = 1;
864         }
865
866       /* Set or reset single step.  */
867       inferior_debug (4, _("darwin_set_sstep (thread=0x%x, enable=%d)\n"),
868                       thread->gdb_port, step);
869       darwin_set_sstep (thread->gdb_port, step);
870       thread->single_step = step;
871
872       darwin_send_reply (inf, thread);
873       thread->msg_state = DARWIN_RUNNING;
874       break;
875
876     case DARWIN_RUNNING:
877       break;
878
879     case DARWIN_STOPPED:
880       kern_return_t kret = thread_resume (thread->gdb_port);
881       MACH_CHECK_ERROR (kret);
882
883       thread->msg_state = DARWIN_RUNNING;
884       break;
885     }
886 }
887
888 /* Resume all threads of the inferior.  */
889
890 static void
891 darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
892 {
893   darwin_inferior *priv = get_darwin_inferior (inf);
894
895   if (priv != nullptr)
896     for (darwin_thread_t *thread : priv->threads)
897       darwin_resume_thread (inf, thread, step, nsignal);
898 }
899
900 struct resume_inferior_threads_param
901 {
902   int step;
903   int nsignal;
904 };
905
906 static int
907 darwin_resume_inferior_threads_it (struct inferior *inf, void *param)
908 {
909   int step = ((struct resume_inferior_threads_param *)param)->step;
910   int nsignal = ((struct resume_inferior_threads_param *)param)->nsignal;
911
912   darwin_resume_inferior_threads (inf, step, nsignal);
913
914   return 0;
915 }
916
917 /* Suspend all threads of INF.  */
918
919 static void
920 darwin_suspend_inferior_threads (struct inferior *inf)
921 {
922   darwin_inferior *priv = get_darwin_inferior (inf);
923
924   for (darwin_thread_t *thread : priv->threads)
925     {
926       switch (thread->msg_state)
927         {
928         case DARWIN_STOPPED:
929         case DARWIN_MESSAGE:
930           break;
931         case DARWIN_RUNNING:
932           {
933             kern_return_t kret = thread_suspend (thread->gdb_port);
934             MACH_CHECK_ERROR (kret);
935             thread->msg_state = DARWIN_STOPPED;
936             break;
937           }
938         }
939     }
940 }
941
942 void
943 darwin_nat_target::resume (ptid_t ptid, int step, enum gdb_signal signal)
944 {
945   struct target_waitstatus status;
946
947   int nsignal;
948
949   inferior_debug
950     (2, _("darwin_resume: pid=%d, tid=0x%lx, step=%d, signal=%d\n"),
951      ptid.pid (), ptid.tid (), step, signal);
952
953   if (signal == GDB_SIGNAL_0)
954     nsignal = 0;
955   else
956     nsignal = gdb_signal_to_host (signal);
957
958   /* Don't try to single step all threads.  */
959   if (step)
960     ptid = inferior_ptid;
961
962   /* minus_one_ptid is RESUME_ALL.  */
963   if (ptid == minus_one_ptid)
964     {
965       struct resume_inferior_threads_param param;
966
967       param.nsignal = nsignal;
968       param.step = step;
969
970       /* Resume threads.  */
971       iterate_over_inferiors (darwin_resume_inferior_threads_it, &param);
972       /* Resume tasks.  */
973       iterate_over_inferiors (darwin_resume_inferior_it, NULL);
974     }
975   else
976     {
977       struct inferior *inf = find_inferior_ptid (ptid);
978       long tid = ptid.tid ();
979
980       /* Stop the inferior (should be useless).  */
981       darwin_suspend_inferior (inf);
982
983       if (tid == 0)
984         darwin_resume_inferior_threads (inf, step, nsignal);
985       else
986         {
987           darwin_thread_t *thread;
988
989           /* Suspend threads of the task.  */
990           darwin_suspend_inferior_threads (inf);
991
992           /* Resume the selected thread.  */
993           thread = darwin_find_thread (inf, tid);
994           gdb_assert (thread);
995           darwin_resume_thread (inf, thread, step, nsignal);
996         }
997
998       /* Resume the task.  */
999       darwin_resume_inferior (inf);
1000     }
1001 }
1002
1003 static ptid_t
1004 darwin_decode_message (mach_msg_header_t *hdr,
1005                        darwin_thread_t **pthread,
1006                        struct inferior **pinf,
1007                        struct target_waitstatus *status)
1008 {
1009   darwin_thread_t *thread;
1010   struct inferior *inf;
1011
1012   /* Exception message.  2401 == 0x961 is exc.  */
1013   if (hdr->msgh_id == 2401)
1014     {
1015       int res;
1016
1017       /* Decode message.  */
1018       res = darwin_decode_exception_message (hdr, &inf, &thread);
1019
1020       if (res < 0)
1021         {
1022           /* Should not happen...  */
1023           printf_unfiltered
1024             (_("darwin_wait: ill-formatted message (id=0x%x)\n"), hdr->msgh_id);
1025           /* FIXME: send a failure reply?  */
1026           status->kind = TARGET_WAITKIND_IGNORE;
1027           return minus_one_ptid;
1028         }
1029       if (inf == NULL)
1030         {
1031           status->kind = TARGET_WAITKIND_IGNORE;
1032           return minus_one_ptid;
1033         }
1034       *pinf = inf;
1035       *pthread = thread;
1036
1037       darwin_inferior *priv = get_darwin_inferior (inf);
1038
1039       priv->pending_messages++;
1040
1041       status->kind = TARGET_WAITKIND_STOPPED;
1042       thread->msg_state = DARWIN_MESSAGE;
1043
1044       inferior_debug (4, _("darwin_wait: thread=0x%x, got %s\n"),
1045                       thread->gdb_port,
1046                       unparse_exception_type (thread->event.ex_type));
1047
1048       switch (thread->event.ex_type)
1049         {
1050         case EXC_BAD_ACCESS:
1051           status->value.sig = GDB_EXC_BAD_ACCESS;
1052           break;
1053         case EXC_BAD_INSTRUCTION:
1054           status->value.sig = GDB_EXC_BAD_INSTRUCTION;
1055           break;
1056         case EXC_ARITHMETIC:
1057           status->value.sig = GDB_EXC_ARITHMETIC;
1058           break;
1059         case EXC_EMULATION:
1060           status->value.sig = GDB_EXC_EMULATION;
1061           break;
1062         case EXC_SOFTWARE:
1063           if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
1064             {
1065               status->value.sig =
1066                 gdb_signal_from_host (thread->event.ex_data[1]);
1067               inferior_debug (5, _("  (signal %d: %s)\n"),
1068                               thread->event.ex_data[1],
1069                               gdb_signal_to_name (status->value.sig));
1070
1071               /* If the thread is stopped because it has received a signal
1072                  that gdb has just sent, continue.  */
1073               if (thread->signaled)
1074                 {
1075                   thread->signaled = 0;
1076                   darwin_send_reply (inf, thread);
1077                   thread->msg_state = DARWIN_RUNNING;
1078                   status->kind = TARGET_WAITKIND_IGNORE;
1079                 }
1080             }
1081           else
1082             status->value.sig = GDB_EXC_SOFTWARE;
1083           break;
1084         case EXC_BREAKPOINT:
1085           /* Many internal GDB routines expect breakpoints to be reported
1086              as GDB_SIGNAL_TRAP, and will report GDB_EXC_BREAKPOINT
1087              as a spurious signal.  */
1088           status->value.sig = GDB_SIGNAL_TRAP;
1089           break;
1090         default:
1091           status->value.sig = GDB_SIGNAL_UNKNOWN;
1092           break;
1093         }
1094
1095       return ptid_t (inf->pid, 0, thread->gdb_port);
1096     }
1097   else if (hdr->msgh_id == 0x48)
1098     {
1099       /* MACH_NOTIFY_DEAD_NAME: notification for exit.  */
1100       int res;
1101
1102       res = darwin_decode_notify_message (hdr, &inf);
1103
1104       if (res < 0)
1105         {
1106           /* Should not happen...  */
1107           printf_unfiltered
1108             (_("darwin_wait: ill-formatted message (id=0x%x, res=%d)\n"),
1109              hdr->msgh_id, res);
1110         }
1111
1112       *pinf = NULL;
1113       *pthread = NULL;
1114
1115       if (res < 0 || inf == NULL)
1116         {
1117           status->kind = TARGET_WAITKIND_IGNORE;
1118           return minus_one_ptid;
1119         }
1120
1121       if (inf != NULL)
1122         {
1123           darwin_inferior *priv = get_darwin_inferior (inf);
1124
1125           if (!priv->no_ptrace)
1126             {
1127               pid_t res_pid;
1128               int wstatus;
1129
1130               res_pid = wait4 (inf->pid, &wstatus, 0, NULL);
1131               if (res_pid < 0 || res_pid != inf->pid)
1132                 {
1133                   printf_unfiltered (_("wait4: res=%d: %s\n"),
1134                                      res_pid, safe_strerror (errno));
1135                   status->kind = TARGET_WAITKIND_IGNORE;
1136                   return minus_one_ptid;
1137                 }
1138               if (WIFEXITED (wstatus))
1139                 {
1140                   status->kind = TARGET_WAITKIND_EXITED;
1141                   status->value.integer = WEXITSTATUS (wstatus);
1142                 }
1143               else
1144                 {
1145                   status->kind = TARGET_WAITKIND_SIGNALLED;
1146                   status->value.sig = gdb_signal_from_host (WTERMSIG (wstatus));
1147                 }
1148
1149               inferior_debug (4, _("darwin_wait: pid=%d exit, status=0x%x\n"),
1150                               res_pid, wstatus);
1151
1152               /* Looks necessary on Leopard and harmless...  */
1153               wait4 (inf->pid, &wstatus, 0, NULL);
1154
1155               inferior_ptid = ptid_t (inf->pid, 0, 0);
1156               return inferior_ptid;
1157             }
1158           else
1159             {
1160               inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
1161               status->kind = TARGET_WAITKIND_EXITED;
1162               status->value.integer = 0; /* Don't know.  */
1163               return ptid_t (inf->pid, 0, 0);
1164             }
1165         }
1166     }
1167
1168   /* Unknown message.  */
1169   warning (_("darwin: got unknown message, id: 0x%x"), hdr->msgh_id);
1170   status->kind = TARGET_WAITKIND_IGNORE;
1171   return minus_one_ptid;
1172 }
1173
1174 static int
1175 cancel_breakpoint (ptid_t ptid)
1176 {
1177   /* Arrange for a breakpoint to be hit again later.  We will handle
1178      the current event, eventually we will resume this thread, and this
1179      breakpoint will trap again.
1180
1181      If we do not do this, then we run the risk that the user will
1182      delete or disable the breakpoint, but the thread will have already
1183      tripped on it.  */
1184
1185   struct regcache *regcache = get_thread_regcache (ptid);
1186   struct gdbarch *gdbarch = regcache->arch ();
1187   CORE_ADDR pc;
1188
1189   pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
1190   if (breakpoint_inserted_here_p (regcache->aspace (), pc))
1191     {
1192       inferior_debug (4, "cancel_breakpoint for thread 0x%lx\n",
1193                       (unsigned long) ptid.tid ());
1194
1195       /* Back up the PC if necessary.  */
1196       if (gdbarch_decr_pc_after_break (gdbarch))
1197         regcache_write_pc (regcache, pc);
1198
1199       return 1;
1200     }
1201   return 0;
1202 }
1203
1204 static ptid_t
1205 darwin_wait (ptid_t ptid, struct target_waitstatus *status)
1206 {
1207   kern_return_t kret;
1208   union
1209   {
1210     mach_msg_header_t hdr;
1211     char data[0x100];
1212   } msgin;
1213   mach_msg_header_t *hdr = &msgin.hdr;
1214   ptid_t res;
1215   darwin_thread_t *thread;
1216   struct inferior *inf;
1217
1218   inferior_debug
1219     (2, _("darwin_wait: waiting for a message pid=%d thread=%lx\n"),
1220      ptid.pid (), ptid.tid ());
1221
1222   /* Handle fake stop events at first.  */
1223   if (darwin_inf_fake_stop != NULL)
1224     {
1225       inf = darwin_inf_fake_stop;
1226       darwin_inf_fake_stop = NULL;
1227
1228       darwin_inferior *priv = get_darwin_inferior (inf);
1229
1230       status->kind = TARGET_WAITKIND_STOPPED;
1231       status->value.sig = GDB_SIGNAL_TRAP;
1232       thread = priv->threads[0];
1233       thread->msg_state = DARWIN_STOPPED;
1234       return ptid_t (inf->pid, 0, thread->gdb_port);
1235     }
1236
1237   do
1238     {
1239       /* set_sigint_trap (); */
1240
1241       /* Wait for a message.  */
1242       kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
1243                        sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
1244
1245       /* clear_sigint_trap (); */
1246
1247       if (kret == MACH_RCV_INTERRUPTED)
1248         {
1249           status->kind = TARGET_WAITKIND_IGNORE;
1250           return minus_one_ptid;
1251         }
1252
1253       if (kret != MACH_MSG_SUCCESS)
1254         {
1255           inferior_debug (5, _("mach_msg: ret=0x%x\n"), kret);
1256           status->kind = TARGET_WAITKIND_SPURIOUS;
1257           return minus_one_ptid;
1258         }
1259
1260       /* Debug: display message.  */
1261       if (darwin_debug_flag > 10)
1262         darwin_dump_message (hdr, darwin_debug_flag > 11);
1263
1264       res = darwin_decode_message (hdr, &thread, &inf, status);
1265       if (res == minus_one_ptid)
1266         continue;
1267
1268       /* Early return in case an inferior has exited.  */
1269       if (inf == NULL)
1270         return res;
1271     }
1272   while (status->kind == TARGET_WAITKIND_IGNORE);
1273
1274   /* Stop all tasks.  */
1275   iterate_over_inferiors (darwin_suspend_inferior_it, NULL);
1276
1277   /* Read pending messages.  */
1278   while (1)
1279     {
1280       struct target_waitstatus status2;
1281       ptid_t ptid2;
1282
1283       kret = mach_msg (&msgin.hdr,
1284                        MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
1285                        sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);
1286
1287       if (kret == MACH_RCV_TIMED_OUT)
1288         break;
1289       if (kret != MACH_MSG_SUCCESS)
1290         {
1291           inferior_debug
1292             (5, _("darwin_wait: mach_msg(pending) ret=0x%x\n"), kret);
1293           break;
1294         }
1295
1296       /* Debug: display message.  */
1297       if (darwin_debug_flag > 10)
1298         darwin_dump_message (hdr, darwin_debug_flag > 11);
1299
1300       ptid2 = darwin_decode_message (hdr, &thread, &inf, &status2);
1301
1302       if (inf != NULL && thread != NULL
1303           && thread->event.ex_type == EXC_BREAKPOINT)
1304         {
1305           if (thread->single_step
1306               || cancel_breakpoint (ptid_t (inf->pid, 0, thread->gdb_port)))
1307             {
1308               gdb_assert (thread->msg_state == DARWIN_MESSAGE);
1309               darwin_send_reply (inf, thread);
1310               thread->msg_state = DARWIN_RUNNING;
1311             }
1312           else
1313             inferior_debug
1314               (3, _("darwin_wait: thread 0x%x hit a non-gdb breakpoint\n"),
1315                thread->gdb_port);
1316         }
1317       else
1318         inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
1319     }
1320   return res;
1321 }
1322
1323 ptid_t
1324 darwin_nat_target::wait (ptid_t ptid, struct target_waitstatus *status,
1325                          int options)
1326 {
1327   return darwin_wait (ptid, status);
1328 }
1329
1330 void
1331 darwin_nat_target::interrupt ()
1332 {
1333   struct inferior *inf = current_inferior ();
1334   darwin_inferior *priv = get_darwin_inferior (inf);
1335
1336   /* FIXME: handle in no_ptrace mode.  */
1337   gdb_assert (!priv->no_ptrace);
1338   ::kill (inf->pid, SIGINT);
1339 }
1340
1341 /* Deallocate threads port and vector.  */
1342
1343 static void
1344 darwin_deallocate_threads (struct inferior *inf)
1345 {
1346   darwin_inferior *priv = get_darwin_inferior (inf);
1347
1348   for (darwin_thread_t *t : priv->threads)
1349     {
1350       kern_return_t kret = mach_port_deallocate (gdb_task, t->gdb_port);
1351       MACH_CHECK_ERROR (kret);
1352     }
1353
1354   priv->threads.clear ();
1355 }
1356
1357 void
1358 darwin_nat_target::mourn_inferior ()
1359 {
1360   struct inferior *inf = current_inferior ();
1361   darwin_inferior *priv = get_darwin_inferior (inf);
1362   kern_return_t kret;
1363   mach_port_t prev;
1364
1365   /* Deallocate threads.  */
1366   darwin_deallocate_threads (inf);
1367
1368   /* Remove notify_port from darwin_port_set.  */
1369   kret = mach_port_move_member (gdb_task,
1370                                 priv->notify_port, MACH_PORT_NULL);
1371   MACH_CHECK_ERROR (kret);
1372
1373   /* Remove task port dead_name notification.  */
1374   kret = mach_port_request_notification (gdb_task, priv->task,
1375                                          MACH_NOTIFY_DEAD_NAME, 0,
1376                                          MACH_PORT_NULL,
1377                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
1378                                          &prev);
1379   /* This can fail if the task is dead.  */
1380   inferior_debug (4, "task=0x%x, prev=0x%x, notify_port=0x%x\n",
1381                   priv->task, prev, priv->notify_port);
1382
1383   if (kret == KERN_SUCCESS)
1384     {
1385       kret = mach_port_deallocate (gdb_task, prev);
1386       MACH_CHECK_ERROR (kret);
1387     }
1388
1389   /* Destroy notify_port.  */
1390   kret = mach_port_destroy (gdb_task, priv->notify_port);
1391   MACH_CHECK_ERROR (kret);
1392
1393   /* Deallocate saved exception ports.  */
1394   darwin_deallocate_exception_ports (priv);
1395
1396   /* Deallocate task port.  */
1397   kret = mach_port_deallocate (gdb_task, priv->task);
1398   MACH_CHECK_ERROR (kret);
1399
1400   inf->priv = NULL;
1401
1402   inf_child_target::mourn_inferior ();
1403 }
1404
1405 static void
1406 darwin_reply_to_all_pending_messages (struct inferior *inf)
1407 {
1408   darwin_inferior *priv = get_darwin_inferior (inf);
1409
1410   for (darwin_thread_t *t : priv->threads)
1411     {
1412       if (t->msg_state == DARWIN_MESSAGE)
1413         darwin_resume_thread (inf, t, 0, 0);
1414     }
1415 }
1416
1417 static void
1418 darwin_stop_inferior (struct inferior *inf)
1419 {
1420   struct target_waitstatus wstatus;
1421   ptid_t ptid;
1422   int res;
1423   darwin_inferior *priv = get_darwin_inferior (inf);
1424
1425   gdb_assert (inf != NULL);
1426
1427   darwin_suspend_inferior (inf);
1428
1429   darwin_reply_to_all_pending_messages (inf);
1430
1431   if (priv->no_ptrace)
1432     return;
1433
1434   res = kill (inf->pid, SIGSTOP);
1435   if (res != 0)
1436     warning (_("cannot kill: %s"), safe_strerror (errno));
1437
1438   /* Wait until the process is really stopped.  */
1439   while (1)
1440     {
1441       ptid = darwin_wait (inferior_ptid, &wstatus);
1442       if (wstatus.kind == TARGET_WAITKIND_STOPPED
1443           && wstatus.value.sig == GDB_SIGNAL_STOP)
1444         break;
1445     }
1446 }
1447
1448 static kern_return_t
1449 darwin_save_exception_ports (darwin_inferior *inf)
1450 {
1451   kern_return_t kret;
1452
1453   inf->exception_info.count =
1454     sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
1455
1456   kret = task_get_exception_ports
1457     (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
1458      &inf->exception_info.count, inf->exception_info.ports,
1459      inf->exception_info.behaviors, inf->exception_info.flavors);
1460   return kret;
1461 }
1462
1463 static kern_return_t
1464 darwin_restore_exception_ports (darwin_inferior *inf)
1465 {
1466   int i;
1467   kern_return_t kret;
1468
1469   for (i = 0; i < inf->exception_info.count; i++)
1470     {
1471       kret = task_set_exception_ports
1472         (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
1473          inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
1474       if (kret != KERN_SUCCESS)
1475         return kret;
1476     }
1477
1478   return KERN_SUCCESS;
1479 }
1480
1481 /* Deallocate saved exception ports.  */
1482
1483 static void
1484 darwin_deallocate_exception_ports (darwin_inferior *inf)
1485 {
1486   int i;
1487   kern_return_t kret;
1488
1489   for (i = 0; i < inf->exception_info.count; i++)
1490     {
1491       kret = mach_port_deallocate (gdb_task, inf->exception_info.ports[i]);
1492       MACH_CHECK_ERROR (kret);
1493     }
1494   inf->exception_info.count = 0;
1495 }
1496
1497 static void
1498 darwin_setup_exceptions (struct inferior *inf)
1499 {
1500   darwin_inferior *priv = get_darwin_inferior (inf);
1501   kern_return_t kret;
1502   exception_mask_t mask;
1503
1504   kret = darwin_save_exception_ports (priv);
1505   if (kret != KERN_SUCCESS)
1506     error (_("Unable to save exception ports, task_get_exception_ports"
1507              "returned: %d"),
1508            kret);
1509
1510   /* Set exception port.  */
1511   if (enable_mach_exceptions)
1512     mask = EXC_MASK_ALL;
1513   else
1514     mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1515   kret = task_set_exception_ports (priv->task, mask, darwin_ex_port,
1516                                    EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1517   if (kret != KERN_SUCCESS)
1518     error (_("Unable to set exception ports, task_set_exception_ports"
1519              "returned: %d"),
1520            kret);
1521 }
1522
1523 void
1524 darwin_nat_target::kill ()
1525 {
1526   struct inferior *inf = current_inferior ();
1527   darwin_inferior *priv = get_darwin_inferior (inf);
1528   struct target_waitstatus wstatus;
1529   ptid_t ptid;
1530   kern_return_t kret;
1531   int res;
1532
1533   if (inferior_ptid == null_ptid)
1534     return;
1535
1536   gdb_assert (inf != NULL);
1537
1538   kret = darwin_restore_exception_ports (priv);
1539   MACH_CHECK_ERROR (kret);
1540
1541   darwin_reply_to_all_pending_messages (inf);
1542
1543   res = ::kill (inf->pid, 9);
1544
1545   if (res == 0)
1546     {
1547       /* On MacOS version Sierra, the darwin_restore_exception_ports call
1548          does not work as expected.
1549          When the kill function is called, the SIGKILL signal is received
1550          by gdb whereas it should have been received by the kernel since
1551          the exception ports have been restored.
1552          This behavior is not the expected one thus gdb does not reply to
1553          the received SIGKILL message. This situation leads to a "busy"
1554          resource from the kernel point of view and the inferior is never
1555          released, causing it to remain as a zombie process, even after
1556          GDB exits.
1557          To work around this, we mark all the threads of the inferior as
1558          signaled thus darwin_decode_message function knows that the kill
1559          signal was sent by gdb and will take the appropriate action
1560          (cancel signal and reply to the signal message).  */
1561       for (darwin_thread_t *thread : priv->threads)
1562         thread->signaled = 1;
1563
1564       darwin_resume_inferior (inf);
1565
1566       ptid = darwin_wait (inferior_ptid, &wstatus);
1567     }
1568   else if (errno != ESRCH)
1569     warning (_("Failed to kill inferior: kill (%d, 9) returned [%s]"),
1570              inf->pid, safe_strerror (errno));
1571
1572   target_mourn_inferior (inferior_ptid);
1573 }
1574
1575 static void
1576 darwin_setup_request_notification (struct inferior *inf)
1577 {
1578   darwin_inferior *priv = get_darwin_inferior (inf);
1579   kern_return_t kret;
1580   mach_port_t prev_not;
1581
1582   kret = mach_port_request_notification (gdb_task, priv->task,
1583                                          MACH_NOTIFY_DEAD_NAME, 0,
1584                                          priv->notify_port,
1585                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
1586                                          &prev_not);
1587   if (kret != KERN_SUCCESS)
1588     error (_("Termination notification request failed, "
1589              "mach_port_request_notification\n"
1590              "returned: %d"),
1591            kret);
1592   if (prev_not != MACH_PORT_NULL)
1593     {
1594       /* This is unexpected, as there should not be any previously
1595          registered notification request.  But this is not a fatal
1596          issue, so just emit a warning.  */
1597       warning (_("\
1598 A task termination request was registered before the debugger registered\n\
1599 its own.  This is unexpected, but should otherwise not have any actual\n\
1600 impact on the debugging session."));
1601     }
1602 }
1603
1604 static void
1605 darwin_attach_pid (struct inferior *inf)
1606 {
1607   kern_return_t kret;
1608
1609   darwin_inferior *priv = new darwin_inferior;
1610   inf->priv.reset (priv);
1611
1612   try
1613     {
1614       kret = task_for_pid (gdb_task, inf->pid, &priv->task);
1615       if (kret != KERN_SUCCESS)
1616         {
1617           int status;
1618
1619           if (!inf->attach_flag)
1620             {
1621               kill (inf->pid, 9);
1622               waitpid (inf->pid, &status, 0);
1623             }
1624
1625           error
1626             (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
1627                " (please check gdb is codesigned - see taskgated(8))"),
1628              inf->pid, mach_error_string (kret), (unsigned long) kret);
1629         }
1630
1631       inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
1632                       priv->task, inf->pid);
1633
1634       if (darwin_ex_port == MACH_PORT_NULL)
1635         {
1636           /* Create a port to get exceptions.  */
1637           kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1638                                      &darwin_ex_port);
1639           if (kret != KERN_SUCCESS)
1640             error (_("Unable to create exception port, mach_port_allocate "
1641                      "returned: %d"),
1642                    kret);
1643
1644           kret = mach_port_insert_right (gdb_task, darwin_ex_port,
1645                                          darwin_ex_port,
1646                                          MACH_MSG_TYPE_MAKE_SEND);
1647           if (kret != KERN_SUCCESS)
1648             error (_("Unable to create exception port, mach_port_insert_right "
1649                      "returned: %d"),
1650                    kret);
1651
1652           /* Create a port set and put ex_port in it.  */
1653           kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
1654                                      &darwin_port_set);
1655           if (kret != KERN_SUCCESS)
1656             error (_("Unable to create port set, mach_port_allocate "
1657                      "returned: %d"),
1658                    kret);
1659
1660           kret = mach_port_move_member (gdb_task, darwin_ex_port,
1661                                         darwin_port_set);
1662           if (kret != KERN_SUCCESS)
1663             error (_("Unable to move exception port into new port set, "
1664                      "mach_port_move_member\n"
1665                      "returned: %d"),
1666                    kret);
1667         }
1668
1669       /* Create a port to be notified when the child task terminates.  */
1670       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1671                                  &priv->notify_port);
1672       if (kret != KERN_SUCCESS)
1673         error (_("Unable to create notification port, mach_port_allocate "
1674                  "returned: %d"),
1675                kret);
1676
1677       kret = mach_port_move_member (gdb_task,
1678                                     priv->notify_port, darwin_port_set);
1679       if (kret != KERN_SUCCESS)
1680         error (_("Unable to move notification port into new port set, "
1681                  "mach_port_move_member\n"
1682                  "returned: %d"),
1683                kret);
1684
1685       darwin_setup_request_notification (inf);
1686
1687       darwin_setup_exceptions (inf);
1688     }
1689   catch (const gdb_exception &ex)
1690     {
1691       exit_inferior (inf);
1692       inferior_ptid = null_ptid;
1693
1694       throw;
1695     }
1696
1697   target_ops *darwin_ops = get_native_target ();
1698   if (!target_is_pushed (darwin_ops))
1699     push_target (darwin_ops);
1700 }
1701
1702 /* Get the thread_info object corresponding to this darwin_thread_info.  */
1703
1704 static struct thread_info *
1705 thread_info_from_private_thread_info (darwin_thread_info *pti)
1706 {
1707   for (struct thread_info *it : all_threads ())
1708     {
1709       darwin_thread_info *iter_pti = get_darwin_thread_info (it);
1710
1711       if (iter_pti->gdb_port == pti->gdb_port)
1712         return it;
1713     }
1714
1715   gdb_assert_not_reached ("did not find gdb thread for darwin thread");
1716 }
1717
1718 static void
1719 darwin_init_thread_list (struct inferior *inf)
1720 {
1721   darwin_check_new_threads (inf);
1722
1723   darwin_inferior *priv = get_darwin_inferior (inf);
1724
1725   gdb_assert (!priv->threads.empty ());
1726
1727   darwin_thread_info *first_pti = priv->threads.front ();
1728   struct thread_info *first_thread
1729     = thread_info_from_private_thread_info (first_pti);
1730
1731   inferior_ptid = first_thread->ptid;
1732 }
1733
1734 /* The child must synchronize with gdb: gdb must set the exception port
1735    before the child call PTRACE_SIGEXC.  We use a pipe to achieve this.
1736    FIXME: is there a lighter way ?  */
1737 static int ptrace_fds[2];
1738
1739 static void
1740 darwin_ptrace_me (void)
1741 {
1742   int res;
1743   char c;
1744
1745   /* Close write end point.  */
1746   if (close (ptrace_fds[1]) < 0)
1747     trace_start_error_with_name ("close");
1748
1749   /* Wait until gdb is ready.  */
1750   res = read (ptrace_fds[0], &c, 1);
1751   if (res != 0)
1752     trace_start_error (_("unable to read from pipe, read returned: %d"), res);
1753
1754   if (close (ptrace_fds[0]) < 0)
1755     trace_start_error_with_name ("close");
1756
1757   /* Get rid of privileges.  */
1758   if (setegid (getgid ()) < 0)
1759     trace_start_error_with_name ("setegid");
1760
1761   /* Set TRACEME.  */
1762   if (PTRACE (PT_TRACE_ME, 0, 0, 0) < 0)
1763     trace_start_error_with_name ("PTRACE");
1764
1765   /* Redirect signals to exception port.  */
1766   if (PTRACE (PT_SIGEXC, 0, 0, 0) < 0)
1767     trace_start_error_with_name ("PTRACE");
1768 }
1769
1770 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2).  */
1771 static void
1772 darwin_pre_ptrace (void)
1773 {
1774   if (pipe (ptrace_fds) != 0)
1775     {
1776       ptrace_fds[0] = -1;
1777       ptrace_fds[1] = -1;
1778       error (_("unable to create a pipe: %s"), safe_strerror (errno));
1779     }
1780
1781   mark_fd_no_cloexec (ptrace_fds[0]);
1782   mark_fd_no_cloexec (ptrace_fds[1]);
1783 }
1784
1785 static void
1786 darwin_ptrace_him (int pid)
1787 {
1788   struct inferior *inf = current_inferior ();
1789
1790   darwin_attach_pid (inf);
1791
1792   /* Let's the child run.  */
1793   close (ptrace_fds[0]);
1794   close (ptrace_fds[1]);
1795
1796   unmark_fd_no_cloexec (ptrace_fds[0]);
1797   unmark_fd_no_cloexec (ptrace_fds[1]);
1798
1799   darwin_init_thread_list (inf);
1800
1801   gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
1802 }
1803
1804 static void
1805 darwin_execvp (const char *file, char * const argv[], char * const env[])
1806 {
1807   posix_spawnattr_t attr;
1808   short ps_flags = 0;
1809   int res;
1810
1811   res = posix_spawnattr_init (&attr);
1812   if (res != 0)
1813     {
1814       fprintf_unfiltered
1815         (gdb_stderr, "Cannot initialize attribute for posix_spawn\n");
1816       return;
1817     }
1818
1819   /* Do like execve: replace the image.  */
1820   ps_flags = POSIX_SPAWN_SETEXEC;
1821
1822   /* Disable ASLR.  The constant doesn't look to be available outside the
1823      kernel include files.  */
1824 #ifndef _POSIX_SPAWN_DISABLE_ASLR
1825 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
1826 #endif
1827   ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
1828   res = posix_spawnattr_setflags (&attr, ps_flags);
1829   if (res != 0)
1830     {
1831       fprintf_unfiltered (gdb_stderr, "Cannot set posix_spawn flags\n");
1832       return;
1833     }
1834
1835   posix_spawnp (NULL, argv[0], NULL, &attr, argv, env);
1836 }
1837
1838 /* Read kernel version, and return TRUE if this host may have System
1839    Integrity Protection (Sierra or later).  */
1840
1841 static bool
1842 may_have_sip ()
1843 {
1844   char str[16];
1845   size_t sz = sizeof (str);
1846   int ret;
1847
1848   ret = sysctlbyname ("kern.osrelease", str, &sz, NULL, 0);
1849   if (ret == 0 && sz < sizeof (str))
1850     {
1851       unsigned long ver = strtoul (str, NULL, 10);
1852       if (ver >= 16)
1853         return true;
1854     }
1855   return false;
1856 }
1857
1858 /* A helper for maybe_cache_shell.  This copies the shell to the
1859    cache.  It will throw an exception on any failure.  */
1860
1861 static void
1862 copy_shell_to_cache (const char *shell, const std::string &new_name)
1863 {
1864   scoped_fd from_fd (gdb_open_cloexec (shell, O_RDONLY, 0));
1865   if (from_fd.get () < 0)
1866     error (_("Could not open shell (%s) for reading: %s"),
1867            shell, safe_strerror (errno));
1868
1869   std::string new_dir = ldirname (new_name.c_str ());
1870   if (!mkdir_recursive (new_dir.c_str ()))
1871     error (_("Could not make cache directory \"%s\": %s"),
1872            new_dir.c_str (), safe_strerror (errno));
1873
1874   gdb::char_vector temp_name = make_temp_filename (new_name);
1875   scoped_fd to_fd (gdb_mkostemp_cloexec (&temp_name[0]));
1876   gdb::unlinker unlink_file_on_error (temp_name.data ());
1877
1878   if (to_fd.get () < 0)
1879     error (_("Could not open temporary file \"%s\" for writing: %s"),
1880            temp_name.data (), safe_strerror (errno));
1881
1882   if (fcopyfile (from_fd.get (), to_fd.get (), nullptr,
1883                  COPYFILE_STAT | COPYFILE_DATA) != 0)
1884     error (_("Could not copy shell to cache as \"%s\": %s"),
1885            temp_name.data (), safe_strerror (errno));
1886
1887   /* Be sure that the caching is atomic so that we don't get bad
1888      results from multiple copies of gdb running at the same time.  */
1889   if (rename (temp_name.data (), new_name.c_str ()) != 0)
1890     error (_("Could not rename shell cache file to \"%s\": %s"),
1891            new_name.c_str (), safe_strerror (errno));
1892
1893   unlink_file_on_error.keep ();
1894 }
1895
1896 /* If $SHELL is restricted, try to cache a copy.  Starting with El
1897    Capitan, macOS introduced System Integrity Protection.  Among other
1898    things, this prevents certain executables from being ptrace'd.  In
1899    particular, executables in /bin, like most shells, are affected.
1900    To work around this, while preserving command-line glob expansion
1901    and redirections, gdb will cache a copy of the shell.  Return true
1902    if all is well -- either the shell is not subject to SIP or it has
1903    been successfully cached.  Returns false if something failed.  */
1904
1905 static bool
1906 maybe_cache_shell ()
1907 {
1908   /* SF_RESTRICTED is defined in sys/stat.h and lets us determine if a
1909      given file is subject to SIP.  */
1910 #ifdef SF_RESTRICTED
1911
1912   /* If a check fails we want to revert -- maybe the user deleted the
1913      cache while gdb was running, or something like that.  */
1914   copied_shell = nullptr;
1915
1916   const char *shell = get_shell ();
1917   if (!IS_ABSOLUTE_PATH (shell))
1918     {
1919       warning (_("This version of macOS has System Integrity Protection.\n\
1920 Normally gdb would try to work around this by caching a copy of your shell,\n\
1921 but because your shell (%s) is not an absolute path, this is being skipped."),
1922                shell);
1923       return false;
1924     }
1925
1926   struct stat sb;
1927   if (stat (shell, &sb) < 0)
1928     {
1929       warning (_("This version of macOS has System Integrity Protection.\n\
1930 Normally gdb would try to work around this by caching a copy of your shell,\n\
1931 but because gdb could not stat your shell (%s), this is being skipped.\n\
1932 The error was: %s"),
1933                shell, safe_strerror (errno));
1934       return false;
1935     }
1936
1937   if ((sb.st_flags & SF_RESTRICTED) == 0)
1938     return true;
1939
1940   /* Put the copy somewhere like ~/Library/Caches/gdb/bin/sh.  */
1941   std::string new_name = get_standard_cache_dir ();
1942   /* There's no need to insert a directory separator here, because
1943      SHELL is known to be absolute.  */
1944   new_name.append (shell);
1945
1946   /* Maybe it was cached by some earlier gdb.  */
1947   if (stat (new_name.c_str (), &sb) != 0 || !S_ISREG (sb.st_mode))
1948     {
1949       try
1950         {
1951           copy_shell_to_cache (shell, new_name);
1952         }
1953       catch (const gdb_exception_error &ex)
1954         {
1955           warning (_("This version of macOS has System Integrity Protection.\n\
1956 Because `startup-with-shell' is enabled, gdb tried to work around SIP by\n\
1957 caching a copy of your shell.  However, this failed:\n\
1958 %s\n\
1959 If you correct the problem, gdb will automatically try again the next time\n\
1960 you \"run\".  To prevent these attempts, you can use:\n\
1961     set startup-with-shell off"),
1962                    ex.what ());
1963           return false;
1964         }
1965
1966       printf_filtered (_("Note: this version of macOS has System Integrity Protection.\n\
1967 Because `startup-with-shell' is enabled, gdb has worked around this by\n\
1968 caching a copy of your shell.  The shell used by \"run\" is now:\n\
1969     %s\n"),
1970                        new_name.c_str ());
1971     }
1972
1973   /* We need to make sure that the new name has the correct lifetime.  */
1974   static std::string saved_shell = std::move (new_name);
1975   copied_shell = saved_shell.c_str ();
1976
1977 #endif /* SF_RESTRICTED */
1978
1979   return true;
1980 }
1981
1982 void
1983 darwin_nat_target::create_inferior (const char *exec_file,
1984                                     const std::string &allargs,
1985                                     char **env, int from_tty)
1986 {
1987   gdb::optional<scoped_restore_tmpl<int>> restore_startup_with_shell;
1988
1989   if (startup_with_shell && may_have_sip ())
1990     {
1991       if (!maybe_cache_shell ())
1992         {
1993           warning (_("startup-with-shell is now temporarily disabled"));
1994           restore_startup_with_shell.emplace (&startup_with_shell, 0);
1995         }
1996     }
1997
1998   /* Do the hard work.  */
1999   fork_inferior (exec_file, allargs, env, darwin_ptrace_me,
2000                  darwin_ptrace_him, darwin_pre_ptrace, copied_shell,
2001                  darwin_execvp);
2002 }
2003 \f
2004
2005 /* Set things up such that the next call to darwin_wait will immediately
2006    return a fake stop event for inferior INF.
2007
2008    This assumes that the inferior's thread list has been initialized,
2009    as it will suspend the inferior's first thread.  */
2010
2011 static void
2012 darwin_setup_fake_stop_event (struct inferior *inf)
2013 {
2014   darwin_inferior *priv = get_darwin_inferior (inf);
2015   darwin_thread_t *thread;
2016   kern_return_t kret;
2017
2018   gdb_assert (darwin_inf_fake_stop == NULL);
2019   darwin_inf_fake_stop = inf;
2020
2021   /* When detecting a fake pending stop event, darwin_wait returns
2022      an event saying that the first thread is in a DARWIN_STOPPED
2023      state.  To make that accurate, we need to suspend that thread
2024      as well.  Otherwise, we'll try resuming it when resuming the
2025      inferior, and get a warning because the thread's suspend count
2026      is already zero, making the resume request useless.  */
2027   thread = priv->threads[0];
2028   kret = thread_suspend (thread->gdb_port);
2029   MACH_CHECK_ERROR (kret);
2030 }
2031
2032 /* Attach to process PID, then initialize for debugging it
2033    and wait for the trace-trap that results from attaching.  */
2034 void
2035 darwin_nat_target::attach (const char *args, int from_tty)
2036 {
2037   pid_t pid;
2038   struct inferior *inf;
2039
2040   pid = parse_pid_to_attach (args);
2041
2042   if (pid == getpid ())         /* Trying to masturbate?  */
2043     error (_("I refuse to debug myself!"));
2044
2045   if (from_tty)
2046     {
2047       char *exec_file = get_exec_file (0);
2048
2049       if (exec_file)
2050         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
2051                            target_pid_to_str (ptid_t (pid)).c_str ());
2052       else
2053         printf_unfiltered (_("Attaching to %s\n"),
2054                            target_pid_to_str (ptid_t (pid)).c_str ());
2055     }
2056
2057   if (pid == 0 || ::kill (pid, 0) < 0)
2058     error (_("Can't attach to process %d: %s (%d)"),
2059            pid, safe_strerror (errno), errno);
2060
2061   inferior_ptid = ptid_t (pid);
2062   inf = current_inferior ();
2063   inferior_appeared (inf, pid);
2064   inf->attach_flag = 1;
2065
2066   darwin_attach_pid (inf);
2067
2068   darwin_suspend_inferior (inf);
2069
2070   darwin_init_thread_list (inf);
2071
2072   darwin_inferior *priv = get_darwin_inferior (inf);
2073
2074   darwin_check_osabi (priv, inferior_ptid.tid ());
2075
2076   darwin_setup_fake_stop_event (inf);
2077
2078   priv->no_ptrace = 1;
2079 }
2080
2081 /* Take a program previously attached to and detaches it.
2082    The program resumes execution and will no longer stop
2083    on signals, etc.  We'd better not have left any breakpoints
2084    in the program or it'll die when it hits one.  For this
2085    to work, it may be necessary for the process to have been
2086    previously attached.  It *might* work if the program was
2087    started via fork.  */
2088
2089 void
2090 darwin_nat_target::detach (inferior *inf, int from_tty)
2091 {
2092   darwin_inferior *priv = get_darwin_inferior (inf);
2093   kern_return_t kret;
2094   int res;
2095
2096   /* Display message.  */
2097   target_announce_detach (from_tty);
2098
2099   /* If ptrace() is in use, stop the process.  */
2100   if (!priv->no_ptrace)
2101     darwin_stop_inferior (inf);
2102
2103   kret = darwin_restore_exception_ports (priv);
2104   MACH_CHECK_ERROR (kret);
2105
2106   if (!priv->no_ptrace)
2107     {
2108       res = PTRACE (PT_DETACH, inf->pid, 0, 0);
2109       if (res != 0)
2110         printf_unfiltered (_("Unable to detach from process-id %d: %s (%d)"),
2111                            inf->pid, safe_strerror (errno), errno);
2112     }
2113
2114   darwin_reply_to_all_pending_messages (inf);
2115
2116   /* When using ptrace, we have just performed a PT_DETACH, which
2117      resumes the inferior.  On the other hand, when we are not using
2118      ptrace, we need to resume its execution ourselves.  */
2119   if (priv->no_ptrace)
2120     darwin_resume_inferior (inf);
2121
2122   mourn_inferior ();
2123 }
2124
2125 std::string
2126 darwin_nat_target::pid_to_str (ptid_t ptid)
2127 {
2128   long tid = ptid.tid ();
2129
2130   if (tid != 0)
2131     return string_printf (_("Thread 0x%lx of process %u"),
2132                           tid, ptid.pid ());
2133
2134   return normal_pid_to_str (ptid);
2135 }
2136
2137 bool
2138 darwin_nat_target::thread_alive (ptid_t ptid)
2139 {
2140   return true;
2141 }
2142
2143 /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
2144    copy it to RDADDR in gdb's address space.
2145    If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
2146    to ADDR in inferior task's address space.
2147    Return 0 on failure; number of bytes read / writen otherwise.  */
2148
2149 static int
2150 darwin_read_write_inferior (task_t task, CORE_ADDR addr,
2151                             gdb_byte *rdaddr, const gdb_byte *wraddr,
2152                             ULONGEST length)
2153 {
2154   kern_return_t kret;
2155   mach_vm_size_t res_length = 0;
2156
2157   inferior_debug (8, _("darwin_read_write_inferior(task=0x%x, %s, len=%s)\n"),
2158                   task, core_addr_to_string (addr), pulongest (length));
2159
2160   /* First read.  */
2161   if (rdaddr != NULL)
2162     {
2163       mach_vm_size_t count;
2164
2165       /* According to target.h(to_xfer_partial), one and only one may be
2166          non-null.  */
2167       gdb_assert (wraddr == NULL);
2168
2169       kret = mach_vm_read_overwrite (task, addr, length,
2170                                      (mach_vm_address_t) rdaddr, &count);
2171       if (kret != KERN_SUCCESS)
2172         {
2173           inferior_debug
2174             (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
2175              core_addr_to_string (addr), mach_error_string (kret));
2176           return 0;
2177         }
2178       return count;
2179     }
2180
2181   /* See above.  */
2182   gdb_assert (wraddr != NULL);
2183
2184   while (length != 0)
2185     {
2186       mach_vm_address_t offset = addr & (mach_page_size - 1);
2187       mach_vm_address_t region_address = (mach_vm_address_t) (addr - offset);
2188       mach_vm_size_t aligned_length =
2189         (mach_vm_size_t) PAGE_ROUND (offset + length);
2190       vm_region_submap_short_info_data_64_t info;
2191       mach_msg_type_number_t count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
2192       natural_t region_depth = 1000;
2193       mach_vm_address_t region_start = region_address;
2194       mach_vm_size_t region_length;
2195       mach_vm_size_t write_length;
2196
2197       /* Read page protection.  */
2198       kret = mach_vm_region_recurse
2199         (task, &region_start, &region_length, &region_depth,
2200          (vm_region_recurse_info_t) &info, &count);
2201
2202       if (kret != KERN_SUCCESS)
2203         {
2204           inferior_debug (1, _("darwin_read_write_inferior: "
2205                                "mach_vm_region_recurse failed at %s: %s\n"),
2206                           core_addr_to_string (region_address),
2207                           mach_error_string (kret));
2208           return res_length;
2209         }
2210
2211       inferior_debug
2212         (9, _("darwin_read_write_inferior: "
2213               "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
2214          core_addr_to_string (region_address),
2215          core_addr_to_string (region_start),
2216          core_addr_to_string (region_length));
2217
2218       /* Check for holes in memory.  */
2219       if (region_start > region_address)
2220         {
2221           warning (_("No memory at %s (vs %s+0x%x).  Nothing written"),
2222                    core_addr_to_string (region_address),
2223                    core_addr_to_string (region_start),
2224                    (unsigned)region_length);
2225           return res_length;
2226         }
2227
2228       /* Adjust the length.  */
2229       region_length -= (region_address - region_start);
2230       if (region_length > aligned_length)
2231         region_length = aligned_length;
2232
2233       /* Make the pages RW.  */
2234       if (!(info.protection & VM_PROT_WRITE))
2235         {
2236           vm_prot_t prot = VM_PROT_READ | VM_PROT_WRITE;
2237
2238           kret = mach_vm_protect (task, region_address, region_length,
2239                                   FALSE, prot);
2240           if (kret != KERN_SUCCESS)
2241             {
2242               prot |= VM_PROT_COPY;
2243               kret = mach_vm_protect (task, region_address, region_length,
2244                                       FALSE, prot);
2245             }
2246           if (kret != KERN_SUCCESS)
2247             {
2248               warning (_("darwin_read_write_inferior: "
2249                          "mach_vm_protect failed at %s "
2250                          "(len=0x%lx, prot=0x%x): %s"),
2251                        core_addr_to_string (region_address),
2252                        (unsigned long) region_length, (unsigned) prot,
2253                        mach_error_string (kret));
2254               return res_length;
2255             }
2256         }
2257
2258       if (offset + length > region_length)
2259         write_length = region_length - offset;
2260       else
2261         write_length = length;
2262
2263       /* Write.  */
2264       kret = mach_vm_write (task, addr, (vm_offset_t) wraddr, write_length);
2265       if (kret != KERN_SUCCESS)
2266         {
2267           warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
2268                    mach_error_string (kret));
2269           return res_length;
2270         }
2271
2272       /* Restore page rights.  */
2273       if (!(info.protection & VM_PROT_WRITE))
2274         {
2275           kret = mach_vm_protect (task, region_address, region_length,
2276                                   FALSE, info.protection);
2277           if (kret != KERN_SUCCESS)
2278             {
2279               warning (_("darwin_read_write_inferior: "
2280                          "mach_vm_protect restore failed at %s "
2281                          "(len=0x%lx): %s"),
2282                        core_addr_to_string (region_address),
2283                        (unsigned long) region_length,
2284                        mach_error_string (kret));
2285             }
2286         }
2287
2288       addr += write_length;
2289       wraddr += write_length;
2290       res_length += write_length;
2291       length -= write_length;
2292     }
2293
2294   return res_length;
2295 }
2296
2297 /* Read LENGTH bytes at offset ADDR of task_dyld_info for TASK, and copy them
2298    to RDADDR (in big endian).
2299    Return 0 on failure; number of bytes read / written otherwise.  */
2300
2301 #ifdef TASK_DYLD_INFO_COUNT
2302 /* This is not available in Darwin 9.  */
2303 static enum target_xfer_status
2304 darwin_read_dyld_info (task_t task, CORE_ADDR addr, gdb_byte *rdaddr,
2305                        ULONGEST length, ULONGEST *xfered_len)
2306 {
2307   struct task_dyld_info task_dyld_info;
2308   mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
2309   kern_return_t kret;
2310
2311   if (addr != 0 || length > sizeof (mach_vm_address_t))
2312     return TARGET_XFER_EOF;
2313
2314   kret = task_info (task, TASK_DYLD_INFO,
2315                     (task_info_t) &task_dyld_info, &count);
2316   MACH_CHECK_ERROR (kret);
2317   if (kret != KERN_SUCCESS)
2318     return TARGET_XFER_E_IO;
2319
2320   store_unsigned_integer (rdaddr, length, BFD_ENDIAN_BIG,
2321                           task_dyld_info.all_image_info_addr);
2322   *xfered_len = (ULONGEST) length;
2323   return TARGET_XFER_OK;
2324 }
2325 #endif
2326
2327 \f
2328
2329 enum target_xfer_status
2330 darwin_nat_target::xfer_partial (enum target_object object, const char *annex,
2331                                  gdb_byte *readbuf, const gdb_byte *writebuf,
2332                                  ULONGEST offset, ULONGEST len,
2333                                  ULONGEST *xfered_len)
2334 {
2335   struct inferior *inf = current_inferior ();
2336   darwin_inferior *priv = get_darwin_inferior (inf);
2337
2338   inferior_debug
2339     (8, _("darwin_xfer_partial(%s, %s, rbuf=%s, wbuf=%s) pid=%u\n"),
2340      core_addr_to_string (offset), pulongest (len),
2341      host_address_to_string (readbuf), host_address_to_string (writebuf),
2342      inf->pid);
2343
2344   switch (object)
2345     {
2346     case TARGET_OBJECT_MEMORY:
2347       {
2348         int l = darwin_read_write_inferior (priv->task, offset,
2349                                             readbuf, writebuf, len);
2350
2351         if (l == 0)
2352           return TARGET_XFER_EOF;
2353         else
2354           {
2355             gdb_assert (l > 0);
2356             *xfered_len = (ULONGEST) l;
2357             return TARGET_XFER_OK;
2358           }
2359       }
2360 #ifdef TASK_DYLD_INFO_COUNT
2361     case TARGET_OBJECT_DARWIN_DYLD_INFO:
2362       if (writebuf != NULL || readbuf == NULL)
2363         {
2364           /* Support only read.  */
2365           return TARGET_XFER_E_IO;
2366         }
2367       return darwin_read_dyld_info (priv->task, offset, readbuf, len,
2368                                     xfered_len);
2369 #endif
2370     default:
2371       return TARGET_XFER_E_IO;
2372     }
2373
2374 }
2375
2376 static void
2377 set_enable_mach_exceptions (const char *args, int from_tty,
2378                             struct cmd_list_element *c)
2379 {
2380   if (inferior_ptid != null_ptid)
2381     {
2382       struct inferior *inf = current_inferior ();
2383       darwin_inferior *priv = get_darwin_inferior (inf);
2384       exception_mask_t mask;
2385       kern_return_t kret;
2386
2387       if (enable_mach_exceptions)
2388         mask = EXC_MASK_ALL;
2389       else
2390         {
2391           darwin_restore_exception_ports (priv);
2392           mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
2393         }
2394       kret = task_set_exception_ports (priv->task, mask, darwin_ex_port,
2395                                        EXCEPTION_DEFAULT, THREAD_STATE_NONE);
2396       MACH_CHECK_ERROR (kret);
2397     }
2398 }
2399
2400 char *
2401 darwin_nat_target::pid_to_exec_file (int pid)
2402 {
2403   static char path[PATH_MAX];
2404   int res;
2405
2406   res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, PATH_MAX);
2407   if (res >= 0)
2408     return path;
2409   else
2410     return NULL;
2411 }
2412
2413 ptid_t
2414 darwin_nat_target::get_ada_task_ptid (long lwp, long thread)
2415 {
2416   struct inferior *inf = current_inferior ();
2417   darwin_inferior *priv = get_darwin_inferior (inf);
2418   kern_return_t kret;
2419   mach_port_name_array_t names;
2420   mach_msg_type_number_t names_count;
2421   mach_port_type_array_t types;
2422   mach_msg_type_number_t types_count;
2423   long res = 0;
2424
2425   /* First linear search.  */
2426   for (darwin_thread_t *t : priv->threads)
2427     {
2428       if (t->inf_port == lwp)
2429         return ptid_t (inferior_ptid.pid (), 0, t->gdb_port);
2430     }
2431
2432   /* Maybe the port was never extract.  Do it now.  */
2433
2434   /* First get inferior port names.  */
2435   kret = mach_port_names (priv->task, &names, &names_count, &types,
2436                           &types_count);
2437   MACH_CHECK_ERROR (kret);
2438   if (kret != KERN_SUCCESS)
2439     return null_ptid;
2440
2441   /* For each name, copy the right in the gdb space and then compare with
2442      our view of the inferior threads.  We don't forget to deallocate the
2443      right.  */
2444   for (int i = 0; i < names_count; i++)
2445     {
2446       mach_port_t local_name;
2447       mach_msg_type_name_t local_type;
2448
2449       /* We just need to know the corresponding name in gdb name space.
2450          So extract and deallocate the right.  */
2451       kret = mach_port_extract_right (priv->task, names[i],
2452                                       MACH_MSG_TYPE_COPY_SEND,
2453                                       &local_name, &local_type);
2454       if (kret != KERN_SUCCESS)
2455         continue;
2456       mach_port_deallocate (gdb_task, local_name);
2457
2458       for (darwin_thread_t *t : priv->threads)
2459         {
2460           if (t->gdb_port == local_name)
2461             {
2462               t->inf_port = names[i];
2463               if (names[i] == lwp)
2464                 res = t->gdb_port;
2465             }
2466         }
2467     }
2468
2469   vm_deallocate (gdb_task, (vm_address_t) names,
2470                  names_count * sizeof (mach_port_t));
2471
2472   if (res)
2473     return ptid_t (inferior_ptid.pid (), 0, res);
2474   else
2475     return null_ptid;
2476 }
2477
2478 bool
2479 darwin_nat_target::supports_multi_process ()
2480 {
2481   return true;
2482 }
2483
2484 void
2485 _initialize_darwin_nat ()
2486 {
2487   kern_return_t kret;
2488
2489   gdb_task = mach_task_self ();
2490   darwin_host_self = mach_host_self ();
2491
2492   /* Read page size.  */
2493   kret = host_page_size (darwin_host_self, &mach_page_size);
2494   if (kret != KERN_SUCCESS)
2495     {
2496       mach_page_size = 0x1000;
2497       MACH_CHECK_ERROR (kret);
2498     }
2499
2500   inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"),
2501                   (unsigned long) mach_task_self (), getpid ());
2502
2503   add_setshow_zuinteger_cmd ("darwin", class_obscure,
2504                              &darwin_debug_flag, _("\
2505 Set if printing inferior communication debugging statements."), _("\
2506 Show if printing inferior communication debugging statements."), NULL,
2507                              NULL, NULL,
2508                              &setdebuglist, &showdebuglist);
2509
2510   add_setshow_boolean_cmd ("mach-exceptions", class_support,
2511                            &enable_mach_exceptions, _("\
2512 Set if mach exceptions are caught."), _("\
2513 Show if mach exceptions are caught."), _("\
2514 When this mode is on, all low level exceptions are reported before being\n\
2515 reported by the kernel."),
2516                            &set_enable_mach_exceptions, NULL,
2517                            &setlist, &showlist);
2518 }