OSDN Git Service

abe285c5a0fe21b8407382b8f39417a35d19e8f0
[pf3gnuchains/pf3gnuchains3x.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
55 #include <mach/mach_error.h>
56 #include <mach/mach_vm.h>
57 #include <mach/mach_init.h>
58 #include <mach/vm_map.h>
59 #include <mach/task.h>
60 #include <mach/mach_port.h>
61 #include <mach/thread_act.h>
62 #include <mach/port.h>
63
64 #include "darwin-nat.h"
65
66 /* Quick overview.
67    Darwin kernel is Mach + BSD derived kernel.  Note that they share the
68    same memory space and are linked together (ie there is no micro-kernel).
69
70    Although ptrace(2) is available on Darwin, it is not complete.  We have
71    to use Mach calls to read and write memory and to modify registers.  We
72    also use Mach to get inferior faults.  As we cannot use select(2) or
73    signals with Mach port (the Mach communication channel), signals are
74    reported to gdb as an exception.  Furthermore we detect death of the
75    inferior through a Mach notification message.  This way we only wait
76    on Mach ports.
77
78    Some Mach documentation is available for Apple xnu source package or
79    from the web.  */
80
81
82 #define PTRACE(CMD, PID, ADDR, SIG) \
83  darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))
84
85 extern boolean_t exc_server (mach_msg_header_t *in, mach_msg_header_t *out);
86
87 static void darwin_stop (ptid_t);
88
89 static void darwin_mourn_inferior (struct target_ops *ops);
90
91 static int darwin_lookup_task (char *args, task_t * ptask, int *ppid);
92
93 static void darwin_kill_inferior (struct target_ops *ops);
94
95 static void darwin_ptrace_me (void);
96
97 static void darwin_ptrace_him (int pid);
98
99 static void darwin_create_inferior (struct target_ops *ops, char *exec_file,
100                                     char *allargs, char **env, int from_tty);
101
102 static void darwin_files_info (struct target_ops *ops);
103
104 /* Current inferior.  */
105 darwin_inferior *darwin_inf = NULL;
106
107 /* Target operations for Darwin.  */
108 static struct target_ops *darwin_ops;
109
110 /* Task identifier of gdb.  */
111 static task_t gdb_task;
112
113 /* A copy of mach_host_self ().  */
114 mach_port_t darwin_host_self;
115
116 /* Exception port.  */
117 mach_port_t darwin_ex_port;
118
119 /* Notification port.  */
120 mach_port_t darwin_not_port;
121
122 /* Port set.  */
123 mach_port_t darwin_port_set;
124
125 /* Page size. */
126 static vm_size_t mach_page_size;
127
128 /* If Set, catch all mach exceptions (before they are converted to signals
129    by the kernel).  */
130 static int enable_mach_exceptions;
131
132 #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
133 #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
134
135 /* Buffer containing received message and to be sent message.  */
136 static union
137 {
138   mach_msg_header_t hdr;
139   char data[1024];
140 } msgin, msgout;
141
142 /* Current message state.
143    If the kernel has sent a message it expects a reply and the inferior
144    can't be killed before.  */
145 static enum msg_state { NO_MESSAGE, GOT_MESSAGE, REPLY_SENT } msg_state;
146
147 /* Unmarshalled received message.  */
148 static struct exc_msg
149 {
150   /* Receive port.  */
151   mach_port_t port;
152
153   /* Thread and task taking the exception.  */
154   mach_port_t thread_port;
155   mach_port_t task_port;
156
157   /* Type of the exception.  */
158   exception_type_t ex_type;
159
160   /* Machine dependent details.  */
161   mach_msg_type_number_t data_count;
162   integer_t ex_data[4];
163 } exc_msg;
164
165
166 /* This controls output of inferior debugging.
167    1 = basic exception handling
168    2 = task management
169    3 = thread management
170    4 = pending_event_handler
171    6 = most chatty level.  */
172
173 static int darwin_debug_flag = 0;
174
175 static void
176 inferior_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
189 void
190 mach_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]");
197   
198   error (_("error on line %u of \"%s\" in function \"%s\": %s (0x%lx)\n"),
199          line, file, func, mach_error_string (ret), (unsigned long) ret);
200 }
201
202 static const char *
203 unparse_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
235 static int
236 darwin_ptrace (const char *name,
237                int request, int pid, PTRACE_TYPE_ARG3 arg3, int arg4)
238 {
239   int ret;
240
241   ret = ptrace (request, pid, (caddr_t) arg3, arg4);
242
243   inferior_debug (2, _("ptrace (%s, %d, 0x%x, %d): %d (%s)\n"),
244                   name, pid, arg3, arg4, ret,
245                   (ret != 0) ? safe_strerror (errno) : _("no error"));
246   return ret;
247 }
248
249 static int
250 cmp_thread_t (const void *l, const void *r)
251 {
252   thread_t lt = *(const thread_t *)l;
253   thread_t lr = *(const thread_t *)r;
254   return (int)(lr - lt);
255 }
256
257 static void
258 darwin_check_new_threads (darwin_inferior *inf)
259 {
260   kern_return_t kret;
261   unsigned int i;
262   thread_array_t thread_list;
263   unsigned int new_nbr;
264   unsigned int old_nbr;
265   unsigned int new_ix, old_ix;
266   VEC (thread_t) *thread_vec;
267
268   /* Get list of threads.  */
269   kret = task_threads (inf->task, &thread_list, &new_nbr);
270   MACH_CHECK_ERROR (kret);
271   if (kret != KERN_SUCCESS)
272     return;
273
274   if (new_nbr > 1)
275     qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
276
277   thread_vec = VEC_alloc (thread_t, new_nbr);
278
279   if (inf->threads)
280     old_nbr = VEC_length (thread_t, inf->threads);
281   else
282     old_nbr = 0;
283
284   for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
285     {
286       thread_t new_id = (new_ix < new_nbr) ?
287         thread_list[new_ix] : THREAD_NULL;
288       thread_t old_id = (old_ix < old_nbr) ?
289         VEC_index (thread_t, inf->threads, old_ix) : THREAD_NULL;
290
291       if (old_id == new_id)
292         {
293           /* Thread still exist.  */
294           VEC_safe_push (thread_t, thread_vec, old_id);
295           new_ix++;
296           old_ix++;
297
298           kret = mach_port_deallocate (gdb_task, old_id);
299           MACH_CHECK_ERROR (kret);
300           continue;
301         }
302       if (new_id < old_id || old_ix == old_nbr)
303         {
304           /* A thread was created.  */
305           struct thread_info *tp;
306
307           tp = add_thread (ptid_build (inf->pid, 0, new_id));
308           VEC_safe_push (thread_t, thread_vec, new_id);
309           new_ix++;
310           continue;
311         }
312       if (new_id > old_id || new_ix == new_nbr)
313         {
314           /* A thread was removed.  */
315           delete_thread (ptid_build (inf->pid, 0, old_id));
316           kret = mach_port_deallocate (gdb_task, old_id);
317           MACH_CHECK_ERROR (kret);
318           old_ix++;
319         }
320     }
321
322   if (inf->threads)
323     VEC_free (thread_t, inf->threads);
324   inf->threads = thread_vec;
325
326   kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
327                         new_nbr * sizeof (int));
328   MACH_CHECK_ERROR (kret);
329 }
330
331 static void
332 darwin_stop (ptid_t t)
333 {
334   int ret;
335
336   ret = kill (ptid_get_pid (inferior_ptid), SIGINT);
337 }
338
339 static void
340 darwin_resume (struct target_ops *ops,
341                ptid_t ptid, int step, enum target_signal signal)
342 {
343   struct target_waitstatus status;
344   int pid;
345   thread_t thread;
346   kern_return_t kret;
347   int res;
348
349   /* minus_one_ptid is RESUME_ALL.  */
350   if (ptid_equal (ptid, minus_one_ptid))
351     ptid = inferior_ptid;
352
353   pid = ptid_get_pid (ptid);
354   thread = ptid_get_tid (ptid);
355
356   inferior_debug
357     (2, _("darwin_resume: state=%d, thread=0x%x, step=%d signal=%d\n"),
358      msg_state, thread, step, signal);
359
360   switch (msg_state)
361     {
362     case GOT_MESSAGE:
363       switch (exc_msg.ex_type)
364         {
365         case EXC_SOFTWARE:
366           if (exc_msg.ex_data[0] == EXC_SOFT_SIGNAL)
367             {
368               int nsignal = target_signal_to_host (signal);
369               res = PTRACE (PT_THUPDATE, pid,
370                             (void *)(uintptr_t)exc_msg.thread_port, nsignal);
371               if (res < 0)
372                 printf_unfiltered (_("ptrace THUP: res=%d\n"), res);
373             }
374           break;
375
376         default:
377           break;
378         }
379           
380       if (thread != 0)
381         {
382           inferior_debug (2, _("darwin_set_sstep (thread=%x, enable=%d)\n"),
383                           thread, step);
384           darwin_set_sstep (thread, step);
385         }
386
387       kret = mach_msg (&msgout.hdr, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
388                        msgout.hdr.msgh_size, 0,
389                        MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
390                        MACH_PORT_NULL);
391       if (kret != 0)
392         printf_unfiltered (_("mach_msg (reply) ret=%d\n"), kret);
393
394       msg_state = REPLY_SENT;
395       break;
396
397     case NO_MESSAGE:
398       if (step)
399         res = PTRACE (PT_STEP, pid, (caddr_t)1, 0);
400       else
401         res = PTRACE (PT_CONTINUE, pid, (caddr_t)1, 0);
402       break;
403
404     default:
405       gdb_assert (0);
406     }
407 }
408
409 kern_return_t
410 catch_exception_raise_state
411   (mach_port_t port,
412    exception_type_t exception_type, mach_exception_data_t exception_data,
413    mach_msg_type_number_t data_count, thread_state_flavor_t * state_flavor,
414    thread_state_t in_state, mach_msg_type_number_t in_state_count,
415    thread_state_t out_state, mach_msg_type_number_t out_state_count)
416 {
417   return KERN_FAILURE;
418 }
419
420 kern_return_t
421 catch_exception_raise_state_identity
422   (mach_port_t port, mach_port_t thread_port, mach_port_t task_port,
423    exception_type_t exception_type, mach_exception_data_t exception_data,
424    mach_msg_type_number_t data_count, thread_state_flavor_t * state_flavor,
425    thread_state_t in_state, mach_msg_type_number_t in_state_count,
426    thread_state_t out_state, mach_msg_type_number_t out_state_count)
427 {
428   kern_return_t kret;
429
430   kret = mach_port_deallocate (mach_task_self (), task_port);
431   MACH_CHECK_ERROR (kret);
432   kret = mach_port_deallocate (mach_task_self (), thread_port);
433   MACH_CHECK_ERROR (kret);
434
435   return KERN_FAILURE;
436 }
437
438 kern_return_t
439 catch_exception_raise (mach_port_t port,
440                        mach_port_t thread_port,
441                        mach_port_t task_port,
442                        exception_type_t exception_type,
443                        exception_data_t exception_data,
444                        mach_msg_type_number_t data_count)
445 {
446   kern_return_t kret;
447   int i;
448   int res;
449
450   /* We got new rights to the task.  Get rid of it.  */
451   kret = mach_port_deallocate (mach_task_self (), task_port);
452   MACH_CHECK_ERROR (kret);
453
454   inferior_debug
455     (7, _("catch_exception_raise: exception_type=%d, data_count=%d\n"),
456      exception_type, data_count);
457   if (darwin_debug_flag > 7)
458     {
459       for (i = 0; i < data_count; i++)
460         printf_unfiltered (" %08x", exception_data[i]);
461       printf_unfiltered ("\n");
462     }
463
464   /* Save the message.
465      FIXME: this should be in a per-thread variable.  */
466   exc_msg.port = port;
467   exc_msg.thread_port = thread_port;
468   exc_msg.task_port = task_port;
469   exc_msg.ex_type = exception_type;
470   exc_msg.data_count = data_count;
471   for (i = 0; i < data_count && i < 4; i++)
472     exc_msg.ex_data[i] = exception_data[i];
473
474   return KERN_SUCCESS;
475 }
476
477 static ptid_t
478 darwin_wait (struct target_ops *ops,
479              ptid_t ptid, struct target_waitstatus *status)
480 {
481   kern_return_t kret;
482   mach_msg_header_t *hdr = &msgin.hdr;
483   pid_t pid = ptid_get_pid (inferior_ptid); /* FIXME.  */
484
485   gdb_assert (msg_state != GOT_MESSAGE);
486
487   inferior_debug (6, _("darwin_wait: waiting for a message\n"));
488
489   /* Wait for a message.  */
490   kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
491                    sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
492
493   if (kret == MACH_RCV_INTERRUPTED)
494     {
495       status->kind = TARGET_WAITKIND_IGNORE;
496       return minus_one_ptid;
497     }
498
499   if (kret != MACH_MSG_SUCCESS)
500     {
501       inferior_debug (1, _("mach_msg: ret=%x\n"), kret);
502       status->kind = TARGET_WAITKIND_SPURIOUS;
503       return minus_one_ptid;
504     }
505
506   /* Debug: display message.  */
507   if (darwin_debug_flag > 10)
508    {
509      const unsigned long *buf = (unsigned long *) hdr;
510      unsigned int i;
511      
512      printf_unfiltered (_(" bits: 0x%x"), hdr->msgh_bits);
513      printf_unfiltered (_(", size: 0x%x"), hdr->msgh_size);
514      printf_unfiltered (_(", remote-port: 0x%x"), hdr->msgh_remote_port);
515      printf_unfiltered (_(", local-port: 0x%x"), hdr->msgh_local_port);
516      printf_unfiltered (_(", reserved: 0x%x"), hdr->msgh_reserved);
517      printf_unfiltered (_(", id: 0x%x\n"), hdr->msgh_id);
518
519      if (darwin_debug_flag > 11)
520         {
521           printf_unfiltered (_("  data:"));
522           for (i = 0; i < hdr->msgh_size; i++)
523             printf_unfiltered (" %08lx", buf[i]);
524           printf_unfiltered (_("\n"));
525         }
526    }
527
528   /* Exception message.  */
529   if (hdr->msgh_local_port == darwin_ex_port)
530     {
531       /* Handle it via the exception server.  */
532       if (!exc_server (&msgin.hdr, &msgout.hdr))
533         {
534           printf_unfiltered (_("exc_server: unknown message (id=%x)\n"),
535                              hdr->msgh_id);
536           status->kind = TARGET_WAITKIND_SPURIOUS;
537           return minus_one_ptid;
538         }
539
540       status->kind = TARGET_WAITKIND_STOPPED;
541
542       inferior_debug (2, _("darwin_wait: thread=%x, got %s\n"),
543                       exc_msg.thread_port, 
544                       unparse_exception_type (exc_msg.ex_type));
545   
546       switch (exc_msg.ex_type)
547         {
548         case EXC_BAD_ACCESS:
549           status->value.sig = TARGET_EXC_BAD_ACCESS;
550           break;
551         case EXC_BAD_INSTRUCTION:
552           status->value.sig = TARGET_EXC_BAD_INSTRUCTION;
553           break;
554         case EXC_ARITHMETIC:
555           status->value.sig = TARGET_EXC_ARITHMETIC;
556           break;
557         case EXC_EMULATION:
558           status->value.sig = TARGET_EXC_EMULATION;
559           break;
560         case EXC_SOFTWARE:
561           if (exc_msg.ex_data[0] == EXC_SOFT_SIGNAL)
562             {
563               status->value.sig = target_signal_from_host (exc_msg.ex_data[1]);
564               inferior_debug (2, _("  (signal %d: %s)\n"),
565                               exc_msg.ex_data[1],
566                               target_signal_to_name (status->value.sig));
567             }
568           else
569             status->value.sig = TARGET_EXC_SOFTWARE;
570           break;
571         case EXC_BREAKPOINT:
572           /* Many internal GDB routines expect breakpoints to be reported
573              as TARGET_SIGNAL_TRAP, and will report TARGET_EXC_BREAKPOINT
574              as a spurious signal. */
575           status->value.sig = TARGET_SIGNAL_TRAP;
576           break;
577         default:
578           status->value.sig = TARGET_SIGNAL_UNKNOWN;
579           break;
580         }
581
582       msg_state = GOT_MESSAGE;
583
584       return ptid_build (pid, 0, exc_msg.thread_port);
585     }
586   else if (hdr->msgh_local_port == darwin_not_port)
587     {
588       pid_t res;
589       int wstatus;
590
591       /* FIXME: translate task port to pid.  */
592       res = wait4 (pid, &wstatus, 0, NULL);
593       if (res != pid)
594         {
595           printf_unfiltered (_("wait4: res=%x\n"), res);
596           wstatus = 0;
597         }
598       status->kind = TARGET_WAITKIND_EXITED;
599       status->value.integer = WEXITSTATUS (wstatus);
600
601       inferior_debug (2, _("darwin_wait: pid=%d exit, status=%x\n"),
602                       pid, wstatus);
603
604       msg_state = NO_MESSAGE;
605
606       return ptid;
607     }
608   else
609     {
610       printf_unfiltered (_("Bad local-port: %x\n"), hdr->msgh_local_port);
611       status->kind = TARGET_WAITKIND_SPURIOUS;
612       return minus_one_ptid;
613     }
614 }
615
616 static void
617 darwin_mourn_inferior (struct target_ops *ops)
618 {
619   struct inferior *inf = current_inferior ();
620   kern_return_t kret;
621   mach_port_t prev;
622   int i;
623
624   unpush_target (darwin_ops);
625
626   /* Deallocate threads.  */
627   if (darwin_inf->threads)
628     {
629       int k;
630       thread_t t;
631       for (k = 0; VEC_iterate (thread_t, darwin_inf->threads, k, t); k++)
632         {
633           kret = mach_port_deallocate (gdb_task, t);
634           MACH_CHECK_ERROR (kret);
635         }
636       VEC_free (thread_t, darwin_inf->threads);
637       darwin_inf->threads = NULL;
638     }
639
640   kret = mach_port_request_notification (gdb_task, darwin_inf->task,
641                                          MACH_NOTIFY_DEAD_NAME, 0,
642                                          darwin_inf->prev_not_port,
643                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
644                                          &prev);
645   /* This can fail if the task is dead.  */
646   if (kret == KERN_SUCCESS)
647     {
648       kret = mach_port_deallocate (gdb_task, prev);
649       MACH_CHECK_ERROR (kret);
650     }
651
652   /* Deallocate saved exception ports.  */
653   for (i = 0; i < darwin_inf->exception_info.count; i++)
654     {
655       kret = mach_port_deallocate
656         (gdb_task, darwin_inf->exception_info.ports[i]);
657       MACH_CHECK_ERROR (kret);
658     }
659   darwin_inf->exception_info.count = 0;
660
661   kret = mach_port_deallocate (gdb_task, darwin_inf->task);
662   MACH_CHECK_ERROR (kret);
663
664   darwin_inf->task = 0;
665   darwin_inf->pid = 0;
666
667   generic_mourn_inferior ();
668 }
669
670 static void
671 darwin_stop_inferior (struct target_ops *ops, darwin_inferior *inf)
672 {
673   struct target_waitstatus wstatus;
674   ptid_t ptid;
675   kern_return_t kret;
676   int status;
677   int res;
678
679   gdb_assert (inf != NULL);
680
681   kret = task_suspend (inf->task);
682   MACH_CHECK_ERROR (kret);
683
684   if (msg_state == GOT_MESSAGE)
685     darwin_resume (darwin_ops, inferior_ptid, 0, 0);
686
687   res = kill (inf->pid, SIGSTOP);
688   if (res != 0)
689     warning (_("cannot kill: %s\n"), safe_strerror (errno));
690
691   ptid = darwin_wait (ops, inferior_ptid, &wstatus);
692   gdb_assert (wstatus.kind = TARGET_WAITKIND_STOPPED);
693 }
694
695 static void
696 darwin_kill_inferior (struct target_ops *ops)
697 {
698   struct target_waitstatus wstatus;
699   ptid_t ptid;
700   kern_return_t kret;
701   int status;
702   int res;
703
704   gdb_assert (darwin_inf != NULL);
705
706   if (ptid_equal (inferior_ptid, null_ptid))
707     return;
708
709   darwin_stop_inferior (ops, darwin_inf);
710
711   res = PTRACE (PT_KILL, darwin_inf->pid, 0, 0);
712   gdb_assert (res == 0);
713
714   if (msg_state == GOT_MESSAGE)
715     {
716       exc_msg.ex_type = 0;
717       darwin_resume (ops, inferior_ptid, 0, 0);
718     }
719
720   kret = task_resume (darwin_inf->task);
721   MACH_CHECK_ERROR (kret);
722
723   ptid = darwin_wait (ops, inferior_ptid, &wstatus);
724
725   /* This double wait seems required...  */
726   res = waitpid (darwin_inf->pid, &status, 0);
727   gdb_assert (res == darwin_inf->pid);
728
729   msg_state = NO_MESSAGE;
730
731   target_mourn_inferior ();
732 }
733
734 /* The child must synchronize with gdb: gdb must set the exception port
735    before the child call PTRACE_SIGEXC.  We use a pipe to achieve this.
736    FIXME: is there a lighter way ?  */
737 static int ptrace_fds[2];
738
739 static void
740 darwin_ptrace_me (void)
741 {
742   int res;
743   char c;
744
745   /* Close write end point.  */
746   close (ptrace_fds[1]);
747
748   /* Wait until gdb is ready.  */
749   res = read (ptrace_fds[0], &c, 1);
750   gdb_assert (res == 0);
751   close (ptrace_fds[0]);
752
753   /* Get rid of privileges.  */
754   setegid (getgid ());
755
756   /* Set TRACEME.  */
757   PTRACE (PT_TRACE_ME, 0, 0, 0);
758
759   /* Redirect signals to exception port.  */
760   PTRACE (PT_SIGEXC, 0, 0, 0);
761 }
762
763 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2).  */
764 static void
765 darwin_pre_ptrace (void)
766 {
767   if (pipe (ptrace_fds) != 0)
768     {
769       ptrace_fds[0] = -1;
770       ptrace_fds[1] = -1;
771       error (_("unable to create a pipe: %s"), safe_strerror (errno));
772     }
773 }
774
775 static kern_return_t
776 darwin_save_exception_ports (darwin_inferior *inf)
777 {
778   kern_return_t kret;
779
780   inf->exception_info.count =
781     sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
782
783   kret = task_get_exception_ports
784     (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
785      &inf->exception_info.count, inf->exception_info.ports,
786      inf->exception_info.behaviors, inf->exception_info.flavors);
787   return kret;
788 }
789
790 static kern_return_t
791 darwin_restore_exception_ports (darwin_inferior *inf)
792 {
793   int i;
794   kern_return_t kret;
795
796   for (i = 0; i < inf->exception_info.count; i++)
797     {
798       kret = task_set_exception_ports
799         (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
800          inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
801       if (kret != KERN_SUCCESS)
802         return kret;
803     }
804
805   return KERN_SUCCESS;
806 }
807
808 static void
809 darwin_attach_pid (int pid)
810 {
811   task_t itask;
812   kern_return_t kret;
813   mach_port_t prev_port;
814   int traps_expected;
815   exception_mask_t mask;
816
817   kret = task_for_pid (gdb_task, pid, &itask);
818   if (kret != KERN_SUCCESS)
819     {
820       int status;
821       struct inferior *inf = current_inferior ();
822
823       if (!inf->attach_flag)
824         {
825           kill (pid, 9);
826           waitpid (pid, &status, 0);
827         }
828
829       error (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
830                " (please check gdb is setgid procmod)"),
831              pid, mach_error_string (kret), (unsigned long) kret);
832     }
833
834   inferior_debug (2, _("inferior task: 0x%08x, pid: %d\n"), itask, pid);
835
836   if (darwin_ex_port == MACH_PORT_NULL)
837     {
838       /* Create a port to get exceptions.  */
839       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
840                                  &darwin_ex_port);
841       gdb_assert (kret == KERN_SUCCESS);
842
843       kret = mach_port_insert_right (gdb_task, darwin_ex_port, darwin_ex_port,
844                                      MACH_MSG_TYPE_MAKE_SEND);
845       gdb_assert (kret == KERN_SUCCESS);
846
847       /* Create a port set and put ex_port in it.  */
848       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
849                                  &darwin_port_set);
850       gdb_assert (kret == KERN_SUCCESS);
851
852       kret = mach_port_move_member (gdb_task, darwin_ex_port, darwin_port_set);
853       gdb_assert (kret == KERN_SUCCESS);
854
855       /* Create a port to be notified when the child task terminates.  */
856       kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
857                                  &darwin_not_port);
858       gdb_assert (kret == KERN_SUCCESS);
859
860       kret = mach_port_insert_right (gdb_task, darwin_not_port, darwin_not_port,
861                                      MACH_MSG_TYPE_MAKE_SEND);
862       gdb_assert (kret == KERN_SUCCESS);
863
864       kret = mach_port_move_member (gdb_task, darwin_not_port, darwin_port_set);
865       gdb_assert (kret == KERN_SUCCESS);
866     }
867
868   kret = mach_port_request_notification (gdb_task, itask,
869                                          MACH_NOTIFY_DEAD_NAME, 0,
870                                          darwin_not_port,
871                                          MACH_MSG_TYPE_MAKE_SEND_ONCE,
872                                          &darwin_inf->prev_not_port);
873   gdb_assert (kret == KERN_SUCCESS);
874
875   darwin_inf->task = itask;
876   darwin_inf->pid = pid;
877
878   kret = darwin_save_exception_ports (darwin_inf);
879   gdb_assert (kret == KERN_SUCCESS);
880
881   /* Set exception port.  */
882   if (enable_mach_exceptions)
883     mask = EXC_MASK_ALL;
884   else
885     mask = EXC_MASK_SOFTWARE;
886   kret = task_set_exception_ports
887     (itask, mask, darwin_ex_port, EXCEPTION_DEFAULT, THREAD_STATE_NONE);
888   gdb_assert (kret == KERN_SUCCESS);
889
890   push_target (darwin_ops);
891 }
892
893 static void
894 darwin_init_thread_list (darwin_inferior *inf)
895 {
896   thread_t thread;
897
898   darwin_check_new_threads (inf);
899
900   gdb_assert (inf->threads && VEC_length (thread_t, inf->threads) > 0);
901   thread = VEC_index (thread_t, inf->threads, 0);
902   inferior_ptid = ptid_build (inf->pid, 0, thread);
903 }
904
905 static void
906 darwin_ptrace_him (int pid)
907 {
908   task_t itask;
909   kern_return_t kret;
910   mach_port_t prev_port;
911   int traps_expected;
912
913   darwin_attach_pid (pid);
914
915   /* Let's the child run.  */
916   close (ptrace_fds[0]);
917   close (ptrace_fds[1]);
918
919   /* fork_inferior automatically add a thread - but it uses a wrong tid.  */
920   delete_thread_silent (inferior_ptid);
921   darwin_init_thread_list (darwin_inf);
922   
923   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
924 }
925
926 static void
927 darwin_create_inferior (struct target_ops *ops, char *exec_file,
928                         char *allargs, char **env, int from_tty)
929 {
930   /* Do the hard work.  */
931   fork_inferior (exec_file, allargs, env, darwin_ptrace_me, darwin_ptrace_him,
932                  darwin_pre_ptrace, NULL);
933   
934   /* Return now in case of error.  */
935   if (ptid_equal (inferior_ptid, null_ptid))
936     return;
937 }
938 \f
939
940 /* Attach to process PID, then initialize for debugging it
941    and wait for the trace-trap that results from attaching.  */
942 static void
943 darwin_attach (struct target_ops *ops, char *args, int from_tty)
944 {
945   pid_t pid;
946   pid_t pid2;
947   int wstatus;
948   int res;
949   struct inferior *inf;
950
951   gdb_assert (msg_state == NO_MESSAGE);
952
953   if (!args)
954     error_no_arg (_("process-id to attach"));
955
956   pid = atoi (args);
957
958   if (pid == getpid ())         /* Trying to masturbate? */
959     error (_("I refuse to debug myself!"));
960
961   if (from_tty)
962     printf_unfiltered (_("Attaching to pid %d\n"), pid);
963
964   res = PTRACE (PT_ATTACHEXC, pid, 0, 0);
965   if (res != 0)
966     error (_("Unable to attach to process-id %d: %s (%d)"),
967            pid, safe_strerror (errno), errno);
968
969   inf = add_inferior (pid);
970   inf->attach_flag = 1;
971
972   darwin_attach_pid (pid);
973
974   pid2 = wait4 (pid, &wstatus, WUNTRACED, NULL);
975   gdb_assert (pid2 == pid);
976   inferior_debug (1, _("darwin_attach: wait4 pid=%d, status=0x%x\n"),
977                   pid2, wstatus);
978
979   
980   darwin_init_thread_list (darwin_inf);
981
982   darwin_check_osabi (darwin_inf, ptid_get_tid (inferior_ptid));
983
984   /* Looks strange, but the kernel doesn't stop the process...
985      (Bug in Leopard ?)
986      Do it manually.  */
987   /* FIXME: doesn't look to work with multi-threads!!  */
988   kill (pid, SIGSTOP);
989 }
990
991 /* Take a program previously attached to and detaches it.
992    The program resumes execution and will no longer stop
993    on signals, etc.  We'd better not have left any breakpoints
994    in the program or it'll die when it hits one.  For this
995    to work, it may be necessary for the process to have been
996    previously attached.  It *might* work if the program was
997    started via fork.  */
998 static void
999 darwin_detach (struct target_ops *ops, char *args, int from_tty)
1000 {
1001   kern_return_t kret;
1002   int res;
1003
1004   if (from_tty)
1005     {
1006       char *exec_file = get_exec_file (0);
1007       if (exec_file == 0)
1008         exec_file = "";
1009       printf_unfiltered (_("Detaching from program: %s, %d\n"), exec_file,
1010                          ptid_get_pid (inferior_ptid));
1011       gdb_flush (gdb_stdout);
1012     }
1013
1014   darwin_stop_inferior (ops, darwin_inf);
1015
1016   kret = darwin_restore_exception_ports (darwin_inf);
1017   MACH_CHECK_ERROR (kret);
1018
1019   if (msg_state == GOT_MESSAGE)
1020     {
1021       exc_msg.ex_type = 0;
1022       darwin_resume (ops, inferior_ptid, 0, 0);
1023     }
1024
1025   kret = task_resume (darwin_inf->task);
1026   gdb_assert (kret == KERN_SUCCESS);
1027
1028   res = PTRACE (PT_DETACH, darwin_inf->pid, 0, 0);
1029   if (res != 0)
1030     printf_unfiltered (_("Unable to detach from process-id %d: %s (%d)"),
1031                        darwin_inf->pid, safe_strerror (errno), errno);
1032
1033   msg_state = NO_MESSAGE;
1034
1035   darwin_mourn_inferior (ops);
1036 }
1037
1038 static void
1039 darwin_files_info (struct target_ops *ops)
1040 {
1041   gdb_assert (darwin_inf != NULL);
1042 }
1043
1044 static char *
1045 darwin_pid_to_str (struct target_ops *ops, ptid_t ptid)
1046 {
1047   static char buf[128];
1048
1049   snprintf (buf, sizeof (buf),
1050             _("process %d gdb-thread 0x%lx"),
1051             (unsigned) ptid_get_pid (ptid),
1052             (unsigned long) ptid_get_tid (ptid));
1053   return buf;
1054 }
1055
1056 static int
1057 darwin_thread_alive (struct target_ops *ops, ptid_t ptid)
1058 {
1059   return 1;
1060 }
1061
1062 /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
1063    copy it to RDADDR in gdb's address space.
1064    If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
1065    to ADDR in inferior task's address space.
1066    Return 0 on failure; number of bytes read / writen  otherwise.  */
1067 static int
1068 darwin_read_write_inferior (task_t task, CORE_ADDR addr,
1069                             char *rdaddr, const char *wraddr, int length)
1070 {
1071   kern_return_t err;
1072   mach_vm_address_t offset = addr & (mach_page_size - 1);
1073   mach_vm_address_t low_address = (mach_vm_address_t) (addr - offset);
1074   mach_vm_size_t aligned_length = (mach_vm_size_t) PAGE_ROUND (offset + length);
1075   pointer_t copied;
1076   int copy_count;
1077   mach_vm_size_t remaining_length;
1078   mach_vm_address_t region_address;
1079   mach_vm_size_t region_length;
1080
1081   inferior_debug (8, _("darwin_read_write_inferior(%s, len=%d)\n"),
1082                   core_addr_to_string (addr), length);
1083   
1084   /* Get memory from inferior with page aligned addresses */
1085   err = mach_vm_read (task, low_address, aligned_length,
1086                       &copied, &copy_count);
1087   if (err != KERN_SUCCESS)
1088     {
1089       warning (_("darwin_read_write_inferior: vm_read failed: %s"), 
1090                mach_error_string (err));
1091       return 0;
1092     }
1093
1094   if (rdaddr != NULL)
1095     memcpy (rdaddr, (char *)copied + offset, length);
1096
1097   if (wraddr == NULL)
1098     goto out;
1099
1100   memcpy ((char *)copied + offset, wraddr, length);
1101
1102   /* Do writes atomically.
1103      First check for holes and unwritable memory.  */
1104   for (region_address = low_address, remaining_length = aligned_length;
1105        region_address < low_address + aligned_length;
1106        region_address += region_length, remaining_length -= region_length)
1107     {
1108       vm_region_basic_info_data_64_t info;
1109       mach_port_t object_name;
1110       mach_vm_address_t old_address = region_address;
1111       mach_msg_type_number_t count;
1112       
1113       region_length = remaining_length;
1114       count = VM_REGION_BASIC_INFO_COUNT_64;
1115       err = mach_vm_region (task, &region_address, &region_length,
1116                             VM_REGION_BASIC_INFO_64,
1117                             (vm_region_info_t) &info, &count, &object_name);
1118       
1119       if (err != KERN_SUCCESS)
1120         {
1121           warning (_("darwin_write_inferior: mach_vm_region failed: %s"), 
1122                    mach_error_string (err));
1123           goto out;
1124         }
1125
1126       /* Check for holes in memory */
1127       if (region_address > old_address)
1128         {
1129           warning (_("No memory at %s (vs %s+0x%x). Nothing written"),
1130                    core_addr_to_string (old_address),
1131                    core_addr_to_string (region_address),
1132                    (unsigned)region_length);
1133           length = 0;
1134           goto out;
1135         }
1136
1137       if (!(info.max_protection & VM_PROT_WRITE))
1138         {
1139           warning (_("Memory at address %s is unwritable. Nothing written"),
1140                    core_addr_to_string (old_address));
1141           length = 0;
1142           goto out;
1143         }
1144
1145       if (!(info.protection & VM_PROT_WRITE))
1146         {
1147           err = mach_vm_protect (task, old_address, region_length,
1148                                  FALSE, info.protection | VM_PROT_WRITE);
1149           if (err != KERN_SUCCESS)
1150             {
1151               warning
1152                 (_("darwin_read_write_inferior: mach_vm_protect failed: %s"), 
1153                  mach_error_string (err));
1154               length = 0;
1155               goto out;
1156             }
1157         }
1158     }
1159
1160   err = mach_vm_write (task, low_address, copied, aligned_length);
1161
1162   if (err != KERN_SUCCESS)
1163     {
1164       warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
1165                mach_error_string (err));
1166       length = 0;
1167     }
1168 out:
1169   mach_vm_deallocate (mach_task_self (), copied, copy_count);
1170   return length;
1171 }
1172
1173 \f
1174 /* Return 0 on failure, number of bytes handled otherwise.  TARGET
1175    is ignored. */
1176 static int
1177 darwin_xfer_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len, int write,
1178                     struct mem_attrib *attrib, struct target_ops *target)
1179 {
1180   task_t task = darwin_inf->task;
1181
1182   if (task == MACH_PORT_NULL)
1183     return 0;
1184
1185   inferior_debug (8, _("darwin_xfer_memory(%s, %d, %c)\n"),
1186                   core_addr_to_string (memaddr), len, write ? 'w' : 'r');
1187
1188   if (write)
1189     return darwin_read_write_inferior (task, memaddr, NULL, myaddr, len);
1190   else
1191     return darwin_read_write_inferior (task, memaddr, myaddr, NULL, len);
1192 }
1193
1194 static LONGEST
1195 darwin_xfer_partial (struct target_ops *ops,
1196                      enum target_object object, const char *annex,
1197                      gdb_byte *readbuf, const gdb_byte *writebuf,
1198                      ULONGEST offset, LONGEST len)
1199 {
1200   inferior_debug (8, _("darwin_xfer_partial(%s, %d, rbuf=%p, wbuf=%p)\n"),
1201                   core_addr_to_string (offset), (int)len, readbuf, writebuf);
1202
1203   if (object != TARGET_OBJECT_MEMORY)
1204     return -1;
1205
1206   return darwin_read_write_inferior (darwin_inf->task, offset,
1207                                      readbuf, writebuf, len);
1208 }
1209
1210 static void
1211 set_enable_mach_exceptions (char *args, int from_tty,
1212                             struct cmd_list_element *c)
1213 {
1214   if (darwin_inf && darwin_inf->task != TASK_NULL)
1215     {
1216       exception_mask_t mask;
1217       kern_return_t kret;
1218
1219       if (enable_mach_exceptions)
1220         mask = EXC_MASK_ALL;
1221       else
1222         {
1223           darwin_restore_exception_ports (darwin_inf);
1224           mask = EXC_MASK_SOFTWARE;
1225         }
1226       kret = task_set_exception_ports (darwin_inf->task, mask, darwin_ex_port,
1227                                        EXCEPTION_DEFAULT, THREAD_STATE_NONE);
1228       MACH_CHECK_ERROR (kret);
1229     }
1230 }
1231
1232 void
1233 _initialize_darwin_inferior ()
1234 {
1235   kern_return_t kret;
1236
1237   gdb_assert (darwin_inf == NULL);
1238   
1239   gdb_task = mach_task_self ();
1240   darwin_host_self = mach_host_self ();
1241
1242   /* Read page size.  */
1243   kret = host_page_size (darwin_host_self, &mach_page_size);
1244   if (kret != KERN_SUCCESS)
1245     {
1246       mach_page_size = 0x1000;
1247       MACH_CHECK_ERROR (kret);
1248     }
1249
1250   darwin_inf = (struct darwin_inferior *)
1251     xmalloc (sizeof (struct darwin_inferior));
1252
1253   memset (darwin_inf, 0, sizeof (*darwin_inf));
1254
1255   darwin_ops = inf_child_target ();
1256
1257   darwin_ops->to_shortname = "darwin-child";
1258   darwin_ops->to_longname = _("Darwin child process");
1259   darwin_ops->to_doc =
1260     _("Darwin child process (started by the \"run\" command).");
1261   darwin_ops->to_create_inferior = darwin_create_inferior;
1262   darwin_ops->to_attach = darwin_attach;
1263   darwin_ops->to_attach_no_wait = 0;
1264   darwin_ops->to_detach = darwin_detach;
1265   darwin_ops->to_files_info = darwin_files_info;
1266   darwin_ops->to_wait = darwin_wait;
1267   darwin_ops->to_mourn_inferior = darwin_mourn_inferior;
1268   darwin_ops->to_kill = darwin_kill_inferior;
1269   darwin_ops->to_stop = darwin_stop;
1270   darwin_ops->to_resume = darwin_resume;
1271   darwin_ops->to_thread_alive = darwin_thread_alive;
1272   darwin_ops->to_pid_to_str = darwin_pid_to_str;
1273   darwin_ops->to_load = NULL;
1274   darwin_ops->deprecated_xfer_memory = darwin_xfer_memory;
1275   darwin_ops->to_xfer_partial = darwin_xfer_partial;
1276   darwin_ops->to_has_thread_control = tc_schedlock /*| tc_switch */;
1277
1278   darwin_complete_target (darwin_ops);
1279
1280   add_target (darwin_ops);
1281
1282   inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"), mach_task_self (),
1283                   getpid ());
1284
1285   add_setshow_zinteger_cmd ("darwin", class_obscure,
1286                             &darwin_debug_flag, _("\
1287 Set if printing inferior communication debugging statements."), _("\
1288 Show if printing inferior communication debugging statements."), NULL,
1289                             NULL, NULL,
1290                             &setdebuglist, &showdebuglist);
1291
1292   add_setshow_boolean_cmd ("mach-exceptions", class_support,
1293                            &enable_mach_exceptions, _("\
1294 Set if mach exceptions are caught."), _("\
1295 Show if mach exceptions are caught."), _("\
1296 When this mode is on, all low level exceptions are reported before being\n\
1297 reported by the kernel."),
1298                            &set_enable_mach_exceptions, NULL,
1299                            &setlist, &showlist);
1300 }