OSDN Git Service

* inf-ptrace.c: Reorder functions.
[pf3gnuchains/pf3gnuchains3x.git] / gdb / inf-ptrace.c
1 /* Low-level child interface to ptrace.
2
3    Copyright 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
4    1998, 1999, 2000, 2001, 2002, 2004, 2005
5    Free Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 59 Temple Place - Suite 330,
22    Boston, MA 02111-1307, USA.  */
23
24 #include "defs.h"
25 #include "command.h"
26 #include "inferior.h"
27 #include "inflow.h"
28 #include "gdbcore.h"
29 #include "observer.h"
30 #include "regcache.h"
31
32 #include "gdb_assert.h"
33 #include "gdb_string.h"
34 #include "gdb_ptrace.h"
35 #include "gdb_wait.h"
36 #include <signal.h>
37
38 #include "inf-child.h"
39
40 /* HACK: Save the ptrace ops returned by inf_ptrace_target.  */
41 static struct target_ops *ptrace_ops_hack;
42 \f
43
44 /* Stub function which causes the inferior that runs it, to be ptrace-able
45    by its parent process.  */
46
47 static void
48 inf_ptrace_me (void)
49 {
50   /* "Trace me, Dr. Memory!"  */
51   ptrace (0, 0, (PTRACE_TYPE_ARG3) 0, 0);
52 }
53
54 /* Stub function which causes the GDB that runs it, to start ptrace-ing
55    the child process.  */
56
57 static void
58 inf_ptrace_him (int pid)
59 {
60   push_target (ptrace_ops_hack);
61
62   /* On some targets, there must be some explicit synchronization
63      between the parent and child processes after the debugger
64      forks, and before the child execs the debuggee program.  This
65      call basically gives permission for the child to exec.  */
66
67   target_acknowledge_created_inferior (pid);
68
69   /* START_INFERIOR_TRAPS_EXPECTED is defined in inferior.h, and will
70      be 1 or 2 depending on whether we're starting without or with a
71      shell.  */
72   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
73
74   /* On some targets, there must be some explicit actions taken after
75      the inferior has been started up.  */
76   target_post_startup_inferior (pid_to_ptid (pid));
77 }
78
79 /* Start an inferior Unix child process and sets inferior_ptid to its
80    pid.  EXEC_FILE is the file to run.  ALLARGS is a string containing
81    the arguments to the program.  ENV is the environment vector to
82    pass.  Errors reported with error().  */
83
84 static void
85 inf_ptrace_create_inferior (char *exec_file, char *allargs, char **env,
86                             int from_tty)
87 {
88   fork_inferior (exec_file, allargs, env, inf_ptrace_me, inf_ptrace_him,
89                  NULL, NULL);
90   /* We are at the first instruction we care about.  */
91   observer_notify_inferior_created (&current_target, from_tty);
92   /* Pedal to the metal...  */
93   proceed ((CORE_ADDR) -1, TARGET_SIGNAL_0, 0);
94 }
95
96 static void
97 inf_ptrace_mourn_inferior (void)
98 {
99   unpush_target (ptrace_ops_hack);
100   generic_mourn_inferior ();
101 }
102
103 /* Attach to process PID, then initialize for debugging it.  */
104
105 static void
106 inf_ptrace_attach (char *args, int from_tty)
107 {
108   char *exec_file;
109   int pid;
110   char *dummy;
111
112   if (!args)
113     error_no_arg (_("process-id to attach"));
114
115   dummy = args;
116   pid = strtol (args, &dummy, 0);
117   /* Some targets don't set errno on errors, grrr!  */
118   if (pid == 0 && args == dummy)
119     error (_("Illegal process-id: %s."), args);
120
121   if (pid == getpid ())         /* Trying to masturbate?  */
122     error (_("I refuse to debug myself!"));
123
124   if (from_tty)
125     {
126       exec_file = (char *) get_exec_file (0);
127
128       if (exec_file)
129         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
130                            target_pid_to_str (pid_to_ptid (pid)));
131       else
132         printf_unfiltered (_("Attaching to %s\n"),
133                            target_pid_to_str (pid_to_ptid (pid)));
134
135       gdb_flush (gdb_stdout);
136     }
137
138 #ifdef PT_ATTACH
139   errno = 0;
140   ptrace (PT_ATTACH, pid, (PTRACE_TYPE_ARG3) 0, 0);
141   if (errno != 0)
142     perror_with_name (("ptrace"));
143   attach_flag = 1;
144 #else
145   error (_("This system does not support attaching to a process"));
146 #endif
147
148   inferior_ptid = pid_to_ptid (pid);
149   push_target (ptrace_ops_hack);
150
151   /* Do this first, before anything has had a chance to query the
152      inferior's symbol table or similar.  */
153   observer_notify_inferior_created (&current_target, from_tty);
154 }
155
156 /* Take a program previously attached to and detaches it.  The program
157    resumes execution and will no longer stop on signals, etc.  We'd
158    better not have left any breakpoints in the program or it'll die
159    when it hits one.  For this to work, it may be necessary for the
160    process to have been previously attached.  It *might* work if the
161    program was started via the normal ptrace (PTRACE_TRACEME).  */
162
163 static void
164 inf_ptrace_detach (char *args, int from_tty)
165 {
166   int sig = 0;
167   int pid = PIDGET (inferior_ptid);
168
169   if (from_tty)
170     {
171       char *exec_file = get_exec_file (0);
172       if (exec_file == 0)
173         exec_file = "";
174       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
175                          target_pid_to_str (pid_to_ptid (pid)));
176       gdb_flush (gdb_stdout);
177     }
178   if (args)
179     sig = atoi (args);
180
181 #ifdef PT_DETACH
182   errno = 0;
183   ptrace (PT_DETACH, pid, (PTRACE_TYPE_ARG3) 1, sig);
184   if (errno != 0)
185     perror_with_name (("ptrace"));
186   attach_flag = 0;
187 #else
188   error (_("This system does not support detaching from a process"));
189 #endif
190
191   inferior_ptid = null_ptid;
192   unpush_target (ptrace_ops_hack);
193 }
194
195 static void
196 inf_ptrace_kill_inferior (void)
197 {
198   int status;
199   int pid = PIDGET (inferior_ptid);
200
201   if (pid == 0)
202     return;
203
204   /* This once used to call "kill" to kill the inferior just in case
205      the inferior was still running.  As others have noted in the past
206      (kingdon) there shouldn't be any way to get here if the inferior
207      is still running -- else there's a major problem elsewere in GDB
208      and it needs to be fixed.
209
210      The kill call causes problems under HP-UX 10, so it's been
211      removed; if this causes problems we'll deal with them as they
212      arise.  */
213   ptrace (PT_KILL, pid, (PTRACE_TYPE_ARG3) 0, 0);
214   wait (&status);
215   target_mourn_inferior ();
216 }
217
218 /* Send a SIGINT to the process group.  This acts just like the user
219    typed a ^C on the controlling terminal.
220
221    FIXME: This may not be correct for all systems.  Some may want to
222    use killpg() instead of kill (-pgrp).  */
223
224 static void
225 inf_ptrace_stop (void)
226 {
227   kill (-inferior_process_group, SIGINT);
228 }
229
230 /* Resume execution of the inferior process.  If STEP is nonzero,
231    single-step it.  If SIGNAL is nonzero, give it that signal.  */
232
233 static void
234 inf_ptrace_resume (ptid_t ptid, int step, enum target_signal signal)
235 {
236   int request = PT_CONTINUE;
237   int pid = PIDGET (ptid);
238
239   if (pid == -1)
240     /* Resume all threads.  */
241     /* I think this only gets used in the non-threaded case, where
242        "resume all threads" and "resume inferior_ptid" are the
243        same.  */
244     pid = PIDGET (inferior_ptid);
245
246   if (step)
247     {
248       /* If this system does not support PT_STEP, a higher level
249          function will have called single_step() to transmute the step
250          request into a continue request (by setting breakpoints on
251          all possible successor instructions), so we don't have to
252          worry about that here.  */
253       request = PT_STEP;
254     }
255
256   /* An address of (PTRACE_TYPE_ARG3)1 tells ptrace to continue from
257      where it was.  If GDB wanted it to start some other way, we have
258      already written a new PC value to the child.  */
259   errno = 0;
260   ptrace (request, pid, (PTRACE_TYPE_ARG3) 1, target_signal_to_host (signal));
261   if (errno != 0)
262     perror_with_name (("ptrace"));
263 }
264
265 /* Wait for child to do something.  Return pid of child, or -1 in case
266    of error; store status through argument pointer OURSTATUS.  */
267
268 static ptid_t
269 inf_ptrace_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
270 {
271   int save_errno;
272   int status;
273   char *execd_pathname = NULL;
274   int exit_status;
275   int related_pid;
276   int syscall_id;
277   enum target_waitkind kind;
278   int pid;
279
280   do
281     {
282       set_sigint_trap ();       /* Causes SIGINT to be passed on to the
283                                    attached process. */
284       set_sigio_trap ();
285
286       pid = wait (&status);
287
288       save_errno = errno;
289
290       clear_sigio_trap ();
291
292       clear_sigint_trap ();
293
294       if (pid == -1)
295         {
296           if (save_errno == EINTR)
297             continue;
298
299           fprintf_unfiltered (gdb_stderr,
300                               "Child process unexpectedly missing: %s.\n",
301                               safe_strerror (save_errno));
302
303           /* Claim it exited with unknown signal.  */
304           ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
305           ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
306           return pid_to_ptid (-1);
307         }
308
309       /* Did it exit?  */
310       if (target_has_exited (pid, status, &exit_status))
311         {
312           /* ??rehrauer: For now, ignore this. */
313           continue;
314         }
315
316       if (!target_thread_alive (pid_to_ptid (pid)))
317         {
318           ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
319           return pid_to_ptid (pid);
320         }
321     }
322   while (pid != PIDGET (inferior_ptid)); /* Some other child died or
323                                             stopped.  */
324
325   store_waitstatus (ourstatus, status);
326   return pid_to_ptid (pid);
327 }
328
329 static int
330 inf_ptrace_has_exited (int pid, int wait_status, int *exit_status)
331 {
332   if (WIFEXITED (wait_status))
333     {
334       *exit_status = WEXITSTATUS (wait_status);
335       return 1;
336     }
337
338   if (WIFSIGNALED (wait_status))
339     {
340       *exit_status = 0;         /* ?? Don't know what else to say here. */
341       return 1;
342     }
343
344   /* ??? Do we really need to consult the event state, too?
345      Assume the wait_state alone suffices.  */
346   return 0;
347 }
348
349 /* Perform a partial transfer to/from the specified object.  For
350    memory transfers, fall back to the old memory xfer functions.  */
351
352 static LONGEST
353 inf_ptrace_xfer_partial (struct target_ops *ops, enum target_object object,
354                          const char *annex, gdb_byte *readbuf,
355                          const gdb_byte *writebuf,
356                          ULONGEST offset, LONGEST len)
357 {
358   switch (object)
359     {
360     case TARGET_OBJECT_MEMORY:
361 #ifdef PT_IO
362       /* OpenBSD 3.1, NetBSD 1.6 and FreeBSD 5.0 have a new PT_IO
363          request that promises to be much more efficient in reading
364          and writing data in the traced process's address space.  */
365       {
366         struct ptrace_io_desc piod;
367         
368         /* NOTE: We assume that there are no distinct address spaces
369            for instruction and data.  */
370         piod.piod_op = writebuf ? PIOD_WRITE_D : PIOD_READ_D;
371         piod.piod_addr = writebuf ? (void *) writebuf : readbuf;
372         piod.piod_offs = (void *) (long) offset;
373         piod.piod_len = len;
374
375         errno = 0;
376         if (ptrace (PT_IO, PIDGET (inferior_ptid), (caddr_t) &piod, 0) == 0)
377           /* Return the actual number of bytes read or written.  */
378           return piod.piod_len;
379         /* If the PT_IO request is somehow not supported, fallback on
380            using PT_WRITE_D/PT_READ_D.  Otherwise we will return zero
381            to indicate failure.  */
382         if (errno != EINVAL)
383           return 0;
384       }
385 #endif
386       {
387         union
388         {
389           PTRACE_TYPE_RET word;
390           unsigned char byte[sizeof (PTRACE_TYPE_RET)];
391         } buffer;
392         ULONGEST rounded_offset;
393         LONGEST partial_len;
394         
395         /* Round the start offset down to the next long word
396            boundary.  */
397         rounded_offset = offset & -(ULONGEST) sizeof (PTRACE_TYPE_RET);
398         
399         /* Since ptrace will transfer a single word starting at that
400            rounded_offset the partial_len needs to be adjusted down to
401            that (remember this function only does a single transfer).
402            Should the required length be even less, adjust it down
403            again.  */
404         partial_len = (rounded_offset + sizeof (PTRACE_TYPE_RET)) - offset;
405         if (partial_len > len)
406           partial_len = len;
407         
408         if (writebuf)
409           {
410             /* If OFFSET:PARTIAL_LEN is smaller than
411                ROUNDED_OFFSET:WORDSIZE then a read/modify write will
412                be needed.  Read in the entire word.  */
413             if (rounded_offset < offset
414                 || (offset + partial_len
415                     < rounded_offset + sizeof (PTRACE_TYPE_RET)))
416               /* Need part of initial word -- fetch it.  */
417               buffer.word = ptrace (PT_READ_I, PIDGET (inferior_ptid),
418                                     (PTRACE_TYPE_ARG3) (long) rounded_offset,
419                                     0);
420             
421             /* Copy data to be written over corresponding part of
422                buffer.  */
423             memcpy (buffer.byte + (offset - rounded_offset),
424                     writebuf, partial_len);
425             
426             errno = 0;
427             ptrace (PT_WRITE_D, PIDGET (inferior_ptid),
428                     (PTRACE_TYPE_ARG3) (long) rounded_offset,
429                     buffer.word);
430             if (errno)
431               {
432                 /* Using the appropriate one (I or D) is necessary for
433                    Gould NP1, at least.  */
434                 errno = 0;
435                 ptrace (PT_WRITE_I, PIDGET (inferior_ptid),
436                         (PTRACE_TYPE_ARG3) (long) rounded_offset,
437                         buffer.word);
438                 if (errno)
439                   return 0;
440               }
441           }
442         if (readbuf)
443           {
444             errno = 0;
445             buffer.word = ptrace (PT_READ_I, PIDGET (inferior_ptid),
446                                   (PTRACE_TYPE_ARG3) (long) rounded_offset, 0);
447             if (errno)
448               return 0;
449             /* Copy appropriate bytes out of the buffer.  */
450             memcpy (readbuf, buffer.byte + (offset - rounded_offset),
451                     partial_len);
452           }
453         return partial_len;
454       }
455
456     case TARGET_OBJECT_UNWIND_TABLE:
457       return -1;
458
459     case TARGET_OBJECT_AUXV:
460       return -1;
461
462     case TARGET_OBJECT_WCOOKIE:
463       return -1;
464
465     default:
466       return -1;
467     }
468 }
469
470 /* Check to see if the given thread is alive.
471
472    FIXME: Is kill() ever the right way to do this?  I doubt it, but
473    for now we're going to try and be compatable with the old thread
474    code.  */
475
476 static int
477 inf_ptrace_thread_alive (ptid_t ptid)
478 {
479   pid_t pid = PIDGET (ptid);
480
481   return (kill (pid, 0) != -1);
482 }
483
484 /* Print status information about what we're accessing.  */
485
486 static void
487 inf_ptrace_files_info (struct target_ops *ignore)
488 {
489   printf_unfiltered (_("\tUsing the running image of %s %s.\n"),
490                      attach_flag ? "attached" : "child",
491                      target_pid_to_str (inferior_ptid));
492 }
493
494 static char *
495 inf_ptrace_pid_to_str (ptid_t ptid)
496 {
497   return normal_pid_to_str (ptid);
498 }
499
500 /* Create a prototype ptrace target.  The client can override it with
501    local methods.  */
502
503 struct target_ops *
504 inf_ptrace_target (void)
505 {
506   struct target_ops *t = inf_child_target ();
507
508   t->to_attach = inf_ptrace_attach;
509   t->to_detach = inf_ptrace_detach;
510   t->to_resume = inf_ptrace_resume;
511   t->to_wait = inf_ptrace_wait;
512   t->to_files_info = inf_ptrace_files_info;
513   t->to_kill = inf_ptrace_kill_inferior;
514   t->to_create_inferior = inf_ptrace_create_inferior;
515   t->to_mourn_inferior = inf_ptrace_mourn_inferior;
516   t->to_thread_alive = inf_ptrace_thread_alive;
517   t->to_pid_to_str = inf_ptrace_pid_to_str;
518   t->to_stop = inf_ptrace_stop;
519   t->to_xfer_partial = inf_ptrace_xfer_partial;
520
521   t->to_has_exited = inf_ptrace_has_exited;
522
523   ptrace_ops_hack = t;
524   return t;
525 }
526 \f
527
528 /* Pointer to a function that returns the oggset within the user area
529    where a particular register is stored.  */
530 static CORE_ADDR (*inf_ptrace_register_u_offset)(int);
531
532 /* Fetch register REGNUM from the inferior.  */
533
534 static void
535 inf_ptrace_fetch_register (int regnum)
536 {
537   CORE_ADDR addr;
538   size_t size;
539   PTRACE_TYPE_RET *buf;
540   int pid, i;
541
542   /* Cater for systems like GNU/Linux, that implement threads as
543      seperate processes.  */
544   pid = ptid_get_lwp (inferior_ptid);
545   if (pid == 0)
546     pid = ptid_get_pid (inferior_ptid);
547
548   /* This isn't really an address, but ptrace thinks of it as one.  */
549   addr = inf_ptrace_register_u_offset (regnum);
550   size = register_size (current_gdbarch, regnum);
551
552   gdb_assert ((size % sizeof (PTRACE_TYPE_RET)) == 0);
553   buf = alloca (size);
554
555   /* Read the register contents from the inferior a chuck at the time.  */
556   for (i = 0; i < size / sizeof (PTRACE_TYPE_RET); i++)
557     {
558       errno = 0;
559       buf[i] = ptrace (PT_READ_U, pid, (PTRACE_TYPE_ARG3) addr, 0);
560       if (errno != 0)
561         error (_("Couldn't read register %s (#%d): %s."), REGISTER_NAME (regnum),
562                regnum, safe_strerror (errno));
563
564       addr += sizeof (PTRACE_TYPE_RET);
565     }
566   regcache_raw_supply (current_regcache, regnum, buf);
567 }
568
569 /* Fetch register REGNUM from the inferior.  If REGNUM is -1, do this
570    for all registers.  */
571
572 static void
573 inf_ptrace_fetch_registers (int regnum)
574 {
575   if (regnum == -1)
576     for (regnum = 0; regnum < NUM_REGS; regnum++)
577       inf_ptrace_fetch_register (regnum);
578   else
579     inf_ptrace_fetch_register (regnum);
580 }
581
582 /* Store register REGNUM into the inferior.  */
583
584 static void
585 inf_ptrace_store_register (int regnum)
586 {
587   CORE_ADDR addr;
588   size_t size;
589   PTRACE_TYPE_RET *buf;
590   int pid, i;
591
592   /* Cater for systems like GNU/Linux, that implement threads as
593      seperate processes.  */
594   pid = ptid_get_lwp (inferior_ptid);
595   if (pid == 0)
596     pid = ptid_get_pid (inferior_ptid);
597
598   /* This isn't really an address, but ptrace thinks of it as one.  */
599   addr = inf_ptrace_register_u_offset (regnum);
600   size = register_size (current_gdbarch, regnum);
601
602   gdb_assert ((size % sizeof (PTRACE_TYPE_RET)) == 0);
603   buf = alloca (size);
604
605   /* Write the register contents into the inferior a chunk at the time.  */
606   regcache_raw_collect (current_regcache, regnum, buf);
607   for (i = 0; i < size / sizeof (PTRACE_TYPE_RET); i++)
608     {
609       errno = 0;
610       ptrace (PT_WRITE_U, pid, (PTRACE_TYPE_ARG3) addr, buf[i]);
611       if (errno != 0)
612         error (_("Couldn't write register %s (#%d): %s."), REGISTER_NAME (regnum),
613                regnum, safe_strerror (errno));
614
615       addr += sizeof (PTRACE_TYPE_RET);
616     }
617 }
618
619 /* Store register REGNUM back into the inferior.  If REGNUM is -1, do
620    this for all registers.  */
621
622 void
623 inf_ptrace_store_registers (int regnum)
624 {
625   if (regnum == -1)
626     for (regnum = 0; regnum < NUM_REGS; regnum++)
627       inf_ptrace_store_register (regnum);
628   else
629     inf_ptrace_store_register (regnum);
630 }
631
632 /* Create a "traditional" ptrace target.  REGISTER_U_OFFSET should be
633    a function returning the offset within the user area where a
634    particular register is stored.  */
635
636 struct target_ops *
637 inf_ptrace_trad_target (CORE_ADDR (*register_u_offset)(int))
638 {
639   struct target_ops *t = inf_ptrace_target();
640
641   gdb_assert (register_u_offset);
642   inf_ptrace_register_u_offset = register_u_offset;
643   t->to_fetch_registers = inf_ptrace_fetch_registers;
644   t->to_store_registers = inf_ptrace_store_registers;
645
646   return t;
647 }