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