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