Update
[gdb.git] / gdb / linux-nat.c
blob876885372df81b6182396a2ba23e5dfdacda1922
1 /* GNU/Linux native-dependent code common to multiple platforms.
3 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
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 3 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, see <http://www.gnu.org/licenses/>. */
21 #include "defs.h"
22 #include "inferior.h"
23 #include "target.h"
24 #include "gdb_string.h"
25 #include "gdb_wait.h"
26 #include "gdb_assert.h"
27 #ifdef HAVE_TKILL_SYSCALL
28 #include <unistd.h>
29 #include <sys/syscall.h>
30 #endif
31 #include <sys/ptrace.h>
32 #include "linux-nat.h"
33 #include "linux-fork.h"
34 #include "gdbthread.h"
35 #include "gdbcmd.h"
36 #include "regcache.h"
37 #include "regset.h"
38 #include "inf-ptrace.h"
39 #include "auxv.h"
40 #include <sys/param.h> /* for MAXPATHLEN */
41 #include <sys/procfs.h> /* for elf_gregset etc. */
42 #include "elf-bfd.h" /* for elfcore_write_* */
43 #include "gregset.h" /* for gregset */
44 #include "gdbcore.h" /* for get_exec_file */
45 #include <ctype.h> /* for isdigit */
46 #include "gdbthread.h" /* for struct thread_info etc. */
47 #include "gdb_stat.h" /* for struct stat */
48 #include <fcntl.h> /* for O_RDONLY */
50 #ifndef O_LARGEFILE
51 #define O_LARGEFILE 0
52 #endif
54 /* If the system headers did not provide the constants, hard-code the normal
55 values. */
56 #ifndef PTRACE_EVENT_FORK
58 #define PTRACE_SETOPTIONS 0x4200
59 #define PTRACE_GETEVENTMSG 0x4201
61 /* options set using PTRACE_SETOPTIONS */
62 #define PTRACE_O_TRACESYSGOOD 0x00000001
63 #define PTRACE_O_TRACEFORK 0x00000002
64 #define PTRACE_O_TRACEVFORK 0x00000004
65 #define PTRACE_O_TRACECLONE 0x00000008
66 #define PTRACE_O_TRACEEXEC 0x00000010
67 #define PTRACE_O_TRACEVFORKDONE 0x00000020
68 #define PTRACE_O_TRACEEXIT 0x00000040
70 /* Wait extended result codes for the above trace options. */
71 #define PTRACE_EVENT_FORK 1
72 #define PTRACE_EVENT_VFORK 2
73 #define PTRACE_EVENT_CLONE 3
74 #define PTRACE_EVENT_EXEC 4
75 #define PTRACE_EVENT_VFORK_DONE 5
76 #define PTRACE_EVENT_EXIT 6
78 #endif /* PTRACE_EVENT_FORK */
80 /* We can't always assume that this flag is available, but all systems
81 with the ptrace event handlers also have __WALL, so it's safe to use
82 here. */
83 #ifndef __WALL
84 #define __WALL 0x40000000 /* Wait for any child. */
85 #endif
87 #ifndef PTRACE_GETSIGINFO
88 #define PTRACE_GETSIGINFO 0x4202
89 #endif
91 /* The single-threaded native GNU/Linux target_ops. We save a pointer for
92 the use of the multi-threaded target. */
93 static struct target_ops *linux_ops;
94 static struct target_ops linux_ops_saved;
96 /* The method to call, if any, when a new thread is attached. */
97 static void (*linux_nat_new_thread) (ptid_t);
99 /* The saved to_xfer_partial method, inherited from inf-ptrace.c.
100 Called by our to_xfer_partial. */
101 static LONGEST (*super_xfer_partial) (struct target_ops *,
102 enum target_object,
103 const char *, gdb_byte *,
104 const gdb_byte *,
105 ULONGEST, LONGEST);
107 static int debug_linux_nat;
108 static void
109 show_debug_linux_nat (struct ui_file *file, int from_tty,
110 struct cmd_list_element *c, const char *value)
112 fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
113 value);
116 static int linux_parent_pid;
118 struct simple_pid_list
120 int pid;
121 int status;
122 struct simple_pid_list *next;
124 struct simple_pid_list *stopped_pids;
126 /* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACEFORK
127 can not be used, 1 if it can. */
129 static int linux_supports_tracefork_flag = -1;
131 /* If we have PTRACE_O_TRACEFORK, this flag indicates whether we also have
132 PTRACE_O_TRACEVFORKDONE. */
134 static int linux_supports_tracevforkdone_flag = -1;
137 /* Trivial list manipulation functions to keep track of a list of
138 new stopped processes. */
139 static void
140 add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
142 struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
143 new_pid->pid = pid;
144 new_pid->status = status;
145 new_pid->next = *listp;
146 *listp = new_pid;
149 static int
150 pull_pid_from_list (struct simple_pid_list **listp, int pid, int *status)
152 struct simple_pid_list **p;
154 for (p = listp; *p != NULL; p = &(*p)->next)
155 if ((*p)->pid == pid)
157 struct simple_pid_list *next = (*p)->next;
158 *status = (*p)->status;
159 xfree (*p);
160 *p = next;
161 return 1;
163 return 0;
166 static void
167 linux_record_stopped_pid (int pid, int status)
169 add_to_pid_list (&stopped_pids, pid, status);
173 /* A helper function for linux_test_for_tracefork, called after fork (). */
175 static void
176 linux_tracefork_child (void)
178 int ret;
180 ptrace (PTRACE_TRACEME, 0, 0, 0);
181 kill (getpid (), SIGSTOP);
182 fork ();
183 _exit (0);
186 /* Wrapper function for waitpid which handles EINTR. */
188 static int
189 my_waitpid (int pid, int *status, int flags)
191 int ret;
194 ret = waitpid (pid, status, flags);
196 while (ret == -1 && errno == EINTR);
198 return ret;
201 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.
203 First, we try to enable fork tracing on ORIGINAL_PID. If this fails,
204 we know that the feature is not available. This may change the tracing
205 options for ORIGINAL_PID, but we'll be setting them shortly anyway.
207 However, if it succeeds, we don't know for sure that the feature is
208 available; old versions of PTRACE_SETOPTIONS ignored unknown options. We
209 create a child process, attach to it, use PTRACE_SETOPTIONS to enable
210 fork tracing, and let it fork. If the process exits, we assume that we
211 can't use TRACEFORK; if we get the fork notification, and we can extract
212 the new child's PID, then we assume that we can. */
214 static void
215 linux_test_for_tracefork (int original_pid)
217 int child_pid, ret, status;
218 long second_pid;
220 linux_supports_tracefork_flag = 0;
221 linux_supports_tracevforkdone_flag = 0;
223 ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACEFORK);
224 if (ret != 0)
225 return;
227 child_pid = fork ();
228 if (child_pid == -1)
229 perror_with_name (("fork"));
231 if (child_pid == 0)
232 linux_tracefork_child ();
234 ret = my_waitpid (child_pid, &status, 0);
235 if (ret == -1)
236 perror_with_name (("waitpid"));
237 else if (ret != child_pid)
238 error (_("linux_test_for_tracefork: waitpid: unexpected result %d."), ret);
239 if (! WIFSTOPPED (status))
240 error (_("linux_test_for_tracefork: waitpid: unexpected status %d."), status);
242 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
243 if (ret != 0)
245 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
246 if (ret != 0)
248 warning (_("linux_test_for_tracefork: failed to kill child"));
249 return;
252 ret = my_waitpid (child_pid, &status, 0);
253 if (ret != child_pid)
254 warning (_("linux_test_for_tracefork: failed to wait for killed child"));
255 else if (!WIFSIGNALED (status))
256 warning (_("linux_test_for_tracefork: unexpected wait status 0x%x from "
257 "killed child"), status);
259 return;
262 /* Check whether PTRACE_O_TRACEVFORKDONE is available. */
263 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0,
264 PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORKDONE);
265 linux_supports_tracevforkdone_flag = (ret == 0);
267 ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
268 if (ret != 0)
269 warning (_("linux_test_for_tracefork: failed to resume child"));
271 ret = my_waitpid (child_pid, &status, 0);
273 if (ret == child_pid && WIFSTOPPED (status)
274 && status >> 16 == PTRACE_EVENT_FORK)
276 second_pid = 0;
277 ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
278 if (ret == 0 && second_pid != 0)
280 int second_status;
282 linux_supports_tracefork_flag = 1;
283 my_waitpid (second_pid, &second_status, 0);
284 ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
285 if (ret != 0)
286 warning (_("linux_test_for_tracefork: failed to kill second child"));
287 my_waitpid (second_pid, &status, 0);
290 else
291 warning (_("linux_test_for_tracefork: unexpected result from waitpid "
292 "(%d, status 0x%x)"), ret, status);
294 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
295 if (ret != 0)
296 warning (_("linux_test_for_tracefork: failed to kill child"));
297 my_waitpid (child_pid, &status, 0);
300 /* Return non-zero iff we have tracefork functionality available.
301 This function also sets linux_supports_tracefork_flag. */
303 static int
304 linux_supports_tracefork (int pid)
306 if (linux_supports_tracefork_flag == -1)
307 linux_test_for_tracefork (pid);
308 return linux_supports_tracefork_flag;
311 static int
312 linux_supports_tracevforkdone (int pid)
314 if (linux_supports_tracefork_flag == -1)
315 linux_test_for_tracefork (pid);
316 return linux_supports_tracevforkdone_flag;
320 void
321 linux_enable_event_reporting (ptid_t ptid)
323 int pid = ptid_get_lwp (ptid);
324 int options;
326 if (pid == 0)
327 pid = ptid_get_pid (ptid);
329 if (! linux_supports_tracefork (pid))
330 return;
332 options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEEXEC
333 | PTRACE_O_TRACECLONE;
334 if (linux_supports_tracevforkdone (pid))
335 options |= PTRACE_O_TRACEVFORKDONE;
337 /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to support
338 read-only process state. */
340 ptrace (PTRACE_SETOPTIONS, pid, 0, options);
343 static void
344 linux_child_post_attach (int pid)
346 linux_enable_event_reporting (pid_to_ptid (pid));
347 check_for_thread_db ();
350 static void
351 linux_child_post_startup_inferior (ptid_t ptid)
353 linux_enable_event_reporting (ptid);
354 check_for_thread_db ();
357 static int
358 linux_child_follow_fork (struct target_ops *ops, int follow_child)
360 ptid_t last_ptid;
361 struct target_waitstatus last_status;
362 int has_vforked;
363 int parent_pid, child_pid;
365 get_last_target_status (&last_ptid, &last_status);
366 has_vforked = (last_status.kind == TARGET_WAITKIND_VFORKED);
367 parent_pid = ptid_get_lwp (last_ptid);
368 if (parent_pid == 0)
369 parent_pid = ptid_get_pid (last_ptid);
370 child_pid = last_status.value.related_pid;
372 if (! follow_child)
374 /* We're already attached to the parent, by default. */
376 /* Before detaching from the child, remove all breakpoints from
377 it. (This won't actually modify the breakpoint list, but will
378 physically remove the breakpoints from the child.) */
379 /* If we vforked this will remove the breakpoints from the parent
380 also, but they'll be reinserted below. */
381 detach_breakpoints (child_pid);
383 /* Detach new forked process? */
384 if (detach_fork)
386 if (info_verbose || debug_linux_nat)
388 target_terminal_ours ();
389 fprintf_filtered (gdb_stdlog,
390 "Detaching after fork from child process %d.\n",
391 child_pid);
394 ptrace (PTRACE_DETACH, child_pid, 0, 0);
396 else
398 struct fork_info *fp;
399 /* Retain child fork in ptrace (stopped) state. */
400 fp = find_fork_pid (child_pid);
401 if (!fp)
402 fp = add_fork (child_pid);
403 fork_save_infrun_state (fp, 0);
406 if (has_vforked)
408 gdb_assert (linux_supports_tracefork_flag >= 0);
409 if (linux_supports_tracevforkdone (0))
411 int status;
413 ptrace (PTRACE_CONT, parent_pid, 0, 0);
414 my_waitpid (parent_pid, &status, __WALL);
415 if ((status >> 16) != PTRACE_EVENT_VFORK_DONE)
416 warning (_("Unexpected waitpid result %06x when waiting for "
417 "vfork-done"), status);
419 else
421 /* We can't insert breakpoints until the child has
422 finished with the shared memory region. We need to
423 wait until that happens. Ideal would be to just
424 call:
425 - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
426 - waitpid (parent_pid, &status, __WALL);
427 However, most architectures can't handle a syscall
428 being traced on the way out if it wasn't traced on
429 the way in.
431 We might also think to loop, continuing the child
432 until it exits or gets a SIGTRAP. One problem is
433 that the child might call ptrace with PTRACE_TRACEME.
435 There's no simple and reliable way to figure out when
436 the vforked child will be done with its copy of the
437 shared memory. We could step it out of the syscall,
438 two instructions, let it go, and then single-step the
439 parent once. When we have hardware single-step, this
440 would work; with software single-step it could still
441 be made to work but we'd have to be able to insert
442 single-step breakpoints in the child, and we'd have
443 to insert -just- the single-step breakpoint in the
444 parent. Very awkward.
446 In the end, the best we can do is to make sure it
447 runs for a little while. Hopefully it will be out of
448 range of any breakpoints we reinsert. Usually this
449 is only the single-step breakpoint at vfork's return
450 point. */
452 usleep (10000);
455 /* Since we vforked, breakpoints were removed in the parent
456 too. Put them back. */
457 reattach_breakpoints (parent_pid);
460 else
462 char child_pid_spelling[40];
464 /* Needed to keep the breakpoint lists in sync. */
465 if (! has_vforked)
466 detach_breakpoints (child_pid);
468 /* Before detaching from the parent, remove all breakpoints from it. */
469 remove_breakpoints ();
471 if (info_verbose || debug_linux_nat)
473 target_terminal_ours ();
474 fprintf_filtered (gdb_stdlog,
475 "Attaching after fork to child process %d.\n",
476 child_pid);
479 /* If we're vforking, we may want to hold on to the parent until
480 the child exits or execs. At exec time we can remove the old
481 breakpoints from the parent and detach it; at exit time we
482 could do the same (or even, sneakily, resume debugging it - the
483 child's exec has failed, or something similar).
485 This doesn't clean up "properly", because we can't call
486 target_detach, but that's OK; if the current target is "child",
487 then it doesn't need any further cleanups, and lin_lwp will
488 generally not encounter vfork (vfork is defined to fork
489 in libpthread.so).
491 The holding part is very easy if we have VFORKDONE events;
492 but keeping track of both processes is beyond GDB at the
493 moment. So we don't expose the parent to the rest of GDB.
494 Instead we quietly hold onto it until such time as we can
495 safely resume it. */
497 if (has_vforked)
498 linux_parent_pid = parent_pid;
499 else if (!detach_fork)
501 struct fork_info *fp;
502 /* Retain parent fork in ptrace (stopped) state. */
503 fp = find_fork_pid (parent_pid);
504 if (!fp)
505 fp = add_fork (parent_pid);
506 fork_save_infrun_state (fp, 0);
508 else
510 target_detach (NULL, 0);
513 inferior_ptid = ptid_build (child_pid, child_pid, 0);
515 /* Reinstall ourselves, since we might have been removed in
516 target_detach (which does other necessary cleanup). */
518 push_target (ops);
519 linux_nat_switch_fork (inferior_ptid);
520 check_for_thread_db ();
522 // fprintf_filtered (gdb_stdlog,
523 // "FOLLOW_INFERIOR_RESET_BREAKPOINTS.\n");
525 /* Reset breakpoints in the child as appropriate. */
526 follow_inferior_reset_breakpoints ();
528 // fprintf_filtered (gdb_stdlog,
529 // "FOLLOW_INFERIOR_RESET_BREAKPOINTS DONE.\n");
532 return 0;
536 static void
537 linux_child_insert_fork_catchpoint (int pid)
539 if (! linux_supports_tracefork (pid))
540 error (_("Your system does not support fork catchpoints."));
543 static void
544 linux_child_insert_vfork_catchpoint (int pid)
546 if (!linux_supports_tracefork (pid))
547 error (_("Your system does not support vfork catchpoints."));
550 static void
551 linux_child_insert_exec_catchpoint (int pid)
553 if (!linux_supports_tracefork (pid))
554 error (_("Your system does not support exec catchpoints."));
557 /* On GNU/Linux there are no real LWP's. The closest thing to LWP's
558 are processes sharing the same VM space. A multi-threaded process
559 is basically a group of such processes. However, such a grouping
560 is almost entirely a user-space issue; the kernel doesn't enforce
561 such a grouping at all (this might change in the future). In
562 general, we'll rely on the threads library (i.e. the GNU/Linux
563 Threads library) to provide such a grouping.
565 It is perfectly well possible to write a multi-threaded application
566 without the assistance of a threads library, by using the clone
567 system call directly. This module should be able to give some
568 rudimentary support for debugging such applications if developers
569 specify the CLONE_PTRACE flag in the clone system call, and are
570 using the Linux kernel 2.4 or above.
572 Note that there are some peculiarities in GNU/Linux that affect
573 this code:
575 - In general one should specify the __WCLONE flag to waitpid in
576 order to make it report events for any of the cloned processes
577 (and leave it out for the initial process). However, if a cloned
578 process has exited the exit status is only reported if the
579 __WCLONE flag is absent. Linux kernel 2.4 has a __WALL flag, but
580 we cannot use it since GDB must work on older systems too.
582 - When a traced, cloned process exits and is waited for by the
583 debugger, the kernel reassigns it to the original parent and
584 keeps it around as a "zombie". Somehow, the GNU/Linux Threads
585 library doesn't notice this, which leads to the "zombie problem":
586 When debugged a multi-threaded process that spawns a lot of
587 threads will run out of processes, even if the threads exit,
588 because the "zombies" stay around. */
590 /* List of known LWPs. */
591 struct lwp_info *lwp_list;
593 /* Number of LWPs in the list. */
594 static int num_lwps;
597 #define GET_LWP(ptid) ptid_get_lwp (ptid)
598 #define GET_PID(ptid) ptid_get_pid (ptid)
599 #define is_lwp(ptid) (GET_LWP (ptid) != 0)
600 #define BUILD_LWP(lwp, pid) ptid_build (pid, lwp, 0)
602 /* If the last reported event was a SIGTRAP, this variable is set to
603 the process id of the LWP/thread that got it. */
604 ptid_t trap_ptid;
607 /* Since we cannot wait (in linux_nat_wait) for the initial process and
608 any cloned processes with a single call to waitpid, we have to use
609 the WNOHANG flag and call waitpid in a loop. To optimize
610 things a bit we use `sigsuspend' to wake us up when a process has
611 something to report (it will send us a SIGCHLD if it has). To make
612 this work we have to juggle with the signal mask. We save the
613 original signal mask such that we can restore it before creating a
614 new process in order to avoid blocking certain signals in the
615 inferior. We then block SIGCHLD during the waitpid/sigsuspend
616 loop. */
618 /* Original signal mask. */
619 static sigset_t normal_mask;
621 /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
622 _initialize_linux_nat. */
623 static sigset_t suspend_mask;
625 /* Signals to block to make that sigsuspend work. */
626 static sigset_t blocked_mask;
629 /* Prototypes for local functions. */
630 static int stop_wait_callback (struct lwp_info *lp, void *data);
631 static int linux_nat_thread_alive (ptid_t ptid);
632 static char *linux_child_pid_to_exec_file (int pid);
634 /* Convert wait status STATUS to a string. Used for printing debug
635 messages only. */
637 static char *
638 status_to_str (int status)
640 static char buf[64];
642 if (WIFSTOPPED (status))
643 snprintf (buf, sizeof (buf), "%s (stopped)",
644 strsignal (WSTOPSIG (status)));
645 else if (WIFSIGNALED (status))
646 snprintf (buf, sizeof (buf), "%s (terminated)",
647 strsignal (WSTOPSIG (status)));
648 else
649 snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
651 return buf;
654 /* Initialize the list of LWPs. Note that this module, contrary to
655 what GDB's generic threads layer does for its thread list,
656 re-initializes the LWP lists whenever we mourn or detach (which
657 doesn't involve mourning) the inferior. */
659 static void
660 init_lwp_list (void)
662 struct lwp_info *lp, *lpnext;
664 for (lp = lwp_list; lp; lp = lpnext)
666 lpnext = lp->next;
667 xfree (lp);
670 lwp_list = NULL;
671 num_lwps = 0;
674 /* Add the LWP specified by PID to the list. Return a pointer to the
675 structure describing the new LWP. The LWP should already be stopped
676 (with an exception for the very first LWP). */
678 static struct lwp_info *
679 add_lwp (ptid_t ptid)
681 struct lwp_info *lp;
683 gdb_assert (is_lwp (ptid));
685 lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
687 memset (lp, 0, sizeof (struct lwp_info));
689 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
691 lp->ptid = ptid;
693 lp->next = lwp_list;
694 lwp_list = lp;
695 ++num_lwps;
697 if (num_lwps > 1 && linux_nat_new_thread != NULL)
698 linux_nat_new_thread (ptid);
700 return lp;
703 /* Remove the LWP specified by PID from the list. */
705 static void
706 delete_lwp (ptid_t ptid)
708 struct lwp_info *lp, *lpprev;
710 lpprev = NULL;
712 for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
713 if (ptid_equal (lp->ptid, ptid))
714 break;
716 if (!lp)
717 return;
719 num_lwps--;
721 if (lpprev)
722 lpprev->next = lp->next;
723 else
724 lwp_list = lp->next;
726 xfree (lp);
729 /* Return a pointer to the structure describing the LWP corresponding
730 to PID. If no corresponding LWP could be found, return NULL. */
732 static struct lwp_info *
733 find_lwp_pid (ptid_t ptid)
735 struct lwp_info *lp;
736 int lwp;
738 if (is_lwp (ptid))
739 lwp = GET_LWP (ptid);
740 else
741 lwp = GET_PID (ptid);
743 for (lp = lwp_list; lp; lp = lp->next)
744 if (lwp == GET_LWP (lp->ptid))
745 return lp;
747 return NULL;
750 /* Call CALLBACK with its second argument set to DATA for every LWP in
751 the list. If CALLBACK returns 1 for a particular LWP, return a
752 pointer to the structure describing that LWP immediately.
753 Otherwise return NULL. */
755 struct lwp_info *
756 iterate_over_lwps (int (*callback) (struct lwp_info *, void *), void *data)
758 struct lwp_info *lp, *lpnext;
760 for (lp = lwp_list; lp; lp = lpnext)
762 lpnext = lp->next;
763 if ((*callback) (lp, data))
764 return lp;
767 return NULL;
770 /* Update our internal state when changing from one fork (checkpoint,
771 et cetera) to another indicated by NEW_PTID. We can only switch
772 single-threaded applications, so we only create one new LWP, and
773 the previous list is discarded. */
775 void
776 linux_nat_switch_fork (ptid_t new_ptid)
778 struct lwp_info *lp;
780 init_lwp_list ();
781 lp = add_lwp (new_ptid);
782 lp->stopped = 1;
785 /* Record a PTID for later deletion. */
787 struct saved_ptids
789 ptid_t ptid;
790 struct saved_ptids *next;
792 static struct saved_ptids *threads_to_delete;
794 static void
795 record_dead_thread (ptid_t ptid)
797 struct saved_ptids *p = xmalloc (sizeof (struct saved_ptids));
798 p->ptid = ptid;
799 p->next = threads_to_delete;
800 threads_to_delete = p;
803 /* Delete any dead threads which are not the current thread. */
805 static void
806 prune_lwps (void)
808 struct saved_ptids **p = &threads_to_delete;
810 while (*p)
811 if (! ptid_equal ((*p)->ptid, inferior_ptid))
813 struct saved_ptids *tmp = *p;
814 delete_thread (tmp->ptid);
815 *p = tmp->next;
816 xfree (tmp);
818 else
819 p = &(*p)->next;
822 /* Callback for iterate_over_threads that finds a thread corresponding
823 to the given LWP. */
825 static int
826 find_thread_from_lwp (struct thread_info *thr, void *dummy)
828 ptid_t *ptid_p = dummy;
830 if (GET_LWP (thr->ptid) && GET_LWP (thr->ptid) == GET_LWP (*ptid_p))
831 return 1;
832 else
833 return 0;
836 /* Handle the exit of a single thread LP. */
838 static void
839 exit_lwp (struct lwp_info *lp)
841 if (in_thread_list (lp->ptid))
843 /* Core GDB cannot deal with us deleting the current thread. */
844 if (!ptid_equal (lp->ptid, inferior_ptid))
845 delete_thread (lp->ptid);
846 else
847 record_dead_thread (lp->ptid);
848 printf_unfiltered (_("[%s exited]\n"),
849 target_pid_to_str (lp->ptid));
851 else
853 /* Even if LP->PTID is not in the global GDB thread list, the
854 LWP may be - with an additional thread ID. We don't need
855 to print anything in this case; thread_db is in use and
856 already took care of that. But it didn't delete the thread
857 in order to handle zombies correctly. */
859 struct thread_info *thr;
861 thr = iterate_over_threads (find_thread_from_lwp, &lp->ptid);
862 if (thr)
864 if (!ptid_equal (thr->ptid, inferior_ptid))
865 delete_thread (thr->ptid);
866 else
867 record_dead_thread (thr->ptid);
871 delete_lwp (lp->ptid);
874 /* Attach to the LWP specified by PID. If VERBOSE is non-zero, print
875 a message telling the user that a new LWP has been added to the
876 process. Return 0 if successful or -1 if the new LWP could not
877 be attached. */
880 lin_lwp_attach_lwp (ptid_t ptid)
882 struct lwp_info *lp;
884 gdb_assert (is_lwp (ptid));
886 /* Make sure SIGCHLD is blocked. We don't want SIGCHLD events
887 to interrupt either the ptrace() or waitpid() calls below. */
888 if (!sigismember (&blocked_mask, SIGCHLD))
890 sigaddset (&blocked_mask, SIGCHLD);
891 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
894 lp = find_lwp_pid (ptid);
896 /* We assume that we're already attached to any LWP that has an id
897 equal to the overall process id, and to any LWP that is already
898 in our list of LWPs. If we're not seeing exit events from threads
899 and we've had PID wraparound since we last tried to stop all threads,
900 this assumption might be wrong; fortunately, this is very unlikely
901 to happen. */
902 if (GET_LWP (ptid) != GET_PID (ptid) && lp == NULL)
904 pid_t pid;
905 int status;
906 int cloned = 0;
908 if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
910 /* If we fail to attach to the thread, issue a warning,
911 but continue. One way this can happen is if thread
912 creation is interrupted; as of Linux kernel 2.6.19, a
913 bug may place threads in the thread list and then fail
914 to create them. */
915 warning (_("Can't attach %s: %s"), target_pid_to_str (ptid),
916 safe_strerror (errno));
917 return -1;
920 if (debug_linux_nat)
921 fprintf_unfiltered (gdb_stdlog,
922 "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
923 target_pid_to_str (ptid));
925 pid = my_waitpid (GET_LWP (ptid), &status, 0);
926 if (pid == -1 && errno == ECHILD)
928 /* Try again with __WCLONE to check cloned processes. */
929 pid = my_waitpid (GET_LWP (ptid), &status, __WCLONE);
930 cloned = 1;
933 gdb_assert (pid == GET_LWP (ptid)
934 && WIFSTOPPED (status) && WSTOPSIG (status));
936 if (lp == NULL)
937 lp = add_lwp (ptid);
938 lp->cloned = cloned;
940 target_post_attach (pid);
942 lp->stopped = 1;
944 if (debug_linux_nat)
946 fprintf_unfiltered (gdb_stdlog,
947 "LLAL: waitpid %s received %s\n",
948 target_pid_to_str (ptid),
949 status_to_str (status));
952 else
954 /* We assume that the LWP representing the original process is
955 already stopped. Mark it as stopped in the data structure
956 that the GNU/linux ptrace layer uses to keep track of
957 threads. Note that this won't have already been done since
958 the main thread will have, we assume, been stopped by an
959 attach from a different layer. */
960 if (lp == NULL)
961 lp = add_lwp (ptid);
962 lp->stopped = 1;
965 return 0;
968 static void
969 linux_nat_attach (char *args, int from_tty)
971 struct lwp_info *lp;
972 pid_t pid;
973 int status;
974 int cloned = 0;
976 /* FIXME: We should probably accept a list of process id's, and
977 attach all of them. */
978 linux_ops->to_attach (args, from_tty);
980 /* Make sure the initial process is stopped. The user-level threads
981 layer might want to poke around in the inferior, and that won't
982 work if things haven't stabilized yet. */
983 pid = my_waitpid (GET_PID (inferior_ptid), &status, 0);
984 if (pid == -1 && errno == ECHILD)
986 warning (_("%s is a cloned process"), target_pid_to_str (inferior_ptid));
988 /* Try again with __WCLONE to check cloned processes. */
989 pid = my_waitpid (GET_PID (inferior_ptid), &status, __WCLONE);
990 cloned = 1;
993 gdb_assert (pid == GET_PID (inferior_ptid)
994 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP);
996 /* Add the initial process as the first LWP to the list. */
997 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid));
998 lp = add_lwp (inferior_ptid);
999 lp->cloned = cloned;
1001 lp->stopped = 1;
1003 /* Fake the SIGSTOP that core GDB expects. */
1004 lp->status = W_STOPCODE (SIGSTOP);
1005 lp->resumed = 1;
1006 if (debug_linux_nat)
1008 fprintf_unfiltered (gdb_stdlog,
1009 "LLA: waitpid %ld, faking SIGSTOP\n", (long) pid);
1013 static int
1014 detach_callback (struct lwp_info *lp, void *data)
1016 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1018 if (debug_linux_nat && lp->status)
1019 fprintf_unfiltered (gdb_stdlog, "DC: Pending %s for %s on detach.\n",
1020 strsignal (WSTOPSIG (lp->status)),
1021 target_pid_to_str (lp->ptid));
1023 while (lp->signalled && lp->stopped)
1025 errno = 0;
1026 if (ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0,
1027 WSTOPSIG (lp->status)) < 0)
1028 error (_("Can't continue %s: %s"), target_pid_to_str (lp->ptid),
1029 safe_strerror (errno));
1031 if (debug_linux_nat)
1032 fprintf_unfiltered (gdb_stdlog,
1033 "DC: PTRACE_CONTINUE (%s, 0, %s) (OK)\n",
1034 target_pid_to_str (lp->ptid),
1035 status_to_str (lp->status));
1037 lp->stopped = 0;
1038 lp->signalled = 0;
1039 lp->status = 0;
1040 /* FIXME drow/2003-08-26: There was a call to stop_wait_callback
1041 here. But since lp->signalled was cleared above,
1042 stop_wait_callback didn't do anything; the process was left
1043 running. Shouldn't we be waiting for it to stop?
1044 I've removed the call, since stop_wait_callback now does do
1045 something when called with lp->signalled == 0. */
1047 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1050 /* We don't actually detach from the LWP that has an id equal to the
1051 overall process id just yet. */
1052 if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
1054 errno = 0;
1055 if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
1056 WSTOPSIG (lp->status)) < 0)
1057 error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
1058 safe_strerror (errno));
1060 if (debug_linux_nat)
1061 fprintf_unfiltered (gdb_stdlog,
1062 "PTRACE_DETACH (%s, %s, 0) (OK)\n",
1063 target_pid_to_str (lp->ptid),
1064 strsignal (WSTOPSIG (lp->status)));
1066 delete_lwp (lp->ptid);
1069 return 0;
1072 static void
1073 linux_nat_detach (char *args, int from_tty)
1075 iterate_over_lwps (detach_callback, NULL);
1077 /* Only the initial process should be left right now. */
1078 gdb_assert (num_lwps == 1);
1080 trap_ptid = null_ptid;
1082 /* Destroy LWP info; it's no longer valid. */
1083 init_lwp_list ();
1085 /* Restore the original signal mask. */
1086 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1087 sigemptyset (&blocked_mask);
1089 inferior_ptid = pid_to_ptid (GET_PID (inferior_ptid));
1090 linux_ops->to_detach (args, from_tty);
1093 /* Resume LP. */
1095 static int
1096 resume_callback (struct lwp_info *lp, void *data)
1098 if (lp->stopped && lp->status == 0)
1100 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
1101 0, TARGET_SIGNAL_0);
1102 if (debug_linux_nat)
1103 fprintf_unfiltered (gdb_stdlog,
1104 "RC: PTRACE_CONT %s, 0, 0 (resume sibling)\n",
1105 target_pid_to_str (lp->ptid));
1106 lp->stopped = 0;
1107 lp->step = 0;
1108 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1111 return 0;
1114 static int
1115 resume_clear_callback (struct lwp_info *lp, void *data)
1117 lp->resumed = 0;
1118 return 0;
1121 static int
1122 resume_set_callback (struct lwp_info *lp, void *data)
1124 lp->resumed = 1;
1125 return 0;
1128 static void
1129 linux_nat_resume (ptid_t ptid, int step, enum target_signal signo)
1131 struct lwp_info *lp;
1132 int resume_all;
1134 if (debug_linux_nat)
1135 fprintf_unfiltered (gdb_stdlog,
1136 "LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
1137 step ? "step" : "resume",
1138 target_pid_to_str (ptid),
1139 signo ? strsignal (signo) : "0",
1140 target_pid_to_str (inferior_ptid));
1142 prune_lwps ();
1144 /* A specific PTID means `step only this process id'. */
1145 resume_all = (PIDGET (ptid) == -1);
1147 if (resume_all)
1148 iterate_over_lwps (resume_set_callback, NULL);
1149 else
1150 iterate_over_lwps (resume_clear_callback, NULL);
1152 /* If PID is -1, it's the current inferior that should be
1153 handled specially. */
1154 if (PIDGET (ptid) == -1)
1155 ptid = inferior_ptid;
1157 lp = find_lwp_pid (ptid);
1158 gdb_assert (lp != NULL);
1160 ptid = pid_to_ptid (GET_LWP (lp->ptid));
1162 /* Remember if we're stepping. */
1163 lp->step = step;
1165 /* Mark this LWP as resumed. */
1166 lp->resumed = 1;
1168 /* If we have a pending wait status for this thread, there is no
1169 point in resuming the process. But first make sure that
1170 linux_nat_wait won't preemptively handle the event - we
1171 should never take this short-circuit if we are going to
1172 leave LP running, since we have skipped resuming all the
1173 other threads. This bit of code needs to be synchronized
1174 with linux_nat_wait. */
1176 if (lp->status && WIFSTOPPED (lp->status))
1178 int saved_signo = target_signal_from_host (WSTOPSIG (lp->status));
1180 if (signal_stop_state (saved_signo) == 0
1181 && signal_print_state (saved_signo) == 0
1182 && signal_pass_state (saved_signo) == 1)
1184 if (debug_linux_nat)
1185 fprintf_unfiltered (gdb_stdlog,
1186 "LLR: Not short circuiting for ignored "
1187 "status 0x%x\n", lp->status);
1189 /* FIXME: What should we do if we are supposed to continue
1190 this thread with a signal? */
1191 gdb_assert (signo == TARGET_SIGNAL_0);
1192 signo = saved_signo;
1193 lp->status = 0;
1197 if (lp->status)
1199 /* FIXME: What should we do if we are supposed to continue
1200 this thread with a signal? */
1201 gdb_assert (signo == TARGET_SIGNAL_0);
1203 if (debug_linux_nat)
1204 fprintf_unfiltered (gdb_stdlog,
1205 "LLR: Short circuiting for status 0x%x\n",
1206 lp->status);
1208 return;
1211 /* Mark LWP as not stopped to prevent it from being continued by
1212 resume_callback. */
1213 lp->stopped = 0;
1215 if (resume_all)
1216 iterate_over_lwps (resume_callback, NULL);
1218 linux_ops->to_resume (ptid, step, signo);
1219 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1221 if (debug_linux_nat)
1222 fprintf_unfiltered (gdb_stdlog,
1223 "LLR: %s %s, %s (resume event thread)\n",
1224 step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1225 target_pid_to_str (ptid),
1226 signo ? strsignal (signo) : "0");
1229 /* Issue kill to specified lwp. */
1231 static int tkill_failed;
1233 static int
1234 kill_lwp (int lwpid, int signo)
1236 errno = 0;
1238 /* Use tkill, if possible, in case we are using nptl threads. If tkill
1239 fails, then we are not using nptl threads and we should be using kill. */
1241 #ifdef HAVE_TKILL_SYSCALL
1242 if (!tkill_failed)
1244 int ret = syscall (__NR_tkill, lwpid, signo);
1245 if (errno != ENOSYS)
1246 return ret;
1247 errno = 0;
1248 tkill_failed = 1;
1250 #endif
1252 return kill (lwpid, signo);
1255 /* Handle a GNU/Linux extended wait response. If we see a clone
1256 event, we need to add the new LWP to our list (and not report the
1257 trap to higher layers). This function returns non-zero if the
1258 event should be ignored and we should wait again. If STOPPING is
1259 true, the new LWP remains stopped, otherwise it is continued. */
1261 static int
1262 linux_handle_extended_wait (struct lwp_info *lp, int status,
1263 int stopping)
1265 int pid = GET_LWP (lp->ptid);
1266 struct target_waitstatus *ourstatus = &lp->waitstatus;
1267 struct lwp_info *new_lp = NULL;
1268 int event = status >> 16;
1270 if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
1271 || event == PTRACE_EVENT_CLONE)
1273 unsigned long new_pid;
1274 int ret;
1276 ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
1278 /* If we haven't already seen the new PID stop, wait for it now. */
1279 if (! pull_pid_from_list (&stopped_pids, new_pid, &status))
1281 /* The new child has a pending SIGSTOP. We can't affect it until it
1282 hits the SIGSTOP, but we're already attached. */
1283 ret = my_waitpid (new_pid, &status,
1284 (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
1285 if (ret == -1)
1286 perror_with_name (_("waiting for new child"));
1287 else if (ret != new_pid)
1288 internal_error (__FILE__, __LINE__,
1289 _("wait returned unexpected PID %d"), ret);
1290 else if (!WIFSTOPPED (status))
1291 internal_error (__FILE__, __LINE__,
1292 _("wait returned unexpected status 0x%x"), status);
1295 ourstatus->value.related_pid = new_pid;
1297 if (event == PTRACE_EVENT_FORK)
1298 ourstatus->kind = TARGET_WAITKIND_FORKED;
1299 else if (event == PTRACE_EVENT_VFORK)
1300 ourstatus->kind = TARGET_WAITKIND_VFORKED;
1301 else
1303 ourstatus->kind = TARGET_WAITKIND_IGNORE;
1304 new_lp = add_lwp (BUILD_LWP (new_pid, GET_PID (inferior_ptid)));
1305 new_lp->cloned = 1;
1307 if (WSTOPSIG (status) != SIGSTOP)
1309 /* This can happen if someone starts sending signals to
1310 the new thread before it gets a chance to run, which
1311 have a lower number than SIGSTOP (e.g. SIGUSR1).
1312 This is an unlikely case, and harder to handle for
1313 fork / vfork than for clone, so we do not try - but
1314 we handle it for clone events here. We'll send
1315 the other signal on to the thread below. */
1317 new_lp->signalled = 1;
1319 else
1320 status = 0;
1322 if (stopping)
1323 new_lp->stopped = 1;
1324 else
1326 new_lp->resumed = 1;
1327 ptrace (PTRACE_CONT, lp->waitstatus.value.related_pid, 0,
1328 status ? WSTOPSIG (status) : 0);
1331 if (debug_linux_nat)
1332 fprintf_unfiltered (gdb_stdlog,
1333 "LHEW: Got clone event from LWP %ld, resuming\n",
1334 GET_LWP (lp->ptid));
1335 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1337 return 1;
1340 return 0;
1343 if (event == PTRACE_EVENT_EXEC)
1345 ourstatus->kind = TARGET_WAITKIND_EXECD;
1346 ourstatus->value.execd_pathname
1347 = xstrdup (linux_child_pid_to_exec_file (pid));
1349 if (linux_parent_pid)
1351 detach_breakpoints (linux_parent_pid);
1352 ptrace (PTRACE_DETACH, linux_parent_pid, 0, 0);
1354 linux_parent_pid = 0;
1357 return 0;
1360 internal_error (__FILE__, __LINE__,
1361 _("unknown ptrace event %d"), event);
1364 /* Wait for LP to stop. Returns the wait status, or 0 if the LWP has
1365 exited. */
1367 static int
1368 wait_lwp (struct lwp_info *lp)
1370 pid_t pid;
1371 int status;
1372 int thread_dead = 0;
1374 gdb_assert (!lp->stopped);
1375 gdb_assert (lp->status == 0);
1377 pid = my_waitpid (GET_LWP (lp->ptid), &status, 0);
1378 if (pid == -1 && errno == ECHILD)
1380 pid = my_waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
1381 if (pid == -1 && errno == ECHILD)
1383 /* The thread has previously exited. We need to delete it
1384 now because, for some vendor 2.4 kernels with NPTL
1385 support backported, there won't be an exit event unless
1386 it is the main thread. 2.6 kernels will report an exit
1387 event for each thread that exits, as expected. */
1388 thread_dead = 1;
1389 if (debug_linux_nat)
1390 fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
1391 target_pid_to_str (lp->ptid));
1395 if (!thread_dead)
1397 gdb_assert (pid == GET_LWP (lp->ptid));
1399 if (debug_linux_nat)
1401 fprintf_unfiltered (gdb_stdlog,
1402 "WL: waitpid %s received %s\n",
1403 target_pid_to_str (lp->ptid),
1404 status_to_str (status));
1408 /* Check if the thread has exited. */
1409 if (WIFEXITED (status) || WIFSIGNALED (status))
1411 thread_dead = 1;
1412 if (debug_linux_nat)
1413 fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
1414 target_pid_to_str (lp->ptid));
1417 if (thread_dead)
1419 exit_lwp (lp);
1420 return 0;
1423 gdb_assert (WIFSTOPPED (status));
1425 /* Handle GNU/Linux's extended waitstatus for trace events. */
1426 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1428 if (debug_linux_nat)
1429 fprintf_unfiltered (gdb_stdlog,
1430 "WL: Handling extended status 0x%06x\n",
1431 status);
1432 if (linux_handle_extended_wait (lp, status, 1))
1433 return wait_lwp (lp);
1436 return status;
1439 /* Save the most recent siginfo for LP. This is currently only called
1440 for SIGTRAP; some ports use the si_addr field for
1441 target_stopped_data_address. In the future, it may also be used to
1442 restore the siginfo of requeued signals. */
1444 static void
1445 save_siginfo (struct lwp_info *lp)
1447 errno = 0;
1448 ptrace (PTRACE_GETSIGINFO, GET_LWP (lp->ptid),
1449 (PTRACE_TYPE_ARG3) 0, &lp->siginfo);
1451 if (errno != 0)
1452 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1455 /* Send a SIGSTOP to LP. */
1457 static int
1458 stop_callback (struct lwp_info *lp, void *data)
1460 if (!lp->stopped && !lp->signalled)
1462 int ret;
1464 if (debug_linux_nat)
1466 fprintf_unfiltered (gdb_stdlog,
1467 "SC: kill %s **<SIGSTOP>**\n",
1468 target_pid_to_str (lp->ptid));
1470 errno = 0;
1471 ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
1472 if (debug_linux_nat)
1474 fprintf_unfiltered (gdb_stdlog,
1475 "SC: lwp kill %d %s\n",
1476 ret,
1477 errno ? safe_strerror (errno) : "ERRNO-OK");
1480 lp->signalled = 1;
1481 gdb_assert (lp->status == 0);
1484 return 0;
1487 /* Wait until LP is stopped. If DATA is non-null it is interpreted as
1488 a pointer to a set of signals to be flushed immediately. */
1490 static int
1491 stop_wait_callback (struct lwp_info *lp, void *data)
1493 sigset_t *flush_mask = data;
1495 if (!lp->stopped)
1497 int status;
1499 status = wait_lwp (lp);
1500 if (status == 0)
1501 return 0;
1503 /* Ignore any signals in FLUSH_MASK. */
1504 if (flush_mask && sigismember (flush_mask, WSTOPSIG (status)))
1506 if (!lp->signalled)
1508 lp->stopped = 1;
1509 return 0;
1512 errno = 0;
1513 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1514 if (debug_linux_nat)
1515 fprintf_unfiltered (gdb_stdlog,
1516 "PTRACE_CONT %s, 0, 0 (%s)\n",
1517 target_pid_to_str (lp->ptid),
1518 errno ? safe_strerror (errno) : "OK");
1520 return stop_wait_callback (lp, flush_mask);
1523 if (WSTOPSIG (status) != SIGSTOP)
1525 if (WSTOPSIG (status) == SIGTRAP)
1527 /* If a LWP other than the LWP that we're reporting an
1528 event for has hit a GDB breakpoint (as opposed to
1529 some random trap signal), then just arrange for it to
1530 hit it again later. We don't keep the SIGTRAP status
1531 and don't forward the SIGTRAP signal to the LWP. We
1532 will handle the current event, eventually we will
1533 resume all LWPs, and this one will get its breakpoint
1534 trap again.
1536 If we do not do this, then we run the risk that the
1537 user will delete or disable the breakpoint, but the
1538 thread will have already tripped on it. */
1540 /* Save the trap's siginfo in case we need it later. */
1541 save_siginfo (lp);
1543 /* Now resume this LWP and get the SIGSTOP event. */
1544 errno = 0;
1545 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1546 if (debug_linux_nat)
1548 fprintf_unfiltered (gdb_stdlog,
1549 "PTRACE_CONT %s, 0, 0 (%s)\n",
1550 target_pid_to_str (lp->ptid),
1551 errno ? safe_strerror (errno) : "OK");
1553 fprintf_unfiltered (gdb_stdlog,
1554 "SWC: Candidate SIGTRAP event in %s\n",
1555 target_pid_to_str (lp->ptid));
1557 /* Hold the SIGTRAP for handling by linux_nat_wait. */
1558 stop_wait_callback (lp, data);
1559 /* If there's another event, throw it back into the queue. */
1560 if (lp->status)
1562 if (debug_linux_nat)
1564 fprintf_unfiltered (gdb_stdlog,
1565 "SWC: kill %s, %s\n",
1566 target_pid_to_str (lp->ptid),
1567 status_to_str ((int) status));
1569 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
1571 /* Save the sigtrap event. */
1572 lp->status = status;
1573 return 0;
1575 else
1577 /* The thread was stopped with a signal other than
1578 SIGSTOP, and didn't accidentally trip a breakpoint. */
1580 if (debug_linux_nat)
1582 fprintf_unfiltered (gdb_stdlog,
1583 "SWC: Pending event %s in %s\n",
1584 status_to_str ((int) status),
1585 target_pid_to_str (lp->ptid));
1587 /* Now resume this LWP and get the SIGSTOP event. */
1588 errno = 0;
1589 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1590 if (debug_linux_nat)
1591 fprintf_unfiltered (gdb_stdlog,
1592 "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
1593 target_pid_to_str (lp->ptid),
1594 errno ? safe_strerror (errno) : "OK");
1596 /* Hold this event/waitstatus while we check to see if
1597 there are any more (we still want to get that SIGSTOP). */
1598 stop_wait_callback (lp, data);
1599 /* If the lp->status field is still empty, use it to hold
1600 this event. If not, then this event must be returned
1601 to the event queue of the LWP. */
1602 if (lp->status == 0)
1603 lp->status = status;
1604 else
1606 if (debug_linux_nat)
1608 fprintf_unfiltered (gdb_stdlog,
1609 "SWC: kill %s, %s\n",
1610 target_pid_to_str (lp->ptid),
1611 status_to_str ((int) status));
1613 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
1615 return 0;
1618 else
1620 /* We caught the SIGSTOP that we intended to catch, so
1621 there's no SIGSTOP pending. */
1622 lp->stopped = 1;
1623 lp->signalled = 0;
1627 return 0;
1630 /* Check whether PID has any pending signals in FLUSH_MASK. If so set
1631 the appropriate bits in PENDING, and return 1 - otherwise return 0. */
1633 static int
1634 linux_nat_has_pending (int pid, sigset_t *pending, sigset_t *flush_mask)
1636 sigset_t blocked, ignored;
1637 int i;
1639 linux_proc_pending_signals (pid, pending, &blocked, &ignored);
1641 if (!flush_mask)
1642 return 0;
1644 for (i = 1; i < NSIG; i++)
1645 if (sigismember (pending, i))
1646 if (!sigismember (flush_mask, i)
1647 || sigismember (&blocked, i)
1648 || sigismember (&ignored, i))
1649 sigdelset (pending, i);
1651 if (sigisemptyset (pending))
1652 return 0;
1654 return 1;
1657 /* DATA is interpreted as a mask of signals to flush. If LP has
1658 signals pending, and they are all in the flush mask, then arrange
1659 to flush them. LP should be stopped, as should all other threads
1660 it might share a signal queue with. */
1662 static int
1663 flush_callback (struct lwp_info *lp, void *data)
1665 sigset_t *flush_mask = data;
1666 sigset_t pending, intersection, blocked, ignored;
1667 int pid, status;
1669 /* Normally, when an LWP exits, it is removed from the LWP list. The
1670 last LWP isn't removed till later, however. So if there is only
1671 one LWP on the list, make sure it's alive. */
1672 if (lwp_list == lp && lp->next == NULL)
1673 if (!linux_nat_thread_alive (lp->ptid))
1674 return 0;
1676 /* Just because the LWP is stopped doesn't mean that new signals
1677 can't arrive from outside, so this function must be careful of
1678 race conditions. However, because all threads are stopped, we
1679 can assume that the pending mask will not shrink unless we resume
1680 the LWP, and that it will then get another signal. We can't
1681 control which one, however. */
1683 if (lp->status)
1685 if (debug_linux_nat)
1686 printf_unfiltered (_("FC: LP has pending status %06x\n"), lp->status);
1687 if (WIFSTOPPED (lp->status) && sigismember (flush_mask, WSTOPSIG (lp->status)))
1688 lp->status = 0;
1691 /* While there is a pending signal we would like to flush, continue
1692 the inferior and collect another signal. But if there's already
1693 a saved status that we don't want to flush, we can't resume the
1694 inferior - if it stopped for some other reason we wouldn't have
1695 anywhere to save the new status. In that case, we must leave the
1696 signal unflushed (and possibly generate an extra SIGINT stop).
1697 That's much less bad than losing a signal. */
1698 while (lp->status == 0
1699 && linux_nat_has_pending (GET_LWP (lp->ptid), &pending, flush_mask))
1701 int ret;
1703 errno = 0;
1704 ret = ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1705 if (debug_linux_nat)
1706 fprintf_unfiltered (gdb_stderr,
1707 "FC: Sent PTRACE_CONT, ret %d %d\n", ret, errno);
1709 lp->stopped = 0;
1710 stop_wait_callback (lp, flush_mask);
1711 if (debug_linux_nat)
1712 fprintf_unfiltered (gdb_stderr,
1713 "FC: Wait finished; saved status is %d\n",
1714 lp->status);
1717 return 0;
1720 /* Return non-zero if LP has a wait status pending. */
1722 static int
1723 status_callback (struct lwp_info *lp, void *data)
1725 /* Only report a pending wait status if we pretend that this has
1726 indeed been resumed. */
1727 return (lp->status != 0 && lp->resumed);
1730 /* Return non-zero if LP isn't stopped. */
1732 static int
1733 running_callback (struct lwp_info *lp, void *data)
1735 return (lp->stopped == 0 || (lp->status != 0 && lp->resumed));
1738 /* Count the LWP's that have had events. */
1740 static int
1741 count_events_callback (struct lwp_info *lp, void *data)
1743 int *count = data;
1745 gdb_assert (count != NULL);
1747 /* Count only LWPs that have a SIGTRAP event pending. */
1748 if (lp->status != 0
1749 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
1750 (*count)++;
1752 return 0;
1755 /* Select the LWP (if any) that is currently being single-stepped. */
1757 static int
1758 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
1760 if (lp->step && lp->status != 0)
1761 return 1;
1762 else
1763 return 0;
1766 /* Select the Nth LWP that has had a SIGTRAP event. */
1768 static int
1769 select_event_lwp_callback (struct lwp_info *lp, void *data)
1771 int *selector = data;
1773 gdb_assert (selector != NULL);
1775 /* Select only LWPs that have a SIGTRAP event pending. */
1776 if (lp->status != 0
1777 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
1778 if ((*selector)-- == 0)
1779 return 1;
1781 return 0;
1784 static int
1785 cancel_breakpoints_callback (struct lwp_info *lp, void *data)
1787 struct lwp_info *event_lp = data;
1789 /* Leave the LWP that has been elected to receive a SIGTRAP alone. */
1790 if (lp == event_lp)
1791 return 0;
1793 /* If a LWP other than the LWP that we're reporting an event for has
1794 hit a GDB breakpoint (as opposed to some random trap signal),
1795 then just arrange for it to hit it again later. We don't keep
1796 the SIGTRAP status and don't forward the SIGTRAP signal to the
1797 LWP. We will handle the current event, eventually we will resume
1798 all LWPs, and this one will get its breakpoint trap again.
1800 If we do not do this, then we run the risk that the user will
1801 delete or disable the breakpoint, but the LWP will have already
1802 tripped on it. */
1804 if (lp->status != 0
1805 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
1806 && breakpoint_inserted_here_p (read_pc_pid (lp->ptid) -
1807 gdbarch_decr_pc_after_break
1808 (current_gdbarch)))
1810 if (debug_linux_nat)
1811 fprintf_unfiltered (gdb_stdlog,
1812 "CBC: Push back breakpoint for %s\n",
1813 target_pid_to_str (lp->ptid));
1815 /* Back up the PC if necessary. */
1816 if (gdbarch_decr_pc_after_break (current_gdbarch))
1817 write_pc_pid (read_pc_pid (lp->ptid) - gdbarch_decr_pc_after_break
1818 (current_gdbarch),
1819 lp->ptid);
1821 /* Throw away the SIGTRAP. */
1822 lp->status = 0;
1825 return 0;
1828 /* Select one LWP out of those that have events pending. */
1830 static void
1831 select_event_lwp (struct lwp_info **orig_lp, int *status)
1833 int num_events = 0;
1834 int random_selector;
1835 struct lwp_info *event_lp;
1837 /* Record the wait status for the original LWP. */
1838 (*orig_lp)->status = *status;
1840 /* Give preference to any LWP that is being single-stepped. */
1841 event_lp = iterate_over_lwps (select_singlestep_lwp_callback, NULL);
1842 if (event_lp != NULL)
1844 if (debug_linux_nat)
1845 fprintf_unfiltered (gdb_stdlog,
1846 "SEL: Select single-step %s\n",
1847 target_pid_to_str (event_lp->ptid));
1849 else
1851 /* No single-stepping LWP. Select one at random, out of those
1852 which have had SIGTRAP events. */
1854 /* First see how many SIGTRAP events we have. */
1855 iterate_over_lwps (count_events_callback, &num_events);
1857 /* Now randomly pick a LWP out of those that have had a SIGTRAP. */
1858 random_selector = (int)
1859 ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
1861 if (debug_linux_nat && num_events > 1)
1862 fprintf_unfiltered (gdb_stdlog,
1863 "SEL: Found %d SIGTRAP events, selecting #%d\n",
1864 num_events, random_selector);
1866 event_lp = iterate_over_lwps (select_event_lwp_callback,
1867 &random_selector);
1870 if (event_lp != NULL)
1872 /* Switch the event LWP. */
1873 *orig_lp = event_lp;
1874 *status = event_lp->status;
1877 /* Flush the wait status for the event LWP. */
1878 (*orig_lp)->status = 0;
1881 /* Return non-zero if LP has been resumed. */
1883 static int
1884 resumed_callback (struct lwp_info *lp, void *data)
1886 return lp->resumed;
1889 /* Stop an active thread, verify it still exists, then resume it. */
1891 static int
1892 stop_and_resume_callback (struct lwp_info *lp, void *data)
1894 struct lwp_info *ptr;
1896 if (!lp->stopped && !lp->signalled)
1898 stop_callback (lp, NULL);
1899 stop_wait_callback (lp, NULL);
1900 /* Resume if the lwp still exists. */
1901 for (ptr = lwp_list; ptr; ptr = ptr->next)
1902 if (lp == ptr)
1904 resume_callback (lp, NULL);
1905 resume_set_callback (lp, NULL);
1908 return 0;
1911 static ptid_t
1912 linux_nat_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
1914 struct lwp_info *lp = NULL;
1915 int options = 0;
1916 int status = 0;
1917 pid_t pid = PIDGET (ptid);
1918 sigset_t flush_mask;
1920 /* The first time we get here after starting a new inferior, we may
1921 not have added it to the LWP list yet - this is the earliest
1922 moment at which we know its PID. */
1923 if (num_lwps == 0)
1925 gdb_assert (!is_lwp (inferior_ptid));
1927 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
1928 GET_PID (inferior_ptid));
1929 lp = add_lwp (inferior_ptid);
1930 lp->resumed = 1;
1933 sigemptyset (&flush_mask);
1935 /* Make sure SIGCHLD is blocked. */
1936 if (!sigismember (&blocked_mask, SIGCHLD))
1938 sigaddset (&blocked_mask, SIGCHLD);
1939 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
1942 retry:
1944 /* Make sure there is at least one LWP that has been resumed. */
1945 gdb_assert (iterate_over_lwps (resumed_callback, NULL));
1947 /* First check if there is a LWP with a wait status pending. */
1948 if (pid == -1)
1950 /* Any LWP that's been resumed will do. */
1951 lp = iterate_over_lwps (status_callback, NULL);
1952 if (lp)
1954 status = lp->status;
1955 lp->status = 0;
1957 if (debug_linux_nat && status)
1958 fprintf_unfiltered (gdb_stdlog,
1959 "LLW: Using pending wait status %s for %s.\n",
1960 status_to_str (status),
1961 target_pid_to_str (lp->ptid));
1964 /* But if we don't fine one, we'll have to wait, and check both
1965 cloned and uncloned processes. We start with the cloned
1966 processes. */
1967 options = __WCLONE | WNOHANG;
1969 else if (is_lwp (ptid))
1971 if (debug_linux_nat)
1972 fprintf_unfiltered (gdb_stdlog,
1973 "LLW: Waiting for specific LWP %s.\n",
1974 target_pid_to_str (ptid));
1976 /* We have a specific LWP to check. */
1977 lp = find_lwp_pid (ptid);
1978 gdb_assert (lp);
1979 status = lp->status;
1980 lp->status = 0;
1982 if (debug_linux_nat && status)
1983 fprintf_unfiltered (gdb_stdlog,
1984 "LLW: Using pending wait status %s for %s.\n",
1985 status_to_str (status),
1986 target_pid_to_str (lp->ptid));
1988 /* If we have to wait, take into account whether PID is a cloned
1989 process or not. And we have to convert it to something that
1990 the layer beneath us can understand. */
1991 options = lp->cloned ? __WCLONE : 0;
1992 pid = GET_LWP (ptid);
1995 if (status && lp->signalled)
1997 /* A pending SIGSTOP may interfere with the normal stream of
1998 events. In a typical case where interference is a problem,
1999 we have a SIGSTOP signal pending for LWP A while
2000 single-stepping it, encounter an event in LWP B, and take the
2001 pending SIGSTOP while trying to stop LWP A. After processing
2002 the event in LWP B, LWP A is continued, and we'll never see
2003 the SIGTRAP associated with the last time we were
2004 single-stepping LWP A. */
2006 /* Resume the thread. It should halt immediately returning the
2007 pending SIGSTOP. */
2008 registers_changed ();
2009 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2010 lp->step, TARGET_SIGNAL_0);
2011 if (debug_linux_nat)
2012 fprintf_unfiltered (gdb_stdlog,
2013 "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
2014 lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2015 target_pid_to_str (lp->ptid));
2016 lp->stopped = 0;
2017 gdb_assert (lp->resumed);
2019 /* This should catch the pending SIGSTOP. */
2020 stop_wait_callback (lp, NULL);
2023 set_sigint_trap (); /* Causes SIGINT to be passed on to the
2024 attached process. */
2025 set_sigio_trap ();
2027 while (status == 0)
2029 pid_t lwpid;
2031 lwpid = my_waitpid (pid, &status, options);
2032 if (lwpid > 0)
2034 gdb_assert (pid == -1 || lwpid == pid);
2036 if (debug_linux_nat)
2038 fprintf_unfiltered (gdb_stdlog,
2039 "LLW: waitpid %ld received %s\n",
2040 (long) lwpid, status_to_str (status));
2043 lp = find_lwp_pid (pid_to_ptid (lwpid));
2045 /* Check for stop events reported by a process we didn't
2046 already know about - anything not already in our LWP
2047 list.
2049 If we're expecting to receive stopped processes after
2050 fork, vfork, and clone events, then we'll just add the
2051 new one to our list and go back to waiting for the event
2052 to be reported - the stopped process might be returned
2053 from waitpid before or after the event is. */
2054 if (WIFSTOPPED (status) && !lp)
2056 linux_record_stopped_pid (lwpid, status);
2057 status = 0;
2058 continue;
2061 /* Make sure we don't report an event for the exit of an LWP not in
2062 our list, i.e. not part of the current process. This can happen
2063 if we detach from a program we original forked and then it
2064 exits. */
2065 if (!WIFSTOPPED (status) && !lp)
2067 status = 0;
2068 continue;
2071 /* NOTE drow/2003-06-17: This code seems to be meant for debugging
2072 CLONE_PTRACE processes which do not use the thread library -
2073 otherwise we wouldn't find the new LWP this way. That doesn't
2074 currently work, and the following code is currently unreachable
2075 due to the two blocks above. If it's fixed some day, this code
2076 should be broken out into a function so that we can also pick up
2077 LWPs from the new interface. */
2078 if (!lp)
2080 lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
2081 if (options & __WCLONE)
2082 lp->cloned = 1;
2084 gdb_assert (WIFSTOPPED (status)
2085 && WSTOPSIG (status) == SIGSTOP);
2086 lp->signalled = 1;
2088 if (!in_thread_list (inferior_ptid))
2090 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
2091 GET_PID (inferior_ptid));
2092 add_thread (inferior_ptid);
2095 add_thread (lp->ptid);
2098 /* Save the trap's siginfo in case we need it later. */
2099 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2100 save_siginfo (lp);
2102 /* Handle GNU/Linux's extended waitstatus for trace events. */
2103 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2105 if (debug_linux_nat)
2106 fprintf_unfiltered (gdb_stdlog,
2107 "LLW: Handling extended status 0x%06x\n",
2108 status);
2109 if (linux_handle_extended_wait (lp, status, 0))
2111 status = 0;
2112 continue;
2116 /* Check if the thread has exited. */
2117 if ((WIFEXITED (status) || WIFSIGNALED (status)) && num_lwps > 1)
2119 /* If this is the main thread, we must stop all threads and
2120 verify if they are still alive. This is because in the nptl
2121 thread model, there is no signal issued for exiting LWPs
2122 other than the main thread. We only get the main thread
2123 exit signal once all child threads have already exited.
2124 If we stop all the threads and use the stop_wait_callback
2125 to check if they have exited we can determine whether this
2126 signal should be ignored or whether it means the end of the
2127 debugged application, regardless of which threading model
2128 is being used. */
2129 if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
2131 lp->stopped = 1;
2132 iterate_over_lwps (stop_and_resume_callback, NULL);
2135 if (debug_linux_nat)
2136 fprintf_unfiltered (gdb_stdlog,
2137 "LLW: %s exited.\n",
2138 target_pid_to_str (lp->ptid));
2140 exit_lwp (lp);
2142 /* If there is at least one more LWP, then the exit signal
2143 was not the end of the debugged application and should be
2144 ignored. */
2145 if (num_lwps > 0)
2147 /* Make sure there is at least one thread running. */
2148 gdb_assert (iterate_over_lwps (running_callback, NULL));
2150 /* Discard the event. */
2151 status = 0;
2152 continue;
2156 /* Check if the current LWP has previously exited. In the nptl
2157 thread model, LWPs other than the main thread do not issue
2158 signals when they exit so we must check whenever the thread
2159 has stopped. A similar check is made in stop_wait_callback(). */
2160 if (num_lwps > 1 && !linux_nat_thread_alive (lp->ptid))
2162 if (debug_linux_nat)
2163 fprintf_unfiltered (gdb_stdlog,
2164 "LLW: %s exited.\n",
2165 target_pid_to_str (lp->ptid));
2167 exit_lwp (lp);
2169 /* Make sure there is at least one thread running. */
2170 gdb_assert (iterate_over_lwps (running_callback, NULL));
2172 /* Discard the event. */
2173 status = 0;
2174 continue;
2177 /* Make sure we don't report a SIGSTOP that we sent
2178 ourselves in an attempt to stop an LWP. */
2179 if (lp->signalled
2180 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2182 if (debug_linux_nat)
2183 fprintf_unfiltered (gdb_stdlog,
2184 "LLW: Delayed SIGSTOP caught for %s.\n",
2185 target_pid_to_str (lp->ptid));
2187 /* This is a delayed SIGSTOP. */
2188 lp->signalled = 0;
2190 registers_changed ();
2191 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2192 lp->step, TARGET_SIGNAL_0);
2193 if (debug_linux_nat)
2194 fprintf_unfiltered (gdb_stdlog,
2195 "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
2196 lp->step ?
2197 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2198 target_pid_to_str (lp->ptid));
2200 lp->stopped = 0;
2201 gdb_assert (lp->resumed);
2203 /* Discard the event. */
2204 status = 0;
2205 continue;
2208 break;
2211 if (pid == -1)
2213 /* Alternate between checking cloned and uncloned processes. */
2214 options ^= __WCLONE;
2216 /* And suspend every time we have checked both. */
2217 if (options & __WCLONE)
2218 sigsuspend (&suspend_mask);
2221 /* We shouldn't end up here unless we want to try again. */
2222 gdb_assert (status == 0);
2225 clear_sigio_trap ();
2226 clear_sigint_trap ();
2228 gdb_assert (lp);
2230 /* Don't report signals that GDB isn't interested in, such as
2231 signals that are neither printed nor stopped upon. Stopping all
2232 threads can be a bit time-consuming so if we want decent
2233 performance with heavily multi-threaded programs, especially when
2234 they're using a high frequency timer, we'd better avoid it if we
2235 can. */
2237 if (WIFSTOPPED (status))
2239 int signo = target_signal_from_host (WSTOPSIG (status));
2241 /* If we get a signal while single-stepping, we may need special
2242 care, e.g. to skip the signal handler. Defer to common code. */
2243 if (!lp->step
2244 && signal_stop_state (signo) == 0
2245 && signal_print_state (signo) == 0
2246 && signal_pass_state (signo) == 1)
2248 /* FIMXE: kettenis/2001-06-06: Should we resume all threads
2249 here? It is not clear we should. GDB may not expect
2250 other threads to run. On the other hand, not resuming
2251 newly attached threads may cause an unwanted delay in
2252 getting them running. */
2253 registers_changed ();
2254 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2255 lp->step, signo);
2256 if (debug_linux_nat)
2257 fprintf_unfiltered (gdb_stdlog,
2258 "LLW: %s %s, %s (preempt 'handle')\n",
2259 lp->step ?
2260 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2261 target_pid_to_str (lp->ptid),
2262 signo ? strsignal (signo) : "0");
2263 lp->stopped = 0;
2264 status = 0;
2265 goto retry;
2268 if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
2270 /* If ^C/BREAK is typed at the tty/console, SIGINT gets
2271 forwarded to the entire process group, that is, all LWP's
2272 will receive it. Since we only want to report it once,
2273 we try to flush it from all LWPs except this one. */
2274 sigaddset (&flush_mask, SIGINT);
2278 /* This LWP is stopped now. */
2279 lp->stopped = 1;
2281 if (debug_linux_nat)
2282 fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
2283 status_to_str (status), target_pid_to_str (lp->ptid));
2285 /* Now stop all other LWP's ... */
2286 iterate_over_lwps (stop_callback, NULL);
2288 /* ... and wait until all of them have reported back that they're no
2289 longer running. */
2290 iterate_over_lwps (stop_wait_callback, &flush_mask);
2291 iterate_over_lwps (flush_callback, &flush_mask);
2293 /* If we're not waiting for a specific LWP, choose an event LWP from
2294 among those that have had events. Giving equal priority to all
2295 LWPs that have had events helps prevent starvation. */
2296 if (pid == -1)
2297 select_event_lwp (&lp, &status);
2299 /* Now that we've selected our final event LWP, cancel any
2300 breakpoints in other LWPs that have hit a GDB breakpoint. See
2301 the comment in cancel_breakpoints_callback to find out why. */
2302 iterate_over_lwps (cancel_breakpoints_callback, lp);
2304 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2306 trap_ptid = lp->ptid;
2307 if (debug_linux_nat)
2308 fprintf_unfiltered (gdb_stdlog,
2309 "LLW: trap_ptid is %s.\n",
2310 target_pid_to_str (trap_ptid));
2312 else
2313 trap_ptid = null_ptid;
2315 if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
2317 *ourstatus = lp->waitstatus;
2318 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
2320 else
2321 store_waitstatus (ourstatus, status);
2323 return lp->ptid;
2326 static int
2327 kill_callback (struct lwp_info *lp, void *data)
2329 errno = 0;
2330 ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
2331 if (debug_linux_nat)
2332 fprintf_unfiltered (gdb_stdlog,
2333 "KC: PTRACE_KILL %s, 0, 0 (%s)\n",
2334 target_pid_to_str (lp->ptid),
2335 errno ? safe_strerror (errno) : "OK");
2337 return 0;
2340 static int
2341 kill_wait_callback (struct lwp_info *lp, void *data)
2343 pid_t pid;
2345 /* We must make sure that there are no pending events (delayed
2346 SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
2347 program doesn't interfere with any following debugging session. */
2349 /* For cloned processes we must check both with __WCLONE and
2350 without, since the exit status of a cloned process isn't reported
2351 with __WCLONE. */
2352 if (lp->cloned)
2356 pid = my_waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
2357 if (pid != (pid_t) -1)
2359 if (debug_linux_nat)
2360 fprintf_unfiltered (gdb_stdlog,
2361 "KWC: wait %s received unknown.\n",
2362 target_pid_to_str (lp->ptid));
2363 /* The Linux kernel sometimes fails to kill a thread
2364 completely after PTRACE_KILL; that goes from the stop
2365 point in do_fork out to the one in
2366 get_signal_to_deliever and waits again. So kill it
2367 again. */
2368 kill_callback (lp, NULL);
2371 while (pid == GET_LWP (lp->ptid));
2373 gdb_assert (pid == -1 && errno == ECHILD);
2378 pid = my_waitpid (GET_LWP (lp->ptid), NULL, 0);
2379 if (pid != (pid_t) -1)
2381 if (debug_linux_nat)
2382 fprintf_unfiltered (gdb_stdlog,
2383 "KWC: wait %s received unk.\n",
2384 target_pid_to_str (lp->ptid));
2385 /* See the call to kill_callback above. */
2386 kill_callback (lp, NULL);
2389 while (pid == GET_LWP (lp->ptid));
2391 gdb_assert (pid == -1 && errno == ECHILD);
2392 return 0;
2395 static void
2396 linux_nat_kill (void)
2398 struct target_waitstatus last;
2399 ptid_t last_ptid;
2400 int status;
2402 /* If we're stopped while forking and we haven't followed yet,
2403 kill the other task. We need to do this first because the
2404 parent will be sleeping if this is a vfork. */
2406 get_last_target_status (&last_ptid, &last);
2408 if (last.kind == TARGET_WAITKIND_FORKED
2409 || last.kind == TARGET_WAITKIND_VFORKED)
2411 ptrace (PT_KILL, last.value.related_pid, 0, 0);
2412 wait (&status);
2415 if (forks_exist_p ())
2416 linux_fork_killall ();
2417 else
2419 /* Kill all LWP's ... */
2420 iterate_over_lwps (kill_callback, NULL);
2422 /* ... and wait until we've flushed all events. */
2423 iterate_over_lwps (kill_wait_callback, NULL);
2426 target_mourn_inferior ();
2429 static void
2430 linux_nat_mourn_inferior (void)
2432 trap_ptid = null_ptid;
2434 /* Destroy LWP info; it's no longer valid. */
2435 init_lwp_list ();
2437 /* Restore the original signal mask. */
2438 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
2439 sigemptyset (&blocked_mask);
2441 if (! forks_exist_p ())
2442 /* Normal case, no other forks available. */
2443 linux_ops->to_mourn_inferior ();
2444 else
2445 /* Multi-fork case. The current inferior_ptid has exited, but
2446 there are other viable forks to debug. Delete the exiting
2447 one and context-switch to the first available. */
2448 linux_fork_mourn_inferior ();
2451 static LONGEST
2452 linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
2453 const char *annex, gdb_byte *readbuf,
2454 const gdb_byte *writebuf,
2455 ULONGEST offset, LONGEST len)
2457 struct cleanup *old_chain = save_inferior_ptid ();
2458 LONGEST xfer;
2460 if (is_lwp (inferior_ptid))
2461 inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
2463 xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
2464 offset, len);
2466 do_cleanups (old_chain);
2467 return xfer;
2470 static int
2471 linux_nat_thread_alive (ptid_t ptid)
2473 gdb_assert (is_lwp (ptid));
2475 errno = 0;
2476 ptrace (PTRACE_PEEKUSER, GET_LWP (ptid), 0, 0);
2477 if (debug_linux_nat)
2478 fprintf_unfiltered (gdb_stdlog,
2479 "LLTA: PTRACE_PEEKUSER %s, 0, 0 (%s)\n",
2480 target_pid_to_str (ptid),
2481 errno ? safe_strerror (errno) : "OK");
2483 /* Not every Linux kernel implements PTRACE_PEEKUSER. But we can
2484 handle that case gracefully since ptrace will first do a lookup
2485 for the process based upon the passed-in pid. If that fails we
2486 will get either -ESRCH or -EPERM, otherwise the child exists and
2487 is alive. */
2488 if (errno == ESRCH || errno == EPERM)
2489 return 0;
2491 return 1;
2494 static char *
2495 linux_nat_pid_to_str (ptid_t ptid)
2497 static char buf[64];
2499 if (lwp_list && lwp_list->next && is_lwp (ptid))
2501 snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
2502 return buf;
2505 return normal_pid_to_str (ptid);
2508 static void
2509 sigchld_handler (int signo)
2511 /* Do nothing. The only reason for this handler is that it allows
2512 us to use sigsuspend in linux_nat_wait above to wait for the
2513 arrival of a SIGCHLD. */
2516 /* Accepts an integer PID; Returns a string representing a file that
2517 can be opened to get the symbols for the child process. */
2519 static char *
2520 linux_child_pid_to_exec_file (int pid)
2522 char *name1, *name2;
2524 name1 = xmalloc (MAXPATHLEN);
2525 name2 = xmalloc (MAXPATHLEN);
2526 make_cleanup (xfree, name1);
2527 make_cleanup (xfree, name2);
2528 memset (name2, 0, MAXPATHLEN);
2530 sprintf (name1, "/proc/%d/exe", pid);
2531 if (readlink (name1, name2, MAXPATHLEN) > 0)
2532 return name2;
2533 else
2534 return name1;
2537 /* Service function for corefiles and info proc. */
2539 static int
2540 read_mapping (FILE *mapfile,
2541 long long *addr,
2542 long long *endaddr,
2543 char *permissions,
2544 long long *offset,
2545 char *device, long long *inode, char *filename)
2547 int ret = fscanf (mapfile, "%llx-%llx %s %llx %s %llx",
2548 addr, endaddr, permissions, offset, device, inode);
2550 filename[0] = '\0';
2551 if (ret > 0 && ret != EOF)
2553 /* Eat everything up to EOL for the filename. This will prevent
2554 weird filenames (such as one with embedded whitespace) from
2555 confusing this code. It also makes this code more robust in
2556 respect to annotations the kernel may add after the filename.
2558 Note the filename is used for informational purposes
2559 only. */
2560 ret += fscanf (mapfile, "%[^\n]\n", filename);
2563 return (ret != 0 && ret != EOF);
2566 /* Fills the "to_find_memory_regions" target vector. Lists the memory
2567 regions in the inferior for a corefile. */
2569 static int
2570 linux_nat_find_memory_regions (int (*func) (CORE_ADDR,
2571 unsigned long,
2572 int, int, int, void *), void *obfd)
2574 long long pid = PIDGET (inferior_ptid);
2575 char mapsfilename[MAXPATHLEN];
2576 FILE *mapsfile;
2577 long long addr, endaddr, size, offset, inode;
2578 char permissions[8], device[8], filename[MAXPATHLEN];
2579 int read, write, exec;
2580 int ret;
2582 /* Compose the filename for the /proc memory map, and open it. */
2583 sprintf (mapsfilename, "/proc/%lld/maps", pid);
2584 if ((mapsfile = fopen (mapsfilename, "r")) == NULL)
2585 error (_("Could not open %s."), mapsfilename);
2587 if (info_verbose)
2588 fprintf_filtered (gdb_stdout,
2589 "Reading memory regions from %s\n", mapsfilename);
2591 /* Now iterate until end-of-file. */
2592 while (read_mapping (mapsfile, &addr, &endaddr, &permissions[0],
2593 &offset, &device[0], &inode, &filename[0]))
2595 size = endaddr - addr;
2597 /* Get the segment's permissions. */
2598 read = (strchr (permissions, 'r') != 0);
2599 write = (strchr (permissions, 'w') != 0);
2600 exec = (strchr (permissions, 'x') != 0);
2602 if (info_verbose)
2604 fprintf_filtered (gdb_stdout,
2605 "Save segment, %lld bytes at 0x%s (%c%c%c)",
2606 size, paddr_nz (addr),
2607 read ? 'r' : ' ',
2608 write ? 'w' : ' ', exec ? 'x' : ' ');
2609 if (filename[0])
2610 fprintf_filtered (gdb_stdout, " for %s", filename);
2611 fprintf_filtered (gdb_stdout, "\n");
2614 /* Invoke the callback function to create the corefile
2615 segment. */
2616 func (addr, size, read, write, exec, obfd);
2618 fclose (mapsfile);
2619 return 0;
2622 /* Records the thread's register state for the corefile note
2623 section. */
2625 static char *
2626 linux_nat_do_thread_registers (bfd *obfd, ptid_t ptid,
2627 char *note_data, int *note_size)
2629 gdb_gregset_t gregs;
2630 gdb_fpregset_t fpregs;
2631 #ifdef FILL_FPXREGSET
2632 gdb_fpxregset_t fpxregs;
2633 #endif
2634 unsigned long lwp = ptid_get_lwp (ptid);
2635 struct regcache *regcache = get_thread_regcache (ptid);
2636 struct gdbarch *gdbarch = get_regcache_arch (regcache);
2637 const struct regset *regset;
2638 int core_regset_p;
2639 struct cleanup *old_chain;
2641 old_chain = save_inferior_ptid ();
2642 inferior_ptid = ptid;
2643 target_fetch_registers (regcache, -1);
2644 do_cleanups (old_chain);
2646 core_regset_p = gdbarch_regset_from_core_section_p (gdbarch);
2647 if (core_regset_p
2648 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg",
2649 sizeof (gregs))) != NULL
2650 && regset->collect_regset != NULL)
2651 regset->collect_regset (regset, regcache, -1,
2652 &gregs, sizeof (gregs));
2653 else
2654 fill_gregset (regcache, &gregs, -1);
2656 note_data = (char *) elfcore_write_prstatus (obfd,
2657 note_data,
2658 note_size,
2659 lwp,
2660 stop_signal, &gregs);
2662 if (core_regset_p
2663 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg2",
2664 sizeof (fpregs))) != NULL
2665 && regset->collect_regset != NULL)
2666 regset->collect_regset (regset, regcache, -1,
2667 &fpregs, sizeof (fpregs));
2668 else
2669 fill_fpregset (regcache, &fpregs, -1);
2671 note_data = (char *) elfcore_write_prfpreg (obfd,
2672 note_data,
2673 note_size,
2674 &fpregs, sizeof (fpregs));
2676 #ifdef FILL_FPXREGSET
2677 if (core_regset_p
2678 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg-xfp",
2679 sizeof (fpxregs))) != NULL
2680 && regset->collect_regset != NULL)
2681 regset->collect_regset (regset, regcache, -1,
2682 &fpxregs, sizeof (fpxregs));
2683 else
2684 fill_fpxregset (regcache, &fpxregs, -1);
2686 note_data = (char *) elfcore_write_prxfpreg (obfd,
2687 note_data,
2688 note_size,
2689 &fpxregs, sizeof (fpxregs));
2690 #endif
2691 return note_data;
2694 struct linux_nat_corefile_thread_data
2696 bfd *obfd;
2697 char *note_data;
2698 int *note_size;
2699 int num_notes;
2702 /* Called by gdbthread.c once per thread. Records the thread's
2703 register state for the corefile note section. */
2705 static int
2706 linux_nat_corefile_thread_callback (struct lwp_info *ti, void *data)
2708 struct linux_nat_corefile_thread_data *args = data;
2710 args->note_data = linux_nat_do_thread_registers (args->obfd,
2711 ti->ptid,
2712 args->note_data,
2713 args->note_size);
2714 args->num_notes++;
2716 return 0;
2719 /* Records the register state for the corefile note section. */
2721 static char *
2722 linux_nat_do_registers (bfd *obfd, ptid_t ptid,
2723 char *note_data, int *note_size)
2725 return linux_nat_do_thread_registers (obfd,
2726 ptid_build (ptid_get_pid (inferior_ptid),
2727 ptid_get_pid (inferior_ptid),
2729 note_data, note_size);
2732 /* Fills the "to_make_corefile_note" target vector. Builds the note
2733 section for a corefile, and returns it in a malloc buffer. */
2735 static char *
2736 linux_nat_make_corefile_notes (bfd *obfd, int *note_size)
2738 struct linux_nat_corefile_thread_data thread_args;
2739 struct cleanup *old_chain;
2740 /* The variable size must be >= sizeof (prpsinfo_t.pr_fname). */
2741 char fname[16] = { '\0' };
2742 /* The variable size must be >= sizeof (prpsinfo_t.pr_psargs). */
2743 char psargs[80] = { '\0' };
2744 char *note_data = NULL;
2745 ptid_t current_ptid = inferior_ptid;
2746 gdb_byte *auxv;
2747 int auxv_len;
2749 if (get_exec_file (0))
2751 strncpy (fname, strrchr (get_exec_file (0), '/') + 1, sizeof (fname));
2752 strncpy (psargs, get_exec_file (0), sizeof (psargs));
2753 if (get_inferior_args ())
2755 char *string_end;
2756 char *psargs_end = psargs + sizeof (psargs);
2758 /* linux_elfcore_write_prpsinfo () handles zero unterminated
2759 strings fine. */
2760 string_end = memchr (psargs, 0, sizeof (psargs));
2761 if (string_end != NULL)
2763 *string_end++ = ' ';
2764 strncpy (string_end, get_inferior_args (),
2765 psargs_end - string_end);
2768 note_data = (char *) elfcore_write_prpsinfo (obfd,
2769 note_data,
2770 note_size, fname, psargs);
2773 /* Dump information for threads. */
2774 thread_args.obfd = obfd;
2775 thread_args.note_data = note_data;
2776 thread_args.note_size = note_size;
2777 thread_args.num_notes = 0;
2778 iterate_over_lwps (linux_nat_corefile_thread_callback, &thread_args);
2779 if (thread_args.num_notes == 0)
2781 /* iterate_over_threads didn't come up with any threads; just
2782 use inferior_ptid. */
2783 note_data = linux_nat_do_registers (obfd, inferior_ptid,
2784 note_data, note_size);
2786 else
2788 note_data = thread_args.note_data;
2791 auxv_len = target_read_alloc (&current_target, TARGET_OBJECT_AUXV,
2792 NULL, &auxv);
2793 if (auxv_len > 0)
2795 note_data = elfcore_write_note (obfd, note_data, note_size,
2796 "CORE", NT_AUXV, auxv, auxv_len);
2797 xfree (auxv);
2800 make_cleanup (xfree, note_data);
2801 return note_data;
2804 /* Implement the "info proc" command. */
2806 static void
2807 linux_nat_info_proc_cmd (char *args, int from_tty)
2809 long long pid = PIDGET (inferior_ptid);
2810 FILE *procfile;
2811 char **argv = NULL;
2812 char buffer[MAXPATHLEN];
2813 char fname1[MAXPATHLEN], fname2[MAXPATHLEN];
2814 int cmdline_f = 1;
2815 int cwd_f = 1;
2816 int exe_f = 1;
2817 int mappings_f = 0;
2818 int environ_f = 0;
2819 int status_f = 0;
2820 int stat_f = 0;
2821 int all = 0;
2822 struct stat dummy;
2824 if (args)
2826 /* Break up 'args' into an argv array. */
2827 if ((argv = buildargv (args)) == NULL)
2828 nomem (0);
2829 else
2830 make_cleanup_freeargv (argv);
2832 while (argv != NULL && *argv != NULL)
2834 if (isdigit (argv[0][0]))
2836 pid = strtoul (argv[0], NULL, 10);
2838 else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
2840 mappings_f = 1;
2842 else if (strcmp (argv[0], "status") == 0)
2844 status_f = 1;
2846 else if (strcmp (argv[0], "stat") == 0)
2848 stat_f = 1;
2850 else if (strcmp (argv[0], "cmd") == 0)
2852 cmdline_f = 1;
2854 else if (strncmp (argv[0], "exe", strlen (argv[0])) == 0)
2856 exe_f = 1;
2858 else if (strcmp (argv[0], "cwd") == 0)
2860 cwd_f = 1;
2862 else if (strncmp (argv[0], "all", strlen (argv[0])) == 0)
2864 all = 1;
2866 else
2868 /* [...] (future options here) */
2870 argv++;
2872 if (pid == 0)
2873 error (_("No current process: you must name one."));
2875 sprintf (fname1, "/proc/%lld", pid);
2876 if (stat (fname1, &dummy) != 0)
2877 error (_("No /proc directory: '%s'"), fname1);
2879 printf_filtered (_("process %lld\n"), pid);
2880 if (cmdline_f || all)
2882 sprintf (fname1, "/proc/%lld/cmdline", pid);
2883 if ((procfile = fopen (fname1, "r")) != NULL)
2885 fgets (buffer, sizeof (buffer), procfile);
2886 printf_filtered ("cmdline = '%s'\n", buffer);
2887 fclose (procfile);
2889 else
2890 warning (_("unable to open /proc file '%s'"), fname1);
2892 if (cwd_f || all)
2894 sprintf (fname1, "/proc/%lld/cwd", pid);
2895 memset (fname2, 0, sizeof (fname2));
2896 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
2897 printf_filtered ("cwd = '%s'\n", fname2);
2898 else
2899 warning (_("unable to read link '%s'"), fname1);
2901 if (exe_f || all)
2903 sprintf (fname1, "/proc/%lld/exe", pid);
2904 memset (fname2, 0, sizeof (fname2));
2905 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
2906 printf_filtered ("exe = '%s'\n", fname2);
2907 else
2908 warning (_("unable to read link '%s'"), fname1);
2910 if (mappings_f || all)
2912 sprintf (fname1, "/proc/%lld/maps", pid);
2913 if ((procfile = fopen (fname1, "r")) != NULL)
2915 long long addr, endaddr, size, offset, inode;
2916 char permissions[8], device[8], filename[MAXPATHLEN];
2918 printf_filtered (_("Mapped address spaces:\n\n"));
2919 if (gdbarch_addr_bit (current_gdbarch) == 32)
2921 printf_filtered ("\t%10s %10s %10s %10s %7s\n",
2922 "Start Addr",
2923 " End Addr",
2924 " Size", " Offset", "objfile");
2926 else
2928 printf_filtered (" %18s %18s %10s %10s %7s\n",
2929 "Start Addr",
2930 " End Addr",
2931 " Size", " Offset", "objfile");
2934 while (read_mapping (procfile, &addr, &endaddr, &permissions[0],
2935 &offset, &device[0], &inode, &filename[0]))
2937 size = endaddr - addr;
2939 /* FIXME: carlton/2003-08-27: Maybe the printf_filtered
2940 calls here (and possibly above) should be abstracted
2941 out into their own functions? Andrew suggests using
2942 a generic local_address_string instead to print out
2943 the addresses; that makes sense to me, too. */
2945 if (gdbarch_addr_bit (current_gdbarch) == 32)
2947 printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
2948 (unsigned long) addr, /* FIXME: pr_addr */
2949 (unsigned long) endaddr,
2950 (int) size,
2951 (unsigned int) offset,
2952 filename[0] ? filename : "");
2954 else
2956 printf_filtered (" %#18lx %#18lx %#10x %#10x %7s\n",
2957 (unsigned long) addr, /* FIXME: pr_addr */
2958 (unsigned long) endaddr,
2959 (int) size,
2960 (unsigned int) offset,
2961 filename[0] ? filename : "");
2965 fclose (procfile);
2967 else
2968 warning (_("unable to open /proc file '%s'"), fname1);
2970 if (status_f || all)
2972 sprintf (fname1, "/proc/%lld/status", pid);
2973 if ((procfile = fopen (fname1, "r")) != NULL)
2975 while (fgets (buffer, sizeof (buffer), procfile) != NULL)
2976 puts_filtered (buffer);
2977 fclose (procfile);
2979 else
2980 warning (_("unable to open /proc file '%s'"), fname1);
2982 if (stat_f || all)
2984 sprintf (fname1, "/proc/%lld/stat", pid);
2985 if ((procfile = fopen (fname1, "r")) != NULL)
2987 int itmp;
2988 char ctmp;
2989 long ltmp;
2991 if (fscanf (procfile, "%d ", &itmp) > 0)
2992 printf_filtered (_("Process: %d\n"), itmp);
2993 if (fscanf (procfile, "(%[^)]) ", &buffer[0]) > 0)
2994 printf_filtered (_("Exec file: %s\n"), buffer);
2995 if (fscanf (procfile, "%c ", &ctmp) > 0)
2996 printf_filtered (_("State: %c\n"), ctmp);
2997 if (fscanf (procfile, "%d ", &itmp) > 0)
2998 printf_filtered (_("Parent process: %d\n"), itmp);
2999 if (fscanf (procfile, "%d ", &itmp) > 0)
3000 printf_filtered (_("Process group: %d\n"), itmp);
3001 if (fscanf (procfile, "%d ", &itmp) > 0)
3002 printf_filtered (_("Session id: %d\n"), itmp);
3003 if (fscanf (procfile, "%d ", &itmp) > 0)
3004 printf_filtered (_("TTY: %d\n"), itmp);
3005 if (fscanf (procfile, "%d ", &itmp) > 0)
3006 printf_filtered (_("TTY owner process group: %d\n"), itmp);
3007 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3008 printf_filtered (_("Flags: 0x%lx\n"), ltmp);
3009 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3010 printf_filtered (_("Minor faults (no memory page): %lu\n"),
3011 (unsigned long) ltmp);
3012 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3013 printf_filtered (_("Minor faults, children: %lu\n"),
3014 (unsigned long) ltmp);
3015 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3016 printf_filtered (_("Major faults (memory page faults): %lu\n"),
3017 (unsigned long) ltmp);
3018 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3019 printf_filtered (_("Major faults, children: %lu\n"),
3020 (unsigned long) ltmp);
3021 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3022 printf_filtered (_("utime: %ld\n"), ltmp);
3023 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3024 printf_filtered (_("stime: %ld\n"), ltmp);
3025 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3026 printf_filtered (_("utime, children: %ld\n"), ltmp);
3027 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3028 printf_filtered (_("stime, children: %ld\n"), ltmp);
3029 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3030 printf_filtered (_("jiffies remaining in current time slice: %ld\n"),
3031 ltmp);
3032 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3033 printf_filtered (_("'nice' value: %ld\n"), ltmp);
3034 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3035 printf_filtered (_("jiffies until next timeout: %lu\n"),
3036 (unsigned long) ltmp);
3037 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3038 printf_filtered (_("jiffies until next SIGALRM: %lu\n"),
3039 (unsigned long) ltmp);
3040 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3041 printf_filtered (_("start time (jiffies since system boot): %ld\n"),
3042 ltmp);
3043 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3044 printf_filtered (_("Virtual memory size: %lu\n"),
3045 (unsigned long) ltmp);
3046 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3047 printf_filtered (_("Resident set size: %lu\n"), (unsigned long) ltmp);
3048 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3049 printf_filtered (_("rlim: %lu\n"), (unsigned long) ltmp);
3050 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3051 printf_filtered (_("Start of text: 0x%lx\n"), ltmp);
3052 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3053 printf_filtered (_("End of text: 0x%lx\n"), ltmp);
3054 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3055 printf_filtered (_("Start of stack: 0x%lx\n"), ltmp);
3056 #if 0 /* Don't know how architecture-dependent the rest is...
3057 Anyway the signal bitmap info is available from "status". */
3058 if (fscanf (procfile, "%lu ", &ltmp) > 0) /* FIXME arch? */
3059 printf_filtered (_("Kernel stack pointer: 0x%lx\n"), ltmp);
3060 if (fscanf (procfile, "%lu ", &ltmp) > 0) /* FIXME arch? */
3061 printf_filtered (_("Kernel instr pointer: 0x%lx\n"), ltmp);
3062 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3063 printf_filtered (_("Pending signals bitmap: 0x%lx\n"), ltmp);
3064 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3065 printf_filtered (_("Blocked signals bitmap: 0x%lx\n"), ltmp);
3066 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3067 printf_filtered (_("Ignored signals bitmap: 0x%lx\n"), ltmp);
3068 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3069 printf_filtered (_("Catched signals bitmap: 0x%lx\n"), ltmp);
3070 if (fscanf (procfile, "%lu ", &ltmp) > 0) /* FIXME arch? */
3071 printf_filtered (_("wchan (system call): 0x%lx\n"), ltmp);
3072 #endif
3073 fclose (procfile);
3075 else
3076 warning (_("unable to open /proc file '%s'"), fname1);
3080 /* Implement the to_xfer_partial interface for memory reads using the /proc
3081 filesystem. Because we can use a single read() call for /proc, this
3082 can be much more efficient than banging away at PTRACE_PEEKTEXT,
3083 but it doesn't support writes. */
3085 static LONGEST
3086 linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
3087 const char *annex, gdb_byte *readbuf,
3088 const gdb_byte *writebuf,
3089 ULONGEST offset, LONGEST len)
3091 LONGEST ret;
3092 int fd;
3093 char filename[64];
3095 if (object != TARGET_OBJECT_MEMORY || !readbuf)
3096 return 0;
3098 /* Don't bother for one word. */
3099 if (len < 3 * sizeof (long))
3100 return 0;
3102 /* We could keep this file open and cache it - possibly one per
3103 thread. That requires some juggling, but is even faster. */
3104 sprintf (filename, "/proc/%d/mem", PIDGET (inferior_ptid));
3105 fd = open (filename, O_RDONLY | O_LARGEFILE);
3106 if (fd == -1)
3107 return 0;
3109 /* If pread64 is available, use it. It's faster if the kernel
3110 supports it (only one syscall), and it's 64-bit safe even on
3111 32-bit platforms (for instance, SPARC debugging a SPARC64
3112 application). */
3113 #ifdef HAVE_PREAD64
3114 if (pread64 (fd, readbuf, len, offset) != len)
3115 #else
3116 if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
3117 #endif
3118 ret = 0;
3119 else
3120 ret = len;
3122 close (fd);
3123 return ret;
3126 /* Parse LINE as a signal set and add its set bits to SIGS. */
3128 static void
3129 add_line_to_sigset (const char *line, sigset_t *sigs)
3131 int len = strlen (line) - 1;
3132 const char *p;
3133 int signum;
3135 if (line[len] != '\n')
3136 error (_("Could not parse signal set: %s"), line);
3138 p = line;
3139 signum = len * 4;
3140 while (len-- > 0)
3142 int digit;
3144 if (*p >= '0' && *p <= '9')
3145 digit = *p - '0';
3146 else if (*p >= 'a' && *p <= 'f')
3147 digit = *p - 'a' + 10;
3148 else
3149 error (_("Could not parse signal set: %s"), line);
3151 signum -= 4;
3153 if (digit & 1)
3154 sigaddset (sigs, signum + 1);
3155 if (digit & 2)
3156 sigaddset (sigs, signum + 2);
3157 if (digit & 4)
3158 sigaddset (sigs, signum + 3);
3159 if (digit & 8)
3160 sigaddset (sigs, signum + 4);
3162 p++;
3166 /* Find process PID's pending signals from /proc/pid/status and set
3167 SIGS to match. */
3169 void
3170 linux_proc_pending_signals (int pid, sigset_t *pending, sigset_t *blocked, sigset_t *ignored)
3172 FILE *procfile;
3173 char buffer[MAXPATHLEN], fname[MAXPATHLEN];
3174 int signum;
3176 sigemptyset (pending);
3177 sigemptyset (blocked);
3178 sigemptyset (ignored);
3179 sprintf (fname, "/proc/%d/status", pid);
3180 procfile = fopen (fname, "r");
3181 if (procfile == NULL)
3182 error (_("Could not open %s"), fname);
3184 while (fgets (buffer, MAXPATHLEN, procfile) != NULL)
3186 /* Normal queued signals are on the SigPnd line in the status
3187 file. However, 2.6 kernels also have a "shared" pending
3188 queue for delivering signals to a thread group, so check for
3189 a ShdPnd line also.
3191 Unfortunately some Red Hat kernels include the shared pending
3192 queue but not the ShdPnd status field. */
3194 if (strncmp (buffer, "SigPnd:\t", 8) == 0)
3195 add_line_to_sigset (buffer + 8, pending);
3196 else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
3197 add_line_to_sigset (buffer + 8, pending);
3198 else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
3199 add_line_to_sigset (buffer + 8, blocked);
3200 else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
3201 add_line_to_sigset (buffer + 8, ignored);
3204 fclose (procfile);
3207 static LONGEST
3208 linux_xfer_partial (struct target_ops *ops, enum target_object object,
3209 const char *annex, gdb_byte *readbuf,
3210 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
3212 LONGEST xfer;
3214 if (object == TARGET_OBJECT_AUXV)
3215 return procfs_xfer_auxv (ops, object, annex, readbuf, writebuf,
3216 offset, len);
3218 xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
3219 offset, len);
3220 if (xfer != 0)
3221 return xfer;
3223 return super_xfer_partial (ops, object, annex, readbuf, writebuf,
3224 offset, len);
3227 /* Create a prototype generic GNU/Linux target. The client can override
3228 it with local methods. */
3230 static void
3231 linux_target_install_ops (struct target_ops *t)
3233 t->to_insert_fork_catchpoint = linux_child_insert_fork_catchpoint;
3234 t->to_insert_vfork_catchpoint = linux_child_insert_vfork_catchpoint;
3235 t->to_insert_exec_catchpoint = linux_child_insert_exec_catchpoint;
3236 t->to_pid_to_exec_file = linux_child_pid_to_exec_file;
3237 t->to_post_startup_inferior = linux_child_post_startup_inferior;
3238 t->to_post_attach = linux_child_post_attach;
3239 t->to_follow_fork = linux_child_follow_fork;
3240 t->to_find_memory_regions = linux_nat_find_memory_regions;
3241 t->to_make_corefile_notes = linux_nat_make_corefile_notes;
3243 super_xfer_partial = t->to_xfer_partial;
3244 t->to_xfer_partial = linux_xfer_partial;
3247 struct target_ops *
3248 linux_target (void)
3250 struct target_ops *t;
3252 t = inf_ptrace_target ();
3253 linux_target_install_ops (t);
3255 return t;
3258 struct target_ops *
3259 linux_trad_target (CORE_ADDR (*register_u_offset)(struct gdbarch *, int, int))
3261 struct target_ops *t;
3263 t = inf_ptrace_trad_target (register_u_offset);
3264 linux_target_install_ops (t);
3266 return t;
3269 void
3270 linux_nat_add_target (struct target_ops *t)
3272 /* Save the provided single-threaded target. We save this in a separate
3273 variable because another target we've inherited from (e.g. inf-ptrace)
3274 may have saved a pointer to T; we want to use it for the final
3275 process stratum target. */
3276 linux_ops_saved = *t;
3277 linux_ops = &linux_ops_saved;
3279 /* Override some methods for multithreading. */
3280 t->to_attach = linux_nat_attach;
3281 t->to_detach = linux_nat_detach;
3282 t->to_resume = linux_nat_resume;
3283 t->to_wait = linux_nat_wait;
3284 t->to_xfer_partial = linux_nat_xfer_partial;
3285 t->to_kill = linux_nat_kill;
3286 t->to_mourn_inferior = linux_nat_mourn_inferior;
3287 t->to_thread_alive = linux_nat_thread_alive;
3288 t->to_pid_to_str = linux_nat_pid_to_str;
3289 t->to_has_thread_control = tc_schedlock;
3291 /* We don't change the stratum; this target will sit at
3292 process_stratum and thread_db will set at thread_stratum. This
3293 is a little strange, since this is a multi-threaded-capable
3294 target, but we want to be on the stack below thread_db, and we
3295 also want to be used for single-threaded processes. */
3297 add_target (t);
3299 /* TODO: Eliminate this and have libthread_db use
3300 find_target_beneath. */
3301 thread_db_init (t);
3304 /* Register a method to call whenever a new thread is attached. */
3305 void
3306 linux_nat_set_new_thread (struct target_ops *t, void (*new_thread) (ptid_t))
3308 /* Save the pointer. We only support a single registered instance
3309 of the GNU/Linux native target, so we do not need to map this to
3310 T. */
3311 linux_nat_new_thread = new_thread;
3314 /* Return the saved siginfo associated with PTID. */
3315 struct siginfo *
3316 linux_nat_get_siginfo (ptid_t ptid)
3318 struct lwp_info *lp = find_lwp_pid (ptid);
3320 gdb_assert (lp != NULL);
3322 return &lp->siginfo;
3325 void
3326 _initialize_linux_nat (void)
3328 struct sigaction action;
3330 add_info ("proc", linux_nat_info_proc_cmd, _("\
3331 Show /proc process information about any running process.\n\
3332 Specify any process id, or use the program being debugged by default.\n\
3333 Specify any of the following keywords for detailed info:\n\
3334 mappings -- list of mapped memory regions.\n\
3335 stat -- list a bunch of random process info.\n\
3336 status -- list a different bunch of random process info.\n\
3337 all -- list all available /proc info."));
3339 /* Save the original signal mask. */
3340 sigprocmask (SIG_SETMASK, NULL, &normal_mask);
3342 action.sa_handler = sigchld_handler;
3343 sigemptyset (&action.sa_mask);
3344 action.sa_flags = SA_RESTART;
3345 sigaction (SIGCHLD, &action, NULL);
3347 /* Make sure we don't block SIGCHLD during a sigsuspend. */
3348 sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
3349 sigdelset (&suspend_mask, SIGCHLD);
3351 sigemptyset (&blocked_mask);
3353 add_setshow_zinteger_cmd ("lin-lwp", no_class, &debug_linux_nat, _("\
3354 Set debugging of GNU/Linux lwp module."), _("\
3355 Show debugging of GNU/Linux lwp module."), _("\
3356 Enables printf debugging output."),
3357 NULL,
3358 show_debug_linux_nat,
3359 &setdebuglist, &showdebuglist);
3363 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
3364 the GNU/Linux Threads library and therefore doesn't really belong
3365 here. */
3367 /* Read variable NAME in the target and return its value if found.
3368 Otherwise return zero. It is assumed that the type of the variable
3369 is `int'. */
3371 static int
3372 get_signo (const char *name)
3374 struct minimal_symbol *ms;
3375 int signo;
3377 ms = lookup_minimal_symbol (name, NULL, NULL);
3378 if (ms == NULL)
3379 return 0;
3381 if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
3382 sizeof (signo)) != 0)
3383 return 0;
3385 return signo;
3388 /* Return the set of signals used by the threads library in *SET. */
3390 void
3391 lin_thread_get_thread_signals (sigset_t *set)
3393 struct sigaction action;
3394 int restart, cancel;
3396 sigemptyset (set);
3398 restart = get_signo ("__pthread_sig_restart");
3399 cancel = get_signo ("__pthread_sig_cancel");
3401 /* LinuxThreads normally uses the first two RT signals, but in some legacy
3402 cases may use SIGUSR1/SIGUSR2. NPTL always uses RT signals, but does
3403 not provide any way for the debugger to query the signal numbers -
3404 fortunately they don't change! */
3406 if (restart == 0)
3407 restart = __SIGRTMIN;
3409 if (cancel == 0)
3410 cancel = __SIGRTMIN + 1;
3412 sigaddset (set, restart);
3413 sigaddset (set, cancel);
3415 /* The GNU/Linux Threads library makes terminating threads send a
3416 special "cancel" signal instead of SIGCHLD. Make sure we catch
3417 those (to prevent them from terminating GDB itself, which is
3418 likely to be their default action) and treat them the same way as
3419 SIGCHLD. */
3421 action.sa_handler = sigchld_handler;
3422 sigemptyset (&action.sa_mask);
3423 action.sa_flags = SA_RESTART;
3424 sigaction (cancel, &action, NULL);
3426 /* We block the "cancel" signal throughout this code ... */
3427 sigaddset (&blocked_mask, cancel);
3428 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
3430 /* ... except during a sigsuspend. */
3431 sigdelset (&suspend_mask, cancel);