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"
40 #include "inf-ptrace.h"
42 #include <sys/param.h> /* for MAXPATHLEN */
43 #include <sys/procfs.h> /* for elf_gregset etc. */
44 #include "elf-bfd.h" /* for elfcore_write_* */
45 #include "gregset.h" /* for gregset */
46 #include "gdbcore.h" /* for get_exec_file */
47 #include <ctype.h> /* for isdigit */
48 #include "gdbthread.h" /* for struct thread_info etc. */
49 #include "gdb_stat.h" /* for struct stat */
50 #include <fcntl.h> /* for O_RDONLY */
56 /* If the system headers did not provide the constants, hard-code the normal
58 #ifndef PTRACE_EVENT_FORK
60 #define PTRACE_SETOPTIONS 0x4200
61 #define PTRACE_GETEVENTMSG 0x4201
63 /* options set using PTRACE_SETOPTIONS */
64 #define PTRACE_O_TRACESYSGOOD 0x00000001
65 #define PTRACE_O_TRACEFORK 0x00000002
66 #define PTRACE_O_TRACEVFORK 0x00000004
67 #define PTRACE_O_TRACECLONE 0x00000008
68 #define PTRACE_O_TRACEEXEC 0x00000010
69 #define PTRACE_O_TRACEVFORKDONE 0x00000020
70 #define PTRACE_O_TRACEEXIT 0x00000040
72 /* Wait extended result codes for the above trace options. */
73 #define PTRACE_EVENT_FORK 1
74 #define PTRACE_EVENT_VFORK 2
75 #define PTRACE_EVENT_CLONE 3
76 #define PTRACE_EVENT_EXEC 4
77 #define PTRACE_EVENT_VFORK_DONE 5
78 #define PTRACE_EVENT_EXIT 6
80 #endif /* PTRACE_EVENT_FORK */
82 /* We can't always assume that this flag is available, but all systems
83 with the ptrace event handlers also have __WALL, so it's safe to use
86 #define __WALL 0x40000000 /* Wait for any child. */
89 /* The single-threaded native GNU/Linux target_ops. We save a pointer for
90 the use of the multi-threaded target. */
91 static struct target_ops *linux_ops;
92 static struct target_ops linux_ops_saved;
94 /* The saved to_xfer_partial method, inherited from inf-ptrace.c.
95 Called by our to_xfer_partial. */
96 static LONGEST (*super_xfer_partial) (struct target_ops *,
98 const char *, gdb_byte *,
102 static int debug_linux_nat;
104 show_debug_linux_nat (struct ui_file *file, int from_tty,
105 struct cmd_list_element *c, const char *value)
107 fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
111 static int linux_parent_pid;
113 struct simple_pid_list
116 struct simple_pid_list *next;
118 struct simple_pid_list *stopped_pids;
120 /* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACEFORK
121 can not be used, 1 if it can. */
123 static int linux_supports_tracefork_flag = -1;
125 /* If we have PTRACE_O_TRACEFORK, this flag indicates whether we also have
126 PTRACE_O_TRACEVFORKDONE. */
128 static int linux_supports_tracevforkdone_flag = -1;
131 /* Trivial list manipulation functions to keep track of a list of
132 new stopped processes. */
134 add_to_pid_list (struct simple_pid_list **listp, int pid)
136 struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
138 new_pid->next = *listp;
143 pull_pid_from_list (struct simple_pid_list **listp, int pid)
145 struct simple_pid_list **p;
147 for (p = listp; *p != NULL; p = &(*p)->next)
148 if ((*p)->pid == pid)
150 struct simple_pid_list *next = (*p)->next;
159 linux_record_stopped_pid (int pid)
161 add_to_pid_list (&stopped_pids, pid);
165 /* A helper function for linux_test_for_tracefork, called after fork (). */
168 linux_tracefork_child (void)
172 ptrace (PTRACE_TRACEME, 0, 0, 0);
173 kill (getpid (), SIGSTOP);
178 /* Wrapper function for waitpid which handles EINTR. */
181 my_waitpid (int pid, int *status, int flags)
186 ret = waitpid (pid, status, flags);
188 while (ret == -1 && errno == EINTR);
193 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.
195 First, we try to enable fork tracing on ORIGINAL_PID. If this fails,
196 we know that the feature is not available. This may change the tracing
197 options for ORIGINAL_PID, but we'll be setting them shortly anyway.
199 However, if it succeeds, we don't know for sure that the feature is
200 available; old versions of PTRACE_SETOPTIONS ignored unknown options. We
201 create a child process, attach to it, use PTRACE_SETOPTIONS to enable
202 fork tracing, and let it fork. If the process exits, we assume that we
203 can't use TRACEFORK; if we get the fork notification, and we can extract
204 the new child's PID, then we assume that we can. */
207 linux_test_for_tracefork (int original_pid)
209 int child_pid, ret, status;
212 linux_supports_tracefork_flag = 0;
213 linux_supports_tracevforkdone_flag = 0;
215 ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACEFORK);
221 perror_with_name (("fork"));
224 linux_tracefork_child ();
226 ret = my_waitpid (child_pid, &status, 0);
228 perror_with_name (("waitpid"));
229 else if (ret != child_pid)
230 error (_("linux_test_for_tracefork: waitpid: unexpected result %d."), ret);
231 if (! WIFSTOPPED (status))
232 error (_("linux_test_for_tracefork: waitpid: unexpected status %d."), status);
234 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
237 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
240 warning (_("linux_test_for_tracefork: failed to kill child"));
244 ret = my_waitpid (child_pid, &status, 0);
245 if (ret != child_pid)
246 warning (_("linux_test_for_tracefork: failed to wait for killed child"));
247 else if (!WIFSIGNALED (status))
248 warning (_("linux_test_for_tracefork: unexpected wait status 0x%x from "
249 "killed child"), status);
254 /* Check whether PTRACE_O_TRACEVFORKDONE is available. */
255 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0,
256 PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORKDONE);
257 linux_supports_tracevforkdone_flag = (ret == 0);
259 ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
261 warning (_("linux_test_for_tracefork: failed to resume child"));
263 ret = my_waitpid (child_pid, &status, 0);
265 if (ret == child_pid && WIFSTOPPED (status)
266 && status >> 16 == PTRACE_EVENT_FORK)
269 ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
270 if (ret == 0 && second_pid != 0)
274 linux_supports_tracefork_flag = 1;
275 my_waitpid (second_pid, &second_status, 0);
276 ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
278 warning (_("linux_test_for_tracefork: failed to kill second child"));
279 my_waitpid (second_pid, &status, 0);
283 warning (_("linux_test_for_tracefork: unexpected result from waitpid "
284 "(%d, status 0x%x)"), ret, status);
286 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
288 warning (_("linux_test_for_tracefork: failed to kill child"));
289 my_waitpid (child_pid, &status, 0);
292 /* Return non-zero iff we have tracefork functionality available.
293 This function also sets linux_supports_tracefork_flag. */
296 linux_supports_tracefork (int pid)
298 if (linux_supports_tracefork_flag == -1)
299 linux_test_for_tracefork (pid);
300 return linux_supports_tracefork_flag;
304 linux_supports_tracevforkdone (int pid)
306 if (linux_supports_tracefork_flag == -1)
307 linux_test_for_tracefork (pid);
308 return linux_supports_tracevforkdone_flag;
313 linux_enable_event_reporting (ptid_t ptid)
315 int pid = ptid_get_lwp (ptid);
319 pid = ptid_get_pid (ptid);
321 if (! linux_supports_tracefork (pid))
324 options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEEXEC
325 | PTRACE_O_TRACECLONE;
326 if (linux_supports_tracevforkdone (pid))
327 options |= PTRACE_O_TRACEVFORKDONE;
329 /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to support
330 read-only process state. */
332 ptrace (PTRACE_SETOPTIONS, pid, 0, options);
336 child_post_attach (int pid)
338 linux_enable_event_reporting (pid_to_ptid (pid));
339 check_for_thread_db ();
343 linux_child_post_startup_inferior (ptid_t ptid)
345 linux_enable_event_reporting (ptid);
346 check_for_thread_db ();
350 child_follow_fork (struct target_ops *ops, int follow_child)
353 struct target_waitstatus last_status;
355 int parent_pid, child_pid;
357 get_last_target_status (&last_ptid, &last_status);
358 has_vforked = (last_status.kind == TARGET_WAITKIND_VFORKED);
359 parent_pid = ptid_get_lwp (last_ptid);
361 parent_pid = ptid_get_pid (last_ptid);
362 child_pid = last_status.value.related_pid;
366 /* We're already attached to the parent, by default. */
368 /* Before detaching from the child, remove all breakpoints from
369 it. (This won't actually modify the breakpoint list, but will
370 physically remove the breakpoints from the child.) */
371 /* If we vforked this will remove the breakpoints from the parent
372 also, but they'll be reinserted below. */
373 detach_breakpoints (child_pid);
375 /* Detach new forked process? */
380 target_terminal_ours ();
381 fprintf_filtered (gdb_stdlog,
382 "Detaching after fork from child process %d.\n",
386 ptrace (PTRACE_DETACH, child_pid, 0, 0);
390 struct fork_info *fp;
391 /* Retain child fork in ptrace (stopped) state. */
392 fp = find_fork_pid (child_pid);
394 fp = add_fork (child_pid);
395 fork_save_infrun_state (fp, 0);
400 gdb_assert (linux_supports_tracefork_flag >= 0);
401 if (linux_supports_tracevforkdone (0))
405 ptrace (PTRACE_CONT, parent_pid, 0, 0);
406 my_waitpid (parent_pid, &status, __WALL);
407 if ((status >> 16) != PTRACE_EVENT_VFORK_DONE)
408 warning (_("Unexpected waitpid result %06x when waiting for "
409 "vfork-done"), status);
413 /* We can't insert breakpoints until the child has
414 finished with the shared memory region. We need to
415 wait until that happens. Ideal would be to just
417 - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
418 - waitpid (parent_pid, &status, __WALL);
419 However, most architectures can't handle a syscall
420 being traced on the way out if it wasn't traced on
423 We might also think to loop, continuing the child
424 until it exits or gets a SIGTRAP. One problem is
425 that the child might call ptrace with PTRACE_TRACEME.
427 There's no simple and reliable way to figure out when
428 the vforked child will be done with its copy of the
429 shared memory. We could step it out of the syscall,
430 two instructions, let it go, and then single-step the
431 parent once. When we have hardware single-step, this
432 would work; with software single-step it could still
433 be made to work but we'd have to be able to insert
434 single-step breakpoints in the child, and we'd have
435 to insert -just- the single-step breakpoint in the
436 parent. Very awkward.
438 In the end, the best we can do is to make sure it
439 runs for a little while. Hopefully it will be out of
440 range of any breakpoints we reinsert. Usually this
441 is only the single-step breakpoint at vfork's return
447 /* Since we vforked, breakpoints were removed in the parent
448 too. Put them back. */
449 reattach_breakpoints (parent_pid);
454 char child_pid_spelling[40];
456 /* Needed to keep the breakpoint lists in sync. */
458 detach_breakpoints (child_pid);
460 /* Before detaching from the parent, remove all breakpoints from it. */
461 remove_breakpoints ();
465 target_terminal_ours ();
466 fprintf_filtered (gdb_stdlog,
467 "Attaching after fork to child process %d.\n",
471 /* If we're vforking, we may want to hold on to the parent until
472 the child exits or execs. At exec time we can remove the old
473 breakpoints from the parent and detach it; at exit time we
474 could do the same (or even, sneakily, resume debugging it - the
475 child's exec has failed, or something similar).
477 This doesn't clean up "properly", because we can't call
478 target_detach, but that's OK; if the current target is "child",
479 then it doesn't need any further cleanups, and lin_lwp will
480 generally not encounter vfork (vfork is defined to fork
483 The holding part is very easy if we have VFORKDONE events;
484 but keeping track of both processes is beyond GDB at the
485 moment. So we don't expose the parent to the rest of GDB.
486 Instead we quietly hold onto it until such time as we can
490 linux_parent_pid = parent_pid;
491 else if (!detach_fork)
493 struct fork_info *fp;
494 /* Retain parent fork in ptrace (stopped) state. */
495 fp = find_fork_pid (parent_pid);
497 fp = add_fork (parent_pid);
498 fork_save_infrun_state (fp, 0);
502 target_detach (NULL, 0);
505 inferior_ptid = pid_to_ptid (child_pid);
507 /* Reinstall ourselves, since we might have been removed in
508 target_detach (which does other necessary cleanup). */
512 /* Reset breakpoints in the child as appropriate. */
513 follow_inferior_reset_breakpoints ();
520 linux_handle_extended_wait (int pid, int status,
521 struct target_waitstatus *ourstatus)
523 int event = status >> 16;
525 if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
526 || event == PTRACE_EVENT_CLONE)
528 unsigned long new_pid;
531 ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
533 /* If we haven't already seen the new PID stop, wait for it now. */
534 if (! pull_pid_from_list (&stopped_pids, new_pid))
536 /* The new child has a pending SIGSTOP. We can't affect it until it
537 hits the SIGSTOP, but we're already attached. */
538 ret = my_waitpid (new_pid, &status,
539 (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
541 perror_with_name (_("waiting for new child"));
542 else if (ret != new_pid)
543 internal_error (__FILE__, __LINE__,
544 _("wait returned unexpected PID %d"), ret);
545 else if (!WIFSTOPPED (status) || WSTOPSIG (status) != SIGSTOP)
546 internal_error (__FILE__, __LINE__,
547 _("wait returned unexpected status 0x%x"), status);
550 if (event == PTRACE_EVENT_FORK)
551 ourstatus->kind = TARGET_WAITKIND_FORKED;
552 else if (event == PTRACE_EVENT_VFORK)
553 ourstatus->kind = TARGET_WAITKIND_VFORKED;
555 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
557 ourstatus->value.related_pid = new_pid;
558 return inferior_ptid;
561 if (event == PTRACE_EVENT_EXEC)
563 ourstatus->kind = TARGET_WAITKIND_EXECD;
564 ourstatus->value.execd_pathname
565 = xstrdup (child_pid_to_exec_file (pid));
567 if (linux_parent_pid)
569 detach_breakpoints (linux_parent_pid);
570 ptrace (PTRACE_DETACH, linux_parent_pid, 0, 0);
572 linux_parent_pid = 0;
575 return inferior_ptid;
578 internal_error (__FILE__, __LINE__,
579 _("unknown ptrace event %d"), event);
584 child_insert_fork_catchpoint (int pid)
586 if (! linux_supports_tracefork (pid))
587 error (_("Your system does not support fork catchpoints."));
591 child_insert_vfork_catchpoint (int pid)
593 if (!linux_supports_tracefork (pid))
594 error (_("Your system does not support vfork catchpoints."));
598 child_insert_exec_catchpoint (int pid)
600 if (!linux_supports_tracefork (pid))
601 error (_("Your system does not support exec catchpoints."));
604 /* On GNU/Linux there are no real LWP's. The closest thing to LWP's
605 are processes sharing the same VM space. A multi-threaded process
606 is basically a group of such processes. However, such a grouping
607 is almost entirely a user-space issue; the kernel doesn't enforce
608 such a grouping at all (this might change in the future). In
609 general, we'll rely on the threads library (i.e. the GNU/Linux
610 Threads library) to provide such a grouping.
612 It is perfectly well possible to write a multi-threaded application
613 without the assistance of a threads library, by using the clone
614 system call directly. This module should be able to give some
615 rudimentary support for debugging such applications if developers
616 specify the CLONE_PTRACE flag in the clone system call, and are
617 using the Linux kernel 2.4 or above.
619 Note that there are some peculiarities in GNU/Linux that affect
622 - In general one should specify the __WCLONE flag to waitpid in
623 order to make it report events for any of the cloned processes
624 (and leave it out for the initial process). However, if a cloned
625 process has exited the exit status is only reported if the
626 __WCLONE flag is absent. Linux kernel 2.4 has a __WALL flag, but
627 we cannot use it since GDB must work on older systems too.
629 - When a traced, cloned process exits and is waited for by the
630 debugger, the kernel reassigns it to the original parent and
631 keeps it around as a "zombie". Somehow, the GNU/Linux Threads
632 library doesn't notice this, which leads to the "zombie problem":
633 When debugged a multi-threaded process that spawns a lot of
634 threads will run out of processes, even if the threads exit,
635 because the "zombies" stay around. */
637 /* List of known LWPs. */
638 static struct lwp_info *lwp_list;
640 /* Number of LWPs in the list. */
644 #define GET_LWP(ptid) ptid_get_lwp (ptid)
645 #define GET_PID(ptid) ptid_get_pid (ptid)
646 #define is_lwp(ptid) (GET_LWP (ptid) != 0)
647 #define BUILD_LWP(lwp, pid) ptid_build (pid, lwp, 0)
649 /* If the last reported event was a SIGTRAP, this variable is set to
650 the process id of the LWP/thread that got it. */
654 /* Since we cannot wait (in linux_nat_wait) for the initial process and
655 any cloned processes with a single call to waitpid, we have to use
656 the WNOHANG flag and call waitpid in a loop. To optimize
657 things a bit we use `sigsuspend' to wake us up when a process has
658 something to report (it will send us a SIGCHLD if it has). To make
659 this work we have to juggle with the signal mask. We save the
660 original signal mask such that we can restore it before creating a
661 new process in order to avoid blocking certain signals in the
662 inferior. We then block SIGCHLD during the waitpid/sigsuspend
665 /* Original signal mask. */
666 static sigset_t normal_mask;
668 /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
669 _initialize_linux_nat. */
670 static sigset_t suspend_mask;
672 /* Signals to block to make that sigsuspend work. */
673 static sigset_t blocked_mask;
676 /* Prototypes for local functions. */
677 static int stop_wait_callback (struct lwp_info *lp, void *data);
678 static int linux_nat_thread_alive (ptid_t ptid);
680 /* Convert wait status STATUS to a string. Used for printing debug
684 status_to_str (int status)
688 if (WIFSTOPPED (status))
689 snprintf (buf, sizeof (buf), "%s (stopped)",
690 strsignal (WSTOPSIG (status)));
691 else if (WIFSIGNALED (status))
692 snprintf (buf, sizeof (buf), "%s (terminated)",
693 strsignal (WSTOPSIG (status)));
695 snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
700 /* Initialize the list of LWPs. Note that this module, contrary to
701 what GDB's generic threads layer does for its thread list,
702 re-initializes the LWP lists whenever we mourn or detach (which
703 doesn't involve mourning) the inferior. */
708 struct lwp_info *lp, *lpnext;
710 for (lp = lwp_list; lp; lp = lpnext)
720 /* Add the LWP specified by PID to the list. Return a pointer to the
721 structure describing the new LWP. */
723 static struct lwp_info *
724 add_lwp (ptid_t ptid)
728 gdb_assert (is_lwp (ptid));
730 lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
732 memset (lp, 0, sizeof (struct lwp_info));
734 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
745 /* Remove the LWP specified by PID from the list. */
748 delete_lwp (ptid_t ptid)
750 struct lwp_info *lp, *lpprev;
754 for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
755 if (ptid_equal (lp->ptid, ptid))
764 lpprev->next = lp->next;
771 /* Return a pointer to the structure describing the LWP corresponding
772 to PID. If no corresponding LWP could be found, return NULL. */
774 static struct lwp_info *
775 find_lwp_pid (ptid_t ptid)
781 lwp = GET_LWP (ptid);
783 lwp = GET_PID (ptid);
785 for (lp = lwp_list; lp; lp = lp->next)
786 if (lwp == GET_LWP (lp->ptid))
792 /* Call CALLBACK with its second argument set to DATA for every LWP in
793 the list. If CALLBACK returns 1 for a particular LWP, return a
794 pointer to the structure describing that LWP immediately.
795 Otherwise return NULL. */
798 iterate_over_lwps (int (*callback) (struct lwp_info *, void *), void *data)
800 struct lwp_info *lp, *lpnext;
802 for (lp = lwp_list; lp; lp = lpnext)
805 if ((*callback) (lp, data))
812 /* Update our internal state when changing from one fork (checkpoint,
813 et cetera) to another indicated by NEW_PTID. We can only switch
814 single-threaded applications, so we only create one new LWP, and
815 the previous list is discarded. */
818 linux_nat_switch_fork (ptid_t new_ptid)
823 lp = add_lwp (new_ptid);
827 /* Record a PTID for later deletion. */
832 struct saved_ptids *next;
834 static struct saved_ptids *threads_to_delete;
837 record_dead_thread (ptid_t ptid)
839 struct saved_ptids *p = xmalloc (sizeof (struct saved_ptids));
841 p->next = threads_to_delete;
842 threads_to_delete = p;
845 /* Delete any dead threads which are not the current thread. */
850 struct saved_ptids **p = &threads_to_delete;
853 if (! ptid_equal ((*p)->ptid, inferior_ptid))
855 struct saved_ptids *tmp = *p;
856 delete_thread (tmp->ptid);
864 /* Callback for iterate_over_threads that finds a thread corresponding
868 find_thread_from_lwp (struct thread_info *thr, void *dummy)
870 ptid_t *ptid_p = dummy;
872 if (GET_LWP (thr->ptid) && GET_LWP (thr->ptid) == GET_LWP (*ptid_p))
878 /* Handle the exit of a single thread LP. */
881 exit_lwp (struct lwp_info *lp)
883 if (in_thread_list (lp->ptid))
885 /* Core GDB cannot deal with us deleting the current thread. */
886 if (!ptid_equal (lp->ptid, inferior_ptid))
887 delete_thread (lp->ptid);
889 record_dead_thread (lp->ptid);
890 printf_unfiltered (_("[%s exited]\n"),
891 target_pid_to_str (lp->ptid));
895 /* Even if LP->PTID is not in the global GDB thread list, the
896 LWP may be - with an additional thread ID. We don't need
897 to print anything in this case; thread_db is in use and
898 already took care of that. But it didn't delete the thread
899 in order to handle zombies correctly. */
901 struct thread_info *thr;
903 thr = iterate_over_threads (find_thread_from_lwp, &lp->ptid);
906 if (!ptid_equal (thr->ptid, inferior_ptid))
907 delete_thread (thr->ptid);
909 record_dead_thread (thr->ptid);
913 delete_lwp (lp->ptid);
916 /* Attach to the LWP specified by PID. If VERBOSE is non-zero, print
917 a message telling the user that a new LWP has been added to the
921 lin_lwp_attach_lwp (ptid_t ptid, int verbose)
923 struct lwp_info *lp, *found_lp;
925 gdb_assert (is_lwp (ptid));
927 /* Make sure SIGCHLD is blocked. We don't want SIGCHLD events
928 to interrupt either the ptrace() or waitpid() calls below. */
929 if (!sigismember (&blocked_mask, SIGCHLD))
931 sigaddset (&blocked_mask, SIGCHLD);
932 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
936 printf_filtered (_("[New %s]\n"), target_pid_to_str (ptid));
938 found_lp = lp = find_lwp_pid (ptid);
942 /* We assume that we're already attached to any LWP that has an id
943 equal to the overall process id, and to any LWP that is already
944 in our list of LWPs. If we're not seeing exit events from threads
945 and we've had PID wraparound since we last tried to stop all threads,
946 this assumption might be wrong; fortunately, this is very unlikely
948 if (GET_LWP (ptid) != GET_PID (ptid) && found_lp == NULL)
953 if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
954 error (_("Can't attach %s: %s"), target_pid_to_str (ptid),
955 safe_strerror (errno));
958 fprintf_unfiltered (gdb_stdlog,
959 "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
960 target_pid_to_str (ptid));
962 pid = my_waitpid (GET_LWP (ptid), &status, 0);
963 if (pid == -1 && errno == ECHILD)
965 /* Try again with __WCLONE to check cloned processes. */
966 pid = my_waitpid (GET_LWP (ptid), &status, __WCLONE);
970 gdb_assert (pid == GET_LWP (ptid)
971 && WIFSTOPPED (status) && WSTOPSIG (status));
973 target_post_attach (pid);
979 fprintf_unfiltered (gdb_stdlog,
980 "LLAL: waitpid %s received %s\n",
981 target_pid_to_str (ptid),
982 status_to_str (status));
987 /* We assume that the LWP representing the original process is
988 already stopped. Mark it as stopped in the data structure
989 that the linux ptrace layer uses to keep track of threads.
990 Note that this won't have already been done since the main
991 thread will have, we assume, been stopped by an attach from a
998 linux_nat_attach (char *args, int from_tty)
1000 struct lwp_info *lp;
1004 /* FIXME: We should probably accept a list of process id's, and
1005 attach all of them. */
1006 linux_ops->to_attach (args, from_tty);
1008 /* Add the initial process as the first LWP to the list. */
1009 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid));
1010 lp = add_lwp (inferior_ptid);
1012 /* Make sure the initial process is stopped. The user-level threads
1013 layer might want to poke around in the inferior, and that won't
1014 work if things haven't stabilized yet. */
1015 pid = my_waitpid (GET_PID (inferior_ptid), &status, 0);
1016 if (pid == -1 && errno == ECHILD)
1018 warning (_("%s is a cloned process"), target_pid_to_str (inferior_ptid));
1020 /* Try again with __WCLONE to check cloned processes. */
1021 pid = my_waitpid (GET_PID (inferior_ptid), &status, __WCLONE);
1025 gdb_assert (pid == GET_PID (inferior_ptid)
1026 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP);
1030 /* Fake the SIGSTOP that core GDB expects. */
1031 lp->status = W_STOPCODE (SIGSTOP);
1033 if (debug_linux_nat)
1035 fprintf_unfiltered (gdb_stdlog,
1036 "LLA: waitpid %ld, faking SIGSTOP\n", (long) pid);
1041 detach_callback (struct lwp_info *lp, void *data)
1043 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1045 if (debug_linux_nat && lp->status)
1046 fprintf_unfiltered (gdb_stdlog, "DC: Pending %s for %s on detach.\n",
1047 strsignal (WSTOPSIG (lp->status)),
1048 target_pid_to_str (lp->ptid));
1050 while (lp->signalled && lp->stopped)
1053 if (ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0,
1054 WSTOPSIG (lp->status)) < 0)
1055 error (_("Can't continue %s: %s"), target_pid_to_str (lp->ptid),
1056 safe_strerror (errno));
1058 if (debug_linux_nat)
1059 fprintf_unfiltered (gdb_stdlog,
1060 "DC: PTRACE_CONTINUE (%s, 0, %s) (OK)\n",
1061 target_pid_to_str (lp->ptid),
1062 status_to_str (lp->status));
1067 /* FIXME drow/2003-08-26: There was a call to stop_wait_callback
1068 here. But since lp->signalled was cleared above,
1069 stop_wait_callback didn't do anything; the process was left
1070 running. Shouldn't we be waiting for it to stop?
1071 I've removed the call, since stop_wait_callback now does do
1072 something when called with lp->signalled == 0. */
1074 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1077 /* We don't actually detach from the LWP that has an id equal to the
1078 overall process id just yet. */
1079 if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
1082 if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
1083 WSTOPSIG (lp->status)) < 0)
1084 error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
1085 safe_strerror (errno));
1087 if (debug_linux_nat)
1088 fprintf_unfiltered (gdb_stdlog,
1089 "PTRACE_DETACH (%s, %s, 0) (OK)\n",
1090 target_pid_to_str (lp->ptid),
1091 strsignal (WSTOPSIG (lp->status)));
1093 delete_lwp (lp->ptid);
1100 linux_nat_detach (char *args, int from_tty)
1102 iterate_over_lwps (detach_callback, NULL);
1104 /* Only the initial process should be left right now. */
1105 gdb_assert (num_lwps == 1);
1107 trap_ptid = null_ptid;
1109 /* Destroy LWP info; it's no longer valid. */
1112 /* Restore the original signal mask. */
1113 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1114 sigemptyset (&blocked_mask);
1116 inferior_ptid = pid_to_ptid (GET_PID (inferior_ptid));
1117 linux_ops->to_detach (args, from_tty);
1123 resume_callback (struct lwp_info *lp, void *data)
1125 if (lp->stopped && lp->status == 0)
1127 struct thread_info *tp;
1129 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
1130 0, TARGET_SIGNAL_0);
1131 if (debug_linux_nat)
1132 fprintf_unfiltered (gdb_stdlog,
1133 "RC: PTRACE_CONT %s, 0, 0 (resume sibling)\n",
1134 target_pid_to_str (lp->ptid));
1143 resume_clear_callback (struct lwp_info *lp, void *data)
1150 resume_set_callback (struct lwp_info *lp, void *data)
1157 linux_nat_resume (ptid_t ptid, int step, enum target_signal signo)
1159 struct lwp_info *lp;
1162 if (debug_linux_nat)
1163 fprintf_unfiltered (gdb_stdlog,
1164 "LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
1165 step ? "step" : "resume",
1166 target_pid_to_str (ptid),
1167 signo ? strsignal (signo) : "0",
1168 target_pid_to_str (inferior_ptid));
1172 /* A specific PTID means `step only this process id'. */
1173 resume_all = (PIDGET (ptid) == -1);
1176 iterate_over_lwps (resume_set_callback, NULL);
1178 iterate_over_lwps (resume_clear_callback, NULL);
1180 /* If PID is -1, it's the current inferior that should be
1181 handled specially. */
1182 if (PIDGET (ptid) == -1)
1183 ptid = inferior_ptid;
1185 lp = find_lwp_pid (ptid);
1188 ptid = pid_to_ptid (GET_LWP (lp->ptid));
1190 /* Remember if we're stepping. */
1193 /* Mark this LWP as resumed. */
1196 /* If we have a pending wait status for this thread, there is no
1197 point in resuming the process. But first make sure that
1198 linux_nat_wait won't preemptively handle the event - we
1199 should never take this short-circuit if we are going to
1200 leave LP running, since we have skipped resuming all the
1201 other threads. This bit of code needs to be synchronized
1202 with linux_nat_wait. */
1204 if (lp->status && WIFSTOPPED (lp->status))
1206 int saved_signo = target_signal_from_host (WSTOPSIG (lp->status));
1208 if (signal_stop_state (saved_signo) == 0
1209 && signal_print_state (saved_signo) == 0
1210 && signal_pass_state (saved_signo) == 1)
1212 if (debug_linux_nat)
1213 fprintf_unfiltered (gdb_stdlog,
1214 "LLR: Not short circuiting for ignored "
1215 "status 0x%x\n", lp->status);
1217 /* FIXME: What should we do if we are supposed to continue
1218 this thread with a signal? */
1219 gdb_assert (signo == TARGET_SIGNAL_0);
1220 signo = saved_signo;
1227 /* FIXME: What should we do if we are supposed to continue
1228 this thread with a signal? */
1229 gdb_assert (signo == TARGET_SIGNAL_0);
1231 if (debug_linux_nat)
1232 fprintf_unfiltered (gdb_stdlog,
1233 "LLR: Short circuiting for status 0x%x\n",
1239 /* Mark LWP as not stopped to prevent it from being continued by
1245 iterate_over_lwps (resume_callback, NULL);
1247 linux_ops->to_resume (ptid, step, signo);
1248 if (debug_linux_nat)
1249 fprintf_unfiltered (gdb_stdlog,
1250 "LLR: %s %s, %s (resume event thread)\n",
1251 step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1252 target_pid_to_str (ptid),
1253 signo ? strsignal (signo) : "0");
1256 /* Issue kill to specified lwp. */
1258 static int tkill_failed;
1261 kill_lwp (int lwpid, int signo)
1265 /* Use tkill, if possible, in case we are using nptl threads. If tkill
1266 fails, then we are not using nptl threads and we should be using kill. */
1268 #ifdef HAVE_TKILL_SYSCALL
1271 int ret = syscall (__NR_tkill, lwpid, signo);
1272 if (errno != ENOSYS)
1279 return kill (lwpid, signo);
1282 /* Handle a GNU/Linux extended wait response. Most of the work we
1283 just pass off to linux_handle_extended_wait, but if it reports a
1284 clone event we need to add the new LWP to our list (and not report
1285 the trap to higher layers). This function returns non-zero if
1286 the event should be ignored and we should wait again. If STOPPING
1287 is true, the new LWP remains stopped, otherwise it is continued. */
1290 linux_nat_handle_extended (struct lwp_info *lp, int status, int stopping)
1292 linux_handle_extended_wait (GET_LWP (lp->ptid), status,
1295 /* TARGET_WAITKIND_SPURIOUS is used to indicate clone events. */
1296 if (lp->waitstatus.kind == TARGET_WAITKIND_SPURIOUS)
1298 struct lwp_info *new_lp;
1299 new_lp = add_lwp (BUILD_LWP (lp->waitstatus.value.related_pid,
1300 GET_PID (inferior_ptid)));
1304 new_lp->stopped = 1;
1306 ptrace (PTRACE_CONT, lp->waitstatus.value.related_pid, 0, 0);
1308 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
1310 if (debug_linux_nat)
1311 fprintf_unfiltered (gdb_stdlog,
1312 "LLHE: Got clone event from LWP %ld, resuming\n",
1313 GET_LWP (lp->ptid));
1314 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1322 /* Wait for LP to stop. Returns the wait status, or 0 if the LWP has
1326 wait_lwp (struct lwp_info *lp)
1330 int thread_dead = 0;
1332 gdb_assert (!lp->stopped);
1333 gdb_assert (lp->status == 0);
1335 pid = my_waitpid (GET_LWP (lp->ptid), &status, 0);
1336 if (pid == -1 && errno == ECHILD)
1338 pid = my_waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
1339 if (pid == -1 && errno == ECHILD)
1341 /* The thread has previously exited. We need to delete it
1342 now because, for some vendor 2.4 kernels with NPTL
1343 support backported, there won't be an exit event unless
1344 it is the main thread. 2.6 kernels will report an exit
1345 event for each thread that exits, as expected. */
1347 if (debug_linux_nat)
1348 fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
1349 target_pid_to_str (lp->ptid));
1355 gdb_assert (pid == GET_LWP (lp->ptid));
1357 if (debug_linux_nat)
1359 fprintf_unfiltered (gdb_stdlog,
1360 "WL: waitpid %s received %s\n",
1361 target_pid_to_str (lp->ptid),
1362 status_to_str (status));
1366 /* Check if the thread has exited. */
1367 if (WIFEXITED (status) || WIFSIGNALED (status))
1370 if (debug_linux_nat)
1371 fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
1372 target_pid_to_str (lp->ptid));
1381 gdb_assert (WIFSTOPPED (status));
1383 /* Handle GNU/Linux's extended waitstatus for trace events. */
1384 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1386 if (debug_linux_nat)
1387 fprintf_unfiltered (gdb_stdlog,
1388 "WL: Handling extended status 0x%06x\n",
1390 if (linux_nat_handle_extended (lp, status, 1))
1391 return wait_lwp (lp);
1397 /* Send a SIGSTOP to LP. */
1400 stop_callback (struct lwp_info *lp, void *data)
1402 if (!lp->stopped && !lp->signalled)
1406 if (debug_linux_nat)
1408 fprintf_unfiltered (gdb_stdlog,
1409 "SC: kill %s **<SIGSTOP>**\n",
1410 target_pid_to_str (lp->ptid));
1413 ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
1414 if (debug_linux_nat)
1416 fprintf_unfiltered (gdb_stdlog,
1417 "SC: lwp kill %d %s\n",
1419 errno ? safe_strerror (errno) : "ERRNO-OK");
1423 gdb_assert (lp->status == 0);
1429 /* Wait until LP is stopped. If DATA is non-null it is interpreted as
1430 a pointer to a set of signals to be flushed immediately. */
1433 stop_wait_callback (struct lwp_info *lp, void *data)
1435 sigset_t *flush_mask = data;
1441 status = wait_lwp (lp);
1445 /* Ignore any signals in FLUSH_MASK. */
1446 if (flush_mask && sigismember (flush_mask, WSTOPSIG (status)))
1455 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1456 if (debug_linux_nat)
1457 fprintf_unfiltered (gdb_stdlog,
1458 "PTRACE_CONT %s, 0, 0 (%s)\n",
1459 target_pid_to_str (lp->ptid),
1460 errno ? safe_strerror (errno) : "OK");
1462 return stop_wait_callback (lp, flush_mask);
1465 if (WSTOPSIG (status) != SIGSTOP)
1467 if (WSTOPSIG (status) == SIGTRAP)
1469 /* If a LWP other than the LWP that we're reporting an
1470 event for has hit a GDB breakpoint (as opposed to
1471 some random trap signal), then just arrange for it to
1472 hit it again later. We don't keep the SIGTRAP status
1473 and don't forward the SIGTRAP signal to the LWP. We
1474 will handle the current event, eventually we will
1475 resume all LWPs, and this one will get its breakpoint
1478 If we do not do this, then we run the risk that the
1479 user will delete or disable the breakpoint, but the
1480 thread will have already tripped on it. */
1482 /* Now resume this LWP and get the SIGSTOP event. */
1484 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1485 if (debug_linux_nat)
1487 fprintf_unfiltered (gdb_stdlog,
1488 "PTRACE_CONT %s, 0, 0 (%s)\n",
1489 target_pid_to_str (lp->ptid),
1490 errno ? safe_strerror (errno) : "OK");
1492 fprintf_unfiltered (gdb_stdlog,
1493 "SWC: Candidate SIGTRAP event in %s\n",
1494 target_pid_to_str (lp->ptid));
1496 /* Hold the SIGTRAP for handling by linux_nat_wait. */
1497 stop_wait_callback (lp, data);
1498 /* If there's another event, throw it back into the queue. */
1501 if (debug_linux_nat)
1503 fprintf_unfiltered (gdb_stdlog,
1504 "SWC: kill %s, %s\n",
1505 target_pid_to_str (lp->ptid),
1506 status_to_str ((int) status));
1508 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
1510 /* Save the sigtrap event. */
1511 lp->status = status;
1516 /* The thread was stopped with a signal other than
1517 SIGSTOP, and didn't accidentally trip a breakpoint. */
1519 if (debug_linux_nat)
1521 fprintf_unfiltered (gdb_stdlog,
1522 "SWC: Pending event %s in %s\n",
1523 status_to_str ((int) status),
1524 target_pid_to_str (lp->ptid));
1526 /* Now resume this LWP and get the SIGSTOP event. */
1528 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1529 if (debug_linux_nat)
1530 fprintf_unfiltered (gdb_stdlog,
1531 "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
1532 target_pid_to_str (lp->ptid),
1533 errno ? safe_strerror (errno) : "OK");
1535 /* Hold this event/waitstatus while we check to see if
1536 there are any more (we still want to get that SIGSTOP). */
1537 stop_wait_callback (lp, data);
1538 /* If the lp->status field is still empty, use it to hold
1539 this event. If not, then this event must be returned
1540 to the event queue of the LWP. */
1541 if (lp->status == 0)
1542 lp->status = status;
1545 if (debug_linux_nat)
1547 fprintf_unfiltered (gdb_stdlog,
1548 "SWC: kill %s, %s\n",
1549 target_pid_to_str (lp->ptid),
1550 status_to_str ((int) status));
1552 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
1559 /* We caught the SIGSTOP that we intended to catch, so
1560 there's no SIGSTOP pending. */
1569 /* Check whether PID has any pending signals in FLUSH_MASK. If so set
1570 the appropriate bits in PENDING, and return 1 - otherwise return 0. */
1573 linux_nat_has_pending (int pid, sigset_t *pending, sigset_t *flush_mask)
1575 sigset_t blocked, ignored;
1578 linux_proc_pending_signals (pid, pending, &blocked, &ignored);
1583 for (i = 1; i < NSIG; i++)
1584 if (sigismember (pending, i))
1585 if (!sigismember (flush_mask, i)
1586 || sigismember (&blocked, i)
1587 || sigismember (&ignored, i))
1588 sigdelset (pending, i);
1590 if (sigisemptyset (pending))
1596 /* DATA is interpreted as a mask of signals to flush. If LP has
1597 signals pending, and they are all in the flush mask, then arrange
1598 to flush them. LP should be stopped, as should all other threads
1599 it might share a signal queue with. */
1602 flush_callback (struct lwp_info *lp, void *data)
1604 sigset_t *flush_mask = data;
1605 sigset_t pending, intersection, blocked, ignored;
1608 /* Normally, when an LWP exits, it is removed from the LWP list. The
1609 last LWP isn't removed till later, however. So if there is only
1610 one LWP on the list, make sure it's alive. */
1611 if (lwp_list == lp && lp->next == NULL)
1612 if (!linux_nat_thread_alive (lp->ptid))
1615 /* Just because the LWP is stopped doesn't mean that new signals
1616 can't arrive from outside, so this function must be careful of
1617 race conditions. However, because all threads are stopped, we
1618 can assume that the pending mask will not shrink unless we resume
1619 the LWP, and that it will then get another signal. We can't
1620 control which one, however. */
1624 if (debug_linux_nat)
1625 printf_unfiltered (_("FC: LP has pending status %06x\n"), lp->status);
1626 if (WIFSTOPPED (lp->status) && sigismember (flush_mask, WSTOPSIG (lp->status)))
1630 while (linux_nat_has_pending (GET_LWP (lp->ptid), &pending, flush_mask))
1635 ret = ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1636 if (debug_linux_nat)
1637 fprintf_unfiltered (gdb_stderr,
1638 "FC: Sent PTRACE_CONT, ret %d %d\n", ret, errno);
1641 stop_wait_callback (lp, flush_mask);
1642 if (debug_linux_nat)
1643 fprintf_unfiltered (gdb_stderr,
1644 "FC: Wait finished; saved status is %d\n",
1651 /* Return non-zero if LP has a wait status pending. */
1654 status_callback (struct lwp_info *lp, void *data)
1656 /* Only report a pending wait status if we pretend that this has
1657 indeed been resumed. */
1658 return (lp->status != 0 && lp->resumed);
1661 /* Return non-zero if LP isn't stopped. */
1664 running_callback (struct lwp_info *lp, void *data)
1666 return (lp->stopped == 0 || (lp->status != 0 && lp->resumed));
1669 /* Count the LWP's that have had events. */
1672 count_events_callback (struct lwp_info *lp, void *data)
1676 gdb_assert (count != NULL);
1678 /* Count only LWPs that have a SIGTRAP event pending. */
1680 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
1686 /* Select the LWP (if any) that is currently being single-stepped. */
1689 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
1691 if (lp->step && lp->status != 0)
1697 /* Select the Nth LWP that has had a SIGTRAP event. */
1700 select_event_lwp_callback (struct lwp_info *lp, void *data)
1702 int *selector = data;
1704 gdb_assert (selector != NULL);
1706 /* Select only LWPs that have a SIGTRAP event pending. */
1708 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
1709 if ((*selector)-- == 0)
1716 cancel_breakpoints_callback (struct lwp_info *lp, void *data)
1718 struct lwp_info *event_lp = data;
1720 /* Leave the LWP that has been elected to receive a SIGTRAP alone. */
1724 /* If a LWP other than the LWP that we're reporting an event for has
1725 hit a GDB breakpoint (as opposed to some random trap signal),
1726 then just arrange for it to hit it again later. We don't keep
1727 the SIGTRAP status and don't forward the SIGTRAP signal to the
1728 LWP. We will handle the current event, eventually we will resume
1729 all LWPs, and this one will get its breakpoint trap again.
1731 If we do not do this, then we run the risk that the user will
1732 delete or disable the breakpoint, but the LWP will have already
1736 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
1737 && breakpoint_inserted_here_p (read_pc_pid (lp->ptid) -
1738 DECR_PC_AFTER_BREAK))
1740 if (debug_linux_nat)
1741 fprintf_unfiltered (gdb_stdlog,
1742 "CBC: Push back breakpoint for %s\n",
1743 target_pid_to_str (lp->ptid));
1745 /* Back up the PC if necessary. */
1746 if (DECR_PC_AFTER_BREAK)
1747 write_pc_pid (read_pc_pid (lp->ptid) - DECR_PC_AFTER_BREAK, lp->ptid);
1749 /* Throw away the SIGTRAP. */
1756 /* Select one LWP out of those that have events pending. */
1759 select_event_lwp (struct lwp_info **orig_lp, int *status)
1762 int random_selector;
1763 struct lwp_info *event_lp;
1765 /* Record the wait status for the original LWP. */
1766 (*orig_lp)->status = *status;
1768 /* Give preference to any LWP that is being single-stepped. */
1769 event_lp = iterate_over_lwps (select_singlestep_lwp_callback, NULL);
1770 if (event_lp != NULL)
1772 if (debug_linux_nat)
1773 fprintf_unfiltered (gdb_stdlog,
1774 "SEL: Select single-step %s\n",
1775 target_pid_to_str (event_lp->ptid));
1779 /* No single-stepping LWP. Select one at random, out of those
1780 which have had SIGTRAP events. */
1782 /* First see how many SIGTRAP events we have. */
1783 iterate_over_lwps (count_events_callback, &num_events);
1785 /* Now randomly pick a LWP out of those that have had a SIGTRAP. */
1786 random_selector = (int)
1787 ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
1789 if (debug_linux_nat && num_events > 1)
1790 fprintf_unfiltered (gdb_stdlog,
1791 "SEL: Found %d SIGTRAP events, selecting #%d\n",
1792 num_events, random_selector);
1794 event_lp = iterate_over_lwps (select_event_lwp_callback,
1798 if (event_lp != NULL)
1800 /* Switch the event LWP. */
1801 *orig_lp = event_lp;
1802 *status = event_lp->status;
1805 /* Flush the wait status for the event LWP. */
1806 (*orig_lp)->status = 0;
1809 /* Return non-zero if LP has been resumed. */
1812 resumed_callback (struct lwp_info *lp, void *data)
1817 /* Stop an active thread, verify it still exists, then resume it. */
1820 stop_and_resume_callback (struct lwp_info *lp, void *data)
1822 struct lwp_info *ptr;
1824 if (!lp->stopped && !lp->signalled)
1826 stop_callback (lp, NULL);
1827 stop_wait_callback (lp, NULL);
1828 /* Resume if the lwp still exists. */
1829 for (ptr = lwp_list; ptr; ptr = ptr->next)
1832 resume_callback (lp, NULL);
1833 resume_set_callback (lp, NULL);
1840 linux_nat_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
1842 struct lwp_info *lp = NULL;
1845 pid_t pid = PIDGET (ptid);
1846 sigset_t flush_mask;
1848 /* The first time we get here after starting a new inferior, we may
1849 not have added it to the LWP list yet - this is the earliest
1850 moment at which we know its PID. */
1853 gdb_assert (!is_lwp (inferior_ptid));
1855 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
1856 GET_PID (inferior_ptid));
1857 lp = add_lwp (inferior_ptid);
1861 sigemptyset (&flush_mask);
1863 /* Make sure SIGCHLD is blocked. */
1864 if (!sigismember (&blocked_mask, SIGCHLD))
1866 sigaddset (&blocked_mask, SIGCHLD);
1867 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
1872 /* Make sure there is at least one LWP that has been resumed. */
1873 gdb_assert (iterate_over_lwps (resumed_callback, NULL));
1875 /* First check if there is a LWP with a wait status pending. */
1878 /* Any LWP that's been resumed will do. */
1879 lp = iterate_over_lwps (status_callback, NULL);
1882 status = lp->status;
1885 if (debug_linux_nat && status)
1886 fprintf_unfiltered (gdb_stdlog,
1887 "LLW: Using pending wait status %s for %s.\n",
1888 status_to_str (status),
1889 target_pid_to_str (lp->ptid));
1892 /* But if we don't fine one, we'll have to wait, and check both
1893 cloned and uncloned processes. We start with the cloned
1895 options = __WCLONE | WNOHANG;
1897 else if (is_lwp (ptid))
1899 if (debug_linux_nat)
1900 fprintf_unfiltered (gdb_stdlog,
1901 "LLW: Waiting for specific LWP %s.\n",
1902 target_pid_to_str (ptid));
1904 /* We have a specific LWP to check. */
1905 lp = find_lwp_pid (ptid);
1907 status = lp->status;
1910 if (debug_linux_nat && status)
1911 fprintf_unfiltered (gdb_stdlog,
1912 "LLW: Using pending wait status %s for %s.\n",
1913 status_to_str (status),
1914 target_pid_to_str (lp->ptid));
1916 /* If we have to wait, take into account whether PID is a cloned
1917 process or not. And we have to convert it to something that
1918 the layer beneath us can understand. */
1919 options = lp->cloned ? __WCLONE : 0;
1920 pid = GET_LWP (ptid);
1923 if (status && lp->signalled)
1925 /* A pending SIGSTOP may interfere with the normal stream of
1926 events. In a typical case where interference is a problem,
1927 we have a SIGSTOP signal pending for LWP A while
1928 single-stepping it, encounter an event in LWP B, and take the
1929 pending SIGSTOP while trying to stop LWP A. After processing
1930 the event in LWP B, LWP A is continued, and we'll never see
1931 the SIGTRAP associated with the last time we were
1932 single-stepping LWP A. */
1934 /* Resume the thread. It should halt immediately returning the
1936 registers_changed ();
1937 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
1938 lp->step, TARGET_SIGNAL_0);
1939 if (debug_linux_nat)
1940 fprintf_unfiltered (gdb_stdlog,
1941 "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
1942 lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1943 target_pid_to_str (lp->ptid));
1945 gdb_assert (lp->resumed);
1947 /* This should catch the pending SIGSTOP. */
1948 stop_wait_callback (lp, NULL);
1951 set_sigint_trap (); /* Causes SIGINT to be passed on to the
1952 attached process. */
1959 lwpid = my_waitpid (pid, &status, options);
1962 gdb_assert (pid == -1 || lwpid == pid);
1964 if (debug_linux_nat)
1966 fprintf_unfiltered (gdb_stdlog,
1967 "LLW: waitpid %ld received %s\n",
1968 (long) lwpid, status_to_str (status));
1971 lp = find_lwp_pid (pid_to_ptid (lwpid));
1973 /* Check for stop events reported by a process we didn't
1974 already know about - anything not already in our LWP
1977 If we're expecting to receive stopped processes after
1978 fork, vfork, and clone events, then we'll just add the
1979 new one to our list and go back to waiting for the event
1980 to be reported - the stopped process might be returned
1981 from waitpid before or after the event is. */
1982 if (WIFSTOPPED (status) && !lp)
1984 linux_record_stopped_pid (lwpid);
1989 /* Make sure we don't report an event for the exit of an LWP not in
1990 our list, i.e. not part of the current process. This can happen
1991 if we detach from a program we original forked and then it
1993 if (!WIFSTOPPED (status) && !lp)
1999 /* NOTE drow/2003-06-17: This code seems to be meant for debugging
2000 CLONE_PTRACE processes which do not use the thread library -
2001 otherwise we wouldn't find the new LWP this way. That doesn't
2002 currently work, and the following code is currently unreachable
2003 due to the two blocks above. If it's fixed some day, this code
2004 should be broken out into a function so that we can also pick up
2005 LWPs from the new interface. */
2008 lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
2009 if (options & __WCLONE)
2012 gdb_assert (WIFSTOPPED (status)
2013 && WSTOPSIG (status) == SIGSTOP);
2016 if (!in_thread_list (inferior_ptid))
2018 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
2019 GET_PID (inferior_ptid));
2020 add_thread (inferior_ptid);
2023 add_thread (lp->ptid);
2024 printf_unfiltered (_("[New %s]\n"),
2025 target_pid_to_str (lp->ptid));
2028 /* Handle GNU/Linux's extended waitstatus for trace events. */
2029 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2031 if (debug_linux_nat)
2032 fprintf_unfiltered (gdb_stdlog,
2033 "LLW: Handling extended status 0x%06x\n",
2035 if (linux_nat_handle_extended (lp, status, 0))
2042 /* Check if the thread has exited. */
2043 if ((WIFEXITED (status) || WIFSIGNALED (status)) && num_lwps > 1)
2045 /* If this is the main thread, we must stop all threads and
2046 verify if they are still alive. This is because in the nptl
2047 thread model, there is no signal issued for exiting LWPs
2048 other than the main thread. We only get the main thread
2049 exit signal once all child threads have already exited.
2050 If we stop all the threads and use the stop_wait_callback
2051 to check if they have exited we can determine whether this
2052 signal should be ignored or whether it means the end of the
2053 debugged application, regardless of which threading model
2055 if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
2058 iterate_over_lwps (stop_and_resume_callback, NULL);
2061 if (debug_linux_nat)
2062 fprintf_unfiltered (gdb_stdlog,
2063 "LLW: %s exited.\n",
2064 target_pid_to_str (lp->ptid));
2068 /* If there is at least one more LWP, then the exit signal
2069 was not the end of the debugged application and should be
2073 /* Make sure there is at least one thread running. */
2074 gdb_assert (iterate_over_lwps (running_callback, NULL));
2076 /* Discard the event. */
2082 /* Check if the current LWP has previously exited. In the nptl
2083 thread model, LWPs other than the main thread do not issue
2084 signals when they exit so we must check whenever the thread
2085 has stopped. A similar check is made in stop_wait_callback(). */
2086 if (num_lwps > 1 && !linux_nat_thread_alive (lp->ptid))
2088 if (debug_linux_nat)
2089 fprintf_unfiltered (gdb_stdlog,
2090 "LLW: %s exited.\n",
2091 target_pid_to_str (lp->ptid));
2095 /* Make sure there is at least one thread running. */
2096 gdb_assert (iterate_over_lwps (running_callback, NULL));
2098 /* Discard the event. */
2103 /* Make sure we don't report a SIGSTOP that we sent
2104 ourselves in an attempt to stop an LWP. */
2106 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2108 if (debug_linux_nat)
2109 fprintf_unfiltered (gdb_stdlog,
2110 "LLW: Delayed SIGSTOP caught for %s.\n",
2111 target_pid_to_str (lp->ptid));
2113 /* This is a delayed SIGSTOP. */
2116 registers_changed ();
2117 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2118 lp->step, TARGET_SIGNAL_0);
2119 if (debug_linux_nat)
2120 fprintf_unfiltered (gdb_stdlog,
2121 "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
2123 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2124 target_pid_to_str (lp->ptid));
2127 gdb_assert (lp->resumed);
2129 /* Discard the event. */
2139 /* Alternate between checking cloned and uncloned processes. */
2140 options ^= __WCLONE;
2142 /* And suspend every time we have checked both. */
2143 if (options & __WCLONE)
2144 sigsuspend (&suspend_mask);
2147 /* We shouldn't end up here unless we want to try again. */
2148 gdb_assert (status == 0);
2151 clear_sigio_trap ();
2152 clear_sigint_trap ();
2156 /* Don't report signals that GDB isn't interested in, such as
2157 signals that are neither printed nor stopped upon. Stopping all
2158 threads can be a bit time-consuming so if we want decent
2159 performance with heavily multi-threaded programs, especially when
2160 they're using a high frequency timer, we'd better avoid it if we
2163 if (WIFSTOPPED (status))
2165 int signo = target_signal_from_host (WSTOPSIG (status));
2167 /* If we get a signal while single-stepping, we may need special
2168 care, e.g. to skip the signal handler. Defer to common code. */
2170 && signal_stop_state (signo) == 0
2171 && signal_print_state (signo) == 0
2172 && signal_pass_state (signo) == 1)
2174 /* FIMXE: kettenis/2001-06-06: Should we resume all threads
2175 here? It is not clear we should. GDB may not expect
2176 other threads to run. On the other hand, not resuming
2177 newly attached threads may cause an unwanted delay in
2178 getting them running. */
2179 registers_changed ();
2180 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2182 if (debug_linux_nat)
2183 fprintf_unfiltered (gdb_stdlog,
2184 "LLW: %s %s, %s (preempt 'handle')\n",
2186 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2187 target_pid_to_str (lp->ptid),
2188 signo ? strsignal (signo) : "0");
2194 if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
2196 /* If ^C/BREAK is typed at the tty/console, SIGINT gets
2197 forwarded to the entire process group, that is, all LWP's
2198 will receive it. Since we only want to report it once,
2199 we try to flush it from all LWPs except this one. */
2200 sigaddset (&flush_mask, SIGINT);
2204 /* This LWP is stopped now. */
2207 if (debug_linux_nat)
2208 fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
2209 status_to_str (status), target_pid_to_str (lp->ptid));
2211 /* Now stop all other LWP's ... */
2212 iterate_over_lwps (stop_callback, NULL);
2214 /* ... and wait until all of them have reported back that they're no
2216 iterate_over_lwps (stop_wait_callback, &flush_mask);
2217 iterate_over_lwps (flush_callback, &flush_mask);
2219 /* If we're not waiting for a specific LWP, choose an event LWP from
2220 among those that have had events. Giving equal priority to all
2221 LWPs that have had events helps prevent starvation. */
2223 select_event_lwp (&lp, &status);
2225 /* Now that we've selected our final event LWP, cancel any
2226 breakpoints in other LWPs that have hit a GDB breakpoint. See
2227 the comment in cancel_breakpoints_callback to find out why. */
2228 iterate_over_lwps (cancel_breakpoints_callback, lp);
2230 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2232 trap_ptid = lp->ptid;
2233 if (debug_linux_nat)
2234 fprintf_unfiltered (gdb_stdlog,
2235 "LLW: trap_ptid is %s.\n",
2236 target_pid_to_str (trap_ptid));
2239 trap_ptid = null_ptid;
2241 if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
2243 *ourstatus = lp->waitstatus;
2244 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
2247 store_waitstatus (ourstatus, status);
2253 kill_callback (struct lwp_info *lp, void *data)
2256 ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
2257 if (debug_linux_nat)
2258 fprintf_unfiltered (gdb_stdlog,
2259 "KC: PTRACE_KILL %s, 0, 0 (%s)\n",
2260 target_pid_to_str (lp->ptid),
2261 errno ? safe_strerror (errno) : "OK");
2267 kill_wait_callback (struct lwp_info *lp, void *data)
2271 /* We must make sure that there are no pending events (delayed
2272 SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
2273 program doesn't interfere with any following debugging session. */
2275 /* For cloned processes we must check both with __WCLONE and
2276 without, since the exit status of a cloned process isn't reported
2282 pid = my_waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
2283 if (pid != (pid_t) -1 && debug_linux_nat)
2285 fprintf_unfiltered (gdb_stdlog,
2286 "KWC: wait %s received unknown.\n",
2287 target_pid_to_str (lp->ptid));
2290 while (pid == GET_LWP (lp->ptid));
2292 gdb_assert (pid == -1 && errno == ECHILD);
2297 pid = my_waitpid (GET_LWP (lp->ptid), NULL, 0);
2298 if (pid != (pid_t) -1 && debug_linux_nat)
2300 fprintf_unfiltered (gdb_stdlog,
2301 "KWC: wait %s received unk.\n",
2302 target_pid_to_str (lp->ptid));
2305 while (pid == GET_LWP (lp->ptid));
2307 gdb_assert (pid == -1 && errno == ECHILD);
2312 linux_nat_kill (void)
2314 struct target_waitstatus last;
2318 /* If we're stopped while forking and we haven't followed yet,
2319 kill the other task. We need to do this first because the
2320 parent will be sleeping if this is a vfork. */
2322 get_last_target_status (&last_ptid, &last);
2324 if (last.kind == TARGET_WAITKIND_FORKED
2325 || last.kind == TARGET_WAITKIND_VFORKED)
2327 ptrace (PT_KILL, last.value.related_pid, 0, 0);
2331 if (forks_exist_p ())
2332 linux_fork_killall ();
2335 /* Kill all LWP's ... */
2336 iterate_over_lwps (kill_callback, NULL);
2338 /* ... and wait until we've flushed all events. */
2339 iterate_over_lwps (kill_wait_callback, NULL);
2342 target_mourn_inferior ();
2346 linux_nat_mourn_inferior (void)
2348 trap_ptid = null_ptid;
2350 /* Destroy LWP info; it's no longer valid. */
2353 /* Restore the original signal mask. */
2354 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
2355 sigemptyset (&blocked_mask);
2357 if (! forks_exist_p ())
2358 /* Normal case, no other forks available. */
2359 linux_ops->to_mourn_inferior ();
2361 /* Multi-fork case. The current inferior_ptid has exited, but
2362 there are other viable forks to debug. Delete the exiting
2363 one and context-switch to the first available. */
2364 linux_fork_mourn_inferior ();
2368 linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
2369 const char *annex, gdb_byte *readbuf,
2370 const gdb_byte *writebuf,
2371 ULONGEST offset, LONGEST len)
2373 struct cleanup *old_chain = save_inferior_ptid ();
2376 if (is_lwp (inferior_ptid))
2377 inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
2379 xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
2382 do_cleanups (old_chain);
2387 linux_nat_thread_alive (ptid_t ptid)
2389 gdb_assert (is_lwp (ptid));
2392 ptrace (PTRACE_PEEKUSER, GET_LWP (ptid), 0, 0);
2393 if (debug_linux_nat)
2394 fprintf_unfiltered (gdb_stdlog,
2395 "LLTA: PTRACE_PEEKUSER %s, 0, 0 (%s)\n",
2396 target_pid_to_str (ptid),
2397 errno ? safe_strerror (errno) : "OK");
2399 /* Not every Linux target implements PTRACE_PEEKUSER.
2400 But we can handle that case gracefully since ptrace
2401 will first do a lookup for the process based upon the
2402 passed-in pid. If that fails we will get either -ESRCH
2403 or -EPERM, otherwise the child exists and is alive. */
2404 if (errno == ESRCH || errno == EPERM)
2411 linux_nat_pid_to_str (ptid_t ptid)
2413 static char buf[64];
2415 if (lwp_list && lwp_list->next && is_lwp (ptid))
2417 snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
2421 return normal_pid_to_str (ptid);
2425 sigchld_handler (int signo)
2427 /* Do nothing. The only reason for this handler is that it allows
2428 us to use sigsuspend in linux_nat_wait above to wait for the
2429 arrival of a SIGCHLD. */
2432 /* Accepts an integer PID; Returns a string representing a file that
2433 can be opened to get the symbols for the child process. */
2436 child_pid_to_exec_file (int pid)
2438 char *name1, *name2;
2440 name1 = xmalloc (MAXPATHLEN);
2441 name2 = xmalloc (MAXPATHLEN);
2442 make_cleanup (xfree, name1);
2443 make_cleanup (xfree, name2);
2444 memset (name2, 0, MAXPATHLEN);
2446 sprintf (name1, "/proc/%d/exe", pid);
2447 if (readlink (name1, name2, MAXPATHLEN) > 0)
2453 /* Service function for corefiles and info proc. */
2456 read_mapping (FILE *mapfile,
2461 char *device, long long *inode, char *filename)
2463 int ret = fscanf (mapfile, "%llx-%llx %s %llx %s %llx",
2464 addr, endaddr, permissions, offset, device, inode);
2467 if (ret > 0 && ret != EOF)
2469 /* Eat everything up to EOL for the filename. This will prevent
2470 weird filenames (such as one with embedded whitespace) from
2471 confusing this code. It also makes this code more robust in
2472 respect to annotations the kernel may add after the filename.
2474 Note the filename is used for informational purposes
2476 ret += fscanf (mapfile, "%[^\n]\n", filename);
2479 return (ret != 0 && ret != EOF);
2482 /* Fills the "to_find_memory_regions" target vector. Lists the memory
2483 regions in the inferior for a corefile. */
2486 linux_nat_find_memory_regions (int (*func) (CORE_ADDR,
2488 int, int, int, void *), void *obfd)
2490 long long pid = PIDGET (inferior_ptid);
2491 char mapsfilename[MAXPATHLEN];
2493 long long addr, endaddr, size, offset, inode;
2494 char permissions[8], device[8], filename[MAXPATHLEN];
2495 int read, write, exec;
2498 /* Compose the filename for the /proc memory map, and open it. */
2499 sprintf (mapsfilename, "/proc/%lld/maps", pid);
2500 if ((mapsfile = fopen (mapsfilename, "r")) == NULL)
2501 error (_("Could not open %s."), mapsfilename);
2504 fprintf_filtered (gdb_stdout,
2505 "Reading memory regions from %s\n", mapsfilename);
2507 /* Now iterate until end-of-file. */
2508 while (read_mapping (mapsfile, &addr, &endaddr, &permissions[0],
2509 &offset, &device[0], &inode, &filename[0]))
2511 size = endaddr - addr;
2513 /* Get the segment's permissions. */
2514 read = (strchr (permissions, 'r') != 0);
2515 write = (strchr (permissions, 'w') != 0);
2516 exec = (strchr (permissions, 'x') != 0);
2520 fprintf_filtered (gdb_stdout,
2521 "Save segment, %lld bytes at 0x%s (%c%c%c)",
2522 size, paddr_nz (addr),
2524 write ? 'w' : ' ', exec ? 'x' : ' ');
2525 if (filename && filename[0])
2526 fprintf_filtered (gdb_stdout, " for %s", filename);
2527 fprintf_filtered (gdb_stdout, "\n");
2530 /* Invoke the callback function to create the corefile
2532 func (addr, size, read, write, exec, obfd);
2538 /* Records the thread's register state for the corefile note
2542 linux_nat_do_thread_registers (bfd *obfd, ptid_t ptid,
2543 char *note_data, int *note_size)
2545 gdb_gregset_t gregs;
2546 gdb_fpregset_t fpregs;
2547 #ifdef FILL_FPXREGSET
2548 gdb_fpxregset_t fpxregs;
2550 unsigned long lwp = ptid_get_lwp (ptid);
2551 struct gdbarch *gdbarch = current_gdbarch;
2552 const struct regset *regset;
2555 core_regset_p = gdbarch_regset_from_core_section_p (gdbarch);
2557 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg",
2558 sizeof (gregs))) != NULL
2559 && regset->collect_regset != NULL)
2560 regset->collect_regset (regset, current_regcache, -1,
2561 &gregs, sizeof (gregs));
2563 fill_gregset (&gregs, -1);
2565 note_data = (char *) elfcore_write_prstatus (obfd,
2569 stop_signal, &gregs);
2572 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg2",
2573 sizeof (fpregs))) != NULL
2574 && regset->collect_regset != NULL)
2575 regset->collect_regset (regset, current_regcache, -1,
2576 &fpregs, sizeof (fpregs));
2578 fill_fpregset (&fpregs, -1);
2580 note_data = (char *) elfcore_write_prfpreg (obfd,
2583 &fpregs, sizeof (fpregs));
2585 #ifdef FILL_FPXREGSET
2587 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg-xfp",
2588 sizeof (fpxregs))) != NULL
2589 && regset->collect_regset != NULL)
2590 regset->collect_regset (regset, current_regcache, -1,
2591 &fpxregs, sizeof (fpxregs));
2593 fill_fpxregset (&fpxregs, -1);
2595 note_data = (char *) elfcore_write_prxfpreg (obfd,
2598 &fpxregs, sizeof (fpxregs));
2603 struct linux_nat_corefile_thread_data
2611 /* Called by gdbthread.c once per thread. Records the thread's
2612 register state for the corefile note section. */
2615 linux_nat_corefile_thread_callback (struct lwp_info *ti, void *data)
2617 struct linux_nat_corefile_thread_data *args = data;
2618 ptid_t saved_ptid = inferior_ptid;
2620 inferior_ptid = ti->ptid;
2621 registers_changed ();
2622 target_fetch_registers (-1); /* FIXME should not be necessary;
2623 fill_gregset should do it automatically. */
2624 args->note_data = linux_nat_do_thread_registers (args->obfd,
2629 inferior_ptid = saved_ptid;
2630 registers_changed ();
2631 target_fetch_registers (-1); /* FIXME should not be necessary;
2632 fill_gregset should do it automatically. */
2636 /* Records the register state for the corefile note section. */
2639 linux_nat_do_registers (bfd *obfd, ptid_t ptid,
2640 char *note_data, int *note_size)
2642 registers_changed ();
2643 target_fetch_registers (-1); /* FIXME should not be necessary;
2644 fill_gregset should do it automatically. */
2645 return linux_nat_do_thread_registers (obfd,
2646 ptid_build (ptid_get_pid (inferior_ptid),
2647 ptid_get_pid (inferior_ptid),
2649 note_data, note_size);
2653 /* Fills the "to_make_corefile_note" target vector. Builds the note
2654 section for a corefile, and returns it in a malloc buffer. */
2657 linux_nat_make_corefile_notes (bfd *obfd, int *note_size)
2659 struct linux_nat_corefile_thread_data thread_args;
2660 struct cleanup *old_chain;
2661 char fname[16] = { '\0' };
2662 char psargs[80] = { '\0' };
2663 char *note_data = NULL;
2664 ptid_t current_ptid = inferior_ptid;
2668 if (get_exec_file (0))
2670 strncpy (fname, strrchr (get_exec_file (0), '/') + 1, sizeof (fname));
2671 strncpy (psargs, get_exec_file (0), sizeof (psargs));
2672 if (get_inferior_args ())
2674 strncat (psargs, " ", sizeof (psargs) - strlen (psargs));
2675 strncat (psargs, get_inferior_args (),
2676 sizeof (psargs) - strlen (psargs));
2678 note_data = (char *) elfcore_write_prpsinfo (obfd,
2680 note_size, fname, psargs);
2683 /* Dump information for threads. */
2684 thread_args.obfd = obfd;
2685 thread_args.note_data = note_data;
2686 thread_args.note_size = note_size;
2687 thread_args.num_notes = 0;
2688 iterate_over_lwps (linux_nat_corefile_thread_callback, &thread_args);
2689 if (thread_args.num_notes == 0)
2691 /* iterate_over_threads didn't come up with any threads; just
2692 use inferior_ptid. */
2693 note_data = linux_nat_do_registers (obfd, inferior_ptid,
2694 note_data, note_size);
2698 note_data = thread_args.note_data;
2701 auxv_len = target_read_alloc (¤t_target, TARGET_OBJECT_AUXV,
2705 note_data = elfcore_write_note (obfd, note_data, note_size,
2706 "CORE", NT_AUXV, auxv, auxv_len);
2710 make_cleanup (xfree, note_data);
2714 /* Implement the "info proc" command. */
2717 linux_nat_info_proc_cmd (char *args, int from_tty)
2719 long long pid = PIDGET (inferior_ptid);
2722 char buffer[MAXPATHLEN];
2723 char fname1[MAXPATHLEN], fname2[MAXPATHLEN];
2736 /* Break up 'args' into an argv array. */
2737 if ((argv = buildargv (args)) == NULL)
2740 make_cleanup_freeargv (argv);
2742 while (argv != NULL && *argv != NULL)
2744 if (isdigit (argv[0][0]))
2746 pid = strtoul (argv[0], NULL, 10);
2748 else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
2752 else if (strcmp (argv[0], "status") == 0)
2756 else if (strcmp (argv[0], "stat") == 0)
2760 else if (strcmp (argv[0], "cmd") == 0)
2764 else if (strncmp (argv[0], "exe", strlen (argv[0])) == 0)
2768 else if (strcmp (argv[0], "cwd") == 0)
2772 else if (strncmp (argv[0], "all", strlen (argv[0])) == 0)
2778 /* [...] (future options here) */
2783 error (_("No current process: you must name one."));
2785 sprintf (fname1, "/proc/%lld", pid);
2786 if (stat (fname1, &dummy) != 0)
2787 error (_("No /proc directory: '%s'"), fname1);
2789 printf_filtered (_("process %lld\n"), pid);
2790 if (cmdline_f || all)
2792 sprintf (fname1, "/proc/%lld/cmdline", pid);
2793 if ((procfile = fopen (fname1, "r")) > 0)
2795 fgets (buffer, sizeof (buffer), procfile);
2796 printf_filtered ("cmdline = '%s'\n", buffer);
2800 warning (_("unable to open /proc file '%s'"), fname1);
2804 sprintf (fname1, "/proc/%lld/cwd", pid);
2805 memset (fname2, 0, sizeof (fname2));
2806 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
2807 printf_filtered ("cwd = '%s'\n", fname2);
2809 warning (_("unable to read link '%s'"), fname1);
2813 sprintf (fname1, "/proc/%lld/exe", pid);
2814 memset (fname2, 0, sizeof (fname2));
2815 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
2816 printf_filtered ("exe = '%s'\n", fname2);
2818 warning (_("unable to read link '%s'"), fname1);
2820 if (mappings_f || all)
2822 sprintf (fname1, "/proc/%lld/maps", pid);
2823 if ((procfile = fopen (fname1, "r")) > 0)
2825 long long addr, endaddr, size, offset, inode;
2826 char permissions[8], device[8], filename[MAXPATHLEN];
2828 printf_filtered (_("Mapped address spaces:\n\n"));
2829 if (TARGET_ADDR_BIT == 32)
2831 printf_filtered ("\t%10s %10s %10s %10s %7s\n",
2834 " Size", " Offset", "objfile");
2838 printf_filtered (" %18s %18s %10s %10s %7s\n",
2841 " Size", " Offset", "objfile");
2844 while (read_mapping (procfile, &addr, &endaddr, &permissions[0],
2845 &offset, &device[0], &inode, &filename[0]))
2847 size = endaddr - addr;
2849 /* FIXME: carlton/2003-08-27: Maybe the printf_filtered
2850 calls here (and possibly above) should be abstracted
2851 out into their own functions? Andrew suggests using
2852 a generic local_address_string instead to print out
2853 the addresses; that makes sense to me, too. */
2855 if (TARGET_ADDR_BIT == 32)
2857 printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
2858 (unsigned long) addr, /* FIXME: pr_addr */
2859 (unsigned long) endaddr,
2861 (unsigned int) offset,
2862 filename[0] ? filename : "");
2866 printf_filtered (" %#18lx %#18lx %#10x %#10x %7s\n",
2867 (unsigned long) addr, /* FIXME: pr_addr */
2868 (unsigned long) endaddr,
2870 (unsigned int) offset,
2871 filename[0] ? filename : "");
2878 warning (_("unable to open /proc file '%s'"), fname1);
2880 if (status_f || all)
2882 sprintf (fname1, "/proc/%lld/status", pid);
2883 if ((procfile = fopen (fname1, "r")) > 0)
2885 while (fgets (buffer, sizeof (buffer), procfile) != NULL)
2886 puts_filtered (buffer);
2890 warning (_("unable to open /proc file '%s'"), fname1);
2894 sprintf (fname1, "/proc/%lld/stat", pid);
2895 if ((procfile = fopen (fname1, "r")) > 0)
2900 if (fscanf (procfile, "%d ", &itmp) > 0)
2901 printf_filtered (_("Process: %d\n"), itmp);
2902 if (fscanf (procfile, "%s ", &buffer[0]) > 0)
2903 printf_filtered (_("Exec file: %s\n"), buffer);
2904 if (fscanf (procfile, "%c ", &ctmp) > 0)
2905 printf_filtered (_("State: %c\n"), ctmp);
2906 if (fscanf (procfile, "%d ", &itmp) > 0)
2907 printf_filtered (_("Parent process: %d\n"), itmp);
2908 if (fscanf (procfile, "%d ", &itmp) > 0)
2909 printf_filtered (_("Process group: %d\n"), itmp);
2910 if (fscanf (procfile, "%d ", &itmp) > 0)
2911 printf_filtered (_("Session id: %d\n"), itmp);
2912 if (fscanf (procfile, "%d ", &itmp) > 0)
2913 printf_filtered (_("TTY: %d\n"), itmp);
2914 if (fscanf (procfile, "%d ", &itmp) > 0)
2915 printf_filtered (_("TTY owner process group: %d\n"), itmp);
2916 if (fscanf (procfile, "%u ", &itmp) > 0)
2917 printf_filtered (_("Flags: 0x%x\n"), itmp);
2918 if (fscanf (procfile, "%u ", &itmp) > 0)
2919 printf_filtered (_("Minor faults (no memory page): %u\n"),
2920 (unsigned int) itmp);
2921 if (fscanf (procfile, "%u ", &itmp) > 0)
2922 printf_filtered (_("Minor faults, children: %u\n"),
2923 (unsigned int) itmp);
2924 if (fscanf (procfile, "%u ", &itmp) > 0)
2925 printf_filtered (_("Major faults (memory page faults): %u\n"),
2926 (unsigned int) itmp);
2927 if (fscanf (procfile, "%u ", &itmp) > 0)
2928 printf_filtered (_("Major faults, children: %u\n"),
2929 (unsigned int) itmp);
2930 if (fscanf (procfile, "%d ", &itmp) > 0)
2931 printf_filtered ("utime: %d\n", itmp);
2932 if (fscanf (procfile, "%d ", &itmp) > 0)
2933 printf_filtered ("stime: %d\n", itmp);
2934 if (fscanf (procfile, "%d ", &itmp) > 0)
2935 printf_filtered ("utime, children: %d\n", itmp);
2936 if (fscanf (procfile, "%d ", &itmp) > 0)
2937 printf_filtered ("stime, children: %d\n", itmp);
2938 if (fscanf (procfile, "%d ", &itmp) > 0)
2939 printf_filtered (_("jiffies remaining in current time slice: %d\n"),
2941 if (fscanf (procfile, "%d ", &itmp) > 0)
2942 printf_filtered ("'nice' value: %d\n", itmp);
2943 if (fscanf (procfile, "%u ", &itmp) > 0)
2944 printf_filtered (_("jiffies until next timeout: %u\n"),
2945 (unsigned int) itmp);
2946 if (fscanf (procfile, "%u ", &itmp) > 0)
2947 printf_filtered ("jiffies until next SIGALRM: %u\n",
2948 (unsigned int) itmp);
2949 if (fscanf (procfile, "%d ", &itmp) > 0)
2950 printf_filtered (_("start time (jiffies since system boot): %d\n"),
2952 if (fscanf (procfile, "%u ", &itmp) > 0)
2953 printf_filtered (_("Virtual memory size: %u\n"),
2954 (unsigned int) itmp);
2955 if (fscanf (procfile, "%u ", &itmp) > 0)
2956 printf_filtered (_("Resident set size: %u\n"), (unsigned int) itmp);
2957 if (fscanf (procfile, "%u ", &itmp) > 0)
2958 printf_filtered ("rlim: %u\n", (unsigned int) itmp);
2959 if (fscanf (procfile, "%u ", &itmp) > 0)
2960 printf_filtered (_("Start of text: 0x%x\n"), itmp);
2961 if (fscanf (procfile, "%u ", &itmp) > 0)
2962 printf_filtered (_("End of text: 0x%x\n"), itmp);
2963 if (fscanf (procfile, "%u ", &itmp) > 0)
2964 printf_filtered (_("Start of stack: 0x%x\n"), itmp);
2965 #if 0 /* Don't know how architecture-dependent the rest is...
2966 Anyway the signal bitmap info is available from "status". */
2967 if (fscanf (procfile, "%u ", &itmp) > 0) /* FIXME arch? */
2968 printf_filtered (_("Kernel stack pointer: 0x%x\n"), itmp);
2969 if (fscanf (procfile, "%u ", &itmp) > 0) /* FIXME arch? */
2970 printf_filtered (_("Kernel instr pointer: 0x%x\n"), itmp);
2971 if (fscanf (procfile, "%d ", &itmp) > 0)
2972 printf_filtered (_("Pending signals bitmap: 0x%x\n"), itmp);
2973 if (fscanf (procfile, "%d ", &itmp) > 0)
2974 printf_filtered (_("Blocked signals bitmap: 0x%x\n"), itmp);
2975 if (fscanf (procfile, "%d ", &itmp) > 0)
2976 printf_filtered (_("Ignored signals bitmap: 0x%x\n"), itmp);
2977 if (fscanf (procfile, "%d ", &itmp) > 0)
2978 printf_filtered (_("Catched signals bitmap: 0x%x\n"), itmp);
2979 if (fscanf (procfile, "%u ", &itmp) > 0) /* FIXME arch? */
2980 printf_filtered (_("wchan (system call): 0x%x\n"), itmp);
2985 warning (_("unable to open /proc file '%s'"), fname1);
2989 /* Implement the to_xfer_partial interface for memory reads using the /proc
2990 filesystem. Because we can use a single read() call for /proc, this
2991 can be much more efficient than banging away at PTRACE_PEEKTEXT,
2992 but it doesn't support writes. */
2995 linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
2996 const char *annex, gdb_byte *readbuf,
2997 const gdb_byte *writebuf,
2998 ULONGEST offset, LONGEST len)
3004 if (object != TARGET_OBJECT_MEMORY || !readbuf)
3007 /* Don't bother for one word. */
3008 if (len < 3 * sizeof (long))
3011 /* We could keep this file open and cache it - possibly one per
3012 thread. That requires some juggling, but is even faster. */
3013 sprintf (filename, "/proc/%d/mem", PIDGET (inferior_ptid));
3014 fd = open (filename, O_RDONLY | O_LARGEFILE);
3018 /* If pread64 is available, use it. It's faster if the kernel
3019 supports it (only one syscall), and it's 64-bit safe even on
3020 32-bit platforms (for instance, SPARC debugging a SPARC64
3023 if (pread64 (fd, readbuf, len, offset) != len)
3025 if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
3035 /* Parse LINE as a signal set and add its set bits to SIGS. */
3038 add_line_to_sigset (const char *line, sigset_t *sigs)
3040 int len = strlen (line) - 1;
3044 if (line[len] != '\n')
3045 error (_("Could not parse signal set: %s"), line);
3053 if (*p >= '0' && *p <= '9')
3055 else if (*p >= 'a' && *p <= 'f')
3056 digit = *p - 'a' + 10;
3058 error (_("Could not parse signal set: %s"), line);
3063 sigaddset (sigs, signum + 1);
3065 sigaddset (sigs, signum + 2);
3067 sigaddset (sigs, signum + 3);
3069 sigaddset (sigs, signum + 4);
3075 /* Find process PID's pending signals from /proc/pid/status and set
3079 linux_proc_pending_signals (int pid, sigset_t *pending, sigset_t *blocked, sigset_t *ignored)
3082 char buffer[MAXPATHLEN], fname[MAXPATHLEN];
3085 sigemptyset (pending);
3086 sigemptyset (blocked);
3087 sigemptyset (ignored);
3088 sprintf (fname, "/proc/%d/status", pid);
3089 procfile = fopen (fname, "r");
3090 if (procfile == NULL)
3091 error (_("Could not open %s"), fname);
3093 while (fgets (buffer, MAXPATHLEN, procfile) != NULL)
3095 /* Normal queued signals are on the SigPnd line in the status
3096 file. However, 2.6 kernels also have a "shared" pending
3097 queue for delivering signals to a thread group, so check for
3100 Unfortunately some Red Hat kernels include the shared pending
3101 queue but not the ShdPnd status field. */
3103 if (strncmp (buffer, "SigPnd:\t", 8) == 0)
3104 add_line_to_sigset (buffer + 8, pending);
3105 else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
3106 add_line_to_sigset (buffer + 8, pending);
3107 else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
3108 add_line_to_sigset (buffer + 8, blocked);
3109 else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
3110 add_line_to_sigset (buffer + 8, ignored);
3117 linux_xfer_partial (struct target_ops *ops, enum target_object object,
3118 const char *annex, gdb_byte *readbuf,
3119 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
3123 if (object == TARGET_OBJECT_AUXV)
3124 return procfs_xfer_auxv (ops, object, annex, readbuf, writebuf,
3127 xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
3132 return super_xfer_partial (ops, object, annex, readbuf, writebuf,
3136 #ifndef FETCH_INFERIOR_REGISTERS
3138 /* Return the address in the core dump or inferior of register
3142 linux_register_u_offset (int regno)
3144 /* FIXME drow/2005-09-04: The hardcoded use of register_addr should go
3145 away. This requires disentangling the various definitions of it
3146 (particularly alpha-nat.c's). */
3147 return register_addr (regno, 0);
3152 /* Create a prototype generic Linux target. The client can override
3153 it with local methods. */
3158 struct target_ops *t;
3160 #ifdef FETCH_INFERIOR_REGISTERS
3161 t = inf_ptrace_target ();
3163 t = inf_ptrace_trad_target (linux_register_u_offset);
3165 t->to_insert_fork_catchpoint = child_insert_fork_catchpoint;
3166 t->to_insert_vfork_catchpoint = child_insert_vfork_catchpoint;
3167 t->to_insert_exec_catchpoint = child_insert_exec_catchpoint;
3168 t->to_pid_to_exec_file = child_pid_to_exec_file;
3169 t->to_post_startup_inferior = linux_child_post_startup_inferior;
3170 t->to_post_attach = child_post_attach;
3171 t->to_follow_fork = child_follow_fork;
3172 t->to_find_memory_regions = linux_nat_find_memory_regions;
3173 t->to_make_corefile_notes = linux_nat_make_corefile_notes;
3175 super_xfer_partial = t->to_xfer_partial;
3176 t->to_xfer_partial = linux_xfer_partial;
3182 linux_nat_add_target (struct target_ops *t)
3184 /* Save the provided single-threaded target. We save this in a separate
3185 variable because another target we've inherited from (e.g. inf-ptrace)
3186 may have saved a pointer to T; we want to use it for the final
3187 process stratum target. */
3188 linux_ops_saved = *t;
3189 linux_ops = &linux_ops_saved;
3191 /* Override some methods for multithreading. */
3192 t->to_attach = linux_nat_attach;
3193 t->to_detach = linux_nat_detach;
3194 t->to_resume = linux_nat_resume;
3195 t->to_wait = linux_nat_wait;
3196 t->to_xfer_partial = linux_nat_xfer_partial;
3197 t->to_kill = linux_nat_kill;
3198 t->to_mourn_inferior = linux_nat_mourn_inferior;
3199 t->to_thread_alive = linux_nat_thread_alive;
3200 t->to_pid_to_str = linux_nat_pid_to_str;
3201 t->to_has_thread_control = tc_schedlock;
3203 /* We don't change the stratum; this target will sit at
3204 process_stratum and thread_db will set at thread_stratum. This
3205 is a little strange, since this is a multi-threaded-capable
3206 target, but we want to be on the stack below thread_db, and we
3207 also want to be used for single-threaded processes. */
3211 /* TODO: Eliminate this and have libthread_db use
3212 find_target_beneath. */
3217 _initialize_linux_nat (void)
3219 struct sigaction action;
3221 add_info ("proc", linux_nat_info_proc_cmd, _("\
3222 Show /proc process information about any running process.\n\
3223 Specify any process id, or use the program being debugged by default.\n\
3224 Specify any of the following keywords for detailed info:\n\
3225 mappings -- list of mapped memory regions.\n\
3226 stat -- list a bunch of random process info.\n\
3227 status -- list a different bunch of random process info.\n\
3228 all -- list all available /proc info."));
3230 /* Save the original signal mask. */
3231 sigprocmask (SIG_SETMASK, NULL, &normal_mask);
3233 action.sa_handler = sigchld_handler;
3234 sigemptyset (&action.sa_mask);
3235 action.sa_flags = SA_RESTART;
3236 sigaction (SIGCHLD, &action, NULL);
3238 /* Make sure we don't block SIGCHLD during a sigsuspend. */
3239 sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
3240 sigdelset (&suspend_mask, SIGCHLD);
3242 sigemptyset (&blocked_mask);
3244 add_setshow_zinteger_cmd ("lin-lwp", no_class, &debug_linux_nat, _("\
3245 Set debugging of GNU/Linux lwp module."), _("\
3246 Show debugging of GNU/Linux lwp module."), _("\
3247 Enables printf debugging output."),
3249 show_debug_linux_nat,
3250 &setdebuglist, &showdebuglist);
3254 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
3255 the GNU/Linux Threads library and therefore doesn't really belong
3258 /* Read variable NAME in the target and return its value if found.
3259 Otherwise return zero. It is assumed that the type of the variable
3263 get_signo (const char *name)
3265 struct minimal_symbol *ms;
3268 ms = lookup_minimal_symbol (name, NULL, NULL);
3272 if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
3273 sizeof (signo)) != 0)
3279 /* Return the set of signals used by the threads library in *SET. */
3282 lin_thread_get_thread_signals (sigset_t *set)
3284 struct sigaction action;
3285 int restart, cancel;
3289 restart = get_signo ("__pthread_sig_restart");
3290 cancel = get_signo ("__pthread_sig_cancel");
3292 /* LinuxThreads normally uses the first two RT signals, but in some legacy
3293 cases may use SIGUSR1/SIGUSR2. NPTL always uses RT signals, but does
3294 not provide any way for the debugger to query the signal numbers -
3295 fortunately they don't change! */
3298 restart = __SIGRTMIN;
3301 cancel = __SIGRTMIN + 1;
3303 sigaddset (set, restart);
3304 sigaddset (set, cancel);
3306 /* The GNU/Linux Threads library makes terminating threads send a
3307 special "cancel" signal instead of SIGCHLD. Make sure we catch
3308 those (to prevent them from terminating GDB itself, which is
3309 likely to be their default action) and treat them the same way as
3312 action.sa_handler = sigchld_handler;
3313 sigemptyset (&action.sa_mask);
3314 action.sa_flags = SA_RESTART;
3315 sigaction (cancel, &action, NULL);
3317 /* We block the "cancel" signal throughout this code ... */
3318 sigaddset (&blocked_mask, cancel);
3319 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
3321 /* ... except during a sigsuspend. */
3322 sigdelset (&suspend_mask, cancel);