1 /* GNU/Linux native-dependent code common to multiple platforms.
3 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006
4 Free Software Foundation, Inc.
6 This file is part of GDB.
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 2 of the License, or
11 (at your option) any later version.
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.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
26 #include "gdb_string.h"
28 #include "gdb_assert.h"
29 #ifdef HAVE_TKILL_SYSCALL
31 #include <sys/syscall.h>
33 #include <sys/ptrace.h>
34 #include "linux-nat.h"
35 #include "linux-fork.h"
36 #include "gdbthread.h"
39 #include "inf-ptrace.h"
41 #include <sys/param.h> /* for MAXPATHLEN */
42 #include <sys/procfs.h> /* for elf_gregset etc. */
43 #include "elf-bfd.h" /* for elfcore_write_* */
44 #include "gregset.h" /* for gregset */
45 #include "gdbcore.h" /* for get_exec_file */
46 #include <ctype.h> /* for isdigit */
47 #include "gdbthread.h" /* for struct thread_info etc. */
48 #include "gdb_stat.h" /* for struct stat */
49 #include <fcntl.h> /* for O_RDONLY */
55 /* If the system headers did not provide the constants, hard-code the normal
57 #ifndef PTRACE_EVENT_FORK
59 #define PTRACE_SETOPTIONS 0x4200
60 #define PTRACE_GETEVENTMSG 0x4201
62 /* options set using PTRACE_SETOPTIONS */
63 #define PTRACE_O_TRACESYSGOOD 0x00000001
64 #define PTRACE_O_TRACEFORK 0x00000002
65 #define PTRACE_O_TRACEVFORK 0x00000004
66 #define PTRACE_O_TRACECLONE 0x00000008
67 #define PTRACE_O_TRACEEXEC 0x00000010
68 #define PTRACE_O_TRACEVFORKDONE 0x00000020
69 #define PTRACE_O_TRACEEXIT 0x00000040
71 /* Wait extended result codes for the above trace options. */
72 #define PTRACE_EVENT_FORK 1
73 #define PTRACE_EVENT_VFORK 2
74 #define PTRACE_EVENT_CLONE 3
75 #define PTRACE_EVENT_EXEC 4
76 #define PTRACE_EVENT_VFORK_DONE 5
77 #define PTRACE_EVENT_EXIT 6
79 #endif /* PTRACE_EVENT_FORK */
81 /* We can't always assume that this flag is available, but all systems
82 with the ptrace event handlers also have __WALL, so it's safe to use
85 #define __WALL 0x40000000 /* Wait for any child. */
88 /* The single-threaded native GNU/Linux target_ops. We save a pointer for
89 the use of the multi-threaded target. */
90 static struct target_ops *linux_ops;
91 static struct target_ops linux_ops_saved;
93 /* The saved to_xfer_partial method, inherited from inf-ptrace.c.
94 Called by our to_xfer_partial. */
95 static LONGEST (*super_xfer_partial) (struct target_ops *,
97 const char *, gdb_byte *,
101 static int debug_linux_nat;
103 show_debug_linux_nat (struct ui_file *file, int from_tty,
104 struct cmd_list_element *c, const char *value)
106 fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
110 static int linux_parent_pid;
112 struct simple_pid_list
115 struct simple_pid_list *next;
117 struct simple_pid_list *stopped_pids;
119 /* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACEFORK
120 can not be used, 1 if it can. */
122 static int linux_supports_tracefork_flag = -1;
124 /* If we have PTRACE_O_TRACEFORK, this flag indicates whether we also have
125 PTRACE_O_TRACEVFORKDONE. */
127 static int linux_supports_tracevforkdone_flag = -1;
130 /* Trivial list manipulation functions to keep track of a list of
131 new stopped processes. */
133 add_to_pid_list (struct simple_pid_list **listp, int pid)
135 struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
137 new_pid->next = *listp;
142 pull_pid_from_list (struct simple_pid_list **listp, int pid)
144 struct simple_pid_list **p;
146 for (p = listp; *p != NULL; p = &(*p)->next)
147 if ((*p)->pid == pid)
149 struct simple_pid_list *next = (*p)->next;
158 linux_record_stopped_pid (int pid)
160 add_to_pid_list (&stopped_pids, pid);
164 /* A helper function for linux_test_for_tracefork, called after fork (). */
167 linux_tracefork_child (void)
171 ptrace (PTRACE_TRACEME, 0, 0, 0);
172 kill (getpid (), SIGSTOP);
177 /* Wrapper function for waitpid which handles EINTR. */
180 my_waitpid (int pid, int *status, int flags)
185 ret = waitpid (pid, status, flags);
187 while (ret == -1 && errno == EINTR);
192 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.
194 First, we try to enable fork tracing on ORIGINAL_PID. If this fails,
195 we know that the feature is not available. This may change the tracing
196 options for ORIGINAL_PID, but we'll be setting them shortly anyway.
198 However, if it succeeds, we don't know for sure that the feature is
199 available; old versions of PTRACE_SETOPTIONS ignored unknown options. We
200 create a child process, attach to it, use PTRACE_SETOPTIONS to enable
201 fork tracing, and let it fork. If the process exits, we assume that we
202 can't use TRACEFORK; if we get the fork notification, and we can extract
203 the new child's PID, then we assume that we can. */
206 linux_test_for_tracefork (int original_pid)
208 int child_pid, ret, status;
211 linux_supports_tracefork_flag = 0;
212 linux_supports_tracevforkdone_flag = 0;
214 ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACEFORK);
220 perror_with_name (("fork"));
223 linux_tracefork_child ();
225 ret = my_waitpid (child_pid, &status, 0);
227 perror_with_name (("waitpid"));
228 else if (ret != child_pid)
229 error (_("linux_test_for_tracefork: waitpid: unexpected result %d."), ret);
230 if (! WIFSTOPPED (status))
231 error (_("linux_test_for_tracefork: waitpid: unexpected status %d."), status);
233 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
236 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
239 warning (_("linux_test_for_tracefork: failed to kill child"));
243 ret = my_waitpid (child_pid, &status, 0);
244 if (ret != child_pid)
245 warning (_("linux_test_for_tracefork: failed to wait for killed child"));
246 else if (!WIFSIGNALED (status))
247 warning (_("linux_test_for_tracefork: unexpected wait status 0x%x from "
248 "killed child"), status);
253 /* Check whether PTRACE_O_TRACEVFORKDONE is available. */
254 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0,
255 PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORKDONE);
256 linux_supports_tracevforkdone_flag = (ret == 0);
258 ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
260 warning (_("linux_test_for_tracefork: failed to resume child"));
262 ret = my_waitpid (child_pid, &status, 0);
264 if (ret == child_pid && WIFSTOPPED (status)
265 && status >> 16 == PTRACE_EVENT_FORK)
268 ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
269 if (ret == 0 && second_pid != 0)
273 linux_supports_tracefork_flag = 1;
274 my_waitpid (second_pid, &second_status, 0);
275 ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
277 warning (_("linux_test_for_tracefork: failed to kill second child"));
281 warning (_("linux_test_for_tracefork: unexpected result from waitpid "
282 "(%d, status 0x%x)"), ret, status);
284 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
286 warning (_("linux_test_for_tracefork: failed to kill child"));
287 my_waitpid (child_pid, &status, 0);
290 /* Return non-zero iff we have tracefork functionality available.
291 This function also sets linux_supports_tracefork_flag. */
294 linux_supports_tracefork (int pid)
296 if (linux_supports_tracefork_flag == -1)
297 linux_test_for_tracefork (pid);
298 return linux_supports_tracefork_flag;
302 linux_supports_tracevforkdone (int pid)
304 if (linux_supports_tracefork_flag == -1)
305 linux_test_for_tracefork (pid);
306 return linux_supports_tracevforkdone_flag;
311 linux_enable_event_reporting (ptid_t ptid)
313 int pid = ptid_get_lwp (ptid);
317 pid = ptid_get_pid (ptid);
319 if (! linux_supports_tracefork (pid))
322 options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEEXEC
323 | PTRACE_O_TRACECLONE;
324 if (linux_supports_tracevforkdone (pid))
325 options |= PTRACE_O_TRACEVFORKDONE;
327 /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to support
328 read-only process state. */
330 ptrace (PTRACE_SETOPTIONS, pid, 0, options);
334 child_post_attach (int pid)
336 linux_enable_event_reporting (pid_to_ptid (pid));
337 check_for_thread_db ();
341 linux_child_post_startup_inferior (ptid_t ptid)
343 linux_enable_event_reporting (ptid);
344 check_for_thread_db ();
348 child_follow_fork (struct target_ops *ops, int follow_child)
351 struct target_waitstatus last_status;
353 int parent_pid, child_pid;
355 get_last_target_status (&last_ptid, &last_status);
356 has_vforked = (last_status.kind == TARGET_WAITKIND_VFORKED);
357 parent_pid = ptid_get_lwp (last_ptid);
359 parent_pid = ptid_get_pid (last_ptid);
360 child_pid = last_status.value.related_pid;
364 /* We're already attached to the parent, by default. */
366 /* Before detaching from the child, remove all breakpoints from
367 it. (This won't actually modify the breakpoint list, but will
368 physically remove the breakpoints from the child.) */
369 /* If we vforked this will remove the breakpoints from the parent
370 also, but they'll be reinserted below. */
371 detach_breakpoints (child_pid);
373 /* Detach new forked process? */
378 target_terminal_ours ();
379 fprintf_filtered (gdb_stdlog,
380 "Detaching after fork from child process %d.\n",
384 ptrace (PTRACE_DETACH, child_pid, 0, 0);
388 struct fork_info *fp;
389 /* Retain child fork in ptrace (stopped) state. */
390 fp = find_fork_pid (child_pid);
392 fp = add_fork (child_pid);
393 fork_save_infrun_state (fp, 0);
398 gdb_assert (linux_supports_tracefork_flag >= 0);
399 if (linux_supports_tracevforkdone (0))
403 ptrace (PTRACE_CONT, parent_pid, 0, 0);
404 my_waitpid (parent_pid, &status, __WALL);
405 if ((status >> 16) != PTRACE_EVENT_VFORK_DONE)
406 warning (_("Unexpected waitpid result %06x when waiting for "
407 "vfork-done"), status);
411 /* We can't insert breakpoints until the child has
412 finished with the shared memory region. We need to
413 wait until that happens. Ideal would be to just
415 - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
416 - waitpid (parent_pid, &status, __WALL);
417 However, most architectures can't handle a syscall
418 being traced on the way out if it wasn't traced on
421 We might also think to loop, continuing the child
422 until it exits or gets a SIGTRAP. One problem is
423 that the child might call ptrace with PTRACE_TRACEME.
425 There's no simple and reliable way to figure out when
426 the vforked child will be done with its copy of the
427 shared memory. We could step it out of the syscall,
428 two instructions, let it go, and then single-step the
429 parent once. When we have hardware single-step, this
430 would work; with software single-step it could still
431 be made to work but we'd have to be able to insert
432 single-step breakpoints in the child, and we'd have
433 to insert -just- the single-step breakpoint in the
434 parent. Very awkward.
436 In the end, the best we can do is to make sure it
437 runs for a little while. Hopefully it will be out of
438 range of any breakpoints we reinsert. Usually this
439 is only the single-step breakpoint at vfork's return
445 /* Since we vforked, breakpoints were removed in the parent
446 too. Put them back. */
447 reattach_breakpoints (parent_pid);
452 char child_pid_spelling[40];
454 /* Needed to keep the breakpoint lists in sync. */
456 detach_breakpoints (child_pid);
458 /* Before detaching from the parent, remove all breakpoints from it. */
459 remove_breakpoints ();
463 target_terminal_ours ();
464 fprintf_filtered (gdb_stdlog,
465 "Attaching after fork to child process %d.\n",
469 /* If we're vforking, we may want to hold on to the parent until
470 the child exits or execs. At exec time we can remove the old
471 breakpoints from the parent and detach it; at exit time we
472 could do the same (or even, sneakily, resume debugging it - the
473 child's exec has failed, or something similar).
475 This doesn't clean up "properly", because we can't call
476 target_detach, but that's OK; if the current target is "child",
477 then it doesn't need any further cleanups, and lin_lwp will
478 generally not encounter vfork (vfork is defined to fork
481 The holding part is very easy if we have VFORKDONE events;
482 but keeping track of both processes is beyond GDB at the
483 moment. So we don't expose the parent to the rest of GDB.
484 Instead we quietly hold onto it until such time as we can
488 linux_parent_pid = parent_pid;
489 else if (!detach_fork)
491 struct fork_info *fp;
492 /* Retain parent fork in ptrace (stopped) state. */
493 fp = find_fork_pid (parent_pid);
495 fp = add_fork (parent_pid);
496 fork_save_infrun_state (fp, 0);
500 target_detach (NULL, 0);
503 inferior_ptid = pid_to_ptid (child_pid);
505 /* Reinstall ourselves, since we might have been removed in
506 target_detach (which does other necessary cleanup). */
510 /* Reset breakpoints in the child as appropriate. */
511 follow_inferior_reset_breakpoints ();
518 linux_handle_extended_wait (int pid, int status,
519 struct target_waitstatus *ourstatus)
521 int event = status >> 16;
523 if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
524 || event == PTRACE_EVENT_CLONE)
526 unsigned long new_pid;
529 ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
531 /* If we haven't already seen the new PID stop, wait for it now. */
532 if (! pull_pid_from_list (&stopped_pids, new_pid))
534 /* The new child has a pending SIGSTOP. We can't affect it until it
535 hits the SIGSTOP, but we're already attached. */
536 ret = my_waitpid (new_pid, &status,
537 (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
539 perror_with_name (_("waiting for new child"));
540 else if (ret != new_pid)
541 internal_error (__FILE__, __LINE__,
542 _("wait returned unexpected PID %d"), ret);
543 else if (!WIFSTOPPED (status) || WSTOPSIG (status) != SIGSTOP)
544 internal_error (__FILE__, __LINE__,
545 _("wait returned unexpected status 0x%x"), status);
548 if (event == PTRACE_EVENT_FORK)
549 ourstatus->kind = TARGET_WAITKIND_FORKED;
550 else if (event == PTRACE_EVENT_VFORK)
551 ourstatus->kind = TARGET_WAITKIND_VFORKED;
553 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
555 ourstatus->value.related_pid = new_pid;
556 return inferior_ptid;
559 if (event == PTRACE_EVENT_EXEC)
561 ourstatus->kind = TARGET_WAITKIND_EXECD;
562 ourstatus->value.execd_pathname
563 = xstrdup (child_pid_to_exec_file (pid));
565 if (linux_parent_pid)
567 detach_breakpoints (linux_parent_pid);
568 ptrace (PTRACE_DETACH, linux_parent_pid, 0, 0);
570 linux_parent_pid = 0;
573 return inferior_ptid;
576 internal_error (__FILE__, __LINE__,
577 _("unknown ptrace event %d"), event);
582 child_insert_fork_catchpoint (int pid)
584 if (! linux_supports_tracefork (pid))
585 error (_("Your system does not support fork catchpoints."));
589 child_insert_vfork_catchpoint (int pid)
591 if (!linux_supports_tracefork (pid))
592 error (_("Your system does not support vfork catchpoints."));
596 child_insert_exec_catchpoint (int pid)
598 if (!linux_supports_tracefork (pid))
599 error (_("Your system does not support exec catchpoints."));
602 /* On GNU/Linux there are no real LWP's. The closest thing to LWP's
603 are processes sharing the same VM space. A multi-threaded process
604 is basically a group of such processes. However, such a grouping
605 is almost entirely a user-space issue; the kernel doesn't enforce
606 such a grouping at all (this might change in the future). In
607 general, we'll rely on the threads library (i.e. the GNU/Linux
608 Threads library) to provide such a grouping.
610 It is perfectly well possible to write a multi-threaded application
611 without the assistance of a threads library, by using the clone
612 system call directly. This module should be able to give some
613 rudimentary support for debugging such applications if developers
614 specify the CLONE_PTRACE flag in the clone system call, and are
615 using the Linux kernel 2.4 or above.
617 Note that there are some peculiarities in GNU/Linux that affect
620 - In general one should specify the __WCLONE flag to waitpid in
621 order to make it report events for any of the cloned processes
622 (and leave it out for the initial process). However, if a cloned
623 process has exited the exit status is only reported if the
624 __WCLONE flag is absent. Linux kernel 2.4 has a __WALL flag, but
625 we cannot use it since GDB must work on older systems too.
627 - When a traced, cloned process exits and is waited for by the
628 debugger, the kernel reassigns it to the original parent and
629 keeps it around as a "zombie". Somehow, the GNU/Linux Threads
630 library doesn't notice this, which leads to the "zombie problem":
631 When debugged a multi-threaded process that spawns a lot of
632 threads will run out of processes, even if the threads exit,
633 because the "zombies" stay around. */
635 /* List of known LWPs. */
636 static struct lwp_info *lwp_list;
638 /* Number of LWPs in the list. */
642 #define GET_LWP(ptid) ptid_get_lwp (ptid)
643 #define GET_PID(ptid) ptid_get_pid (ptid)
644 #define is_lwp(ptid) (GET_LWP (ptid) != 0)
645 #define BUILD_LWP(lwp, pid) ptid_build (pid, lwp, 0)
647 /* If the last reported event was a SIGTRAP, this variable is set to
648 the process id of the LWP/thread that got it. */
652 /* Since we cannot wait (in linux_nat_wait) for the initial process and
653 any cloned processes with a single call to waitpid, we have to use
654 the WNOHANG flag and call waitpid in a loop. To optimize
655 things a bit we use `sigsuspend' to wake us up when a process has
656 something to report (it will send us a SIGCHLD if it has). To make
657 this work we have to juggle with the signal mask. We save the
658 original signal mask such that we can restore it before creating a
659 new process in order to avoid blocking certain signals in the
660 inferior. We then block SIGCHLD during the waitpid/sigsuspend
663 /* Original signal mask. */
664 static sigset_t normal_mask;
666 /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
667 _initialize_linux_nat. */
668 static sigset_t suspend_mask;
670 /* Signals to block to make that sigsuspend work. */
671 static sigset_t blocked_mask;
674 /* Prototypes for local functions. */
675 static int stop_wait_callback (struct lwp_info *lp, void *data);
676 static int linux_nat_thread_alive (ptid_t ptid);
678 /* Convert wait status STATUS to a string. Used for printing debug
682 status_to_str (int status)
686 if (WIFSTOPPED (status))
687 snprintf (buf, sizeof (buf), "%s (stopped)",
688 strsignal (WSTOPSIG (status)));
689 else if (WIFSIGNALED (status))
690 snprintf (buf, sizeof (buf), "%s (terminated)",
691 strsignal (WSTOPSIG (status)));
693 snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
698 /* Initialize the list of LWPs. Note that this module, contrary to
699 what GDB's generic threads layer does for its thread list,
700 re-initializes the LWP lists whenever we mourn or detach (which
701 doesn't involve mourning) the inferior. */
706 struct lwp_info *lp, *lpnext;
708 for (lp = lwp_list; lp; lp = lpnext)
718 /* Add the LWP specified by PID to the list. Return a pointer to the
719 structure describing the new LWP. */
721 static struct lwp_info *
722 add_lwp (ptid_t ptid)
726 gdb_assert (is_lwp (ptid));
728 lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
730 memset (lp, 0, sizeof (struct lwp_info));
732 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
743 /* Remove the LWP specified by PID from the list. */
746 delete_lwp (ptid_t ptid)
748 struct lwp_info *lp, *lpprev;
752 for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
753 if (ptid_equal (lp->ptid, ptid))
762 lpprev->next = lp->next;
769 /* Return a pointer to the structure describing the LWP corresponding
770 to PID. If no corresponding LWP could be found, return NULL. */
772 static struct lwp_info *
773 find_lwp_pid (ptid_t ptid)
779 lwp = GET_LWP (ptid);
781 lwp = GET_PID (ptid);
783 for (lp = lwp_list; lp; lp = lp->next)
784 if (lwp == GET_LWP (lp->ptid))
790 /* Call CALLBACK with its second argument set to DATA for every LWP in
791 the list. If CALLBACK returns 1 for a particular LWP, return a
792 pointer to the structure describing that LWP immediately.
793 Otherwise return NULL. */
796 iterate_over_lwps (int (*callback) (struct lwp_info *, void *), void *data)
798 struct lwp_info *lp, *lpnext;
800 for (lp = lwp_list; lp; lp = lpnext)
803 if ((*callback) (lp, data))
810 /* Update our internal state when changing from one fork (checkpoint,
811 et cetera) to another indicated by NEW_PTID. We can only switch
812 single-threaded applications, so we only create one new LWP, and
813 the previous list is discarded. */
816 linux_nat_switch_fork (ptid_t new_ptid)
821 lp = add_lwp (new_ptid);
825 /* Record a PTID for later deletion. */
830 struct saved_ptids *next;
832 static struct saved_ptids *threads_to_delete;
835 record_dead_thread (ptid_t ptid)
837 struct saved_ptids *p = xmalloc (sizeof (struct saved_ptids));
839 p->next = threads_to_delete;
840 threads_to_delete = p;
843 /* Delete any dead threads which are not the current thread. */
848 struct saved_ptids **p = &threads_to_delete;
851 if (! ptid_equal ((*p)->ptid, inferior_ptid))
853 struct saved_ptids *tmp = *p;
854 delete_thread (tmp->ptid);
862 /* Callback for iterate_over_threads that finds a thread corresponding
866 find_thread_from_lwp (struct thread_info *thr, void *dummy)
868 ptid_t *ptid_p = dummy;
870 if (GET_LWP (thr->ptid) && GET_LWP (thr->ptid) == GET_LWP (*ptid_p))
876 /* Handle the exit of a single thread LP. */
879 exit_lwp (struct lwp_info *lp)
881 if (in_thread_list (lp->ptid))
883 /* Core GDB cannot deal with us deleting the current thread. */
884 if (!ptid_equal (lp->ptid, inferior_ptid))
885 delete_thread (lp->ptid);
887 record_dead_thread (lp->ptid);
888 printf_unfiltered (_("[%s exited]\n"),
889 target_pid_to_str (lp->ptid));
893 /* Even if LP->PTID is not in the global GDB thread list, the
894 LWP may be - with an additional thread ID. We don't need
895 to print anything in this case; thread_db is in use and
896 already took care of that. But it didn't delete the thread
897 in order to handle zombies correctly. */
899 struct thread_info *thr;
901 thr = iterate_over_threads (find_thread_from_lwp, &lp->ptid);
902 if (thr && !ptid_equal (thr->ptid, inferior_ptid))
903 delete_thread (thr->ptid);
905 record_dead_thread (thr->ptid);
908 delete_lwp (lp->ptid);
911 /* Attach to the LWP specified by PID. If VERBOSE is non-zero, print
912 a message telling the user that a new LWP has been added to the
916 lin_lwp_attach_lwp (ptid_t ptid, int verbose)
918 struct lwp_info *lp, *found_lp;
920 gdb_assert (is_lwp (ptid));
922 /* Make sure SIGCHLD is blocked. We don't want SIGCHLD events
923 to interrupt either the ptrace() or waitpid() calls below. */
924 if (!sigismember (&blocked_mask, SIGCHLD))
926 sigaddset (&blocked_mask, SIGCHLD);
927 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
931 printf_filtered (_("[New %s]\n"), target_pid_to_str (ptid));
933 found_lp = lp = find_lwp_pid (ptid);
937 /* We assume that we're already attached to any LWP that has an id
938 equal to the overall process id, and to any LWP that is already
939 in our list of LWPs. If we're not seeing exit events from threads
940 and we've had PID wraparound since we last tried to stop all threads,
941 this assumption might be wrong; fortunately, this is very unlikely
943 if (GET_LWP (ptid) != GET_PID (ptid) && found_lp == NULL)
948 if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
949 error (_("Can't attach %s: %s"), target_pid_to_str (ptid),
950 safe_strerror (errno));
953 fprintf_unfiltered (gdb_stdlog,
954 "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
955 target_pid_to_str (ptid));
957 pid = my_waitpid (GET_LWP (ptid), &status, 0);
958 if (pid == -1 && errno == ECHILD)
960 /* Try again with __WCLONE to check cloned processes. */
961 pid = my_waitpid (GET_LWP (ptid), &status, __WCLONE);
965 gdb_assert (pid == GET_LWP (ptid)
966 && WIFSTOPPED (status) && WSTOPSIG (status));
968 target_post_attach (pid);
974 fprintf_unfiltered (gdb_stdlog,
975 "LLAL: waitpid %s received %s\n",
976 target_pid_to_str (ptid),
977 status_to_str (status));
982 /* We assume that the LWP representing the original process is
983 already stopped. Mark it as stopped in the data structure
984 that the linux ptrace layer uses to keep track of threads.
985 Note that this won't have already been done since the main
986 thread will have, we assume, been stopped by an attach from a
993 linux_nat_attach (char *args, int from_tty)
999 /* FIXME: We should probably accept a list of process id's, and
1000 attach all of them. */
1001 linux_ops->to_attach (args, from_tty);
1003 /* Add the initial process as the first LWP to the list. */
1004 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid));
1005 lp = add_lwp (inferior_ptid);
1007 /* Make sure the initial process is stopped. The user-level threads
1008 layer might want to poke around in the inferior, and that won't
1009 work if things haven't stabilized yet. */
1010 pid = my_waitpid (GET_PID (inferior_ptid), &status, 0);
1011 if (pid == -1 && errno == ECHILD)
1013 warning (_("%s is a cloned process"), target_pid_to_str (inferior_ptid));
1015 /* Try again with __WCLONE to check cloned processes. */
1016 pid = my_waitpid (GET_PID (inferior_ptid), &status, __WCLONE);
1020 gdb_assert (pid == GET_PID (inferior_ptid)
1021 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP);
1025 /* Fake the SIGSTOP that core GDB expects. */
1026 lp->status = W_STOPCODE (SIGSTOP);
1028 if (debug_linux_nat)
1030 fprintf_unfiltered (gdb_stdlog,
1031 "LLA: waitpid %ld, faking SIGSTOP\n", (long) pid);
1036 detach_callback (struct lwp_info *lp, void *data)
1038 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1040 if (debug_linux_nat && lp->status)
1041 fprintf_unfiltered (gdb_stdlog, "DC: Pending %s for %s on detach.\n",
1042 strsignal (WSTOPSIG (lp->status)),
1043 target_pid_to_str (lp->ptid));
1045 while (lp->signalled && lp->stopped)
1048 if (ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0,
1049 WSTOPSIG (lp->status)) < 0)
1050 error (_("Can't continue %s: %s"), target_pid_to_str (lp->ptid),
1051 safe_strerror (errno));
1053 if (debug_linux_nat)
1054 fprintf_unfiltered (gdb_stdlog,
1055 "DC: PTRACE_CONTINUE (%s, 0, %s) (OK)\n",
1056 target_pid_to_str (lp->ptid),
1057 status_to_str (lp->status));
1062 /* FIXME drow/2003-08-26: There was a call to stop_wait_callback
1063 here. But since lp->signalled was cleared above,
1064 stop_wait_callback didn't do anything; the process was left
1065 running. Shouldn't we be waiting for it to stop?
1066 I've removed the call, since stop_wait_callback now does do
1067 something when called with lp->signalled == 0. */
1069 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1072 /* We don't actually detach from the LWP that has an id equal to the
1073 overall process id just yet. */
1074 if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
1077 if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
1078 WSTOPSIG (lp->status)) < 0)
1079 error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
1080 safe_strerror (errno));
1082 if (debug_linux_nat)
1083 fprintf_unfiltered (gdb_stdlog,
1084 "PTRACE_DETACH (%s, %s, 0) (OK)\n",
1085 target_pid_to_str (lp->ptid),
1086 strsignal (WSTOPSIG (lp->status)));
1088 delete_lwp (lp->ptid);
1095 linux_nat_detach (char *args, int from_tty)
1097 iterate_over_lwps (detach_callback, NULL);
1099 /* Only the initial process should be left right now. */
1100 gdb_assert (num_lwps == 1);
1102 trap_ptid = null_ptid;
1104 /* Destroy LWP info; it's no longer valid. */
1107 /* Restore the original signal mask. */
1108 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1109 sigemptyset (&blocked_mask);
1111 inferior_ptid = pid_to_ptid (GET_PID (inferior_ptid));
1112 linux_ops->to_detach (args, from_tty);
1118 resume_callback (struct lwp_info *lp, void *data)
1120 if (lp->stopped && lp->status == 0)
1122 struct thread_info *tp;
1124 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
1125 0, TARGET_SIGNAL_0);
1126 if (debug_linux_nat)
1127 fprintf_unfiltered (gdb_stdlog,
1128 "RC: PTRACE_CONT %s, 0, 0 (resume sibling)\n",
1129 target_pid_to_str (lp->ptid));
1138 resume_clear_callback (struct lwp_info *lp, void *data)
1145 resume_set_callback (struct lwp_info *lp, void *data)
1152 linux_nat_resume (ptid_t ptid, int step, enum target_signal signo)
1154 struct lwp_info *lp;
1157 if (debug_linux_nat)
1158 fprintf_unfiltered (gdb_stdlog,
1159 "LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
1160 step ? "step" : "resume",
1161 target_pid_to_str (ptid),
1162 signo ? strsignal (signo) : "0",
1163 target_pid_to_str (inferior_ptid));
1167 /* A specific PTID means `step only this process id'. */
1168 resume_all = (PIDGET (ptid) == -1);
1171 iterate_over_lwps (resume_set_callback, NULL);
1173 iterate_over_lwps (resume_clear_callback, NULL);
1175 /* If PID is -1, it's the current inferior that should be
1176 handled specially. */
1177 if (PIDGET (ptid) == -1)
1178 ptid = inferior_ptid;
1180 lp = find_lwp_pid (ptid);
1183 ptid = pid_to_ptid (GET_LWP (lp->ptid));
1185 /* Remember if we're stepping. */
1188 /* Mark this LWP as resumed. */
1191 /* If we have a pending wait status for this thread, there is no
1192 point in resuming the process. But first make sure that
1193 linux_nat_wait won't preemptively handle the event - we
1194 should never take this short-circuit if we are going to
1195 leave LP running, since we have skipped resuming all the
1196 other threads. This bit of code needs to be synchronized
1197 with linux_nat_wait. */
1199 if (lp->status && WIFSTOPPED (lp->status))
1201 int saved_signo = target_signal_from_host (WSTOPSIG (lp->status));
1203 if (signal_stop_state (saved_signo) == 0
1204 && signal_print_state (saved_signo) == 0
1205 && signal_pass_state (saved_signo) == 1)
1207 if (debug_linux_nat)
1208 fprintf_unfiltered (gdb_stdlog,
1209 "LLR: Not short circuiting for ignored "
1210 "status 0x%x\n", lp->status);
1212 /* FIXME: What should we do if we are supposed to continue
1213 this thread with a signal? */
1214 gdb_assert (signo == TARGET_SIGNAL_0);
1215 signo = saved_signo;
1222 /* FIXME: What should we do if we are supposed to continue
1223 this thread with a signal? */
1224 gdb_assert (signo == TARGET_SIGNAL_0);
1226 if (debug_linux_nat)
1227 fprintf_unfiltered (gdb_stdlog,
1228 "LLR: Short circuiting for status 0x%x\n",
1234 /* Mark LWP as not stopped to prevent it from being continued by
1240 iterate_over_lwps (resume_callback, NULL);
1242 linux_ops->to_resume (ptid, step, signo);
1243 if (debug_linux_nat)
1244 fprintf_unfiltered (gdb_stdlog,
1245 "LLR: %s %s, %s (resume event thread)\n",
1246 step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1247 target_pid_to_str (ptid),
1248 signo ? strsignal (signo) : "0");
1251 /* Issue kill to specified lwp. */
1253 static int tkill_failed;
1256 kill_lwp (int lwpid, int signo)
1260 /* Use tkill, if possible, in case we are using nptl threads. If tkill
1261 fails, then we are not using nptl threads and we should be using kill. */
1263 #ifdef HAVE_TKILL_SYSCALL
1266 int ret = syscall (__NR_tkill, lwpid, signo);
1267 if (errno != ENOSYS)
1274 return kill (lwpid, signo);
1277 /* Handle a GNU/Linux extended wait response. Most of the work we
1278 just pass off to linux_handle_extended_wait, but if it reports a
1279 clone event we need to add the new LWP to our list (and not report
1280 the trap to higher layers). This function returns non-zero if
1281 the event should be ignored and we should wait again. */
1284 linux_nat_handle_extended (struct lwp_info *lp, int status)
1286 linux_handle_extended_wait (GET_LWP (lp->ptid), status,
1289 /* TARGET_WAITKIND_SPURIOUS is used to indicate clone events. */
1290 if (lp->waitstatus.kind == TARGET_WAITKIND_SPURIOUS)
1292 struct lwp_info *new_lp;
1293 new_lp = add_lwp (BUILD_LWP (lp->waitstatus.value.related_pid,
1294 GET_PID (inferior_ptid)));
1296 new_lp->stopped = 1;
1298 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
1300 if (debug_linux_nat)
1301 fprintf_unfiltered (gdb_stdlog,
1302 "LLHE: Got clone event from LWP %ld, resuming\n",
1303 GET_LWP (lp->ptid));
1304 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1312 /* Wait for LP to stop. Returns the wait status, or 0 if the LWP has
1316 wait_lwp (struct lwp_info *lp)
1320 int thread_dead = 0;
1322 gdb_assert (!lp->stopped);
1323 gdb_assert (lp->status == 0);
1325 pid = my_waitpid (GET_LWP (lp->ptid), &status, 0);
1326 if (pid == -1 && errno == ECHILD)
1328 pid = my_waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
1329 if (pid == -1 && errno == ECHILD)
1331 /* The thread has previously exited. We need to delete it
1332 now because, for some vendor 2.4 kernels with NPTL
1333 support backported, there won't be an exit event unless
1334 it is the main thread. 2.6 kernels will report an exit
1335 event for each thread that exits, as expected. */
1337 if (debug_linux_nat)
1338 fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
1339 target_pid_to_str (lp->ptid));
1345 gdb_assert (pid == GET_LWP (lp->ptid));
1347 if (debug_linux_nat)
1349 fprintf_unfiltered (gdb_stdlog,
1350 "WL: waitpid %s received %s\n",
1351 target_pid_to_str (lp->ptid),
1352 status_to_str (status));
1356 /* Check if the thread has exited. */
1357 if (WIFEXITED (status) || WIFSIGNALED (status))
1360 if (debug_linux_nat)
1361 fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
1362 target_pid_to_str (lp->ptid));
1371 gdb_assert (WIFSTOPPED (status));
1373 /* Handle GNU/Linux's extended waitstatus for trace events. */
1374 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1376 if (debug_linux_nat)
1377 fprintf_unfiltered (gdb_stdlog,
1378 "WL: Handling extended status 0x%06x\n",
1380 if (linux_nat_handle_extended (lp, status))
1381 return wait_lwp (lp);
1387 /* Send a SIGSTOP to LP. */
1390 stop_callback (struct lwp_info *lp, void *data)
1392 if (!lp->stopped && !lp->signalled)
1396 if (debug_linux_nat)
1398 fprintf_unfiltered (gdb_stdlog,
1399 "SC: kill %s **<SIGSTOP>**\n",
1400 target_pid_to_str (lp->ptid));
1403 ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
1404 if (debug_linux_nat)
1406 fprintf_unfiltered (gdb_stdlog,
1407 "SC: lwp kill %d %s\n",
1409 errno ? safe_strerror (errno) : "ERRNO-OK");
1413 gdb_assert (lp->status == 0);
1419 /* Wait until LP is stopped. If DATA is non-null it is interpreted as
1420 a pointer to a set of signals to be flushed immediately. */
1423 stop_wait_callback (struct lwp_info *lp, void *data)
1425 sigset_t *flush_mask = data;
1431 status = wait_lwp (lp);
1435 /* Ignore any signals in FLUSH_MASK. */
1436 if (flush_mask && sigismember (flush_mask, WSTOPSIG (status)))
1445 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1446 if (debug_linux_nat)
1447 fprintf_unfiltered (gdb_stdlog,
1448 "PTRACE_CONT %s, 0, 0 (%s)\n",
1449 target_pid_to_str (lp->ptid),
1450 errno ? safe_strerror (errno) : "OK");
1452 return stop_wait_callback (lp, flush_mask);
1455 if (WSTOPSIG (status) != SIGSTOP)
1457 if (WSTOPSIG (status) == SIGTRAP)
1459 /* If a LWP other than the LWP that we're reporting an
1460 event for has hit a GDB breakpoint (as opposed to
1461 some random trap signal), then just arrange for it to
1462 hit it again later. We don't keep the SIGTRAP status
1463 and don't forward the SIGTRAP signal to the LWP. We
1464 will handle the current event, eventually we will
1465 resume all LWPs, and this one will get its breakpoint
1468 If we do not do this, then we run the risk that the
1469 user will delete or disable the breakpoint, but the
1470 thread will have already tripped on it. */
1472 /* Now resume this LWP and get the SIGSTOP event. */
1474 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1475 if (debug_linux_nat)
1477 fprintf_unfiltered (gdb_stdlog,
1478 "PTRACE_CONT %s, 0, 0 (%s)\n",
1479 target_pid_to_str (lp->ptid),
1480 errno ? safe_strerror (errno) : "OK");
1482 fprintf_unfiltered (gdb_stdlog,
1483 "SWC: Candidate SIGTRAP event in %s\n",
1484 target_pid_to_str (lp->ptid));
1486 /* Hold the SIGTRAP for handling by linux_nat_wait. */
1487 stop_wait_callback (lp, data);
1488 /* If there's another event, throw it back into the queue. */
1491 if (debug_linux_nat)
1493 fprintf_unfiltered (gdb_stdlog,
1494 "SWC: kill %s, %s\n",
1495 target_pid_to_str (lp->ptid),
1496 status_to_str ((int) status));
1498 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
1500 /* Save the sigtrap event. */
1501 lp->status = status;
1506 /* The thread was stopped with a signal other than
1507 SIGSTOP, and didn't accidentally trip a breakpoint. */
1509 if (debug_linux_nat)
1511 fprintf_unfiltered (gdb_stdlog,
1512 "SWC: Pending event %s in %s\n",
1513 status_to_str ((int) status),
1514 target_pid_to_str (lp->ptid));
1516 /* Now resume this LWP and get the SIGSTOP event. */
1518 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1519 if (debug_linux_nat)
1520 fprintf_unfiltered (gdb_stdlog,
1521 "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
1522 target_pid_to_str (lp->ptid),
1523 errno ? safe_strerror (errno) : "OK");
1525 /* Hold this event/waitstatus while we check to see if
1526 there are any more (we still want to get that SIGSTOP). */
1527 stop_wait_callback (lp, data);
1528 /* If the lp->status field is still empty, use it to hold
1529 this event. If not, then this event must be returned
1530 to the event queue of the LWP. */
1531 if (lp->status == 0)
1532 lp->status = status;
1535 if (debug_linux_nat)
1537 fprintf_unfiltered (gdb_stdlog,
1538 "SWC: kill %s, %s\n",
1539 target_pid_to_str (lp->ptid),
1540 status_to_str ((int) status));
1542 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
1549 /* We caught the SIGSTOP that we intended to catch, so
1550 there's no SIGSTOP pending. */
1559 /* Check whether PID has any pending signals in FLUSH_MASK. If so set
1560 the appropriate bits in PENDING, and return 1 - otherwise return 0. */
1563 linux_nat_has_pending (int pid, sigset_t *pending, sigset_t *flush_mask)
1565 sigset_t blocked, ignored;
1568 linux_proc_pending_signals (pid, pending, &blocked, &ignored);
1573 for (i = 1; i < NSIG; i++)
1574 if (sigismember (pending, i))
1575 if (!sigismember (flush_mask, i)
1576 || sigismember (&blocked, i)
1577 || sigismember (&ignored, i))
1578 sigdelset (pending, i);
1580 if (sigisemptyset (pending))
1586 /* DATA is interpreted as a mask of signals to flush. If LP has
1587 signals pending, and they are all in the flush mask, then arrange
1588 to flush them. LP should be stopped, as should all other threads
1589 it might share a signal queue with. */
1592 flush_callback (struct lwp_info *lp, void *data)
1594 sigset_t *flush_mask = data;
1595 sigset_t pending, intersection, blocked, ignored;
1598 /* Normally, when an LWP exits, it is removed from the LWP list. The
1599 last LWP isn't removed till later, however. So if there is only
1600 one LWP on the list, make sure it's alive. */
1601 if (lwp_list == lp && lp->next == NULL)
1602 if (!linux_nat_thread_alive (lp->ptid))
1605 /* Just because the LWP is stopped doesn't mean that new signals
1606 can't arrive from outside, so this function must be careful of
1607 race conditions. However, because all threads are stopped, we
1608 can assume that the pending mask will not shrink unless we resume
1609 the LWP, and that it will then get another signal. We can't
1610 control which one, however. */
1614 if (debug_linux_nat)
1615 printf_unfiltered (_("FC: LP has pending status %06x\n"), lp->status);
1616 if (WIFSTOPPED (lp->status) && sigismember (flush_mask, WSTOPSIG (lp->status)))
1620 while (linux_nat_has_pending (GET_LWP (lp->ptid), &pending, flush_mask))
1625 ret = ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1626 if (debug_linux_nat)
1627 fprintf_unfiltered (gdb_stderr,
1628 "FC: Sent PTRACE_CONT, ret %d %d\n", ret, errno);
1631 stop_wait_callback (lp, flush_mask);
1632 if (debug_linux_nat)
1633 fprintf_unfiltered (gdb_stderr,
1634 "FC: Wait finished; saved status is %d\n",
1641 /* Return non-zero if LP has a wait status pending. */
1644 status_callback (struct lwp_info *lp, void *data)
1646 /* Only report a pending wait status if we pretend that this has
1647 indeed been resumed. */
1648 return (lp->status != 0 && lp->resumed);
1651 /* Return non-zero if LP isn't stopped. */
1654 running_callback (struct lwp_info *lp, void *data)
1656 return (lp->stopped == 0 || (lp->status != 0 && lp->resumed));
1659 /* Count the LWP's that have had events. */
1662 count_events_callback (struct lwp_info *lp, void *data)
1666 gdb_assert (count != NULL);
1668 /* Count only LWPs that have a SIGTRAP event pending. */
1670 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
1676 /* Select the LWP (if any) that is currently being single-stepped. */
1679 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
1681 if (lp->step && lp->status != 0)
1687 /* Select the Nth LWP that has had a SIGTRAP event. */
1690 select_event_lwp_callback (struct lwp_info *lp, void *data)
1692 int *selector = data;
1694 gdb_assert (selector != NULL);
1696 /* Select only LWPs that have a SIGTRAP event pending. */
1698 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
1699 if ((*selector)-- == 0)
1706 cancel_breakpoints_callback (struct lwp_info *lp, void *data)
1708 struct lwp_info *event_lp = data;
1710 /* Leave the LWP that has been elected to receive a SIGTRAP alone. */
1714 /* If a LWP other than the LWP that we're reporting an event for has
1715 hit a GDB breakpoint (as opposed to some random trap signal),
1716 then just arrange for it to hit it again later. We don't keep
1717 the SIGTRAP status and don't forward the SIGTRAP signal to the
1718 LWP. We will handle the current event, eventually we will resume
1719 all LWPs, and this one will get its breakpoint trap again.
1721 If we do not do this, then we run the risk that the user will
1722 delete or disable the breakpoint, but the LWP will have already
1726 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
1727 && breakpoint_inserted_here_p (read_pc_pid (lp->ptid) -
1728 DECR_PC_AFTER_BREAK))
1730 if (debug_linux_nat)
1731 fprintf_unfiltered (gdb_stdlog,
1732 "CBC: Push back breakpoint for %s\n",
1733 target_pid_to_str (lp->ptid));
1735 /* Back up the PC if necessary. */
1736 if (DECR_PC_AFTER_BREAK)
1737 write_pc_pid (read_pc_pid (lp->ptid) - DECR_PC_AFTER_BREAK, lp->ptid);
1739 /* Throw away the SIGTRAP. */
1746 /* Select one LWP out of those that have events pending. */
1749 select_event_lwp (struct lwp_info **orig_lp, int *status)
1752 int random_selector;
1753 struct lwp_info *event_lp;
1755 /* Record the wait status for the original LWP. */
1756 (*orig_lp)->status = *status;
1758 /* Give preference to any LWP that is being single-stepped. */
1759 event_lp = iterate_over_lwps (select_singlestep_lwp_callback, NULL);
1760 if (event_lp != NULL)
1762 if (debug_linux_nat)
1763 fprintf_unfiltered (gdb_stdlog,
1764 "SEL: Select single-step %s\n",
1765 target_pid_to_str (event_lp->ptid));
1769 /* No single-stepping LWP. Select one at random, out of those
1770 which have had SIGTRAP events. */
1772 /* First see how many SIGTRAP events we have. */
1773 iterate_over_lwps (count_events_callback, &num_events);
1775 /* Now randomly pick a LWP out of those that have had a SIGTRAP. */
1776 random_selector = (int)
1777 ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
1779 if (debug_linux_nat && num_events > 1)
1780 fprintf_unfiltered (gdb_stdlog,
1781 "SEL: Found %d SIGTRAP events, selecting #%d\n",
1782 num_events, random_selector);
1784 event_lp = iterate_over_lwps (select_event_lwp_callback,
1788 if (event_lp != NULL)
1790 /* Switch the event LWP. */
1791 *orig_lp = event_lp;
1792 *status = event_lp->status;
1795 /* Flush the wait status for the event LWP. */
1796 (*orig_lp)->status = 0;
1799 /* Return non-zero if LP has been resumed. */
1802 resumed_callback (struct lwp_info *lp, void *data)
1807 /* Stop an active thread, verify it still exists, then resume it. */
1810 stop_and_resume_callback (struct lwp_info *lp, void *data)
1812 struct lwp_info *ptr;
1814 if (!lp->stopped && !lp->signalled)
1816 stop_callback (lp, NULL);
1817 stop_wait_callback (lp, NULL);
1818 /* Resume if the lwp still exists. */
1819 for (ptr = lwp_list; ptr; ptr = ptr->next)
1822 resume_callback (lp, NULL);
1823 resume_set_callback (lp, NULL);
1830 linux_nat_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
1832 struct lwp_info *lp = NULL;
1835 pid_t pid = PIDGET (ptid);
1836 sigset_t flush_mask;
1838 /* The first time we get here after starting a new inferior, we may
1839 not have added it to the LWP list yet - this is the earliest
1840 moment at which we know its PID. */
1843 gdb_assert (!is_lwp (inferior_ptid));
1845 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
1846 GET_PID (inferior_ptid));
1847 lp = add_lwp (inferior_ptid);
1851 sigemptyset (&flush_mask);
1853 /* Make sure SIGCHLD is blocked. */
1854 if (!sigismember (&blocked_mask, SIGCHLD))
1856 sigaddset (&blocked_mask, SIGCHLD);
1857 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
1862 /* Make sure there is at least one LWP that has been resumed. */
1863 gdb_assert (iterate_over_lwps (resumed_callback, NULL));
1865 /* First check if there is a LWP with a wait status pending. */
1868 /* Any LWP that's been resumed will do. */
1869 lp = iterate_over_lwps (status_callback, NULL);
1872 status = lp->status;
1875 if (debug_linux_nat && status)
1876 fprintf_unfiltered (gdb_stdlog,
1877 "LLW: Using pending wait status %s for %s.\n",
1878 status_to_str (status),
1879 target_pid_to_str (lp->ptid));
1882 /* But if we don't fine one, we'll have to wait, and check both
1883 cloned and uncloned processes. We start with the cloned
1885 options = __WCLONE | WNOHANG;
1887 else if (is_lwp (ptid))
1889 if (debug_linux_nat)
1890 fprintf_unfiltered (gdb_stdlog,
1891 "LLW: Waiting for specific LWP %s.\n",
1892 target_pid_to_str (ptid));
1894 /* We have a specific LWP to check. */
1895 lp = find_lwp_pid (ptid);
1897 status = lp->status;
1900 if (debug_linux_nat && status)
1901 fprintf_unfiltered (gdb_stdlog,
1902 "LLW: Using pending wait status %s for %s.\n",
1903 status_to_str (status),
1904 target_pid_to_str (lp->ptid));
1906 /* If we have to wait, take into account whether PID is a cloned
1907 process or not. And we have to convert it to something that
1908 the layer beneath us can understand. */
1909 options = lp->cloned ? __WCLONE : 0;
1910 pid = GET_LWP (ptid);
1913 if (status && lp->signalled)
1915 /* A pending SIGSTOP may interfere with the normal stream of
1916 events. In a typical case where interference is a problem,
1917 we have a SIGSTOP signal pending for LWP A while
1918 single-stepping it, encounter an event in LWP B, and take the
1919 pending SIGSTOP while trying to stop LWP A. After processing
1920 the event in LWP B, LWP A is continued, and we'll never see
1921 the SIGTRAP associated with the last time we were
1922 single-stepping LWP A. */
1924 /* Resume the thread. It should halt immediately returning the
1926 registers_changed ();
1927 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
1928 lp->step, TARGET_SIGNAL_0);
1929 if (debug_linux_nat)
1930 fprintf_unfiltered (gdb_stdlog,
1931 "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
1932 lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1933 target_pid_to_str (lp->ptid));
1935 gdb_assert (lp->resumed);
1937 /* This should catch the pending SIGSTOP. */
1938 stop_wait_callback (lp, NULL);
1941 set_sigint_trap (); /* Causes SIGINT to be passed on to the
1942 attached process. */
1949 lwpid = my_waitpid (pid, &status, options);
1952 gdb_assert (pid == -1 || lwpid == pid);
1954 if (debug_linux_nat)
1956 fprintf_unfiltered (gdb_stdlog,
1957 "LLW: waitpid %ld received %s\n",
1958 (long) lwpid, status_to_str (status));
1961 lp = find_lwp_pid (pid_to_ptid (lwpid));
1963 /* Check for stop events reported by a process we didn't
1964 already know about - anything not already in our LWP
1967 If we're expecting to receive stopped processes after
1968 fork, vfork, and clone events, then we'll just add the
1969 new one to our list and go back to waiting for the event
1970 to be reported - the stopped process might be returned
1971 from waitpid before or after the event is. */
1972 if (WIFSTOPPED (status) && !lp)
1974 linux_record_stopped_pid (lwpid);
1979 /* Make sure we don't report an event for the exit of an LWP not in
1980 our list, i.e. not part of the current process. This can happen
1981 if we detach from a program we original forked and then it
1983 if (!WIFSTOPPED (status) && !lp)
1989 /* NOTE drow/2003-06-17: This code seems to be meant for debugging
1990 CLONE_PTRACE processes which do not use the thread library -
1991 otherwise we wouldn't find the new LWP this way. That doesn't
1992 currently work, and the following code is currently unreachable
1993 due to the two blocks above. If it's fixed some day, this code
1994 should be broken out into a function so that we can also pick up
1995 LWPs from the new interface. */
1998 lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
1999 if (options & __WCLONE)
2002 gdb_assert (WIFSTOPPED (status)
2003 && WSTOPSIG (status) == SIGSTOP);
2006 if (!in_thread_list (inferior_ptid))
2008 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
2009 GET_PID (inferior_ptid));
2010 add_thread (inferior_ptid);
2013 add_thread (lp->ptid);
2014 printf_unfiltered (_("[New %s]\n"),
2015 target_pid_to_str (lp->ptid));
2018 /* Handle GNU/Linux's extended waitstatus for trace events. */
2019 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2021 if (debug_linux_nat)
2022 fprintf_unfiltered (gdb_stdlog,
2023 "LLW: Handling extended status 0x%06x\n",
2025 if (linux_nat_handle_extended (lp, status))
2032 /* Check if the thread has exited. */
2033 if ((WIFEXITED (status) || WIFSIGNALED (status)) && num_lwps > 1)
2035 /* If this is the main thread, we must stop all threads and
2036 verify if they are still alive. This is because in the nptl
2037 thread model, there is no signal issued for exiting LWPs
2038 other than the main thread. We only get the main thread
2039 exit signal once all child threads have already exited.
2040 If we stop all the threads and use the stop_wait_callback
2041 to check if they have exited we can determine whether this
2042 signal should be ignored or whether it means the end of the
2043 debugged application, regardless of which threading model
2045 if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
2048 iterate_over_lwps (stop_and_resume_callback, NULL);
2051 if (debug_linux_nat)
2052 fprintf_unfiltered (gdb_stdlog,
2053 "LLW: %s exited.\n",
2054 target_pid_to_str (lp->ptid));
2058 /* If there is at least one more LWP, then the exit signal
2059 was not the end of the debugged application and should be
2063 /* Make sure there is at least one thread running. */
2064 gdb_assert (iterate_over_lwps (running_callback, NULL));
2066 /* Discard the event. */
2072 /* Check if the current LWP has previously exited. In the nptl
2073 thread model, LWPs other than the main thread do not issue
2074 signals when they exit so we must check whenever the thread
2075 has stopped. A similar check is made in stop_wait_callback(). */
2076 if (num_lwps > 1 && !linux_nat_thread_alive (lp->ptid))
2078 if (debug_linux_nat)
2079 fprintf_unfiltered (gdb_stdlog,
2080 "LLW: %s exited.\n",
2081 target_pid_to_str (lp->ptid));
2085 /* Make sure there is at least one thread running. */
2086 gdb_assert (iterate_over_lwps (running_callback, NULL));
2088 /* Discard the event. */
2093 /* Make sure we don't report a SIGSTOP that we sent
2094 ourselves in an attempt to stop an LWP. */
2096 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2098 if (debug_linux_nat)
2099 fprintf_unfiltered (gdb_stdlog,
2100 "LLW: Delayed SIGSTOP caught for %s.\n",
2101 target_pid_to_str (lp->ptid));
2103 /* This is a delayed SIGSTOP. */
2106 registers_changed ();
2107 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2108 lp->step, TARGET_SIGNAL_0);
2109 if (debug_linux_nat)
2110 fprintf_unfiltered (gdb_stdlog,
2111 "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
2113 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2114 target_pid_to_str (lp->ptid));
2117 gdb_assert (lp->resumed);
2119 /* Discard the event. */
2129 /* Alternate between checking cloned and uncloned processes. */
2130 options ^= __WCLONE;
2132 /* And suspend every time we have checked both. */
2133 if (options & __WCLONE)
2134 sigsuspend (&suspend_mask);
2137 /* We shouldn't end up here unless we want to try again. */
2138 gdb_assert (status == 0);
2141 clear_sigio_trap ();
2142 clear_sigint_trap ();
2146 /* Don't report signals that GDB isn't interested in, such as
2147 signals that are neither printed nor stopped upon. Stopping all
2148 threads can be a bit time-consuming so if we want decent
2149 performance with heavily multi-threaded programs, especially when
2150 they're using a high frequency timer, we'd better avoid it if we
2153 if (WIFSTOPPED (status))
2155 int signo = target_signal_from_host (WSTOPSIG (status));
2157 if (signal_stop_state (signo) == 0
2158 && signal_print_state (signo) == 0
2159 && signal_pass_state (signo) == 1)
2161 /* FIMXE: kettenis/2001-06-06: Should we resume all threads
2162 here? It is not clear we should. GDB may not expect
2163 other threads to run. On the other hand, not resuming
2164 newly attached threads may cause an unwanted delay in
2165 getting them running. */
2166 registers_changed ();
2167 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2169 if (debug_linux_nat)
2170 fprintf_unfiltered (gdb_stdlog,
2171 "LLW: %s %s, %s (preempt 'handle')\n",
2173 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2174 target_pid_to_str (lp->ptid),
2175 signo ? strsignal (signo) : "0");
2181 if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
2183 /* If ^C/BREAK is typed at the tty/console, SIGINT gets
2184 forwarded to the entire process group, that is, all LWP's
2185 will receive it. Since we only want to report it once,
2186 we try to flush it from all LWPs except this one. */
2187 sigaddset (&flush_mask, SIGINT);
2191 /* This LWP is stopped now. */
2194 if (debug_linux_nat)
2195 fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
2196 status_to_str (status), target_pid_to_str (lp->ptid));
2198 /* Now stop all other LWP's ... */
2199 iterate_over_lwps (stop_callback, NULL);
2201 /* ... and wait until all of them have reported back that they're no
2203 iterate_over_lwps (stop_wait_callback, &flush_mask);
2204 iterate_over_lwps (flush_callback, &flush_mask);
2206 /* If we're not waiting for a specific LWP, choose an event LWP from
2207 among those that have had events. Giving equal priority to all
2208 LWPs that have had events helps prevent starvation. */
2210 select_event_lwp (&lp, &status);
2212 /* Now that we've selected our final event LWP, cancel any
2213 breakpoints in other LWPs that have hit a GDB breakpoint. See
2214 the comment in cancel_breakpoints_callback to find out why. */
2215 iterate_over_lwps (cancel_breakpoints_callback, lp);
2217 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2219 trap_ptid = lp->ptid;
2220 if (debug_linux_nat)
2221 fprintf_unfiltered (gdb_stdlog,
2222 "LLW: trap_ptid is %s.\n",
2223 target_pid_to_str (trap_ptid));
2226 trap_ptid = null_ptid;
2228 if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
2230 *ourstatus = lp->waitstatus;
2231 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
2234 store_waitstatus (ourstatus, status);
2240 kill_callback (struct lwp_info *lp, void *data)
2243 ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
2244 if (debug_linux_nat)
2245 fprintf_unfiltered (gdb_stdlog,
2246 "KC: PTRACE_KILL %s, 0, 0 (%s)\n",
2247 target_pid_to_str (lp->ptid),
2248 errno ? safe_strerror (errno) : "OK");
2254 kill_wait_callback (struct lwp_info *lp, void *data)
2258 /* We must make sure that there are no pending events (delayed
2259 SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
2260 program doesn't interfere with any following debugging session. */
2262 /* For cloned processes we must check both with __WCLONE and
2263 without, since the exit status of a cloned process isn't reported
2269 pid = my_waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
2270 if (pid != (pid_t) -1 && debug_linux_nat)
2272 fprintf_unfiltered (gdb_stdlog,
2273 "KWC: wait %s received unknown.\n",
2274 target_pid_to_str (lp->ptid));
2277 while (pid == GET_LWP (lp->ptid));
2279 gdb_assert (pid == -1 && errno == ECHILD);
2284 pid = my_waitpid (GET_LWP (lp->ptid), NULL, 0);
2285 if (pid != (pid_t) -1 && debug_linux_nat)
2287 fprintf_unfiltered (gdb_stdlog,
2288 "KWC: wait %s received unk.\n",
2289 target_pid_to_str (lp->ptid));
2292 while (pid == GET_LWP (lp->ptid));
2294 gdb_assert (pid == -1 && errno == ECHILD);
2299 linux_nat_kill (void)
2301 struct target_waitstatus last;
2305 /* If we're stopped while forking and we haven't followed yet,
2306 kill the other task. We need to do this first because the
2307 parent will be sleeping if this is a vfork. */
2309 get_last_target_status (&last_ptid, &last);
2311 if (last.kind == TARGET_WAITKIND_FORKED
2312 || last.kind == TARGET_WAITKIND_VFORKED)
2314 ptrace (PT_KILL, last.value.related_pid, 0, 0);
2318 if (forks_exist_p ())
2319 linux_fork_killall ();
2322 /* Kill all LWP's ... */
2323 iterate_over_lwps (kill_callback, NULL);
2325 /* ... and wait until we've flushed all events. */
2326 iterate_over_lwps (kill_wait_callback, NULL);
2329 target_mourn_inferior ();
2333 linux_nat_mourn_inferior (void)
2335 trap_ptid = null_ptid;
2337 /* Destroy LWP info; it's no longer valid. */
2340 /* Restore the original signal mask. */
2341 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
2342 sigemptyset (&blocked_mask);
2344 if (! forks_exist_p ())
2345 /* Normal case, no other forks available. */
2346 linux_ops->to_mourn_inferior ();
2348 /* Multi-fork case. The current inferior_ptid has exited, but
2349 there are other viable forks to debug. Delete the exiting
2350 one and context-switch to the first available. */
2351 linux_fork_mourn_inferior ();
2355 linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
2356 const char *annex, gdb_byte *readbuf,
2357 const gdb_byte *writebuf,
2358 ULONGEST offset, LONGEST len)
2360 struct cleanup *old_chain = save_inferior_ptid ();
2363 if (is_lwp (inferior_ptid))
2364 inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
2366 xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
2369 do_cleanups (old_chain);
2374 linux_nat_thread_alive (ptid_t ptid)
2376 gdb_assert (is_lwp (ptid));
2379 ptrace (PTRACE_PEEKUSER, GET_LWP (ptid), 0, 0);
2380 if (debug_linux_nat)
2381 fprintf_unfiltered (gdb_stdlog,
2382 "LLTA: PTRACE_PEEKUSER %s, 0, 0 (%s)\n",
2383 target_pid_to_str (ptid),
2384 errno ? safe_strerror (errno) : "OK");
2392 linux_nat_pid_to_str (ptid_t ptid)
2394 static char buf[64];
2396 if (lwp_list && lwp_list->next && is_lwp (ptid))
2398 snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
2402 return normal_pid_to_str (ptid);
2406 sigchld_handler (int signo)
2408 /* Do nothing. The only reason for this handler is that it allows
2409 us to use sigsuspend in linux_nat_wait above to wait for the
2410 arrival of a SIGCHLD. */
2413 /* Accepts an integer PID; Returns a string representing a file that
2414 can be opened to get the symbols for the child process. */
2417 child_pid_to_exec_file (int pid)
2419 char *name1, *name2;
2421 name1 = xmalloc (MAXPATHLEN);
2422 name2 = xmalloc (MAXPATHLEN);
2423 make_cleanup (xfree, name1);
2424 make_cleanup (xfree, name2);
2425 memset (name2, 0, MAXPATHLEN);
2427 sprintf (name1, "/proc/%d/exe", pid);
2428 if (readlink (name1, name2, MAXPATHLEN) > 0)
2434 /* Service function for corefiles and info proc. */
2437 read_mapping (FILE *mapfile,
2442 char *device, long long *inode, char *filename)
2444 int ret = fscanf (mapfile, "%llx-%llx %s %llx %s %llx",
2445 addr, endaddr, permissions, offset, device, inode);
2448 if (ret > 0 && ret != EOF)
2450 /* Eat everything up to EOL for the filename. This will prevent
2451 weird filenames (such as one with embedded whitespace) from
2452 confusing this code. It also makes this code more robust in
2453 respect to annotations the kernel may add after the filename.
2455 Note the filename is used for informational purposes
2457 ret += fscanf (mapfile, "%[^\n]\n", filename);
2460 return (ret != 0 && ret != EOF);
2463 /* Fills the "to_find_memory_regions" target vector. Lists the memory
2464 regions in the inferior for a corefile. */
2467 linux_nat_find_memory_regions (int (*func) (CORE_ADDR,
2469 int, int, int, void *), void *obfd)
2471 long long pid = PIDGET (inferior_ptid);
2472 char mapsfilename[MAXPATHLEN];
2474 long long addr, endaddr, size, offset, inode;
2475 char permissions[8], device[8], filename[MAXPATHLEN];
2476 int read, write, exec;
2479 /* Compose the filename for the /proc memory map, and open it. */
2480 sprintf (mapsfilename, "/proc/%lld/maps", pid);
2481 if ((mapsfile = fopen (mapsfilename, "r")) == NULL)
2482 error (_("Could not open %s."), mapsfilename);
2485 fprintf_filtered (gdb_stdout,
2486 "Reading memory regions from %s\n", mapsfilename);
2488 /* Now iterate until end-of-file. */
2489 while (read_mapping (mapsfile, &addr, &endaddr, &permissions[0],
2490 &offset, &device[0], &inode, &filename[0]))
2492 size = endaddr - addr;
2494 /* Get the segment's permissions. */
2495 read = (strchr (permissions, 'r') != 0);
2496 write = (strchr (permissions, 'w') != 0);
2497 exec = (strchr (permissions, 'x') != 0);
2501 fprintf_filtered (gdb_stdout,
2502 "Save segment, %lld bytes at 0x%s (%c%c%c)",
2503 size, paddr_nz (addr),
2505 write ? 'w' : ' ', exec ? 'x' : ' ');
2506 if (filename && filename[0])
2507 fprintf_filtered (gdb_stdout, " for %s", filename);
2508 fprintf_filtered (gdb_stdout, "\n");
2511 /* Invoke the callback function to create the corefile
2513 func (addr, size, read, write, exec, obfd);
2519 /* Records the thread's register state for the corefile note
2523 linux_nat_do_thread_registers (bfd *obfd, ptid_t ptid,
2524 char *note_data, int *note_size)
2526 gdb_gregset_t gregs;
2527 gdb_fpregset_t fpregs;
2528 #ifdef FILL_FPXREGSET
2529 gdb_fpxregset_t fpxregs;
2531 unsigned long lwp = ptid_get_lwp (ptid);
2533 fill_gregset (&gregs, -1);
2534 note_data = (char *) elfcore_write_prstatus (obfd,
2538 stop_signal, &gregs);
2540 fill_fpregset (&fpregs, -1);
2541 note_data = (char *) elfcore_write_prfpreg (obfd,
2544 &fpregs, sizeof (fpregs));
2545 #ifdef FILL_FPXREGSET
2546 fill_fpxregset (&fpxregs, -1);
2547 note_data = (char *) elfcore_write_prxfpreg (obfd,
2550 &fpxregs, sizeof (fpxregs));
2555 struct linux_nat_corefile_thread_data
2563 /* Called by gdbthread.c once per thread. Records the thread's
2564 register state for the corefile note section. */
2567 linux_nat_corefile_thread_callback (struct lwp_info *ti, void *data)
2569 struct linux_nat_corefile_thread_data *args = data;
2570 ptid_t saved_ptid = inferior_ptid;
2572 inferior_ptid = ti->ptid;
2573 registers_changed ();
2574 target_fetch_registers (-1); /* FIXME should not be necessary;
2575 fill_gregset should do it automatically. */
2576 args->note_data = linux_nat_do_thread_registers (args->obfd,
2581 inferior_ptid = saved_ptid;
2582 registers_changed ();
2583 target_fetch_registers (-1); /* FIXME should not be necessary;
2584 fill_gregset should do it automatically. */
2588 /* Records the register state for the corefile note section. */
2591 linux_nat_do_registers (bfd *obfd, ptid_t ptid,
2592 char *note_data, int *note_size)
2594 registers_changed ();
2595 target_fetch_registers (-1); /* FIXME should not be necessary;
2596 fill_gregset should do it automatically. */
2597 return linux_nat_do_thread_registers (obfd,
2598 ptid_build (ptid_get_pid (inferior_ptid),
2599 ptid_get_pid (inferior_ptid),
2601 note_data, note_size);
2605 /* Fills the "to_make_corefile_note" target vector. Builds the note
2606 section for a corefile, and returns it in a malloc buffer. */
2609 linux_nat_make_corefile_notes (bfd *obfd, int *note_size)
2611 struct linux_nat_corefile_thread_data thread_args;
2612 struct cleanup *old_chain;
2613 char fname[16] = { '\0' };
2614 char psargs[80] = { '\0' };
2615 char *note_data = NULL;
2616 ptid_t current_ptid = inferior_ptid;
2620 if (get_exec_file (0))
2622 strncpy (fname, strrchr (get_exec_file (0), '/') + 1, sizeof (fname));
2623 strncpy (psargs, get_exec_file (0), sizeof (psargs));
2624 if (get_inferior_args ())
2626 strncat (psargs, " ", sizeof (psargs) - strlen (psargs));
2627 strncat (psargs, get_inferior_args (),
2628 sizeof (psargs) - strlen (psargs));
2630 note_data = (char *) elfcore_write_prpsinfo (obfd,
2632 note_size, fname, psargs);
2635 /* Dump information for threads. */
2636 thread_args.obfd = obfd;
2637 thread_args.note_data = note_data;
2638 thread_args.note_size = note_size;
2639 thread_args.num_notes = 0;
2640 iterate_over_lwps (linux_nat_corefile_thread_callback, &thread_args);
2641 if (thread_args.num_notes == 0)
2643 /* iterate_over_threads didn't come up with any threads; just
2644 use inferior_ptid. */
2645 note_data = linux_nat_do_registers (obfd, inferior_ptid,
2646 note_data, note_size);
2650 note_data = thread_args.note_data;
2653 auxv_len = target_auxv_read (¤t_target, &auxv);
2656 note_data = elfcore_write_note (obfd, note_data, note_size,
2657 "CORE", NT_AUXV, auxv, auxv_len);
2661 make_cleanup (xfree, note_data);
2665 /* Implement the "info proc" command. */
2668 linux_nat_info_proc_cmd (char *args, int from_tty)
2670 long long pid = PIDGET (inferior_ptid);
2673 char buffer[MAXPATHLEN];
2674 char fname1[MAXPATHLEN], fname2[MAXPATHLEN];
2687 /* Break up 'args' into an argv array. */
2688 if ((argv = buildargv (args)) == NULL)
2691 make_cleanup_freeargv (argv);
2693 while (argv != NULL && *argv != NULL)
2695 if (isdigit (argv[0][0]))
2697 pid = strtoul (argv[0], NULL, 10);
2699 else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
2703 else if (strcmp (argv[0], "status") == 0)
2707 else if (strcmp (argv[0], "stat") == 0)
2711 else if (strcmp (argv[0], "cmd") == 0)
2715 else if (strncmp (argv[0], "exe", strlen (argv[0])) == 0)
2719 else if (strcmp (argv[0], "cwd") == 0)
2723 else if (strncmp (argv[0], "all", strlen (argv[0])) == 0)
2729 /* [...] (future options here) */
2734 error (_("No current process: you must name one."));
2736 sprintf (fname1, "/proc/%lld", pid);
2737 if (stat (fname1, &dummy) != 0)
2738 error (_("No /proc directory: '%s'"), fname1);
2740 printf_filtered (_("process %lld\n"), pid);
2741 if (cmdline_f || all)
2743 sprintf (fname1, "/proc/%lld/cmdline", pid);
2744 if ((procfile = fopen (fname1, "r")) > 0)
2746 fgets (buffer, sizeof (buffer), procfile);
2747 printf_filtered ("cmdline = '%s'\n", buffer);
2751 warning (_("unable to open /proc file '%s'"), fname1);
2755 sprintf (fname1, "/proc/%lld/cwd", pid);
2756 memset (fname2, 0, sizeof (fname2));
2757 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
2758 printf_filtered ("cwd = '%s'\n", fname2);
2760 warning (_("unable to read link '%s'"), fname1);
2764 sprintf (fname1, "/proc/%lld/exe", pid);
2765 memset (fname2, 0, sizeof (fname2));
2766 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
2767 printf_filtered ("exe = '%s'\n", fname2);
2769 warning (_("unable to read link '%s'"), fname1);
2771 if (mappings_f || all)
2773 sprintf (fname1, "/proc/%lld/maps", pid);
2774 if ((procfile = fopen (fname1, "r")) > 0)
2776 long long addr, endaddr, size, offset, inode;
2777 char permissions[8], device[8], filename[MAXPATHLEN];
2779 printf_filtered (_("Mapped address spaces:\n\n"));
2780 if (TARGET_ADDR_BIT == 32)
2782 printf_filtered ("\t%10s %10s %10s %10s %7s\n",
2785 " Size", " Offset", "objfile");
2789 printf_filtered (" %18s %18s %10s %10s %7s\n",
2792 " Size", " Offset", "objfile");
2795 while (read_mapping (procfile, &addr, &endaddr, &permissions[0],
2796 &offset, &device[0], &inode, &filename[0]))
2798 size = endaddr - addr;
2800 /* FIXME: carlton/2003-08-27: Maybe the printf_filtered
2801 calls here (and possibly above) should be abstracted
2802 out into their own functions? Andrew suggests using
2803 a generic local_address_string instead to print out
2804 the addresses; that makes sense to me, too. */
2806 if (TARGET_ADDR_BIT == 32)
2808 printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
2809 (unsigned long) addr, /* FIXME: pr_addr */
2810 (unsigned long) endaddr,
2812 (unsigned int) offset,
2813 filename[0] ? filename : "");
2817 printf_filtered (" %#18lx %#18lx %#10x %#10x %7s\n",
2818 (unsigned long) addr, /* FIXME: pr_addr */
2819 (unsigned long) endaddr,
2821 (unsigned int) offset,
2822 filename[0] ? filename : "");
2829 warning (_("unable to open /proc file '%s'"), fname1);
2831 if (status_f || all)
2833 sprintf (fname1, "/proc/%lld/status", pid);
2834 if ((procfile = fopen (fname1, "r")) > 0)
2836 while (fgets (buffer, sizeof (buffer), procfile) != NULL)
2837 puts_filtered (buffer);
2841 warning (_("unable to open /proc file '%s'"), fname1);
2845 sprintf (fname1, "/proc/%lld/stat", pid);
2846 if ((procfile = fopen (fname1, "r")) > 0)
2851 if (fscanf (procfile, "%d ", &itmp) > 0)
2852 printf_filtered (_("Process: %d\n"), itmp);
2853 if (fscanf (procfile, "%s ", &buffer[0]) > 0)
2854 printf_filtered (_("Exec file: %s\n"), buffer);
2855 if (fscanf (procfile, "%c ", &ctmp) > 0)
2856 printf_filtered (_("State: %c\n"), ctmp);
2857 if (fscanf (procfile, "%d ", &itmp) > 0)
2858 printf_filtered (_("Parent process: %d\n"), itmp);
2859 if (fscanf (procfile, "%d ", &itmp) > 0)
2860 printf_filtered (_("Process group: %d\n"), itmp);
2861 if (fscanf (procfile, "%d ", &itmp) > 0)
2862 printf_filtered (_("Session id: %d\n"), itmp);
2863 if (fscanf (procfile, "%d ", &itmp) > 0)
2864 printf_filtered (_("TTY: %d\n"), itmp);
2865 if (fscanf (procfile, "%d ", &itmp) > 0)
2866 printf_filtered (_("TTY owner process group: %d\n"), itmp);
2867 if (fscanf (procfile, "%u ", &itmp) > 0)
2868 printf_filtered (_("Flags: 0x%x\n"), itmp);
2869 if (fscanf (procfile, "%u ", &itmp) > 0)
2870 printf_filtered (_("Minor faults (no memory page): %u\n"),
2871 (unsigned int) itmp);
2872 if (fscanf (procfile, "%u ", &itmp) > 0)
2873 printf_filtered (_("Minor faults, children: %u\n"),
2874 (unsigned int) itmp);
2875 if (fscanf (procfile, "%u ", &itmp) > 0)
2876 printf_filtered (_("Major faults (memory page faults): %u\n"),
2877 (unsigned int) itmp);
2878 if (fscanf (procfile, "%u ", &itmp) > 0)
2879 printf_filtered (_("Major faults, children: %u\n"),
2880 (unsigned int) itmp);
2881 if (fscanf (procfile, "%d ", &itmp) > 0)
2882 printf_filtered ("utime: %d\n", itmp);
2883 if (fscanf (procfile, "%d ", &itmp) > 0)
2884 printf_filtered ("stime: %d\n", itmp);
2885 if (fscanf (procfile, "%d ", &itmp) > 0)
2886 printf_filtered ("utime, children: %d\n", itmp);
2887 if (fscanf (procfile, "%d ", &itmp) > 0)
2888 printf_filtered ("stime, children: %d\n", itmp);
2889 if (fscanf (procfile, "%d ", &itmp) > 0)
2890 printf_filtered (_("jiffies remaining in current time slice: %d\n"),
2892 if (fscanf (procfile, "%d ", &itmp) > 0)
2893 printf_filtered ("'nice' value: %d\n", itmp);
2894 if (fscanf (procfile, "%u ", &itmp) > 0)
2895 printf_filtered (_("jiffies until next timeout: %u\n"),
2896 (unsigned int) itmp);
2897 if (fscanf (procfile, "%u ", &itmp) > 0)
2898 printf_filtered ("jiffies until next SIGALRM: %u\n",
2899 (unsigned int) itmp);
2900 if (fscanf (procfile, "%d ", &itmp) > 0)
2901 printf_filtered (_("start time (jiffies since system boot): %d\n"),
2903 if (fscanf (procfile, "%u ", &itmp) > 0)
2904 printf_filtered (_("Virtual memory size: %u\n"),
2905 (unsigned int) itmp);
2906 if (fscanf (procfile, "%u ", &itmp) > 0)
2907 printf_filtered (_("Resident set size: %u\n"), (unsigned int) itmp);
2908 if (fscanf (procfile, "%u ", &itmp) > 0)
2909 printf_filtered ("rlim: %u\n", (unsigned int) itmp);
2910 if (fscanf (procfile, "%u ", &itmp) > 0)
2911 printf_filtered (_("Start of text: 0x%x\n"), itmp);
2912 if (fscanf (procfile, "%u ", &itmp) > 0)
2913 printf_filtered (_("End of text: 0x%x\n"), itmp);
2914 if (fscanf (procfile, "%u ", &itmp) > 0)
2915 printf_filtered (_("Start of stack: 0x%x\n"), itmp);
2916 #if 0 /* Don't know how architecture-dependent the rest is...
2917 Anyway the signal bitmap info is available from "status". */
2918 if (fscanf (procfile, "%u ", &itmp) > 0) /* FIXME arch? */
2919 printf_filtered (_("Kernel stack pointer: 0x%x\n"), itmp);
2920 if (fscanf (procfile, "%u ", &itmp) > 0) /* FIXME arch? */
2921 printf_filtered (_("Kernel instr pointer: 0x%x\n"), itmp);
2922 if (fscanf (procfile, "%d ", &itmp) > 0)
2923 printf_filtered (_("Pending signals bitmap: 0x%x\n"), itmp);
2924 if (fscanf (procfile, "%d ", &itmp) > 0)
2925 printf_filtered (_("Blocked signals bitmap: 0x%x\n"), itmp);
2926 if (fscanf (procfile, "%d ", &itmp) > 0)
2927 printf_filtered (_("Ignored signals bitmap: 0x%x\n"), itmp);
2928 if (fscanf (procfile, "%d ", &itmp) > 0)
2929 printf_filtered (_("Catched signals bitmap: 0x%x\n"), itmp);
2930 if (fscanf (procfile, "%u ", &itmp) > 0) /* FIXME arch? */
2931 printf_filtered (_("wchan (system call): 0x%x\n"), itmp);
2936 warning (_("unable to open /proc file '%s'"), fname1);
2940 /* Implement the to_xfer_partial interface for memory reads using the /proc
2941 filesystem. Because we can use a single read() call for /proc, this
2942 can be much more efficient than banging away at PTRACE_PEEKTEXT,
2943 but it doesn't support writes. */
2946 linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
2947 const char *annex, gdb_byte *readbuf,
2948 const gdb_byte *writebuf,
2949 ULONGEST offset, LONGEST len)
2955 if (object != TARGET_OBJECT_MEMORY || !readbuf)
2958 /* Don't bother for one word. */
2959 if (len < 3 * sizeof (long))
2962 /* We could keep this file open and cache it - possibly one per
2963 thread. That requires some juggling, but is even faster. */
2964 sprintf (filename, "/proc/%d/mem", PIDGET (inferior_ptid));
2965 fd = open (filename, O_RDONLY | O_LARGEFILE);
2969 /* If pread64 is available, use it. It's faster if the kernel
2970 supports it (only one syscall), and it's 64-bit safe even on
2971 32-bit platforms (for instance, SPARC debugging a SPARC64
2974 if (pread64 (fd, readbuf, len, offset) != len)
2976 if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
2986 /* Parse LINE as a signal set and add its set bits to SIGS. */
2989 add_line_to_sigset (const char *line, sigset_t *sigs)
2991 int len = strlen (line) - 1;
2995 if (line[len] != '\n')
2996 error (_("Could not parse signal set: %s"), line);
3004 if (*p >= '0' && *p <= '9')
3006 else if (*p >= 'a' && *p <= 'f')
3007 digit = *p - 'a' + 10;
3009 error (_("Could not parse signal set: %s"), line);
3014 sigaddset (sigs, signum + 1);
3016 sigaddset (sigs, signum + 2);
3018 sigaddset (sigs, signum + 3);
3020 sigaddset (sigs, signum + 4);
3026 /* Find process PID's pending signals from /proc/pid/status and set
3030 linux_proc_pending_signals (int pid, sigset_t *pending, sigset_t *blocked, sigset_t *ignored)
3033 char buffer[MAXPATHLEN], fname[MAXPATHLEN];
3036 sigemptyset (pending);
3037 sigemptyset (blocked);
3038 sigemptyset (ignored);
3039 sprintf (fname, "/proc/%d/status", pid);
3040 procfile = fopen (fname, "r");
3041 if (procfile == NULL)
3042 error (_("Could not open %s"), fname);
3044 while (fgets (buffer, MAXPATHLEN, procfile) != NULL)
3046 /* Normal queued signals are on the SigPnd line in the status
3047 file. However, 2.6 kernels also have a "shared" pending
3048 queue for delivering signals to a thread group, so check for
3051 Unfortunately some Red Hat kernels include the shared pending
3052 queue but not the ShdPnd status field. */
3054 if (strncmp (buffer, "SigPnd:\t", 8) == 0)
3055 add_line_to_sigset (buffer + 8, pending);
3056 else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
3057 add_line_to_sigset (buffer + 8, pending);
3058 else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
3059 add_line_to_sigset (buffer + 8, blocked);
3060 else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
3061 add_line_to_sigset (buffer + 8, ignored);
3068 linux_xfer_partial (struct target_ops *ops, enum target_object object,
3069 const char *annex, gdb_byte *readbuf,
3070 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
3074 if (object == TARGET_OBJECT_AUXV)
3075 return procfs_xfer_auxv (ops, object, annex, readbuf, writebuf,
3078 xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
3083 return super_xfer_partial (ops, object, annex, readbuf, writebuf,
3087 #ifndef FETCH_INFERIOR_REGISTERS
3089 /* Return the address in the core dump or inferior of register
3093 linux_register_u_offset (int regno)
3095 /* FIXME drow/2005-09-04: The hardcoded use of register_addr should go
3096 away. This requires disentangling the various definitions of it
3097 (particularly alpha-nat.c's). */
3098 return register_addr (regno, 0);
3103 /* Create a prototype generic Linux target. The client can override
3104 it with local methods. */
3109 struct target_ops *t;
3111 #ifdef FETCH_INFERIOR_REGISTERS
3112 t = inf_ptrace_target ();
3114 t = inf_ptrace_trad_target (linux_register_u_offset);
3116 t->to_insert_fork_catchpoint = child_insert_fork_catchpoint;
3117 t->to_insert_vfork_catchpoint = child_insert_vfork_catchpoint;
3118 t->to_insert_exec_catchpoint = child_insert_exec_catchpoint;
3119 t->to_pid_to_exec_file = child_pid_to_exec_file;
3120 t->to_post_startup_inferior = linux_child_post_startup_inferior;
3121 t->to_post_attach = child_post_attach;
3122 t->to_follow_fork = child_follow_fork;
3123 t->to_find_memory_regions = linux_nat_find_memory_regions;
3124 t->to_make_corefile_notes = linux_nat_make_corefile_notes;
3126 super_xfer_partial = t->to_xfer_partial;
3127 t->to_xfer_partial = linux_xfer_partial;
3133 linux_nat_add_target (struct target_ops *t)
3135 extern void thread_db_init (struct target_ops *);
3137 /* Save the provided single-threaded target. We save this in a separate
3138 variable because another target we've inherited from (e.g. inf-ptrace)
3139 may have saved a pointer to T; we want to use it for the final
3140 process stratum target. */
3141 linux_ops_saved = *t;
3142 linux_ops = &linux_ops_saved;
3144 /* Override some methods for multithreading. */
3145 t->to_attach = linux_nat_attach;
3146 t->to_detach = linux_nat_detach;
3147 t->to_resume = linux_nat_resume;
3148 t->to_wait = linux_nat_wait;
3149 t->to_xfer_partial = linux_nat_xfer_partial;
3150 t->to_kill = linux_nat_kill;
3151 t->to_mourn_inferior = linux_nat_mourn_inferior;
3152 t->to_thread_alive = linux_nat_thread_alive;
3153 t->to_pid_to_str = linux_nat_pid_to_str;
3154 t->to_has_thread_control = tc_schedlock;
3156 /* We don't change the stratum; this target will sit at
3157 process_stratum and thread_db will set at thread_stratum. This
3158 is a little strange, since this is a multi-threaded-capable
3159 target, but we want to be on the stack below thread_db, and we
3160 also want to be used for single-threaded processes. */
3164 /* TODO: Eliminate this and have libthread_db use
3165 find_target_beneath. */
3170 _initialize_linux_nat (void)
3172 struct sigaction action;
3174 add_info ("proc", linux_nat_info_proc_cmd, _("\
3175 Show /proc process information about any running process.\n\
3176 Specify any process id, or use the program being debugged by default.\n\
3177 Specify any of the following keywords for detailed info:\n\
3178 mappings -- list of mapped memory regions.\n\
3179 stat -- list a bunch of random process info.\n\
3180 status -- list a different bunch of random process info.\n\
3181 all -- list all available /proc info."));
3183 /* Save the original signal mask. */
3184 sigprocmask (SIG_SETMASK, NULL, &normal_mask);
3186 action.sa_handler = sigchld_handler;
3187 sigemptyset (&action.sa_mask);
3188 action.sa_flags = SA_RESTART;
3189 sigaction (SIGCHLD, &action, NULL);
3191 /* Make sure we don't block SIGCHLD during a sigsuspend. */
3192 sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
3193 sigdelset (&suspend_mask, SIGCHLD);
3195 sigemptyset (&blocked_mask);
3197 add_setshow_zinteger_cmd ("lin-lwp", no_class, &debug_linux_nat, _("\
3198 Set debugging of GNU/Linux lwp module."), _("\
3199 Show debugging of GNU/Linux lwp module."), _("\
3200 Enables printf debugging output."),
3202 show_debug_linux_nat,
3203 &setdebuglist, &showdebuglist);
3207 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
3208 the GNU/Linux Threads library and therefore doesn't really belong
3211 /* Read variable NAME in the target and return its value if found.
3212 Otherwise return zero. It is assumed that the type of the variable
3216 get_signo (const char *name)
3218 struct minimal_symbol *ms;
3221 ms = lookup_minimal_symbol (name, NULL, NULL);
3225 if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
3226 sizeof (signo)) != 0)
3232 /* Return the set of signals used by the threads library in *SET. */
3235 lin_thread_get_thread_signals (sigset_t *set)
3237 struct sigaction action;
3238 int restart, cancel;
3242 restart = get_signo ("__pthread_sig_restart");
3243 cancel = get_signo ("__pthread_sig_cancel");
3245 /* LinuxThreads normally uses the first two RT signals, but in some legacy
3246 cases may use SIGUSR1/SIGUSR2. NPTL always uses RT signals, but does
3247 not provide any way for the debugger to query the signal numbers -
3248 fortunately they don't change! */
3251 restart = __SIGRTMIN;
3254 cancel = __SIGRTMIN + 1;
3256 sigaddset (set, restart);
3257 sigaddset (set, cancel);
3259 /* The GNU/Linux Threads library makes terminating threads send a
3260 special "cancel" signal instead of SIGCHLD. Make sure we catch
3261 those (to prevent them from terminating GDB itself, which is
3262 likely to be their default action) and treat them the same way as
3265 action.sa_handler = sigchld_handler;
3266 sigemptyset (&action.sa_mask);
3267 action.sa_flags = SA_RESTART;
3268 sigaction (cancel, &action, NULL);
3270 /* We block the "cancel" signal throughout this code ... */
3271 sigaddset (&blocked_mask, cancel);
3272 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
3274 /* ... except during a sigsuspend. */
3275 sigdelset (&suspend_mask, cancel);