]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/darwin-nat.c
convert to_thread_address_space to use TARGET_DEFAULT_FUNC
[thirdparty/binutils-gdb.git] / gdb / darwin-nat.c
CommitLineData
a80b95ba 1/* Darwin support for GDB, the GNU debugger.
ecd75fc8 2 Copyright (C) 2008-2014 Free Software Foundation, Inc.
a80b95ba
TG
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
47d48711 19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
a80b95ba
TG
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 "gdb.h"
29#include "gdbcmd.h"
30#include "gdbcore.h"
31#include "gdbthread.h"
32#include "regcache.h"
33#include "event-top.h"
34#include "inf-loop.h"
53ce3c39 35#include <sys/stat.h>
a80b95ba
TG
36#include "exceptions.h"
37#include "inf-child.h"
38#include "value.h"
39#include "arch-utils.h"
40#include "bfd.h"
ece0061f 41#include "bfd/mach-o.h"
a80b95ba
TG
42
43#include <sys/ptrace.h>
44#include <sys/signal.h>
45#include <machine/setjmp.h>
46#include <sys/types.h>
47#include <unistd.h>
48#include <signal.h>
49#include <string.h>
50#include <ctype.h>
a80b95ba
TG
51#include <sys/sysctl.h>
52#include <sys/proc.h>
bb00b29d
TG
53#include <libproc.h>
54#include <sys/syscall.h>
e69860f1 55#include <spawn.h>
a80b95ba
TG
56
57#include <mach/mach_error.h>
58#include <mach/mach_vm.h>
59#include <mach/mach_init.h>
60#include <mach/vm_map.h>
61#include <mach/task.h>
62#include <mach/mach_port.h>
63#include <mach/thread_act.h>
64#include <mach/port.h>
65
66#include "darwin-nat.h"
21ff4686 67#include "common/filestuff.h"
a80b95ba
TG
68
69/* Quick overview.
70 Darwin kernel is Mach + BSD derived kernel. Note that they share the
71 same memory space and are linked together (ie there is no micro-kernel).
72
73 Although ptrace(2) is available on Darwin, it is not complete. We have
74 to use Mach calls to read and write memory and to modify registers. We
75 also use Mach to get inferior faults. As we cannot use select(2) or
76 signals with Mach port (the Mach communication channel), signals are
77 reported to gdb as an exception. Furthermore we detect death of the
78 inferior through a Mach notification message. This way we only wait
79 on Mach ports.
80
81 Some Mach documentation is available for Apple xnu source package or
82 from the web. */
83
84
85#define PTRACE(CMD, PID, ADDR, SIG) \
86 darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))
87
1eab8a48 88static void darwin_stop (struct target_ops *self, ptid_t);
a80b95ba 89
bb00b29d 90static void darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
2ea28649 91 enum gdb_signal signal);
bb00b29d 92static void darwin_resume (ptid_t ptid, int step,
2ea28649 93 enum gdb_signal signal);
bb00b29d
TG
94
95static ptid_t darwin_wait_to (struct target_ops *ops, ptid_t ptid,
96 struct target_waitstatus *status, int options);
97static ptid_t darwin_wait (ptid_t ptid, struct target_waitstatus *status);
98
a80b95ba
TG
99static void darwin_mourn_inferior (struct target_ops *ops);
100
2ab1c2d9 101static void darwin_kill_inferior (struct target_ops *ops);
a80b95ba
TG
102
103static void darwin_ptrace_me (void);
104
105static void darwin_ptrace_him (int pid);
106
107static void darwin_create_inferior (struct target_ops *ops, char *exec_file,
108 char *allargs, char **env, int from_tty);
109
110static void darwin_files_info (struct target_ops *ops);
111
bb00b29d
TG
112static char *darwin_pid_to_str (struct target_ops *ops, ptid_t tpid);
113
114static int darwin_thread_alive (struct target_ops *ops, ptid_t tpid);
a80b95ba 115
a41f2563
TG
116static void darwin_encode_reply (mig_reply_error_t *reply,
117 mach_msg_header_t *hdr, integer_t code);
118
a80b95ba
TG
119/* Target operations for Darwin. */
120static struct target_ops *darwin_ops;
121
122/* Task identifier of gdb. */
123static task_t gdb_task;
124
125/* A copy of mach_host_self (). */
126mach_port_t darwin_host_self;
127
128/* Exception port. */
129mach_port_t darwin_ex_port;
130
a6290449 131/* Port set, to wait for answer on all ports. */
a80b95ba
TG
132mach_port_t darwin_port_set;
133
0963b4bd 134/* Page size. */
a80b95ba
TG
135static vm_size_t mach_page_size;
136
137/* If Set, catch all mach exceptions (before they are converted to signals
138 by the kernel). */
139static int enable_mach_exceptions;
140
bb00b29d
TG
141/* Inferior that should report a fake stop event. */
142static struct inferior *darwin_inf_fake_stop;
143
a80b95ba
TG
144#define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
145#define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
146
bb00b29d 147/* This controls output of inferior debugging. */
ccce17b0 148static unsigned int darwin_debug_flag = 0;
a80b95ba 149
15c19d39
TG
150/* Create a __TEXT __info_plist section in the executable so that gdb could
151 be signed. This is required to get an authorization for task_for_pid.
152
a6290449
TG
153 Once gdb is built, you must codesign it with any system-trusted signing
154 authority. See taskgated(8) for details. */
15c19d39
TG
155static const unsigned char info_plist[]
156__attribute__ ((section ("__TEXT,__info_plist"),used)) =
157 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
158 "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
159 " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
160 "<plist version=\"1.0\">\n"
161 "<dict>\n"
162 " <key>CFBundleIdentifier</key>\n"
163 " <string>org.gnu.gdb</string>\n"
164 " <key>CFBundleName</key>\n"
165 " <string>gdb</string>\n"
166 " <key>CFBundleVersion</key>\n"
167 " <string>1.0</string>\n"
168 " <key>SecTaskAccess</key>\n"
169 " <array>\n"
170 " <string>allowed</string>\n"
171 " <string>debug</string>\n"
172 " </array>\n"
173 "</dict>\n"
174 "</plist>\n";
175
a80b95ba
TG
176static void
177inferior_debug (int level, const char *fmt, ...)
178{
179 va_list ap;
180
181 if (darwin_debug_flag < level)
182 return;
183
184 va_start (ap, fmt);
185 printf_unfiltered (_("[%d inferior]: "), getpid ());
186 vprintf_unfiltered (fmt, ap);
187 va_end (ap);
188}
189
190void
191mach_check_error (kern_return_t ret, const char *file,
192 unsigned int line, const char *func)
193{
194 if (ret == KERN_SUCCESS)
195 return;
196 if (func == NULL)
197 func = _("[UNKNOWN]");
bb00b29d 198
4f1cdeec 199 warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)"),
bb00b29d 200 file, line, func, mach_error_string (ret), (unsigned long) ret);
a80b95ba
TG
201}
202
203static const char *
204unparse_exception_type (unsigned int i)
205{
206 static char unknown_exception_buf[32];
207
208 switch (i)
209 {
210 case EXC_BAD_ACCESS:
211 return "EXC_BAD_ACCESS";
212 case EXC_BAD_INSTRUCTION:
213 return "EXC_BAD_INSTRUCTION";
214 case EXC_ARITHMETIC:
215 return "EXC_ARITHMETIC";
216 case EXC_EMULATION:
217 return "EXC_EMULATION";
218 case EXC_SOFTWARE:
219 return "EXC_SOFTWARE";
220 case EXC_BREAKPOINT:
221 return "EXC_BREAKPOINT";
222 case EXC_SYSCALL:
223 return "EXC_SYSCALL";
224 case EXC_MACH_SYSCALL:
225 return "EXC_MACH_SYSCALL";
226 case EXC_RPC_ALERT:
227 return "EXC_RPC_ALERT";
228 case EXC_CRASH:
229 return "EXC_CRASH";
230 default:
231 snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
232 return unknown_exception_buf;
233 }
234}
235
a7aa0d73
JB
236/* Set errno to zero, and then call ptrace with the given arguments.
237 If inferior debugging traces are on, then also print a debug
238 trace.
239
240 The returned value is the same as the value returned by ptrace,
241 except in the case where that value is -1 but errno is zero.
242 This case is documented to be a non-error situation, so we
243 return zero in that case. */
244
a80b95ba
TG
245static int
246darwin_ptrace (const char *name,
247 int request, int pid, PTRACE_TYPE_ARG3 arg3, int arg4)
248{
249 int ret;
250
a7aa0d73 251 errno = 0;
a80b95ba 252 ret = ptrace (request, pid, (caddr_t) arg3, arg4);
a7aa0d73
JB
253 if (ret == -1 && errno == 0)
254 ret = 0;
a80b95ba 255
bb00b29d 256 inferior_debug (4, _("ptrace (%s, %d, 0x%x, %d): %d (%s)\n"),
a80b95ba 257 name, pid, arg3, arg4, ret,
a3224241 258 (ret != 0) ? safe_strerror (errno) : _("no error"));
a80b95ba
TG
259 return ret;
260}
261
262static int
263cmp_thread_t (const void *l, const void *r)
264{
bb00b29d
TG
265 thread_t tl = *(const thread_t *)l;
266 thread_t tr = *(const thread_t *)r;
267 return (int)(tl - tr);
a80b95ba
TG
268}
269
270static void
bb00b29d 271darwin_check_new_threads (struct inferior *inf)
a80b95ba
TG
272{
273 kern_return_t kret;
274 unsigned int i;
275 thread_array_t thread_list;
276 unsigned int new_nbr;
277 unsigned int old_nbr;
278 unsigned int new_ix, old_ix;
bb00b29d
TG
279 darwin_inferior *darwin_inf = inf->private;
280 VEC (darwin_thread_t) *thread_vec;
a80b95ba
TG
281
282 /* Get list of threads. */
bb00b29d 283 kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
a80b95ba
TG
284 MACH_CHECK_ERROR (kret);
285 if (kret != KERN_SUCCESS)
286 return;
287
bb00b29d 288 /* Sort the list. */
a80b95ba
TG
289 if (new_nbr > 1)
290 qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
291
bb00b29d
TG
292 if (darwin_inf->threads)
293 old_nbr = VEC_length (darwin_thread_t, darwin_inf->threads);
a80b95ba
TG
294 else
295 old_nbr = 0;
296
bb00b29d
TG
297 /* Quick check for no changes. */
298 if (old_nbr == new_nbr)
299 {
300 for (i = 0; i < new_nbr; i++)
301 if (thread_list[i]
302 != VEC_index (darwin_thread_t, darwin_inf->threads, i)->gdb_port)
303 break;
304 if (i == new_nbr)
305 {
15a9128a
TG
306 /* Deallocate ports. */
307 for (i = 0; i < new_nbr; i++)
308 {
309 kret = mach_port_deallocate (mach_task_self (), thread_list[i]);
310 MACH_CHECK_ERROR (kret);
311 }
312
313 /* Deallocate the buffer. */
bb00b29d
TG
314 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
315 new_nbr * sizeof (int));
316 MACH_CHECK_ERROR (kret);
15a9128a 317
bb00b29d
TG
318 return;
319 }
320 }
321
322 thread_vec = VEC_alloc (darwin_thread_t, new_nbr);
323
a80b95ba
TG
324 for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
325 {
326 thread_t new_id = (new_ix < new_nbr) ?
327 thread_list[new_ix] : THREAD_NULL;
bb00b29d
TG
328 darwin_thread_t *old = (old_ix < old_nbr) ?
329 VEC_index (darwin_thread_t, darwin_inf->threads, old_ix) : NULL;
330 thread_t old_id = old ? old->gdb_port : THREAD_NULL;
331
332 inferior_debug
c8c9911f 333 (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:0x%x old_id:0x%x\n"),
bb00b29d 334 new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);
a80b95ba
TG
335
336 if (old_id == new_id)
337 {
338 /* Thread still exist. */
bb00b29d 339 VEC_safe_push (darwin_thread_t, thread_vec, old);
a80b95ba
TG
340 new_ix++;
341 old_ix++;
342
15a9128a
TG
343 /* Deallocate the port. */
344 kret = mach_port_deallocate (gdb_task, new_id);
a80b95ba 345 MACH_CHECK_ERROR (kret);
15a9128a 346
a80b95ba
TG
347 continue;
348 }
bb00b29d
TG
349 if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
350 {
351 /* Ignore dead ports.
352 In some weird cases, we might get dead ports. They should
353 correspond to dead thread so they could safely be ignored. */
354 new_ix++;
355 continue;
356 }
357 if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
a80b95ba
TG
358 {
359 /* A thread was created. */
360 struct thread_info *tp;
bb00b29d 361 struct private_thread_info *pti;
a80b95ba 362
41bf6aca 363 pti = XCNEW (struct private_thread_info);
bb00b29d
TG
364 pti->gdb_port = new_id;
365 pti->msg_state = DARWIN_RUNNING;
366
367 /* Add a new thread unless this is the first one ever met. */
368 if (!(old_nbr == 0 && new_ix == 0))
369 tp = add_thread_with_info (ptid_build (inf->pid, 0, new_id), pti);
370 else
371 {
372 tp = find_thread_ptid (ptid_build (inf->pid, 0, 0));
373 gdb_assert (tp);
374 tp->private = pti;
375 }
376 VEC_safe_push (darwin_thread_t, thread_vec, pti);
a80b95ba
TG
377 new_ix++;
378 continue;
379 }
bb00b29d 380 if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
a80b95ba
TG
381 {
382 /* A thread was removed. */
383 delete_thread (ptid_build (inf->pid, 0, old_id));
384 kret = mach_port_deallocate (gdb_task, old_id);
385 MACH_CHECK_ERROR (kret);
386 old_ix++;
bb00b29d 387 continue;
a80b95ba 388 }
f3574227 389 gdb_assert_not_reached ("unexpected thread case");
a80b95ba
TG
390 }
391
bb00b29d
TG
392 if (darwin_inf->threads)
393 VEC_free (darwin_thread_t, darwin_inf->threads);
394 darwin_inf->threads = thread_vec;
a80b95ba 395
15a9128a 396 /* Deallocate the buffer. */
a80b95ba
TG
397 kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
398 new_nbr * sizeof (int));
399 MACH_CHECK_ERROR (kret);
400}
401
bb00b29d
TG
402static int
403find_inferior_task_it (struct inferior *inf, void *port_ptr)
a80b95ba 404{
bb00b29d
TG
405 return inf->private->task == *(task_t*)port_ptr;
406}
a80b95ba 407
bb00b29d
TG
408static int
409find_inferior_notify_it (struct inferior *inf, void *port_ptr)
410{
411 return inf->private->notify_port == *(task_t*)port_ptr;
a80b95ba
TG
412}
413
bb00b29d
TG
414/* Return an inferior by task port. */
415static struct inferior *
416darwin_find_inferior_by_task (task_t port)
a80b95ba 417{
bb00b29d
TG
418 return iterate_over_inferiors (&find_inferior_task_it, &port);
419}
a80b95ba 420
bb00b29d
TG
421/* Return an inferior by notification port. */
422static struct inferior *
423darwin_find_inferior_by_notify (mach_port_t port)
424{
425 return iterate_over_inferiors (&find_inferior_notify_it, &port);
426}
a80b95ba 427
bb00b29d
TG
428/* Return a thread by port. */
429static darwin_thread_t *
430darwin_find_thread (struct inferior *inf, thread_t thread)
431{
432 darwin_thread_t *t;
433 int k;
434
435 for (k = 0;
436 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
437 k++)
438 if (t->gdb_port == thread)
439 return t;
440 return NULL;
441}
a80b95ba 442
bb00b29d 443/* Suspend (ie stop) an inferior at Mach level. */
a80b95ba 444
bb00b29d
TG
445static void
446darwin_suspend_inferior (struct inferior *inf)
447{
448 if (!inf->private->suspended)
a80b95ba 449 {
bb00b29d 450 kern_return_t kret;
a80b95ba 451
bb00b29d
TG
452 kret = task_suspend (inf->private->task);
453 MACH_CHECK_ERROR (kret);
a80b95ba 454
bb00b29d
TG
455 inf->private->suspended = 1;
456 }
457}
a80b95ba 458
bb00b29d 459/* Resume an inferior at Mach level. */
a80b95ba 460
bb00b29d
TG
461static void
462darwin_resume_inferior (struct inferior *inf)
463{
464 if (inf->private->suspended)
465 {
466 kern_return_t kret;
a80b95ba 467
bb00b29d
TG
468 kret = task_resume (inf->private->task);
469 MACH_CHECK_ERROR (kret);
470
471 inf->private->suspended = 0;
a80b95ba
TG
472 }
473}
474
bb00b29d
TG
475/* Iterator functions. */
476
477static int
478darwin_suspend_inferior_it (struct inferior *inf, void *arg)
a80b95ba 479{
bb00b29d
TG
480 darwin_suspend_inferior (inf);
481 darwin_check_new_threads (inf);
482 return 0;
483}
484
485static int
486darwin_resume_inferior_it (struct inferior *inf, void *arg)
487{
488 darwin_resume_inferior (inf);
489 return 0;
a80b95ba
TG
490}
491
bb00b29d
TG
492static void
493darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
494{
495 printf_unfiltered (_("message header:\n"));
496 printf_unfiltered (_(" bits: 0x%x\n"), hdr->msgh_bits);
497 printf_unfiltered (_(" size: 0x%x\n"), hdr->msgh_size);
498 printf_unfiltered (_(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
499 printf_unfiltered (_(" local-port: 0x%x\n"), hdr->msgh_local_port);
500 printf_unfiltered (_(" reserved: 0x%x\n"), hdr->msgh_reserved);
501 printf_unfiltered (_(" id: 0x%x\n"), hdr->msgh_id);
502
503 if (disp_body)
504 {
505 const unsigned char *data;
a6290449 506 const unsigned int *ldata;
bb00b29d
TG
507 int size;
508 int i;
509
510 data = (unsigned char *)(hdr + 1);
511 size = hdr->msgh_size - sizeof (mach_msg_header_t);
512
513 if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
514 {
515 mach_msg_body_t *bod = (mach_msg_body_t*)data;
516 mach_msg_port_descriptor_t *desc =
517 (mach_msg_port_descriptor_t *)(bod + 1);
518 int k;
519 NDR_record_t *ndr;
520 printf_unfiltered (_("body: descriptor_count=%u\n"),
521 bod->msgh_descriptor_count);
522 data += sizeof (mach_msg_body_t);
523 size -= sizeof (mach_msg_body_t);
524 for (k = 0; k < bod->msgh_descriptor_count; k++)
525 switch (desc[k].type)
526 {
527 case MACH_MSG_PORT_DESCRIPTOR:
528 printf_unfiltered
529 (_(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
530 k, desc[k].type, desc[k].name, desc[k].disposition);
531 break;
532 default:
533 printf_unfiltered (_(" descr %d: type=%u\n"),
534 k, desc[k].type);
535 break;
536 }
537 data += bod->msgh_descriptor_count
538 * sizeof (mach_msg_port_descriptor_t);
539 size -= bod->msgh_descriptor_count
540 * sizeof (mach_msg_port_descriptor_t);
541 ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
542 printf_unfiltered
543 (_("NDR: mig=%02x if=%02x encod=%02x "
544 "int=%02x char=%02x float=%02x\n"),
545 ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
546 ndr->int_rep, ndr->char_rep, ndr->float_rep);
547 data += sizeof (NDR_record_t);
548 size -= sizeof (NDR_record_t);
549 }
550
551 printf_unfiltered (_(" data:"));
a6290449
TG
552 ldata = (const unsigned int *)data;
553 for (i = 0; i < size / sizeof (unsigned int); i++)
554 printf_unfiltered (" %08x", ldata[i]);
bb00b29d
TG
555 printf_unfiltered (_("\n"));
556 }
557}
558
559static int
560darwin_decode_exception_message (mach_msg_header_t *hdr,
561 struct inferior **pinf,
562 darwin_thread_t **pthread)
a80b95ba 563{
bb00b29d
TG
564 mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
565 mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
566 NDR_record_t *ndr;
567 integer_t *data;
568 struct inferior *inf;
569 darwin_thread_t *thread;
570 task_t task_port;
571 thread_t thread_port;
a80b95ba 572 kern_return_t kret;
bb00b29d 573 int i;
a80b95ba 574
a41f2563
TG
575 /* Check message destination. */
576 if (hdr->msgh_local_port != darwin_ex_port)
bb00b29d
TG
577 return -1;
578
579 /* Check message header. */
580 if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
581 return -1;
582
583 /* Check descriptors. */
584 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
585 + sizeof (*ndr) + 2 * sizeof (integer_t))
586 || bod->msgh_descriptor_count != 2
587 || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
588 || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
589 || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
590 || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
591 return -1;
592
593 /* Check data representation. */
594 ndr = (NDR_record_t *)(desc + 2);
595 if (ndr->mig_vers != NDR_PROTOCOL_2_0
596 || ndr->if_vers != NDR_PROTOCOL_2_0
597 || ndr->mig_encoding != NDR_record.mig_encoding
598 || ndr->int_rep != NDR_record.int_rep
599 || ndr->char_rep != NDR_record.char_rep
600 || ndr->float_rep != NDR_record.float_rep)
601 return -1;
602
603 /* Ok, the hard work. */
604 data = (integer_t *)(ndr + 1);
605
bb00b29d
TG
606 task_port = desc[1].name;
607 thread_port = desc[0].name;
a41f2563 608
15a9128a
TG
609 /* We got new rights to the task, get rid of it. Do not get rid of thread
610 right, as we will need it to find the thread. */
a41f2563
TG
611 kret = mach_port_deallocate (mach_task_self (), task_port);
612 MACH_CHECK_ERROR (kret);
a41f2563
TG
613
614 /* Find process by port. */
bb00b29d 615 inf = darwin_find_inferior_by_task (task_port);
bb00b29d 616 *pinf = inf;
a41f2563
TG
617 if (inf == NULL)
618 {
619 /* Not a known inferior. This could happen if the child fork, as
620 the created process will inherit its exception port.
621 FIXME: should the exception port be restored ? */
622 kern_return_t kret;
623 mig_reply_error_t reply;
624
15a9128a
TG
625 /* Free thread port (we don't know it). */
626 kret = mach_port_deallocate (mach_task_self (), thread_port);
627 MACH_CHECK_ERROR (kret);
628
a41f2563
TG
629 darwin_encode_reply (&reply, hdr, KERN_SUCCESS);
630
631 kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
632 reply.Head.msgh_size, 0,
633 MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
634 MACH_PORT_NULL);
635 MACH_CHECK_ERROR (kret);
636
637 return 0;
638 }
bb00b29d
TG
639
640 /* Find thread by port. */
641 /* Check for new threads. Do it early so that the port in the exception
642 message can be deallocated. */
643 darwin_check_new_threads (inf);
644
15a9128a
TG
645 /* Free the thread port (as gdb knows the thread, it has already has a right
646 for it, so this just decrement a reference counter). */
647 kret = mach_port_deallocate (mach_task_self (), thread_port);
648 MACH_CHECK_ERROR (kret);
649
bb00b29d
TG
650 thread = darwin_find_thread (inf, thread_port);
651 if (thread == NULL)
652 return -1;
653 *pthread = thread;
654
a6290449
TG
655 /* The thread should be running. However we have observed cases where a
656 thread got a SIGTTIN message after being stopped. */
484a26a8
TG
657 gdb_assert (thread->msg_state != DARWIN_MESSAGE);
658
bb00b29d 659 /* Finish decoding. */
bb00b29d
TG
660 thread->event.header = *hdr;
661 thread->event.thread_port = thread_port;
662 thread->event.task_port = task_port;
663 thread->event.ex_type = data[0];
664 thread->event.data_count = data[1];
665
666 if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
667 + sizeof (*ndr) + 2 * sizeof (integer_t)
668 + data[1] * sizeof (integer_t)))
669 return -1;
670 for (i = 0; i < data[1]; i++)
671 thread->event.ex_data[i] = data[2 + i];
672
673 thread->msg_state = DARWIN_MESSAGE;
674
675 return 0;
676}
677
678static void
679darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
680 integer_t code)
681{
682 mach_msg_header_t *rh = &reply->Head;
a6290449
TG
683
684 rh->msgh_bits = MACH_MSGH_BITS (MACH_MSGH_BITS_REMOTE (hdr->msgh_bits), 0);
bb00b29d 685 rh->msgh_remote_port = hdr->msgh_remote_port;
a6290449 686 rh->msgh_size = (mach_msg_size_t) sizeof (mig_reply_error_t);
bb00b29d
TG
687 rh->msgh_local_port = MACH_PORT_NULL;
688 rh->msgh_id = hdr->msgh_id + 100;
689
690 reply->NDR = NDR_record;
691 reply->RetCode = code;
a80b95ba
TG
692}
693
bb00b29d
TG
694static void
695darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
a80b95ba
TG
696{
697 kern_return_t kret;
bb00b29d 698 mig_reply_error_t reply;
a80b95ba 699
bb00b29d
TG
700 darwin_encode_reply (&reply, &thread->event.header, 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);
a80b95ba
TG
706 MACH_CHECK_ERROR (kret);
707
bb00b29d
TG
708 inf->private->pending_messages--;
709}
710
711static void
712darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
713 int step, int nsignal)
714{
715 kern_return_t kret;
716 int res;
717
a80b95ba 718 inferior_debug
bb00b29d
TG
719 (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
720 thread->msg_state, thread->gdb_port, step, nsignal);
721
722 switch (thread->msg_state)
a80b95ba 723 {
bb00b29d
TG
724 case DARWIN_MESSAGE:
725 if (thread->event.ex_type == EXC_SOFTWARE
726 && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
727 {
728 /* Either deliver a new signal or cancel the signal received. */
729 res = PTRACE (PT_THUPDATE, inf->pid,
730 (void *)(uintptr_t)thread->gdb_port, nsignal);
731 if (res < 0)
732 inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
733 }
734 else if (nsignal)
735 {
736 /* Note: ptrace is allowed only if the process is stopped.
737 Directly send the signal to the thread. */
738 res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
739 inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
740 thread->gdb_port, nsignal, res);
741 thread->signaled = 1;
742 }
743
d987a266
TG
744 /* Set or reset single step. */
745 if (step != thread->single_step)
746 {
c8c9911f 747 inferior_debug (4, _("darwin_set_sstep (thread=0x%x, enable=%d)\n"),
d987a266
TG
748 thread->gdb_port, step);
749 darwin_set_sstep (thread->gdb_port, step);
750 thread->single_step = step;
751 }
bb00b29d
TG
752
753 darwin_send_reply (inf, thread);
754 thread->msg_state = DARWIN_RUNNING;
755 break;
756
757 case DARWIN_RUNNING:
758 break;
759
760 case DARWIN_STOPPED:
761 kret = thread_resume (thread->gdb_port);
762 MACH_CHECK_ERROR (kret);
763
764 thread->msg_state = DARWIN_RUNNING;
765 break;
a80b95ba 766 }
bb00b29d 767}
a80b95ba 768
bb00b29d 769/* Resume all threads of the inferior. */
a80b95ba 770
bb00b29d
TG
771static void
772darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
773{
774 darwin_thread_t *thread;
775 int k;
776
777 for (k = 0;
778 VEC_iterate (darwin_thread_t, inf->private->threads, k, thread);
779 k++)
780 darwin_resume_thread (inf, thread, step, nsignal);
a80b95ba
TG
781}
782
bb00b29d 783struct resume_inferior_threads_param
a80b95ba 784{
bb00b29d
TG
785 int step;
786 int nsignal;
787};
788
789static int
790darwin_resume_inferior_threads_it (struct inferior *inf, void *param)
791{
792 int step = ((struct resume_inferior_threads_param *)param)->step;
793 int nsignal = ((struct resume_inferior_threads_param *)param)->nsignal;
794
795 darwin_resume_inferior_threads (inf, step, nsignal);
796
797 return 0;
798}
799
800/* Suspend all threads of INF. */
801
802static void
803darwin_suspend_inferior_threads (struct inferior *inf)
804{
805 darwin_thread_t *thread;
a80b95ba 806 kern_return_t kret;
bb00b29d
TG
807 int k;
808
809 for (k = 0;
810 VEC_iterate (darwin_thread_t, inf->private->threads, k, thread);
811 k++)
812 switch (thread->msg_state)
813 {
814 case DARWIN_STOPPED:
815 case DARWIN_MESSAGE:
816 break;
817 case DARWIN_RUNNING:
818 kret = thread_suspend (thread->gdb_port);
819 MACH_CHECK_ERROR (kret);
820 thread->msg_state = DARWIN_STOPPED;
821 break;
822 }
823}
a80b95ba 824
bb00b29d 825static void
2ea28649 826darwin_resume (ptid_t ptid, int step, enum gdb_signal signal)
bb00b29d
TG
827{
828 struct target_waitstatus status;
829 int pid;
a80b95ba 830
bb00b29d
TG
831 kern_return_t kret;
832 int res;
833 int nsignal;
834 struct inferior *inf;
a80b95ba 835
bb00b29d
TG
836 inferior_debug
837 (2, _("darwin_resume: pid=%d, tid=0x%x, step=%d, signal=%d\n"),
838 ptid_get_pid (ptid), ptid_get_tid (ptid), step, signal);
839
a493e3e2 840 if (signal == GDB_SIGNAL_0)
bb00b29d
TG
841 nsignal = 0;
842 else
2ea28649 843 nsignal = gdb_signal_to_host (signal);
a80b95ba 844
bb00b29d
TG
845 /* Don't try to single step all threads. */
846 if (step)
847 ptid = inferior_ptid;
848
849 /* minus_one_ptid is RESUME_ALL. */
850 if (ptid_equal (ptid, minus_one_ptid))
a80b95ba 851 {
bb00b29d
TG
852 struct resume_inferior_threads_param param;
853
854 param.nsignal = nsignal;
855 param.step = step;
a80b95ba 856
bb00b29d
TG
857 /* Resume threads. */
858 iterate_over_inferiors (darwin_resume_inferior_threads_it, &param);
859 /* Resume tasks. */
860 iterate_over_inferiors (darwin_resume_inferior_it, NULL);
861 }
862 else
a80b95ba 863 {
bb00b29d
TG
864 struct inferior *inf = find_inferior_pid (ptid_get_pid (ptid));
865 long tid = ptid_get_tid (ptid);
866
867 /* Stop the inferior (should be useless). */
868 darwin_suspend_inferior (inf);
869
870 if (tid == 0)
871 darwin_resume_inferior_threads (inf, step, nsignal);
872 else
873 {
874 darwin_thread_t *thread;
875
876 /* Suspend threads of the task. */
877 darwin_suspend_inferior_threads (inf);
878
879 /* Resume the selected thread. */
880 thread = darwin_find_thread (inf, tid);
881 gdb_assert (thread);
882 darwin_resume_thread (inf, thread, step, nsignal);
883 }
884
885 /* Resume the task. */
886 darwin_resume_inferior (inf);
a80b95ba 887 }
bb00b29d 888}
a80b95ba 889
bb00b29d
TG
890static void
891darwin_resume_to (struct target_ops *ops, ptid_t ptid, int step,
2ea28649 892 enum gdb_signal signal)
bb00b29d
TG
893{
894 return darwin_resume (ptid, step, signal);
895}
896
897static ptid_t
898darwin_decode_message (mach_msg_header_t *hdr,
899 darwin_thread_t **pthread,
900 struct inferior **pinf,
901 struct target_waitstatus *status)
902{
903 darwin_thread_t *thread;
904 struct inferior *inf;
a80b95ba 905
a41f2563
TG
906 /* Exception message. 2401 == 0x961 is exc. */
907 if (hdr->msgh_id == 2401)
a80b95ba 908 {
bb00b29d
TG
909 int res;
910
911 /* Decode message. */
912 res = darwin_decode_exception_message (hdr, &inf, &thread);
913
914 if (res < 0)
a80b95ba 915 {
bb00b29d 916 /* Should not happen... */
c8c9911f
JB
917 printf_unfiltered
918 (_("darwin_wait: ill-formatted message (id=0x%x)\n"), hdr->msgh_id);
bb00b29d 919 /* FIXME: send a failure reply? */
a41f2563
TG
920 status->kind = TARGET_WAITKIND_IGNORE;
921 return minus_one_ptid;
922 }
923 if (inf == NULL)
924 {
925 status->kind = TARGET_WAITKIND_IGNORE;
a80b95ba
TG
926 return minus_one_ptid;
927 }
bb00b29d
TG
928 *pinf = inf;
929 *pthread = thread;
930 inf->private->pending_messages++;
a80b95ba
TG
931
932 status->kind = TARGET_WAITKIND_STOPPED;
bb00b29d
TG
933 thread->msg_state = DARWIN_MESSAGE;
934
c8c9911f 935 inferior_debug (4, _("darwin_wait: thread=0x%x, got %s\n"),
bb00b29d
TG
936 thread->gdb_port,
937 unparse_exception_type (thread->event.ex_type));
a80b95ba 938
bb00b29d 939 switch (thread->event.ex_type)
a80b95ba
TG
940 {
941 case EXC_BAD_ACCESS:
4e225075 942 status->value.sig = GDB_EXC_BAD_ACCESS;
a80b95ba
TG
943 break;
944 case EXC_BAD_INSTRUCTION:
4e225075 945 status->value.sig = GDB_EXC_BAD_INSTRUCTION;
a80b95ba
TG
946 break;
947 case EXC_ARITHMETIC:
4e225075 948 status->value.sig = GDB_EXC_ARITHMETIC;
a80b95ba
TG
949 break;
950 case EXC_EMULATION:
4e225075 951 status->value.sig = GDB_EXC_EMULATION;
a80b95ba
TG
952 break;
953 case EXC_SOFTWARE:
bb00b29d 954 if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
a80b95ba 955 {
bb00b29d 956 status->value.sig =
2ea28649 957 gdb_signal_from_host (thread->event.ex_data[1]);
bb00b29d
TG
958 inferior_debug (5, _(" (signal %d: %s)\n"),
959 thread->event.ex_data[1],
2ea28649 960 gdb_signal_to_name (status->value.sig));
bb00b29d
TG
961
962 /* If the thread is stopped because it has received a signal
963 that gdb has just sent, continue. */
964 if (thread->signaled)
965 {
966 thread->signaled = 0;
967 darwin_send_reply (inf, thread);
968 thread->msg_state = DARWIN_RUNNING;
969 status->kind = TARGET_WAITKIND_IGNORE;
970 }
a80b95ba
TG
971 }
972 else
4e225075 973 status->value.sig = GDB_EXC_SOFTWARE;
a80b95ba
TG
974 break;
975 case EXC_BREAKPOINT:
976 /* Many internal GDB routines expect breakpoints to be reported
4e225075 977 as GDB_SIGNAL_TRAP, and will report GDB_EXC_BREAKPOINT
0963b4bd 978 as a spurious signal. */
a493e3e2 979 status->value.sig = GDB_SIGNAL_TRAP;
a80b95ba
TG
980 break;
981 default:
a493e3e2 982 status->value.sig = GDB_SIGNAL_UNKNOWN;
a80b95ba
TG
983 break;
984 }
985
bb00b29d
TG
986 return ptid_build (inf->pid, 0, thread->gdb_port);
987 }
a41f2563 988 else if (hdr->msgh_id == 0x48)
bb00b29d 989 {
a41f2563
TG
990 /* MACH_NOTIFY_DEAD_NAME: notification for exit. */
991 *pinf = NULL;
992 *pthread = NULL;
bb00b29d 993
a41f2563
TG
994 inf = darwin_find_inferior_by_notify (hdr->msgh_local_port);
995 if (inf != NULL)
996 {
997 if (!inf->private->no_ptrace)
bb00b29d 998 {
a41f2563
TG
999 pid_t res;
1000 int wstatus;
1001
1002 res = wait4 (inf->pid, &wstatus, 0, NULL);
1003 if (res < 0 || res != inf->pid)
1004 {
1005 printf_unfiltered (_("wait4: res=%d: %s\n"),
1006 res, safe_strerror (errno));
1007 status->kind = TARGET_WAITKIND_IGNORE;
1008 return minus_one_ptid;
1009 }
1010 if (WIFEXITED (wstatus))
1011 {
1012 status->kind = TARGET_WAITKIND_EXITED;
1013 status->value.integer = WEXITSTATUS (wstatus);
1014 }
1015 else
1016 {
1017 status->kind = TARGET_WAITKIND_SIGNALLED;
1018 status->value.sig = WTERMSIG (wstatus);
1019 }
1020
1021 inferior_debug (4, _("darwin_wait: pid=%d exit, status=0x%x\n"),
1022 res, wstatus);
1023
1024 /* Looks necessary on Leopard and harmless... */
1025 wait4 (inf->pid, &wstatus, 0, NULL);
1026
1027 return ptid_build (inf->pid, 0, 0);
bb00b29d
TG
1028 }
1029 else
1030 {
a41f2563
TG
1031 inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
1032 status->kind = TARGET_WAITKIND_EXITED;
1033 status->value.integer = 0; /* Don't know. */
1034 return ptid_build (inf->pid, 0, 0);
bb00b29d 1035 }
bb00b29d
TG
1036 }
1037 }
1038
a41f2563 1039 /* Unknown message. */
86ad98c3 1040 warning (_("darwin: got unknown message, id: 0x%x"), hdr->msgh_id);
a41f2563 1041 status->kind = TARGET_WAITKIND_IGNORE;
bb00b29d
TG
1042 return minus_one_ptid;
1043}
1044
1045static int
1046cancel_breakpoint (ptid_t ptid)
1047{
0963b4bd 1048 /* Arrange for a breakpoint to be hit again later. We will handle
bb00b29d
TG
1049 the current event, eventually we will resume this thread, and this
1050 breakpoint will trap again.
1051
1052 If we do not do this, then we run the risk that the user will
1053 delete or disable the breakpoint, but the thread will have already
1054 tripped on it. */
1055
1056 struct regcache *regcache = get_thread_regcache (ptid);
1057 struct gdbarch *gdbarch = get_regcache_arch (regcache);
1058 CORE_ADDR pc;
a80b95ba 1059
118e6252 1060 pc = regcache_read_pc (regcache) - target_decr_pc_after_break (gdbarch);
40625c9d 1061 if (breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
bb00b29d 1062 {
c8c9911f 1063 inferior_debug (4, "cancel_breakpoint for thread 0x%x\n",
bb00b29d
TG
1064 ptid_get_tid (ptid));
1065
1066 /* Back up the PC if necessary. */
118e6252 1067 if (target_decr_pc_after_break (gdbarch))
bb00b29d
TG
1068 regcache_write_pc (regcache, pc);
1069
1070 return 1;
a80b95ba 1071 }
bb00b29d
TG
1072 return 0;
1073}
1074
1075static ptid_t
1076darwin_wait (ptid_t ptid, struct target_waitstatus *status)
1077{
1078 kern_return_t kret;
1079 union
1080 {
1081 mach_msg_header_t hdr;
1082 char data[0x100];
1083 } msgin;
1084 mach_msg_header_t *hdr = &msgin.hdr;
1085 ptid_t res;
1086 darwin_thread_t *thread;
1087 struct inferior *inf;
1088
1089 inferior_debug
1090 (2, _("darwin_wait: waiting for a message pid=%d thread=%lx\n"),
1091 ptid_get_pid (ptid), ptid_get_tid (ptid));
1092
1093 /* Handle fake stop events at first. */
1094 if (darwin_inf_fake_stop != NULL)
1095 {
1096 inf = darwin_inf_fake_stop;
1097 darwin_inf_fake_stop = NULL;
1098
1099 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 1100 status->value.sig = GDB_SIGNAL_TRAP;
bb00b29d
TG
1101 thread = VEC_index (darwin_thread_t, inf->private->threads, 0);
1102 thread->msg_state = DARWIN_STOPPED;
1103 return ptid_build (inf->pid, 0, thread->gdb_port);
1104 }
1105
1106 do
1107 {
1108 /* set_sigint_trap (); */
1109
1110 /* Wait for a message. */
1111 kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
1112 sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
1113
1114 /* clear_sigint_trap (); */
1115
1116 if (kret == MACH_RCV_INTERRUPTED)
1117 {
1118 status->kind = TARGET_WAITKIND_IGNORE;
1119 return minus_one_ptid;
1120 }
1121
1122 if (kret != MACH_MSG_SUCCESS)
1123 {
c8c9911f 1124 inferior_debug (5, _("mach_msg: ret=0x%x\n"), kret);
bb00b29d
TG
1125 status->kind = TARGET_WAITKIND_SPURIOUS;
1126 return minus_one_ptid;
1127 }
1128
1129 /* Debug: display message. */
1130 if (darwin_debug_flag > 10)
1131 darwin_dump_message (hdr, darwin_debug_flag > 11);
1132
1133 res = darwin_decode_message (hdr, &thread, &inf, status);
a41f2563
TG
1134 if (ptid_equal (res, minus_one_ptid))
1135 continue;
bb00b29d 1136
a41f2563 1137 /* Early return in case an inferior has exited. */
bb00b29d
TG
1138 if (inf == NULL)
1139 return res;
1140 }
1141 while (status->kind == TARGET_WAITKIND_IGNORE);
1142
1143 /* Stop all tasks. */
1144 iterate_over_inferiors (darwin_suspend_inferior_it, NULL);
1145
1146 /* Read pending messages. */
1147 while (1)
a80b95ba 1148 {
bb00b29d
TG
1149 struct target_waitstatus status2;
1150 ptid_t ptid2;
1151
1152 kret = mach_msg (&msgin.hdr,
1153 MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
1154 sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);
1155
1156 if (kret == MACH_RCV_TIMED_OUT)
1157 break;
1158 if (kret != MACH_MSG_SUCCESS)
1159 {
1160 inferior_debug
c8c9911f 1161 (5, _("darwin_wait: mach_msg(pending) ret=0x%x\n"), kret);
bb00b29d
TG
1162 break;
1163 }
1164
a41f2563
TG
1165 /* Debug: display message. */
1166 if (darwin_debug_flag > 10)
1167 darwin_dump_message (hdr, darwin_debug_flag > 11);
1168
bb00b29d 1169 ptid2 = darwin_decode_message (hdr, &thread, &inf, &status2);
a80b95ba 1170
bb00b29d
TG
1171 if (inf != NULL && thread != NULL
1172 && thread->event.ex_type == EXC_BREAKPOINT)
a80b95ba 1173 {
bb00b29d
TG
1174 if (thread->single_step
1175 || cancel_breakpoint (ptid_build (inf->pid, 0, thread->gdb_port)))
1176 {
1177 gdb_assert (thread->msg_state == DARWIN_MESSAGE);
1178 darwin_send_reply (inf, thread);
1179 thread->msg_state = DARWIN_RUNNING;
1180 }
1181 else
1182 inferior_debug
c8c9911f 1183 (3, _("darwin_wait: thread 0x%x hit a non-gdb breakpoint\n"),
bb00b29d 1184 thread->gdb_port);
a80b95ba 1185 }
bb00b29d
TG
1186 else
1187 inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
1188 }
1189 return res;
1190}
a80b95ba 1191
bb00b29d 1192static ptid_t
a6290449 1193darwin_wait_to (struct target_ops *ops,
bb00b29d
TG
1194 ptid_t ptid, struct target_waitstatus *status, int options)
1195{
1196 return darwin_wait (ptid, status);
1197}
a80b95ba 1198
bb00b29d 1199static void
1eab8a48 1200darwin_stop (struct target_ops *self, ptid_t t)
bb00b29d
TG
1201{
1202 struct inferior *inf = current_inferior ();
a80b95ba 1203
bb00b29d
TG
1204 /* FIXME: handle in no_ptrace mode. */
1205 gdb_assert (!inf->private->no_ptrace);
1206 kill (inf->pid, SIGINT);
a80b95ba
TG
1207}
1208
1209static void
1210darwin_mourn_inferior (struct target_ops *ops)
1211{
1212 struct inferior *inf = current_inferior ();
1213 kern_return_t kret;
1214 mach_port_t prev;
1215 int i;
1216
a80b95ba 1217 /* Deallocate threads. */
bb00b29d 1218 if (inf->private->threads)
a80b95ba
TG
1219 {
1220 int k;
bb00b29d
TG
1221 darwin_thread_t *t;
1222 for (k = 0;
1223 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1224 k++)
a80b95ba 1225 {
bb00b29d 1226 kret = mach_port_deallocate (gdb_task, t->gdb_port);
a80b95ba
TG
1227 MACH_CHECK_ERROR (kret);
1228 }
bb00b29d
TG
1229 VEC_free (darwin_thread_t, inf->private->threads);
1230 inf->private->threads = NULL;
a80b95ba
TG
1231 }
1232
bb00b29d
TG
1233 kret = mach_port_move_member (gdb_task,
1234 inf->private->notify_port, MACH_PORT_NULL);
fda184b6 1235 MACH_CHECK_ERROR (kret);
bb00b29d
TG
1236
1237 kret = mach_port_request_notification (gdb_task, inf->private->task,
a80b95ba 1238 MACH_NOTIFY_DEAD_NAME, 0,
bb00b29d 1239 MACH_PORT_NULL,
a80b95ba
TG
1240 MACH_MSG_TYPE_MAKE_SEND_ONCE,
1241 &prev);
1242 /* This can fail if the task is dead. */
c8c9911f 1243 inferior_debug (4, "task=0x%x, prev=0x%x, notify_port=0x%x\n",
bb00b29d
TG
1244 inf->private->task, prev, inf->private->notify_port);
1245
a80b95ba
TG
1246 if (kret == KERN_SUCCESS)
1247 {
1248 kret = mach_port_deallocate (gdb_task, prev);
1249 MACH_CHECK_ERROR (kret);
1250 }
1251
bb00b29d
TG
1252 kret = mach_port_destroy (gdb_task, inf->private->notify_port);
1253 MACH_CHECK_ERROR (kret);
1254
1255
a80b95ba 1256 /* Deallocate saved exception ports. */
bb00b29d 1257 for (i = 0; i < inf->private->exception_info.count; i++)
a80b95ba
TG
1258 {
1259 kret = mach_port_deallocate
bb00b29d 1260 (gdb_task, inf->private->exception_info.ports[i]);
a80b95ba
TG
1261 MACH_CHECK_ERROR (kret);
1262 }
bb00b29d 1263 inf->private->exception_info.count = 0;
a80b95ba 1264
bb00b29d 1265 kret = mach_port_deallocate (gdb_task, inf->private->task);
a80b95ba
TG
1266 MACH_CHECK_ERROR (kret);
1267
bb00b29d
TG
1268 xfree (inf->private);
1269 inf->private = NULL;
a80b95ba 1270
c1ee2fb3 1271 inf_child_mourn_inferior (ops);
a80b95ba
TG
1272}
1273
1274static void
bb00b29d 1275darwin_reply_to_all_pending_messages (struct inferior *inf)
a80b95ba 1276{
bb00b29d
TG
1277 int k;
1278 darwin_thread_t *t;
a80b95ba 1279
bb00b29d
TG
1280 for (k = 0;
1281 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
1282 k++)
1283 {
1284 if (t->msg_state == DARWIN_MESSAGE)
1285 darwin_resume_thread (inf, t, 0, 0);
1286 }
a80b95ba
TG
1287}
1288
1289static void
bb00b29d 1290darwin_stop_inferior (struct inferior *inf)
a80b95ba
TG
1291{
1292 struct target_waitstatus wstatus;
1293 ptid_t ptid;
1294 kern_return_t kret;
1295 int status;
1296 int res;
1297
bb00b29d 1298 gdb_assert (inf != NULL);
a80b95ba 1299
bb00b29d 1300 darwin_suspend_inferior (inf);
a80b95ba 1301
bb00b29d 1302 darwin_reply_to_all_pending_messages (inf);
a80b95ba 1303
bb00b29d
TG
1304 if (inf->private->no_ptrace)
1305 return;
a80b95ba 1306
bb00b29d
TG
1307 res = kill (inf->pid, SIGSTOP);
1308 if (res != 0)
b37520b6 1309 warning (_("cannot kill: %s"), safe_strerror (errno));
a80b95ba 1310
bb00b29d
TG
1311 /* Wait until the process is really stopped. */
1312 while (1)
a80b95ba 1313 {
bb00b29d
TG
1314 ptid = darwin_wait (inferior_ptid, &wstatus);
1315 if (wstatus.kind == TARGET_WAITKIND_STOPPED
a493e3e2 1316 && wstatus.value.sig == GDB_SIGNAL_STOP)
bb00b29d 1317 break;
a80b95ba
TG
1318 }
1319}
1320
1321static kern_return_t
1322darwin_save_exception_ports (darwin_inferior *inf)
1323{
1324 kern_return_t kret;
1325
1326 inf->exception_info.count =
1327 sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
1328
1329 kret = task_get_exception_ports
1330 (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
1331 &inf->exception_info.count, inf->exception_info.ports,
1332 inf->exception_info.behaviors, inf->exception_info.flavors);
1333 return kret;
1334}
1335
1336static kern_return_t
1337darwin_restore_exception_ports (darwin_inferior *inf)
1338{
1339 int i;
1340 kern_return_t kret;
1341
1342 for (i = 0; i < inf->exception_info.count; i++)
1343 {
1344 kret = task_set_exception_ports
1345 (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
1346 inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
1347 if (kret != KERN_SUCCESS)
1348 return kret;
1349 }
1350
1351 return KERN_SUCCESS;
1352}
1353
1354static void
bb00b29d
TG
1355darwin_kill_inferior (struct target_ops *ops)
1356{
1357 struct inferior *inf = current_inferior ();
1358 struct target_waitstatus wstatus;
1359 ptid_t ptid;
1360 kern_return_t kret;
1361 int status;
1362 int res;
1363
1364 if (ptid_equal (inferior_ptid, null_ptid))
1365 return;
1366
1367 gdb_assert (inf != NULL);
1368
ee41036f
TG
1369 kret = darwin_restore_exception_ports (inf->private);
1370 MACH_CHECK_ERROR (kret);
bb00b29d 1371
ee41036f 1372 darwin_reply_to_all_pending_messages (inf);
bb00b29d 1373
ee41036f 1374 res = kill (inf->pid, 9);
bb00b29d 1375
ee41036f 1376 if (res == 0)
bb00b29d 1377 {
bb00b29d 1378 darwin_resume_inferior (inf);
a6290449 1379
bb00b29d
TG
1380 ptid = darwin_wait (inferior_ptid, &wstatus);
1381 }
ee41036f
TG
1382 else if (errno != ESRCH)
1383 warning (_("Failed to kill inferior: kill (%d, 9) returned [%s]"),
1384 inf->pid, safe_strerror (errno));
bb00b29d
TG
1385
1386 target_mourn_inferior ();
1387}
1388
1389static void
1390darwin_attach_pid (struct inferior *inf)
a80b95ba 1391{
a80b95ba
TG
1392 kern_return_t kret;
1393 mach_port_t prev_port;
1394 int traps_expected;
bb00b29d 1395 mach_port_t prev_not;
a80b95ba
TG
1396 exception_mask_t mask;
1397
41bf6aca 1398 inf->private = XCNEW (darwin_inferior);
bb00b29d
TG
1399
1400 kret = task_for_pid (gdb_task, inf->pid, &inf->private->task);
a80b95ba
TG
1401 if (kret != KERN_SUCCESS)
1402 {
1403 int status;
a80b95ba
TG
1404
1405 if (!inf->attach_flag)
1406 {
bb00b29d
TG
1407 kill (inf->pid, 9);
1408 waitpid (inf->pid, &status, 0);
a80b95ba
TG
1409 }
1410
1411 error (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
15c19d39 1412 " (please check gdb is codesigned - see taskgated(8))"),
bb00b29d 1413 inf->pid, mach_error_string (kret), (unsigned long) kret);
a80b95ba
TG
1414 }
1415
bb00b29d
TG
1416 inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
1417 inf->private->task, inf->pid);
a80b95ba
TG
1418
1419 if (darwin_ex_port == MACH_PORT_NULL)
1420 {
1421 /* Create a port to get exceptions. */
1422 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1423 &darwin_ex_port);
fda184b6
JB
1424 if (kret != KERN_SUCCESS)
1425 error (_("Unable to create exception port, mach_port_allocate "
1426 "returned: %d"),
1427 kret);
a80b95ba
TG
1428
1429 kret = mach_port_insert_right (gdb_task, darwin_ex_port, darwin_ex_port,
1430 MACH_MSG_TYPE_MAKE_SEND);
fda184b6
JB
1431 if (kret != KERN_SUCCESS)
1432 error (_("Unable to create exception port, mach_port_insert_right "
1433 "returned: %d"),
1434 kret);
a80b95ba
TG
1435
1436 /* Create a port set and put ex_port in it. */
1437 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
1438 &darwin_port_set);
fda184b6
JB
1439 if (kret != KERN_SUCCESS)
1440 error (_("Unable to create port set, mach_port_allocate "
1441 "returned: %d"),
1442 kret);
a80b95ba
TG
1443
1444 kret = mach_port_move_member (gdb_task, darwin_ex_port, darwin_port_set);
fda184b6
JB
1445 if (kret != KERN_SUCCESS)
1446 error (_("Unable to move exception port into new port set, "
1447 "mach_port_move_member\n"
1448 "returned: %d"),
1449 kret);
bb00b29d 1450 }
a80b95ba 1451
bb00b29d
TG
1452 /* Create a port to be notified when the child task terminates. */
1453 kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
1454 &inf->private->notify_port);
fda184b6
JB
1455 if (kret != KERN_SUCCESS)
1456 error (_("Unable to create notification port, mach_port_allocate "
1457 "returned: %d"),
1458 kret);
a80b95ba 1459
bb00b29d
TG
1460 kret = mach_port_move_member (gdb_task,
1461 inf->private->notify_port, darwin_port_set);
fda184b6
JB
1462 if (kret != KERN_SUCCESS)
1463 error (_("Unable to move notification port into new port set, "
1464 "mach_port_move_member\n"
1465 "returned: %d"),
1466 kret);
a80b95ba 1467
bb00b29d 1468 kret = mach_port_request_notification (gdb_task, inf->private->task,
a80b95ba 1469 MACH_NOTIFY_DEAD_NAME, 0,
bb00b29d 1470 inf->private->notify_port,
a80b95ba 1471 MACH_MSG_TYPE_MAKE_SEND_ONCE,
bb00b29d 1472 &prev_not);
fda184b6
JB
1473 if (kret != KERN_SUCCESS)
1474 error (_("Termination notification request failed, "
1475 "mach_port_request_notification\n"
1476 "returned: %d"),
1477 kret);
1478 if (prev_not != MACH_PORT_NULL)
1479 {
1480 /* This is unexpected, as there should not be any previously
1481 registered notification request. But this is not a fatal
1482 issue, so just emit a warning. */
1483 warning (_("\
1484A task termination request was registered before the debugger registered\n\
1485its own. This is unexpected, but should otherwise not have any actual\n\
1486impact on the debugging session."));
1487 }
a80b95ba 1488
bb00b29d 1489 kret = darwin_save_exception_ports (inf->private);
fda184b6
JB
1490 if (kret != KERN_SUCCESS)
1491 error (_("Unable to save exception ports, task_get_exception_ports"
1492 "returned: %d"),
1493 kret);
a80b95ba
TG
1494
1495 /* Set exception port. */
1496 if (enable_mach_exceptions)
1497 mask = EXC_MASK_ALL;
1498 else
bb00b29d
TG
1499 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
1500 kret = task_set_exception_ports (inf->private->task, mask, darwin_ex_port,
1501 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
fda184b6
JB
1502 if (kret != KERN_SUCCESS)
1503 error (_("Unable to set exception ports, task_set_exception_ports"
1504 "returned: %d"),
1505 kret);
a80b95ba 1506
6a3cb8e8
PA
1507 if (!target_is_pushed (darwin_ops))
1508 push_target (darwin_ops);
a80b95ba
TG
1509}
1510
1511static void
bb00b29d 1512darwin_init_thread_list (struct inferior *inf)
a80b95ba 1513{
bb00b29d
TG
1514 darwin_thread_t *thread;
1515 ptid_t new_ptid;
a80b95ba
TG
1516
1517 darwin_check_new_threads (inf);
1518
bb00b29d
TG
1519 gdb_assert (inf->private->threads
1520 && VEC_length (darwin_thread_t, inf->private->threads) > 0);
1521 thread = VEC_index (darwin_thread_t, inf->private->threads, 0);
1522
1523 /* Note: fork_inferior automatically add a thead but it uses a wrong ptid.
1524 Fix up. */
1525 new_ptid = ptid_build (inf->pid, 0, thread->gdb_port);
1526 thread_change_ptid (inferior_ptid, new_ptid);
1527 inferior_ptid = new_ptid;
1528}
1529
1530/* The child must synchronize with gdb: gdb must set the exception port
1531 before the child call PTRACE_SIGEXC. We use a pipe to achieve this.
1532 FIXME: is there a lighter way ? */
1533static int ptrace_fds[2];
1534
1535static void
1536darwin_ptrace_me (void)
1537{
1538 int res;
1539 char c;
1540
1541 /* Close write end point. */
1542 close (ptrace_fds[1]);
1543
1544 /* Wait until gdb is ready. */
1545 res = read (ptrace_fds[0], &c, 1);
fda184b6
JB
1546 if (res != 0)
1547 error (_("unable to read from pipe, read returned: %d"), res);
bb00b29d
TG
1548 close (ptrace_fds[0]);
1549
1550 /* Get rid of privileges. */
1551 setegid (getgid ());
1552
1553 /* Set TRACEME. */
1554 PTRACE (PT_TRACE_ME, 0, 0, 0);
1555
1556 /* Redirect signals to exception port. */
1557 PTRACE (PT_SIGEXC, 0, 0, 0);
1558}
1559
1560/* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2). */
1561static void
1562darwin_pre_ptrace (void)
1563{
1564 if (pipe (ptrace_fds) != 0)
1565 {
1566 ptrace_fds[0] = -1;
1567 ptrace_fds[1] = -1;
1568 error (_("unable to create a pipe: %s"), safe_strerror (errno));
1569 }
21ff4686
TT
1570
1571 mark_fd_no_cloexec (ptrace_fds[0]);
1572 mark_fd_no_cloexec (ptrace_fds[1]);
a80b95ba
TG
1573}
1574
1575static void
1576darwin_ptrace_him (int pid)
1577{
1578 task_t itask;
1579 kern_return_t kret;
1580 mach_port_t prev_port;
1581 int traps_expected;
bb00b29d 1582 struct inferior *inf = current_inferior ();
a80b95ba 1583
bb00b29d 1584 darwin_attach_pid (inf);
a80b95ba
TG
1585
1586 /* Let's the child run. */
1587 close (ptrace_fds[0]);
1588 close (ptrace_fds[1]);
1589
21ff4686
TT
1590 unmark_fd_no_cloexec (ptrace_fds[0]);
1591 unmark_fd_no_cloexec (ptrace_fds[1]);
1592
bb00b29d
TG
1593 darwin_init_thread_list (inf);
1594
a80b95ba
TG
1595 startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
1596}
1597
e69860f1
TG
1598static void
1599darwin_execvp (const char *file, char * const argv[], char * const env[])
1600{
1601 posix_spawnattr_t attr;
1602 short ps_flags = 0;
f00c55f8 1603 int res;
e69860f1 1604
f00c55f8
TG
1605 res = posix_spawnattr_init (&attr);
1606 if (res != 0)
e69860f1
TG
1607 {
1608 fprintf_unfiltered
1609 (gdb_stderr, "Cannot initialize attribute for posix_spawn\n");
1610 return;
1611 }
1612
1613 /* Do like execve: replace the image. */
1614 ps_flags = POSIX_SPAWN_SETEXEC;
1615
1616 /* Disable ASLR. The constant doesn't look to be available outside the
1617 kernel include files. */
1618#ifndef _POSIX_SPAWN_DISABLE_ASLR
1619#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
1620#endif
1621 ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
f00c55f8
TG
1622 res = posix_spawnattr_setflags (&attr, ps_flags);
1623 if (res != 0)
e69860f1 1624 {
f00c55f8 1625 fprintf_unfiltered (gdb_stderr, "Cannot set posix_spawn flags\n");
e69860f1
TG
1626 return;
1627 }
1628
1629 posix_spawnp (NULL, argv[0], NULL, &attr, argv, env);
1630}
1631
a80b95ba
TG
1632static void
1633darwin_create_inferior (struct target_ops *ops, char *exec_file,
1634 char *allargs, char **env, int from_tty)
1635{
1636 /* Do the hard work. */
1637 fork_inferior (exec_file, allargs, env, darwin_ptrace_me, darwin_ptrace_him,
e69860f1 1638 darwin_pre_ptrace, NULL, darwin_execvp);
bb00b29d 1639
a80b95ba
TG
1640 /* Return now in case of error. */
1641 if (ptid_equal (inferior_ptid, null_ptid))
1642 return;
1643}
1644\f
1645
726ce67c
JB
1646/* Set things up such that the next call to darwin_wait will immediately
1647 return a fake stop event for inferior INF.
1648
1649 This assumes that the inferior's thread list has been initialized,
1650 as it will suspend the inferior's first thread. */
1651
1652static void
1653darwin_setup_fake_stop_event (struct inferior *inf)
1654{
1655 darwin_thread_t *thread;
1656 kern_return_t kret;
1657
1658 gdb_assert (darwin_inf_fake_stop == NULL);
1659 darwin_inf_fake_stop = inf;
1660
1661 /* When detecting a fake pending stop event, darwin_wait returns
1662 an event saying that the first thread is in a DARWIN_STOPPED
1663 state. To make that accurate, we need to suspend that thread
1664 as well. Otherwise, we'll try resuming it when resuming the
1665 inferior, and get a warning because the thread's suspend count
1666 is already zero, making the resume request useless. */
1667 thread = VEC_index (darwin_thread_t, inf->private->threads, 0);
1668 kret = thread_suspend (thread->gdb_port);
1669 MACH_CHECK_ERROR (kret);
1670}
1671
a80b95ba
TG
1672/* Attach to process PID, then initialize for debugging it
1673 and wait for the trace-trap that results from attaching. */
1674static void
1675darwin_attach (struct target_ops *ops, char *args, int from_tty)
1676{
1677 pid_t pid;
1678 pid_t pid2;
1679 int wstatus;
1680 int res;
1681 struct inferior *inf;
bb00b29d 1682 kern_return_t kret;
a80b95ba 1683
74164c56 1684 pid = parse_pid_to_attach (args);
a80b95ba 1685
74164c56 1686 if (pid == getpid ()) /* Trying to masturbate? */
a80b95ba
TG
1687 error (_("I refuse to debug myself!"));
1688
1689 if (from_tty)
bb00b29d
TG
1690 {
1691 char *exec_file = get_exec_file (0);
a80b95ba 1692
bb00b29d
TG
1693 if (exec_file)
1694 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
1695 target_pid_to_str (pid_to_ptid (pid)));
1696 else
1697 printf_unfiltered (_("Attaching to %s\n"),
1698 target_pid_to_str (pid_to_ptid (pid)));
1699
1700 gdb_flush (gdb_stdout);
1701 }
1702
1703 if (pid == 0 || kill (pid, 0) < 0)
1704 error (_("Can't attach to process %d: %s (%d)"),
1705 pid, safe_strerror (errno), errno);
a80b95ba 1706
bb00b29d 1707 inferior_ptid = pid_to_ptid (pid);
6c95b8df
PA
1708 inf = current_inferior ();
1709 inferior_appeared (inf, pid);
a80b95ba 1710 inf->attach_flag = 1;
6c95b8df 1711
bb00b29d
TG
1712 /* Always add a main thread. */
1713 add_thread_silent (inferior_ptid);
a80b95ba 1714
bb00b29d 1715 darwin_attach_pid (inf);
a80b95ba 1716
bb00b29d 1717 darwin_suspend_inferior (inf);
a80b95ba 1718
bb00b29d 1719 darwin_init_thread_list (inf);
a80b95ba 1720
bb00b29d 1721 darwin_check_osabi (inf->private, ptid_get_tid (inferior_ptid));
a80b95ba 1722
726ce67c
JB
1723 darwin_setup_fake_stop_event (inf);
1724
bb00b29d 1725 inf->private->no_ptrace = 1;
a80b95ba
TG
1726}
1727
1728/* Take a program previously attached to and detaches it.
1729 The program resumes execution and will no longer stop
1730 on signals, etc. We'd better not have left any breakpoints
1731 in the program or it'll die when it hits one. For this
1732 to work, it may be necessary for the process to have been
1733 previously attached. It *might* work if the program was
1734 started via fork. */
1735static void
52554a0e 1736darwin_detach (struct target_ops *ops, const char *args, int from_tty)
a80b95ba 1737{
bb00b29d
TG
1738 pid_t pid = ptid_get_pid (inferior_ptid);
1739 struct inferior *inf = current_inferior ();
a80b95ba
TG
1740 kern_return_t kret;
1741 int res;
1742
bb00b29d 1743 /* Display message. */
a80b95ba
TG
1744 if (from_tty)
1745 {
1746 char *exec_file = get_exec_file (0);
1747 if (exec_file == 0)
1748 exec_file = "";
bb00b29d
TG
1749 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
1750 target_pid_to_str (pid_to_ptid (pid)));
a80b95ba
TG
1751 gdb_flush (gdb_stdout);
1752 }
1753
bb00b29d
TG
1754 /* If ptrace() is in use, stop the process. */
1755 if (!inf->private->no_ptrace)
1756 darwin_stop_inferior (inf);
a80b95ba 1757
bb00b29d 1758 kret = darwin_restore_exception_ports (inf->private);
a80b95ba
TG
1759 MACH_CHECK_ERROR (kret);
1760
bb00b29d 1761 if (!inf->private->no_ptrace)
a80b95ba 1762 {
bb00b29d
TG
1763 res = PTRACE (PT_DETACH, inf->pid, 0, 0);
1764 if (res != 0)
1765 printf_unfiltered (_("Unable to detach from process-id %d: %s (%d)"),
1766 inf->pid, safe_strerror (errno), errno);
a80b95ba
TG
1767 }
1768
bb00b29d 1769 darwin_reply_to_all_pending_messages (inf);
a80b95ba 1770
5e9bc145
JB
1771 /* When using ptrace, we have just performed a PT_DETACH, which
1772 resumes the inferior. On the other hand, when we are not using
1773 ptrace, we need to resume its execution ourselves. */
1774 if (inf->private->no_ptrace)
1775 darwin_resume_inferior (inf);
a80b95ba
TG
1776
1777 darwin_mourn_inferior (ops);
1778}
1779
1780static void
1781darwin_files_info (struct target_ops *ops)
1782{
a80b95ba
TG
1783}
1784
1785static char *
117de6a9 1786darwin_pid_to_str (struct target_ops *ops, ptid_t ptid)
a80b95ba 1787{
bb00b29d
TG
1788 static char buf[80];
1789 long tid = ptid_get_tid (ptid);
1790
1791 if (tid != 0)
1792 {
1793 snprintf (buf, sizeof (buf), _("Thread 0x%lx of process %u"),
1794 tid, ptid_get_pid (ptid));
1795 return buf;
1796 }
a80b95ba 1797
bb00b29d 1798 return normal_pid_to_str (ptid);
a80b95ba
TG
1799}
1800
1801static int
28439f5e 1802darwin_thread_alive (struct target_ops *ops, ptid_t ptid)
a80b95ba
TG
1803{
1804 return 1;
1805}
1806
1807/* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
1808 copy it to RDADDR in gdb's address space.
1809 If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
1810 to ADDR in inferior task's address space.
f00c55f8 1811 Return 0 on failure; number of bytes read / writen otherwise. */
a80b95ba
TG
1812static int
1813darwin_read_write_inferior (task_t task, CORE_ADDR addr,
b9dd1947 1814 gdb_byte *rdaddr, const gdb_byte *wraddr,
b55e14c7 1815 ULONGEST length)
a80b95ba 1816{
bb00b29d 1817 kern_return_t kret;
a80b95ba
TG
1818 mach_vm_address_t offset = addr & (mach_page_size - 1);
1819 mach_vm_address_t low_address = (mach_vm_address_t) (addr - offset);
1820 mach_vm_size_t aligned_length = (mach_vm_size_t) PAGE_ROUND (offset + length);
1821 pointer_t copied;
b9dd1947 1822 mach_msg_type_number_t copy_count;
a80b95ba
TG
1823 mach_vm_size_t remaining_length;
1824 mach_vm_address_t region_address;
1825 mach_vm_size_t region_length;
1826
b55e14c7
YQ
1827 inferior_debug (8, _("darwin_read_write_inferior(task=0x%x, %s, len=%s)\n"),
1828 task, core_addr_to_string (addr), pulongest (length));
bb00b29d 1829
0963b4bd 1830 /* Get memory from inferior with page aligned addresses. */
bb00b29d 1831 kret = mach_vm_read (task, low_address, aligned_length,
a80b95ba 1832 &copied, &copy_count);
bb00b29d 1833 if (kret != KERN_SUCCESS)
a80b95ba 1834 {
bb00b29d
TG
1835 inferior_debug
1836 (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
1837 core_addr_to_string (addr), mach_error_string (kret));
a80b95ba
TG
1838 return 0;
1839 }
1840
1841 if (rdaddr != NULL)
1842 memcpy (rdaddr, (char *)copied + offset, length);
1843
1844 if (wraddr == NULL)
1845 goto out;
1846
1847 memcpy ((char *)copied + offset, wraddr, length);
1848
1849 /* Do writes atomically.
1850 First check for holes and unwritable memory. */
1851 for (region_address = low_address, remaining_length = aligned_length;
1852 region_address < low_address + aligned_length;
1853 region_address += region_length, remaining_length -= region_length)
1854 {
bb00b29d
TG
1855 vm_region_submap_short_info_data_64_t info;
1856 mach_vm_address_t region_start = region_address;
a80b95ba 1857 mach_msg_type_number_t count;
bb00b29d
TG
1858 natural_t region_depth;
1859
1860 region_depth = 100000;
1861 count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
1862 kret = mach_vm_region_recurse
1863 (task, &region_start, &region_length, &region_depth,
1864 (vm_region_recurse_info_t) &info, &count);
1865
1866 if (kret != KERN_SUCCESS)
a80b95ba 1867 {
bb00b29d
TG
1868 inferior_debug (1, _("darwin_read_write_inferior: "
1869 "mach_vm_region_recurse failed at %s: %s\n"),
1870 core_addr_to_string (region_address),
1871 mach_error_string (kret));
a80b95ba
TG
1872 goto out;
1873 }
1874
bb00b29d
TG
1875 inferior_debug
1876 (9, _("darwin_read_write_inferior: "
1877 "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
1878 core_addr_to_string (region_address),
1879 core_addr_to_string (region_start),
1880 core_addr_to_string (region_length));
1881
0963b4bd 1882 /* Check for holes in memory. */
bb00b29d 1883 if (region_start > region_address)
a80b95ba 1884 {
0963b4bd 1885 warning (_("No memory at %s (vs %s+0x%x). Nothing written"),
a80b95ba 1886 core_addr_to_string (region_address),
bb00b29d 1887 core_addr_to_string (region_start),
a80b95ba
TG
1888 (unsigned)region_length);
1889 length = 0;
1890 goto out;
1891 }
1892
bb00b29d
TG
1893 /* Adjust the length. */
1894 region_length -= (region_address - region_start);
1895
a80b95ba
TG
1896 if (!(info.max_protection & VM_PROT_WRITE))
1897 {
bb00b29d
TG
1898 kret = mach_vm_protect
1899 (task, region_address, region_length,
1900 TRUE, info.max_protection | VM_PROT_WRITE | VM_PROT_COPY);
1901 if (kret != KERN_SUCCESS)
1902 {
1903 warning (_("darwin_read_write_inf: "
1904 "mach_vm_protect max failed at %s: %s"),
1905 core_addr_to_string (region_address),
1906 mach_error_string (kret));
1907 length = 0;
1908 goto out;
1909 }
a80b95ba
TG
1910 }
1911
1912 if (!(info.protection & VM_PROT_WRITE))
1913 {
bb00b29d 1914 kret = mach_vm_protect (task, region_address, region_length,
a80b95ba 1915 FALSE, info.protection | VM_PROT_WRITE);
bb00b29d 1916 if (kret != KERN_SUCCESS)
a80b95ba 1917 {
bb00b29d
TG
1918 warning (_("darwin_read_write_inf: "
1919 "mach_vm_protect failed at %s (len=0x%lx): %s"),
1920 core_addr_to_string (region_address),
1921 (unsigned long)region_length, mach_error_string (kret));
a80b95ba
TG
1922 length = 0;
1923 goto out;
1924 }
1925 }
1926 }
1927
bb00b29d 1928 kret = mach_vm_write (task, low_address, copied, aligned_length);
a80b95ba 1929
bb00b29d 1930 if (kret != KERN_SUCCESS)
a80b95ba
TG
1931 {
1932 warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
bb00b29d 1933 mach_error_string (kret));
a80b95ba
TG
1934 length = 0;
1935 }
1936out:
1937 mach_vm_deallocate (mach_task_self (), copied, copy_count);
1938 return length;
1939}
1940
f00c55f8
TG
1941/* Read LENGTH bytes at offset ADDR of task_dyld_info for TASK, and copy them
1942 to RDADDR.
569283d4 1943 Return 0 on failure; number of bytes read / written otherwise. */
f00c55f8 1944
b967eb24 1945#ifdef TASK_DYLD_INFO_COUNT
569283d4 1946/* This is not available in Darwin 9. */
9b409511 1947static enum target_xfer_status
b9dd1947 1948darwin_read_dyld_info (task_t task, CORE_ADDR addr, gdb_byte *rdaddr,
9b409511 1949 ULONGEST length, ULONGEST *xfered_len)
f00c55f8
TG
1950{
1951 struct task_dyld_info task_dyld_info;
1952 mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
1953 int sz = TASK_DYLD_INFO_COUNT * sizeof (natural_t);
1954 kern_return_t kret;
1955
1956 if (addr >= sz)
9b409511 1957 return TARGET_XFER_EOF;
f00c55f8
TG
1958
1959 kret = task_info (task, TASK_DYLD_INFO, (task_info_t) &task_dyld_info, &count);
1960 MACH_CHECK_ERROR (kret);
1961 if (kret != KERN_SUCCESS)
2ed4b548 1962 return TARGET_XFER_E_IO;
f00c55f8
TG
1963 /* Truncate. */
1964 if (addr + length > sz)
1965 length = sz - addr;
1966 memcpy (rdaddr, (char *)&task_dyld_info + addr, length);
9b409511
YQ
1967 *xfered_len = (ULONGEST) length;
1968 return TARGET_XFER_OK;
f00c55f8 1969}
569283d4 1970#endif
f00c55f8 1971
a80b95ba 1972\f
a80b95ba 1973
1b281443 1974static enum target_xfer_status
a80b95ba
TG
1975darwin_xfer_partial (struct target_ops *ops,
1976 enum target_object object, const char *annex,
1977 gdb_byte *readbuf, const gdb_byte *writebuf,
9b409511 1978 ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
a80b95ba 1979{
bb00b29d
TG
1980 struct inferior *inf = current_inferior ();
1981
1982 inferior_debug
b55e14c7
YQ
1983 (8, _("darwin_xfer_partial(%s, %s, rbuf=%s, wbuf=%s) pid=%u\n"),
1984 core_addr_to_string (offset), pulongest (len),
854f4b0e
TG
1985 host_address_to_string (readbuf), host_address_to_string (writebuf),
1986 inf->pid);
a80b95ba 1987
f00c55f8
TG
1988 switch (object)
1989 {
1990 case TARGET_OBJECT_MEMORY:
9b409511
YQ
1991 {
1992 int l = darwin_read_write_inferior (inf->private->task, offset,
1993 readbuf, writebuf, len);
1994
1995 if (l == 0)
1996 return TARGET_XFER_EOF;
1997 else
1998 {
1999 gdb_assert (l > 0);
2000 *xfered_len = (ULONGEST) l;
2001 return TARGET_XFER_OK;
2002 }
2003 }
569283d4 2004#ifdef TASK_DYLD_INFO_COUNT
f00c55f8
TG
2005 case TARGET_OBJECT_DARWIN_DYLD_INFO:
2006 if (writebuf != NULL || readbuf == NULL)
2007 {
2008 /* Support only read. */
2ed4b548 2009 return TARGET_XFER_E_IO;
f00c55f8 2010 }
9b409511
YQ
2011 return darwin_read_dyld_info (inf->private->task, offset, readbuf, len,
2012 xfered_len);
569283d4 2013#endif
f00c55f8 2014 default:
2ed4b548 2015 return TARGET_XFER_E_IO;
f00c55f8 2016 }
a80b95ba 2017
a80b95ba
TG
2018}
2019
2020static void
2021set_enable_mach_exceptions (char *args, int from_tty,
2022 struct cmd_list_element *c)
2023{
bb00b29d 2024 if (!ptid_equal (inferior_ptid, null_ptid))
a80b95ba 2025 {
bb00b29d 2026 struct inferior *inf = current_inferior ();
a80b95ba
TG
2027 exception_mask_t mask;
2028 kern_return_t kret;
2029
2030 if (enable_mach_exceptions)
2031 mask = EXC_MASK_ALL;
2032 else
2033 {
bb00b29d
TG
2034 darwin_restore_exception_ports (inf->private);
2035 mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
a80b95ba 2036 }
bb00b29d 2037 kret = task_set_exception_ports (inf->private->task, mask, darwin_ex_port,
a80b95ba
TG
2038 EXCEPTION_DEFAULT, THREAD_STATE_NONE);
2039 MACH_CHECK_ERROR (kret);
2040 }
2041}
2042
bb00b29d 2043static char *
8dd27370 2044darwin_pid_to_exec_file (struct target_ops *self, int pid)
bb00b29d 2045{
b4ab256d 2046 static char path[PATH_MAX];
bb00b29d
TG
2047 int res;
2048
d8d2a3ee 2049 res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, PATH_MAX);
bb00b29d
TG
2050 if (res >= 0)
2051 return path;
2052 else
2053 return NULL;
2054}
2055
2056static ptid_t
1e6b91a4 2057darwin_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
bb00b29d
TG
2058{
2059 int i;
2060 darwin_thread_t *t;
2061 int k;
2062 struct inferior *inf = current_inferior ();
2063 kern_return_t kret;
2064 mach_port_name_array_t names;
2065 mach_msg_type_number_t names_count;
2066 mach_port_type_array_t types;
2067 mach_msg_type_number_t types_count;
2068 long res = 0;
2069
2070 /* First linear search. */
2071 for (k = 0;
2072 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
2073 k++)
2074 if (t->inf_port == lwp)
2075 return ptid_build (ptid_get_pid (inferior_ptid), 0, t->gdb_port);
2076
2077 /* Maybe the port was never extract. Do it now. */
2078
2079 /* First get inferior port names. */
2080 kret = mach_port_names (inf->private->task, &names, &names_count, &types,
2081 &types_count);
2082 MACH_CHECK_ERROR (kret);
2083 if (kret != KERN_SUCCESS)
2084 return null_ptid;
2085
2086 /* For each name, copy the right in the gdb space and then compare with
2087 our view of the inferior threads. We don't forget to deallocate the
2088 right. */
2089 for (i = 0; i < names_count; i++)
2090 {
2091 mach_port_t local_name;
2092 mach_msg_type_name_t local_type;
2093
2094 /* We just need to know the corresponding name in gdb name space.
2095 So extract and deallocate the right. */
2096 kret = mach_port_extract_right (inf->private->task, names[i],
2097 MACH_MSG_TYPE_COPY_SEND,
2098 &local_name, &local_type);
2099 if (kret != KERN_SUCCESS)
2100 continue;
2101 mach_port_deallocate (gdb_task, local_name);
2102
2103 for (k = 0;
2104 VEC_iterate (darwin_thread_t, inf->private->threads, k, t);
2105 k++)
2106 if (t->gdb_port == local_name)
2107 {
2108 t->inf_port = names[i];
2109 if (names[i] == lwp)
2110 res = t->gdb_port;
2111 }
2112 }
2113
2114 vm_deallocate (gdb_task, (vm_address_t) names,
2115 names_count * sizeof (mach_port_t));
2116
2117 if (res)
2118 return ptid_build (ptid_get_pid (inferior_ptid), 0, res);
2119 else
2120 return null_ptid;
2121}
2122
2123static int
86ce2668 2124darwin_supports_multi_process (struct target_ops *self)
bb00b29d
TG
2125{
2126 return 1;
2127}
2128
c381a3f6
JB
2129/* -Wmissing-prototypes */
2130extern initialize_file_ftype _initialize_darwin_inferior;
2131
a80b95ba 2132void
bb00b29d 2133_initialize_darwin_inferior (void)
a80b95ba
TG
2134{
2135 kern_return_t kret;
2136
a80b95ba
TG
2137 gdb_task = mach_task_self ();
2138 darwin_host_self = mach_host_self ();
2139
2140 /* Read page size. */
2141 kret = host_page_size (darwin_host_self, &mach_page_size);
2142 if (kret != KERN_SUCCESS)
2143 {
2144 mach_page_size = 0x1000;
2145 MACH_CHECK_ERROR (kret);
2146 }
2147
a80b95ba
TG
2148 darwin_ops = inf_child_target ();
2149
a80b95ba
TG
2150 darwin_ops->to_create_inferior = darwin_create_inferior;
2151 darwin_ops->to_attach = darwin_attach;
2152 darwin_ops->to_attach_no_wait = 0;
2153 darwin_ops->to_detach = darwin_detach;
2154 darwin_ops->to_files_info = darwin_files_info;
bb00b29d 2155 darwin_ops->to_wait = darwin_wait_to;
a80b95ba
TG
2156 darwin_ops->to_mourn_inferior = darwin_mourn_inferior;
2157 darwin_ops->to_kill = darwin_kill_inferior;
2158 darwin_ops->to_stop = darwin_stop;
bb00b29d 2159 darwin_ops->to_resume = darwin_resume_to;
a80b95ba
TG
2160 darwin_ops->to_thread_alive = darwin_thread_alive;
2161 darwin_ops->to_pid_to_str = darwin_pid_to_str;
bb00b29d 2162 darwin_ops->to_pid_to_exec_file = darwin_pid_to_exec_file;
a80b95ba 2163 darwin_ops->to_load = NULL;
a80b95ba 2164 darwin_ops->to_xfer_partial = darwin_xfer_partial;
bb00b29d
TG
2165 darwin_ops->to_supports_multi_process = darwin_supports_multi_process;
2166 darwin_ops->to_get_ada_task_ptid = darwin_get_ada_task_ptid;
a80b95ba
TG
2167
2168 darwin_complete_target (darwin_ops);
2169
2170 add_target (darwin_ops);
2171
2172 inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"), mach_task_self (),
2173 getpid ());
2174
ccce17b0
YQ
2175 add_setshow_zuinteger_cmd ("darwin", class_obscure,
2176 &darwin_debug_flag, _("\
a80b95ba
TG
2177Set if printing inferior communication debugging statements."), _("\
2178Show if printing inferior communication debugging statements."), NULL,
ccce17b0
YQ
2179 NULL, NULL,
2180 &setdebuglist, &showdebuglist);
a80b95ba
TG
2181
2182 add_setshow_boolean_cmd ("mach-exceptions", class_support,
2183 &enable_mach_exceptions, _("\
2184Set if mach exceptions are caught."), _("\
2185Show if mach exceptions are caught."), _("\
2186When this mode is on, all low level exceptions are reported before being\n\
2187reported by the kernel."),
2188 &set_enable_mach_exceptions, NULL,
2189 &setlist, &showlist);
2190}