1 /* GNU/Linux native-dependent code common to multiple platforms.
3 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
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/>. */
24 #include "gdb_string.h"
26 #include "gdb_assert.h"
27 #ifdef HAVE_TKILL_SYSCALL
29 #include <sys/syscall.h>
31 #include <sys/ptrace.h>
32 #include "linux-nat.h"
33 #include "linux-fork.h"
34 #include "gdbthread.h"
38 #include "inf-ptrace.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 #include "event-loop.h"
51 #include "event-top.h"
53 #include <sys/types.h>
54 #include "gdb_dirent.h"
55 #include "xml-support.h"
60 #define SPUFS_MAGIC 0x23c9b64e
63 #ifdef HAVE_PERSONALITY
64 # include <sys/personality.h>
65 # if !HAVE_DECL_ADDR_NO_RANDOMIZE
66 # define ADDR_NO_RANDOMIZE 0x0040000
68 #endif /* HAVE_PERSONALITY */
70 /* This comment documents high-level logic of this file.
72 Waiting for events in sync mode
73 ===============================
75 When waiting for an event in a specific thread, we just use waitpid, passing
76 the specific pid, and not passing WNOHANG.
78 When waiting for an event in all threads, waitpid is not quite good. Prior to
79 version 2.4, Linux can either wait for event in main thread, or in secondary
80 threads. (2.4 has the __WALL flag). So, if we use blocking waitpid, we might
81 miss an event. The solution is to use non-blocking waitpid, together with
82 sigsuspend. First, we use non-blocking waitpid to get an event in the main
83 process, if any. Second, we use non-blocking waitpid with the __WCLONED
84 flag to check for events in cloned processes. If nothing is found, we use
85 sigsuspend to wait for SIGCHLD. When SIGCHLD arrives, it means something
86 happened to a child process -- and SIGCHLD will be delivered both for events
87 in main debugged process and in cloned processes. As soon as we know there's
88 an event, we get back to calling nonblocking waitpid with and without __WCLONED.
90 Note that SIGCHLD should be blocked between waitpid and sigsuspend calls,
91 so that we don't miss a signal. If SIGCHLD arrives in between, when it's
92 blocked, the signal becomes pending and sigsuspend immediately
93 notices it and returns.
95 Waiting for events in async mode
96 ================================
98 In async mode, GDB should always be ready to handle both user input
99 and target events, so neither blocking waitpid nor sigsuspend are
100 viable options. Instead, we should asynchronously notify the GDB main
101 event loop whenever there's an unprocessed event from the target. We
102 detect asynchronous target events by handling SIGCHLD signals. To
103 notify the event loop about target events, the self-pipe trick is used
104 --- a pipe is registered as waitable event source in the event loop,
105 the event loop select/poll's on the read end of this pipe (as well on
106 other event sources, e.g., stdin), and the SIGCHLD handler writes a
107 byte to this pipe. This is more portable than relying on
108 pselect/ppoll, since on kernels that lack those syscalls, libc
109 emulates them with select/poll+sigprocmask, and that is racy
110 (a.k.a. plain broken).
112 Obviously, if we fail to notify the event loop if there's a target
113 event, it's bad. OTOH, if we notify the event loop when there's no
114 event from the target, linux_nat_wait will detect that there's no real
115 event to report, and return event of type TARGET_WAITKIND_IGNORE.
116 This is mostly harmless, but it will waste time and is better avoided.
118 The main design point is that every time GDB is outside linux-nat.c,
119 we have a SIGCHLD handler installed that is called when something
120 happens to the target and notifies the GDB event loop. Whenever GDB
121 core decides to handle the event, and calls into linux-nat.c, we
122 process things as in sync mode, except that the we never block in
125 While processing an event, we may end up momentarily blocked in
126 waitpid calls. Those waitpid calls, while blocking, are guarantied to
127 return quickly. E.g., in all-stop mode, before reporting to the core
128 that an LWP hit a breakpoint, all LWPs are stopped by sending them
129 SIGSTOP, and synchronously waiting for the SIGSTOP to be reported.
130 Note that this is different from blocking indefinitely waiting for the
131 next event --- here, we're already handling an event.
136 We stop threads by sending a SIGSTOP. The use of SIGSTOP instead of another
137 signal is not entirely significant; we just need for a signal to be delivered,
138 so that we can intercept it. SIGSTOP's advantage is that it can not be
139 blocked. A disadvantage is that it is not a real-time signal, so it can only
140 be queued once; we do not keep track of other sources of SIGSTOP.
142 Two other signals that can't be blocked are SIGCONT and SIGKILL. But we can't
143 use them, because they have special behavior when the signal is generated -
144 not when it is delivered. SIGCONT resumes the entire thread group and SIGKILL
145 kills the entire thread group.
147 A delivered SIGSTOP would stop the entire thread group, not just the thread we
148 tkill'd. But we never let the SIGSTOP be delivered; we always intercept and
149 cancel it (by PTRACE_CONT without passing SIGSTOP).
151 We could use a real-time signal instead. This would solve those problems; we
152 could use PTRACE_GETSIGINFO to locate the specific stop signals sent by GDB.
153 But we would still have to have some support for SIGSTOP, since PTRACE_ATTACH
154 generates it, and there are races with trying to find a signal that is not
158 #define O_LARGEFILE 0
161 /* If the system headers did not provide the constants, hard-code the normal
163 #ifndef PTRACE_EVENT_FORK
165 #define PTRACE_SETOPTIONS 0x4200
166 #define PTRACE_GETEVENTMSG 0x4201
168 /* options set using PTRACE_SETOPTIONS */
169 #define PTRACE_O_TRACESYSGOOD 0x00000001
170 #define PTRACE_O_TRACEFORK 0x00000002
171 #define PTRACE_O_TRACEVFORK 0x00000004
172 #define PTRACE_O_TRACECLONE 0x00000008
173 #define PTRACE_O_TRACEEXEC 0x00000010
174 #define PTRACE_O_TRACEVFORKDONE 0x00000020
175 #define PTRACE_O_TRACEEXIT 0x00000040
177 /* Wait extended result codes for the above trace options. */
178 #define PTRACE_EVENT_FORK 1
179 #define PTRACE_EVENT_VFORK 2
180 #define PTRACE_EVENT_CLONE 3
181 #define PTRACE_EVENT_EXEC 4
182 #define PTRACE_EVENT_VFORK_DONE 5
183 #define PTRACE_EVENT_EXIT 6
185 #endif /* PTRACE_EVENT_FORK */
187 /* Unlike other extended result codes, WSTOPSIG (status) on
188 PTRACE_O_TRACESYSGOOD syscall events doesn't return SIGTRAP, but
189 instead SIGTRAP with bit 7 set. */
190 #define SYSCALL_SIGTRAP (SIGTRAP | 0x80)
192 /* We can't always assume that this flag is available, but all systems
193 with the ptrace event handlers also have __WALL, so it's safe to use
196 #define __WALL 0x40000000 /* Wait for any child. */
199 #ifndef PTRACE_GETSIGINFO
200 # define PTRACE_GETSIGINFO 0x4202
201 # define PTRACE_SETSIGINFO 0x4203
204 /* The single-threaded native GNU/Linux target_ops. We save a pointer for
205 the use of the multi-threaded target. */
206 static struct target_ops *linux_ops;
207 static struct target_ops linux_ops_saved;
209 /* The method to call, if any, when a new thread is attached. */
210 static void (*linux_nat_new_thread) (ptid_t);
212 /* The method to call, if any, when the siginfo object needs to be
213 converted between the layout returned by ptrace, and the layout in
214 the architecture of the inferior. */
215 static int (*linux_nat_siginfo_fixup) (struct siginfo *,
219 /* The saved to_xfer_partial method, inherited from inf-ptrace.c.
220 Called by our to_xfer_partial. */
221 static LONGEST (*super_xfer_partial) (struct target_ops *,
223 const char *, gdb_byte *,
227 static int debug_linux_nat;
229 show_debug_linux_nat (struct ui_file *file, int from_tty,
230 struct cmd_list_element *c, const char *value)
232 fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
236 static int debug_linux_nat_async = 0;
238 show_debug_linux_nat_async (struct ui_file *file, int from_tty,
239 struct cmd_list_element *c, const char *value)
241 fprintf_filtered (file, _("Debugging of GNU/Linux async lwp module is %s.\n"),
245 static int disable_randomization = 1;
248 show_disable_randomization (struct ui_file *file, int from_tty,
249 struct cmd_list_element *c, const char *value)
251 #ifdef HAVE_PERSONALITY
252 fprintf_filtered (file, _("\
253 Disabling randomization of debuggee's virtual address space is %s.\n"),
255 #else /* !HAVE_PERSONALITY */
257 Disabling randomization of debuggee's virtual address space is unsupported on\n\
258 this platform.\n"), file);
259 #endif /* !HAVE_PERSONALITY */
263 set_disable_randomization (char *args, int from_tty, struct cmd_list_element *c)
265 #ifndef HAVE_PERSONALITY
267 Disabling randomization of debuggee's virtual address space is unsupported on\n\
269 #endif /* !HAVE_PERSONALITY */
272 static int linux_parent_pid;
274 struct simple_pid_list
278 struct simple_pid_list *next;
280 struct simple_pid_list *stopped_pids;
282 /* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACEFORK
283 can not be used, 1 if it can. */
285 static int linux_supports_tracefork_flag = -1;
287 /* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACESYSGOOD
288 can not be used, 1 if it can. */
290 static int linux_supports_tracesysgood_flag = -1;
292 /* If we have PTRACE_O_TRACEFORK, this flag indicates whether we also have
293 PTRACE_O_TRACEVFORKDONE. */
295 static int linux_supports_tracevforkdone_flag = -1;
297 /* Async mode support */
299 /* Zero if the async mode, although enabled, is masked, which means
300 linux_nat_wait should behave as if async mode was off. */
301 static int linux_nat_async_mask_value = 1;
303 /* Stores the current used ptrace() options. */
304 static int current_ptrace_options = 0;
306 /* The read/write ends of the pipe registered as waitable file in the
308 static int linux_nat_event_pipe[2] = { -1, -1 };
310 /* Flush the event pipe. */
313 async_file_flush (void)
320 ret = read (linux_nat_event_pipe[0], &buf, 1);
322 while (ret >= 0 || (ret == -1 && errno == EINTR));
325 /* Put something (anything, doesn't matter what, or how much) in event
326 pipe, so that the select/poll in the event-loop realizes we have
327 something to process. */
330 async_file_mark (void)
334 /* It doesn't really matter what the pipe contains, as long we end
335 up with something in it. Might as well flush the previous
341 ret = write (linux_nat_event_pipe[1], "+", 1);
343 while (ret == -1 && errno == EINTR);
345 /* Ignore EAGAIN. If the pipe is full, the event loop will already
346 be awakened anyway. */
349 static void linux_nat_async (void (*callback)
350 (enum inferior_event_type event_type, void *context),
352 static int linux_nat_async_mask (int mask);
353 static int kill_lwp (int lwpid, int signo);
355 static int stop_callback (struct lwp_info *lp, void *data);
357 static void block_child_signals (sigset_t *prev_mask);
358 static void restore_child_signals_mask (sigset_t *prev_mask);
361 static struct lwp_info *add_lwp (ptid_t ptid);
362 static void purge_lwp_list (int pid);
363 static struct lwp_info *find_lwp_pid (ptid_t ptid);
366 /* Trivial list manipulation functions to keep track of a list of
367 new stopped processes. */
369 add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
371 struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
373 new_pid->status = status;
374 new_pid->next = *listp;
379 pull_pid_from_list (struct simple_pid_list **listp, int pid, int *status)
381 struct simple_pid_list **p;
383 for (p = listp; *p != NULL; p = &(*p)->next)
384 if ((*p)->pid == pid)
386 struct simple_pid_list *next = (*p)->next;
387 *status = (*p)->status;
396 linux_record_stopped_pid (int pid, int status)
398 add_to_pid_list (&stopped_pids, pid, status);
402 /* A helper function for linux_test_for_tracefork, called after fork (). */
405 linux_tracefork_child (void)
409 ptrace (PTRACE_TRACEME, 0, 0, 0);
410 kill (getpid (), SIGSTOP);
415 /* Wrapper function for waitpid which handles EINTR. */
418 my_waitpid (int pid, int *status, int flags)
424 ret = waitpid (pid, status, flags);
426 while (ret == -1 && errno == EINTR);
431 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.
433 First, we try to enable fork tracing on ORIGINAL_PID. If this fails,
434 we know that the feature is not available. This may change the tracing
435 options for ORIGINAL_PID, but we'll be setting them shortly anyway.
437 However, if it succeeds, we don't know for sure that the feature is
438 available; old versions of PTRACE_SETOPTIONS ignored unknown options. We
439 create a child process, attach to it, use PTRACE_SETOPTIONS to enable
440 fork tracing, and let it fork. If the process exits, we assume that we
441 can't use TRACEFORK; if we get the fork notification, and we can extract
442 the new child's PID, then we assume that we can. */
445 linux_test_for_tracefork (int original_pid)
447 int child_pid, ret, status;
451 /* We don't want those ptrace calls to be interrupted. */
452 block_child_signals (&prev_mask);
454 linux_supports_tracefork_flag = 0;
455 linux_supports_tracevforkdone_flag = 0;
457 ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACEFORK);
460 restore_child_signals_mask (&prev_mask);
466 perror_with_name (("fork"));
469 linux_tracefork_child ();
471 ret = my_waitpid (child_pid, &status, 0);
473 perror_with_name (("waitpid"));
474 else if (ret != child_pid)
475 error (_("linux_test_for_tracefork: waitpid: unexpected result %d."), ret);
476 if (! WIFSTOPPED (status))
477 error (_("linux_test_for_tracefork: waitpid: unexpected status %d."), status);
479 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
482 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
485 warning (_("linux_test_for_tracefork: failed to kill child"));
486 restore_child_signals_mask (&prev_mask);
490 ret = my_waitpid (child_pid, &status, 0);
491 if (ret != child_pid)
492 warning (_("linux_test_for_tracefork: failed to wait for killed child"));
493 else if (!WIFSIGNALED (status))
494 warning (_("linux_test_for_tracefork: unexpected wait status 0x%x from "
495 "killed child"), status);
497 restore_child_signals_mask (&prev_mask);
501 /* Check whether PTRACE_O_TRACEVFORKDONE is available. */
502 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0,
503 PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORKDONE);
504 linux_supports_tracevforkdone_flag = (ret == 0);
506 ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
508 warning (_("linux_test_for_tracefork: failed to resume child"));
510 ret = my_waitpid (child_pid, &status, 0);
512 if (ret == child_pid && WIFSTOPPED (status)
513 && status >> 16 == PTRACE_EVENT_FORK)
516 ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
517 if (ret == 0 && second_pid != 0)
521 linux_supports_tracefork_flag = 1;
522 my_waitpid (second_pid, &second_status, 0);
523 ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
525 warning (_("linux_test_for_tracefork: failed to kill second child"));
526 my_waitpid (second_pid, &status, 0);
530 warning (_("linux_test_for_tracefork: unexpected result from waitpid "
531 "(%d, status 0x%x)"), ret, status);
533 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
535 warning (_("linux_test_for_tracefork: failed to kill child"));
536 my_waitpid (child_pid, &status, 0);
538 restore_child_signals_mask (&prev_mask);
541 /* Determine if PTRACE_O_TRACESYSGOOD can be used to follow syscalls.
543 We try to enable syscall tracing on ORIGINAL_PID. If this fails,
544 we know that the feature is not available. This may change the tracing
545 options for ORIGINAL_PID, but we'll be setting them shortly anyway. */
548 linux_test_for_tracesysgood (int original_pid)
553 /* We don't want those ptrace calls to be interrupted. */
554 block_child_signals (&prev_mask);
556 linux_supports_tracesysgood_flag = 0;
558 ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACESYSGOOD);
562 linux_supports_tracesysgood_flag = 1;
564 restore_child_signals_mask (&prev_mask);
567 /* Determine wether we support PTRACE_O_TRACESYSGOOD option available.
568 This function also sets linux_supports_tracesysgood_flag. */
571 linux_supports_tracesysgood (int pid)
573 if (linux_supports_tracesysgood_flag == -1)
574 linux_test_for_tracesysgood (pid);
575 return linux_supports_tracesysgood_flag;
578 /* Return non-zero iff we have tracefork functionality available.
579 This function also sets linux_supports_tracefork_flag. */
582 linux_supports_tracefork (int pid)
584 if (linux_supports_tracefork_flag == -1)
585 linux_test_for_tracefork (pid);
586 return linux_supports_tracefork_flag;
590 linux_supports_tracevforkdone (int pid)
592 if (linux_supports_tracefork_flag == -1)
593 linux_test_for_tracefork (pid);
594 return linux_supports_tracevforkdone_flag;
598 linux_enable_tracesysgood (ptid_t ptid)
600 int pid = ptid_get_lwp (ptid);
603 pid = ptid_get_pid (ptid);
605 if (linux_supports_tracesysgood (pid) == 0)
608 current_ptrace_options |= PTRACE_O_TRACESYSGOOD;
610 ptrace (PTRACE_SETOPTIONS, pid, 0, current_ptrace_options);
615 linux_enable_event_reporting (ptid_t ptid)
617 int pid = ptid_get_lwp (ptid);
620 pid = ptid_get_pid (ptid);
622 if (! linux_supports_tracefork (pid))
625 current_ptrace_options |= PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK
626 | PTRACE_O_TRACEEXEC | PTRACE_O_TRACECLONE;
628 if (linux_supports_tracevforkdone (pid))
629 current_ptrace_options |= PTRACE_O_TRACEVFORKDONE;
631 /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to support
632 read-only process state. */
634 ptrace (PTRACE_SETOPTIONS, pid, 0, current_ptrace_options);
638 linux_child_post_attach (int pid)
640 linux_enable_event_reporting (pid_to_ptid (pid));
641 check_for_thread_db ();
642 linux_enable_tracesysgood (pid_to_ptid (pid));
646 linux_child_post_startup_inferior (ptid_t ptid)
648 linux_enable_event_reporting (ptid);
649 check_for_thread_db ();
650 linux_enable_tracesysgood (ptid);
654 linux_child_follow_fork (struct target_ops *ops, int follow_child)
658 int parent_pid, child_pid;
660 block_child_signals (&prev_mask);
662 has_vforked = (inferior_thread ()->pending_follow.kind
663 == TARGET_WAITKIND_VFORKED);
664 parent_pid = ptid_get_lwp (inferior_ptid);
666 parent_pid = ptid_get_pid (inferior_ptid);
667 child_pid = PIDGET (inferior_thread ()->pending_follow.value.related_pid);
670 linux_enable_event_reporting (pid_to_ptid (child_pid));
674 /* We're already attached to the parent, by default. */
676 /* Before detaching from the child, remove all breakpoints from
677 it. If we forked, then this has already been taken care of
678 by infrun.c. If we vforked however, any breakpoint inserted
679 in the parent is visible in the child, even those added while
680 stopped in a vfork catchpoint. This won't actually modify
681 the breakpoint list, but will physically remove the
682 breakpoints from the child. This will remove the breakpoints
683 from the parent also, but they'll be reinserted below. */
685 detach_breakpoints (child_pid);
687 /* Detach new forked process? */
690 if (info_verbose || debug_linux_nat)
692 target_terminal_ours ();
693 fprintf_filtered (gdb_stdlog,
694 "Detaching after fork from child process %d.\n",
698 ptrace (PTRACE_DETACH, child_pid, 0, 0);
702 struct inferior *parent_inf, *child_inf;
704 struct cleanup *old_chain;
706 /* Add process to GDB's tables. */
707 child_inf = add_inferior (child_pid);
709 parent_inf = current_inferior ();
710 child_inf->attach_flag = parent_inf->attach_flag;
711 copy_terminal_info (child_inf, parent_inf);
713 old_chain = save_inferior_ptid ();
715 inferior_ptid = ptid_build (child_pid, child_pid, 0);
716 add_thread (inferior_ptid);
717 lp = add_lwp (inferior_ptid);
720 check_for_thread_db ();
722 do_cleanups (old_chain);
727 gdb_assert (linux_supports_tracefork_flag >= 0);
728 if (linux_supports_tracevforkdone (0))
732 ptrace (PTRACE_CONT, parent_pid, 0, 0);
733 my_waitpid (parent_pid, &status, __WALL);
734 if ((status >> 16) != PTRACE_EVENT_VFORK_DONE)
735 warning (_("Unexpected waitpid result %06x when waiting for "
736 "vfork-done"), status);
740 /* We can't insert breakpoints until the child has
741 finished with the shared memory region. We need to
742 wait until that happens. Ideal would be to just
744 - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
745 - waitpid (parent_pid, &status, __WALL);
746 However, most architectures can't handle a syscall
747 being traced on the way out if it wasn't traced on
750 We might also think to loop, continuing the child
751 until it exits or gets a SIGTRAP. One problem is
752 that the child might call ptrace with PTRACE_TRACEME.
754 There's no simple and reliable way to figure out when
755 the vforked child will be done with its copy of the
756 shared memory. We could step it out of the syscall,
757 two instructions, let it go, and then single-step the
758 parent once. When we have hardware single-step, this
759 would work; with software single-step it could still
760 be made to work but we'd have to be able to insert
761 single-step breakpoints in the child, and we'd have
762 to insert -just- the single-step breakpoint in the
763 parent. Very awkward.
765 In the end, the best we can do is to make sure it
766 runs for a little while. Hopefully it will be out of
767 range of any breakpoints we reinsert. Usually this
768 is only the single-step breakpoint at vfork's return
774 /* Since we vforked, breakpoints were removed in the parent
775 too. Put them back. */
776 reattach_breakpoints (parent_pid);
781 struct thread_info *tp;
782 struct inferior *parent_inf, *child_inf;
785 /* Before detaching from the parent, remove all breakpoints from it. */
786 remove_breakpoints ();
788 if (info_verbose || debug_linux_nat)
790 target_terminal_ours ();
791 fprintf_filtered (gdb_stdlog,
792 "Attaching after fork to child process %d.\n",
796 /* Add the new inferior first, so that the target_detach below
797 doesn't unpush the target. */
799 child_inf = add_inferior (child_pid);
801 parent_inf = current_inferior ();
802 child_inf->attach_flag = parent_inf->attach_flag;
803 copy_terminal_info (child_inf, parent_inf);
805 /* If we're vforking, we may want to hold on to the parent until
806 the child exits or execs. At exec time we can remove the old
807 breakpoints from the parent and detach it; at exit time we
808 could do the same (or even, sneakily, resume debugging it - the
809 child's exec has failed, or something similar).
811 This doesn't clean up "properly", because we can't call
812 target_detach, but that's OK; if the current target is "child",
813 then it doesn't need any further cleanups, and lin_lwp will
814 generally not encounter vfork (vfork is defined to fork
817 The holding part is very easy if we have VFORKDONE events;
818 but keeping track of both processes is beyond GDB at the
819 moment. So we don't expose the parent to the rest of GDB.
820 Instead we quietly hold onto it until such time as we can
825 struct lwp_info *parent_lwp;
827 linux_parent_pid = parent_pid;
829 /* Get rid of the inferior on the core side as well. */
830 inferior_ptid = null_ptid;
831 detach_inferior (parent_pid);
833 /* Also get rid of all its lwps. We will detach from this
834 inferior soon-ish, but, we will still get an exit event
835 reported through waitpid when it exits. If we didn't get
836 rid of the lwps from our list, we would end up reporting
837 the inferior exit to the core, which would then try to
838 mourn a non-existing (from the core's perspective)
840 parent_lwp = find_lwp_pid (pid_to_ptid (parent_pid));
841 purge_lwp_list (GET_PID (parent_lwp->ptid));
842 linux_parent_pid = parent_pid;
844 else if (detach_fork)
845 target_detach (NULL, 0);
847 inferior_ptid = ptid_build (child_pid, child_pid, 0);
848 add_thread (inferior_ptid);
849 lp = add_lwp (inferior_ptid);
852 check_for_thread_db ();
855 restore_child_signals_mask (&prev_mask);
861 linux_child_insert_fork_catchpoint (int pid)
863 if (! linux_supports_tracefork (pid))
864 error (_("Your system does not support fork catchpoints."));
868 linux_child_insert_vfork_catchpoint (int pid)
870 if (!linux_supports_tracefork (pid))
871 error (_("Your system does not support vfork catchpoints."));
875 linux_child_insert_exec_catchpoint (int pid)
877 if (!linux_supports_tracefork (pid))
878 error (_("Your system does not support exec catchpoints."));
882 linux_child_set_syscall_catchpoint (int pid, int needed, int any_count,
883 int table_size, int *table)
885 if (! linux_supports_tracesysgood (pid))
886 error (_("Your system does not support syscall catchpoints."));
887 /* On GNU/Linux, we ignore the arguments. It means that we only
888 enable the syscall catchpoints, but do not disable them.
890 Also, we do not use the `table' information because we do not
891 filter system calls here. We let GDB do the logic for us. */
895 /* On GNU/Linux there are no real LWP's. The closest thing to LWP's
896 are processes sharing the same VM space. A multi-threaded process
897 is basically a group of such processes. However, such a grouping
898 is almost entirely a user-space issue; the kernel doesn't enforce
899 such a grouping at all (this might change in the future). In
900 general, we'll rely on the threads library (i.e. the GNU/Linux
901 Threads library) to provide such a grouping.
903 It is perfectly well possible to write a multi-threaded application
904 without the assistance of a threads library, by using the clone
905 system call directly. This module should be able to give some
906 rudimentary support for debugging such applications if developers
907 specify the CLONE_PTRACE flag in the clone system call, and are
908 using the Linux kernel 2.4 or above.
910 Note that there are some peculiarities in GNU/Linux that affect
913 - In general one should specify the __WCLONE flag to waitpid in
914 order to make it report events for any of the cloned processes
915 (and leave it out for the initial process). However, if a cloned
916 process has exited the exit status is only reported if the
917 __WCLONE flag is absent. Linux kernel 2.4 has a __WALL flag, but
918 we cannot use it since GDB must work on older systems too.
920 - When a traced, cloned process exits and is waited for by the
921 debugger, the kernel reassigns it to the original parent and
922 keeps it around as a "zombie". Somehow, the GNU/Linux Threads
923 library doesn't notice this, which leads to the "zombie problem":
924 When debugged a multi-threaded process that spawns a lot of
925 threads will run out of processes, even if the threads exit,
926 because the "zombies" stay around. */
928 /* List of known LWPs. */
929 struct lwp_info *lwp_list;
932 /* Original signal mask. */
933 static sigset_t normal_mask;
935 /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
936 _initialize_linux_nat. */
937 static sigset_t suspend_mask;
939 /* Signals to block to make that sigsuspend work. */
940 static sigset_t blocked_mask;
942 /* SIGCHLD action. */
943 struct sigaction sigchld_action;
945 /* Block child signals (SIGCHLD and linux threads signals), and store
946 the previous mask in PREV_MASK. */
949 block_child_signals (sigset_t *prev_mask)
951 /* Make sure SIGCHLD is blocked. */
952 if (!sigismember (&blocked_mask, SIGCHLD))
953 sigaddset (&blocked_mask, SIGCHLD);
955 sigprocmask (SIG_BLOCK, &blocked_mask, prev_mask);
958 /* Restore child signals mask, previously returned by
959 block_child_signals. */
962 restore_child_signals_mask (sigset_t *prev_mask)
964 sigprocmask (SIG_SETMASK, prev_mask, NULL);
968 /* Prototypes for local functions. */
969 static int stop_wait_callback (struct lwp_info *lp, void *data);
970 static int linux_thread_alive (ptid_t ptid);
971 static char *linux_child_pid_to_exec_file (int pid);
972 static int cancel_breakpoint (struct lwp_info *lp);
975 /* Convert wait status STATUS to a string. Used for printing debug
979 status_to_str (int status)
983 if (WIFSTOPPED (status))
985 if (WSTOPSIG (status) == SYSCALL_SIGTRAP)
986 snprintf (buf, sizeof (buf), "%s (stopped at syscall)",
987 strsignal (SIGTRAP));
989 snprintf (buf, sizeof (buf), "%s (stopped)",
990 strsignal (WSTOPSIG (status)));
992 else if (WIFSIGNALED (status))
993 snprintf (buf, sizeof (buf), "%s (terminated)",
994 strsignal (WSTOPSIG (status)));
996 snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
1001 /* Initialize the list of LWPs. Note that this module, contrary to
1002 what GDB's generic threads layer does for its thread list,
1003 re-initializes the LWP lists whenever we mourn or detach (which
1004 doesn't involve mourning) the inferior. */
1007 init_lwp_list (void)
1009 struct lwp_info *lp, *lpnext;
1011 for (lp = lwp_list; lp; lp = lpnext)
1020 /* Remove all LWPs belong to PID from the lwp list. */
1023 purge_lwp_list (int pid)
1025 struct lwp_info *lp, *lpprev, *lpnext;
1029 for (lp = lwp_list; lp; lp = lpnext)
1033 if (ptid_get_pid (lp->ptid) == pid)
1036 lwp_list = lp->next;
1038 lpprev->next = lp->next;
1047 /* Return the number of known LWPs in the tgid given by PID. */
1053 struct lwp_info *lp;
1055 for (lp = lwp_list; lp; lp = lp->next)
1056 if (ptid_get_pid (lp->ptid) == pid)
1062 /* Add the LWP specified by PID to the list. Return a pointer to the
1063 structure describing the new LWP. The LWP should already be stopped
1064 (with an exception for the very first LWP). */
1066 static struct lwp_info *
1067 add_lwp (ptid_t ptid)
1069 struct lwp_info *lp;
1071 gdb_assert (is_lwp (ptid));
1073 lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
1075 memset (lp, 0, sizeof (struct lwp_info));
1077 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
1081 lp->next = lwp_list;
1084 if (num_lwps (GET_PID (ptid)) > 1 && linux_nat_new_thread != NULL)
1085 linux_nat_new_thread (ptid);
1090 /* Remove the LWP specified by PID from the list. */
1093 delete_lwp (ptid_t ptid)
1095 struct lwp_info *lp, *lpprev;
1099 for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
1100 if (ptid_equal (lp->ptid, ptid))
1107 lpprev->next = lp->next;
1109 lwp_list = lp->next;
1114 /* Return a pointer to the structure describing the LWP corresponding
1115 to PID. If no corresponding LWP could be found, return NULL. */
1117 static struct lwp_info *
1118 find_lwp_pid (ptid_t ptid)
1120 struct lwp_info *lp;
1124 lwp = GET_LWP (ptid);
1126 lwp = GET_PID (ptid);
1128 for (lp = lwp_list; lp; lp = lp->next)
1129 if (lwp == GET_LWP (lp->ptid))
1135 /* Returns true if PTID matches filter FILTER. FILTER can be the wild
1136 card MINUS_ONE_PTID (all ptid match it); can be a ptid representing
1137 a process (ptid_is_pid returns true), in which case, all lwps of
1138 that give process match, lwps of other process do not; or, it can
1139 represent a specific thread, in which case, only that thread will
1140 match true. PTID must represent an LWP, it can never be a wild
1144 ptid_match (ptid_t ptid, ptid_t filter)
1146 /* Since both parameters have the same type, prevent easy mistakes
1148 gdb_assert (!ptid_equal (ptid, minus_one_ptid)
1149 && !ptid_equal (ptid, null_ptid));
1151 if (ptid_equal (filter, minus_one_ptid))
1153 if (ptid_is_pid (filter)
1154 && ptid_get_pid (ptid) == ptid_get_pid (filter))
1156 else if (ptid_equal (ptid, filter))
1162 /* Call CALLBACK with its second argument set to DATA for every LWP in
1163 the list. If CALLBACK returns 1 for a particular LWP, return a
1164 pointer to the structure describing that LWP immediately.
1165 Otherwise return NULL. */
1168 iterate_over_lwps (ptid_t filter,
1169 int (*callback) (struct lwp_info *, void *),
1172 struct lwp_info *lp, *lpnext;
1174 for (lp = lwp_list; lp; lp = lpnext)
1178 if (ptid_match (lp->ptid, filter))
1180 if ((*callback) (lp, data))
1188 /* Update our internal state when changing from one checkpoint to
1189 another indicated by NEW_PTID. We can only switch single-threaded
1190 applications, so we only create one new LWP, and the previous list
1194 linux_nat_switch_fork (ptid_t new_ptid)
1196 struct lwp_info *lp;
1198 purge_lwp_list (GET_PID (inferior_ptid));
1200 lp = add_lwp (new_ptid);
1203 /* This changes the thread's ptid while preserving the gdb thread
1204 num. Also changes the inferior pid, while preserving the
1206 thread_change_ptid (inferior_ptid, new_ptid);
1208 /* We've just told GDB core that the thread changed target id, but,
1209 in fact, it really is a different thread, with different register
1211 registers_changed ();
1214 /* Handle the exit of a single thread LP. */
1217 exit_lwp (struct lwp_info *lp)
1219 struct thread_info *th = find_thread_ptid (lp->ptid);
1223 if (print_thread_events)
1224 printf_unfiltered (_("[%s exited]\n"), target_pid_to_str (lp->ptid));
1226 delete_thread (lp->ptid);
1229 delete_lwp (lp->ptid);
1232 /* Return an lwp's tgid, found in `/proc/PID/status'. */
1235 linux_proc_get_tgid (int lwpid)
1241 snprintf (buf, sizeof (buf), "/proc/%d/status", (int) lwpid);
1242 status_file = fopen (buf, "r");
1243 if (status_file != NULL)
1245 while (fgets (buf, sizeof (buf), status_file))
1247 if (strncmp (buf, "Tgid:", 5) == 0)
1249 tgid = strtoul (buf + strlen ("Tgid:"), NULL, 10);
1254 fclose (status_file);
1260 /* Detect `T (stopped)' in `/proc/PID/status'.
1261 Other states including `T (tracing stop)' are reported as false. */
1264 pid_is_stopped (pid_t pid)
1270 snprintf (buf, sizeof (buf), "/proc/%d/status", (int) pid);
1271 status_file = fopen (buf, "r");
1272 if (status_file != NULL)
1276 while (fgets (buf, sizeof (buf), status_file))
1278 if (strncmp (buf, "State:", 6) == 0)
1284 if (have_state && strstr (buf, "T (stopped)") != NULL)
1286 fclose (status_file);
1291 /* Wait for the LWP specified by LP, which we have just attached to.
1292 Returns a wait status for that LWP, to cache. */
1295 linux_nat_post_attach_wait (ptid_t ptid, int first, int *cloned,
1298 pid_t new_pid, pid = GET_LWP (ptid);
1301 if (pid_is_stopped (pid))
1303 if (debug_linux_nat)
1304 fprintf_unfiltered (gdb_stdlog,
1305 "LNPAW: Attaching to a stopped process\n");
1307 /* The process is definitely stopped. It is in a job control
1308 stop, unless the kernel predates the TASK_STOPPED /
1309 TASK_TRACED distinction, in which case it might be in a
1310 ptrace stop. Make sure it is in a ptrace stop; from there we
1311 can kill it, signal it, et cetera.
1313 First make sure there is a pending SIGSTOP. Since we are
1314 already attached, the process can not transition from stopped
1315 to running without a PTRACE_CONT; so we know this signal will
1316 go into the queue. The SIGSTOP generated by PTRACE_ATTACH is
1317 probably already in the queue (unless this kernel is old
1318 enough to use TASK_STOPPED for ptrace stops); but since SIGSTOP
1319 is not an RT signal, it can only be queued once. */
1320 kill_lwp (pid, SIGSTOP);
1322 /* Finally, resume the stopped process. This will deliver the SIGSTOP
1323 (or a higher priority signal, just like normal PTRACE_ATTACH). */
1324 ptrace (PTRACE_CONT, pid, 0, 0);
1327 /* Make sure the initial process is stopped. The user-level threads
1328 layer might want to poke around in the inferior, and that won't
1329 work if things haven't stabilized yet. */
1330 new_pid = my_waitpid (pid, &status, 0);
1331 if (new_pid == -1 && errno == ECHILD)
1334 warning (_("%s is a cloned process"), target_pid_to_str (ptid));
1336 /* Try again with __WCLONE to check cloned processes. */
1337 new_pid = my_waitpid (pid, &status, __WCLONE);
1341 gdb_assert (pid == new_pid);
1343 if (!WIFSTOPPED (status))
1345 /* The pid we tried to attach has apparently just exited. */
1346 if (debug_linux_nat)
1347 fprintf_unfiltered (gdb_stdlog, "LNPAW: Failed to stop %d: %s",
1348 pid, status_to_str (status));
1352 if (WSTOPSIG (status) != SIGSTOP)
1355 if (debug_linux_nat)
1356 fprintf_unfiltered (gdb_stdlog,
1357 "LNPAW: Received %s after attaching\n",
1358 status_to_str (status));
1364 /* Attach to the LWP specified by PID. Return 0 if successful or -1
1365 if the new LWP could not be attached. */
1368 lin_lwp_attach_lwp (ptid_t ptid)
1370 struct lwp_info *lp;
1373 gdb_assert (is_lwp (ptid));
1375 block_child_signals (&prev_mask);
1377 lp = find_lwp_pid (ptid);
1379 /* We assume that we're already attached to any LWP that has an id
1380 equal to the overall process id, and to any LWP that is already
1381 in our list of LWPs. If we're not seeing exit events from threads
1382 and we've had PID wraparound since we last tried to stop all threads,
1383 this assumption might be wrong; fortunately, this is very unlikely
1385 if (GET_LWP (ptid) != GET_PID (ptid) && lp == NULL)
1387 int status, cloned = 0, signalled = 0;
1389 if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
1391 /* If we fail to attach to the thread, issue a warning,
1392 but continue. One way this can happen is if thread
1393 creation is interrupted; as of Linux kernel 2.6.19, a
1394 bug may place threads in the thread list and then fail
1396 warning (_("Can't attach %s: %s"), target_pid_to_str (ptid),
1397 safe_strerror (errno));
1398 restore_child_signals_mask (&prev_mask);
1402 if (debug_linux_nat)
1403 fprintf_unfiltered (gdb_stdlog,
1404 "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
1405 target_pid_to_str (ptid));
1407 status = linux_nat_post_attach_wait (ptid, 0, &cloned, &signalled);
1408 if (!WIFSTOPPED (status))
1411 lp = add_lwp (ptid);
1413 lp->cloned = cloned;
1414 lp->signalled = signalled;
1415 if (WSTOPSIG (status) != SIGSTOP)
1418 lp->status = status;
1421 target_post_attach (GET_LWP (lp->ptid));
1423 if (debug_linux_nat)
1425 fprintf_unfiltered (gdb_stdlog,
1426 "LLAL: waitpid %s received %s\n",
1427 target_pid_to_str (ptid),
1428 status_to_str (status));
1433 /* We assume that the LWP representing the original process is
1434 already stopped. Mark it as stopped in the data structure
1435 that the GNU/linux ptrace layer uses to keep track of
1436 threads. Note that this won't have already been done since
1437 the main thread will have, we assume, been stopped by an
1438 attach from a different layer. */
1440 lp = add_lwp (ptid);
1444 restore_child_signals_mask (&prev_mask);
1449 linux_nat_create_inferior (struct target_ops *ops,
1450 char *exec_file, char *allargs, char **env,
1453 #ifdef HAVE_PERSONALITY
1454 int personality_orig = 0, personality_set = 0;
1455 #endif /* HAVE_PERSONALITY */
1457 /* The fork_child mechanism is synchronous and calls target_wait, so
1458 we have to mask the async mode. */
1460 #ifdef HAVE_PERSONALITY
1461 if (disable_randomization)
1464 personality_orig = personality (0xffffffff);
1465 if (errno == 0 && !(personality_orig & ADDR_NO_RANDOMIZE))
1467 personality_set = 1;
1468 personality (personality_orig | ADDR_NO_RANDOMIZE);
1470 if (errno != 0 || (personality_set
1471 && !(personality (0xffffffff) & ADDR_NO_RANDOMIZE)))
1472 warning (_("Error disabling address space randomization: %s"),
1473 safe_strerror (errno));
1475 #endif /* HAVE_PERSONALITY */
1477 linux_ops->to_create_inferior (ops, exec_file, allargs, env, from_tty);
1479 #ifdef HAVE_PERSONALITY
1480 if (personality_set)
1483 personality (personality_orig);
1485 warning (_("Error restoring address space randomization: %s"),
1486 safe_strerror (errno));
1488 #endif /* HAVE_PERSONALITY */
1492 linux_nat_attach (struct target_ops *ops, char *args, int from_tty)
1494 struct lwp_info *lp;
1498 linux_ops->to_attach (ops, args, from_tty);
1500 /* The ptrace base target adds the main thread with (pid,0,0)
1501 format. Decorate it with lwp info. */
1502 ptid = BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid));
1503 thread_change_ptid (inferior_ptid, ptid);
1505 /* Add the initial process as the first LWP to the list. */
1506 lp = add_lwp (ptid);
1508 status = linux_nat_post_attach_wait (lp->ptid, 1, &lp->cloned,
1510 if (!WIFSTOPPED (status))
1512 if (WIFEXITED (status))
1514 int exit_code = WEXITSTATUS (status);
1516 target_terminal_ours ();
1517 target_mourn_inferior ();
1519 error (_("Unable to attach: program exited normally."));
1521 error (_("Unable to attach: program exited with code %d."),
1524 else if (WIFSIGNALED (status))
1526 enum target_signal signo;
1528 target_terminal_ours ();
1529 target_mourn_inferior ();
1531 signo = target_signal_from_host (WTERMSIG (status));
1532 error (_("Unable to attach: program terminated with signal "
1534 target_signal_to_name (signo),
1535 target_signal_to_string (signo));
1538 internal_error (__FILE__, __LINE__,
1539 _("unexpected status %d for PID %ld"),
1540 status, (long) GET_LWP (ptid));
1545 /* Save the wait status to report later. */
1547 if (debug_linux_nat)
1548 fprintf_unfiltered (gdb_stdlog,
1549 "LNA: waitpid %ld, saving status %s\n",
1550 (long) GET_PID (lp->ptid), status_to_str (status));
1552 lp->status = status;
1554 if (target_can_async_p ())
1555 target_async (inferior_event_handler, 0);
1558 /* Get pending status of LP. */
1560 get_pending_status (struct lwp_info *lp, int *status)
1562 enum target_signal signo = TARGET_SIGNAL_0;
1564 /* If we paused threads momentarily, we may have stored pending
1565 events in lp->status or lp->waitstatus (see stop_wait_callback),
1566 and GDB core hasn't seen any signal for those threads.
1567 Otherwise, the last signal reported to the core is found in the
1568 thread object's stop_signal.
1570 There's a corner case that isn't handled here at present. Only
1571 if the thread stopped with a TARGET_WAITKIND_STOPPED does
1572 stop_signal make sense as a real signal to pass to the inferior.
1573 Some catchpoint related events, like
1574 TARGET_WAITKIND_(V)FORK|EXEC|SYSCALL, have their stop_signal set
1575 to TARGET_SIGNAL_SIGTRAP when the catchpoint triggers. But,
1576 those traps are debug API (ptrace in our case) related and
1577 induced; the inferior wouldn't see them if it wasn't being
1578 traced. Hence, we should never pass them to the inferior, even
1579 when set to pass state. Since this corner case isn't handled by
1580 infrun.c when proceeding with a signal, for consistency, neither
1581 do we handle it here (or elsewhere in the file we check for
1582 signal pass state). Normally SIGTRAP isn't set to pass state, so
1583 this is really a corner case. */
1585 if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
1586 signo = TARGET_SIGNAL_0; /* a pending ptrace event, not a real signal. */
1587 else if (lp->status)
1588 signo = target_signal_from_host (WSTOPSIG (lp->status));
1589 else if (non_stop && !is_executing (lp->ptid))
1591 struct thread_info *tp = find_thread_ptid (lp->ptid);
1592 signo = tp->stop_signal;
1596 struct target_waitstatus last;
1599 get_last_target_status (&last_ptid, &last);
1601 if (GET_LWP (lp->ptid) == GET_LWP (last_ptid))
1603 struct thread_info *tp = find_thread_ptid (lp->ptid);
1604 signo = tp->stop_signal;
1610 if (signo == TARGET_SIGNAL_0)
1612 if (debug_linux_nat)
1613 fprintf_unfiltered (gdb_stdlog,
1614 "GPT: lwp %s has no pending signal\n",
1615 target_pid_to_str (lp->ptid));
1617 else if (!signal_pass_state (signo))
1619 if (debug_linux_nat)
1620 fprintf_unfiltered (gdb_stdlog, "\
1621 GPT: lwp %s had signal %s, but it is in no pass state\n",
1622 target_pid_to_str (lp->ptid),
1623 target_signal_to_string (signo));
1627 *status = W_STOPCODE (target_signal_to_host (signo));
1629 if (debug_linux_nat)
1630 fprintf_unfiltered (gdb_stdlog,
1631 "GPT: lwp %s has pending signal %s\n",
1632 target_pid_to_str (lp->ptid),
1633 target_signal_to_string (signo));
1640 detach_callback (struct lwp_info *lp, void *data)
1642 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1644 if (debug_linux_nat && lp->status)
1645 fprintf_unfiltered (gdb_stdlog, "DC: Pending %s for %s on detach.\n",
1646 strsignal (WSTOPSIG (lp->status)),
1647 target_pid_to_str (lp->ptid));
1649 /* If there is a pending SIGSTOP, get rid of it. */
1652 if (debug_linux_nat)
1653 fprintf_unfiltered (gdb_stdlog,
1654 "DC: Sending SIGCONT to %s\n",
1655 target_pid_to_str (lp->ptid));
1657 kill_lwp (GET_LWP (lp->ptid), SIGCONT);
1661 /* We don't actually detach from the LWP that has an id equal to the
1662 overall process id just yet. */
1663 if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
1667 /* Pass on any pending signal for this LWP. */
1668 get_pending_status (lp, &status);
1671 if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
1672 WSTOPSIG (status)) < 0)
1673 error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
1674 safe_strerror (errno));
1676 if (debug_linux_nat)
1677 fprintf_unfiltered (gdb_stdlog,
1678 "PTRACE_DETACH (%s, %s, 0) (OK)\n",
1679 target_pid_to_str (lp->ptid),
1680 strsignal (WSTOPSIG (status)));
1682 delete_lwp (lp->ptid);
1689 linux_nat_detach (struct target_ops *ops, char *args, int from_tty)
1693 enum target_signal sig;
1694 struct lwp_info *main_lwp;
1696 pid = GET_PID (inferior_ptid);
1698 if (target_can_async_p ())
1699 linux_nat_async (NULL, 0);
1701 /* Stop all threads before detaching. ptrace requires that the
1702 thread is stopped to sucessfully detach. */
1703 iterate_over_lwps (pid_to_ptid (pid), stop_callback, NULL);
1704 /* ... and wait until all of them have reported back that
1705 they're no longer running. */
1706 iterate_over_lwps (pid_to_ptid (pid), stop_wait_callback, NULL);
1708 iterate_over_lwps (pid_to_ptid (pid), detach_callback, NULL);
1710 /* Only the initial process should be left right now. */
1711 gdb_assert (num_lwps (GET_PID (inferior_ptid)) == 1);
1713 main_lwp = find_lwp_pid (pid_to_ptid (pid));
1715 /* Pass on any pending signal for the last LWP. */
1716 if ((args == NULL || *args == '\0')
1717 && get_pending_status (main_lwp, &status) != -1
1718 && WIFSTOPPED (status))
1720 /* Put the signal number in ARGS so that inf_ptrace_detach will
1721 pass it along with PTRACE_DETACH. */
1723 sprintf (args, "%d", (int) WSTOPSIG (status));
1724 fprintf_unfiltered (gdb_stdlog,
1725 "LND: Sending signal %s to %s\n",
1727 target_pid_to_str (main_lwp->ptid));
1730 delete_lwp (main_lwp->ptid);
1732 if (forks_exist_p ())
1734 /* Multi-fork case. The current inferior_ptid is being detached
1735 from, but there are other viable forks to debug. Detach from
1736 the current fork, and context-switch to the first
1738 linux_fork_detach (args, from_tty);
1740 if (non_stop && target_can_async_p ())
1741 target_async (inferior_event_handler, 0);
1744 linux_ops->to_detach (ops, args, from_tty);
1750 resume_callback (struct lwp_info *lp, void *data)
1752 if (lp->stopped && lp->status == 0)
1754 if (debug_linux_nat)
1755 fprintf_unfiltered (gdb_stdlog,
1756 "RC: PTRACE_CONT %s, 0, 0 (resuming sibling)\n",
1757 target_pid_to_str (lp->ptid));
1759 linux_ops->to_resume (linux_ops,
1760 pid_to_ptid (GET_LWP (lp->ptid)),
1761 0, TARGET_SIGNAL_0);
1762 if (debug_linux_nat)
1763 fprintf_unfiltered (gdb_stdlog,
1764 "RC: PTRACE_CONT %s, 0, 0 (resume sibling)\n",
1765 target_pid_to_str (lp->ptid));
1768 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1770 else if (lp->stopped && debug_linux_nat)
1771 fprintf_unfiltered (gdb_stdlog, "RC: Not resuming sibling %s (has pending)\n",
1772 target_pid_to_str (lp->ptid));
1773 else if (debug_linux_nat)
1774 fprintf_unfiltered (gdb_stdlog, "RC: Not resuming sibling %s (not stopped)\n",
1775 target_pid_to_str (lp->ptid));
1781 resume_clear_callback (struct lwp_info *lp, void *data)
1788 resume_set_callback (struct lwp_info *lp, void *data)
1795 linux_nat_resume (struct target_ops *ops,
1796 ptid_t ptid, int step, enum target_signal signo)
1799 struct lwp_info *lp;
1802 if (debug_linux_nat)
1803 fprintf_unfiltered (gdb_stdlog,
1804 "LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
1805 step ? "step" : "resume",
1806 target_pid_to_str (ptid),
1807 signo ? strsignal (signo) : "0",
1808 target_pid_to_str (inferior_ptid));
1810 block_child_signals (&prev_mask);
1812 /* A specific PTID means `step only this process id'. */
1813 resume_many = (ptid_equal (minus_one_ptid, ptid)
1814 || ptid_is_pid (ptid));
1818 /* Mark the lwps we're resuming as resumed. */
1819 iterate_over_lwps (minus_one_ptid, resume_clear_callback, NULL);
1820 iterate_over_lwps (ptid, resume_set_callback, NULL);
1823 iterate_over_lwps (minus_one_ptid, resume_set_callback, NULL);
1825 /* See if it's the current inferior that should be handled
1828 lp = find_lwp_pid (inferior_ptid);
1830 lp = find_lwp_pid (ptid);
1831 gdb_assert (lp != NULL);
1833 /* Remember if we're stepping. */
1836 /* If we have a pending wait status for this thread, there is no
1837 point in resuming the process. But first make sure that
1838 linux_nat_wait won't preemptively handle the event - we
1839 should never take this short-circuit if we are going to
1840 leave LP running, since we have skipped resuming all the
1841 other threads. This bit of code needs to be synchronized
1842 with linux_nat_wait. */
1844 if (lp->status && WIFSTOPPED (lp->status))
1847 struct inferior *inf;
1849 inf = find_inferior_pid (ptid_get_pid (lp->ptid));
1851 saved_signo = target_signal_from_host (WSTOPSIG (lp->status));
1853 /* Defer to common code if we're gaining control of the
1855 if (inf->stop_soon == NO_STOP_QUIETLY
1856 && signal_stop_state (saved_signo) == 0
1857 && signal_print_state (saved_signo) == 0
1858 && signal_pass_state (saved_signo) == 1)
1860 if (debug_linux_nat)
1861 fprintf_unfiltered (gdb_stdlog,
1862 "LLR: Not short circuiting for ignored "
1863 "status 0x%x\n", lp->status);
1865 /* FIXME: What should we do if we are supposed to continue
1866 this thread with a signal? */
1867 gdb_assert (signo == TARGET_SIGNAL_0);
1868 signo = saved_signo;
1875 /* FIXME: What should we do if we are supposed to continue
1876 this thread with a signal? */
1877 gdb_assert (signo == TARGET_SIGNAL_0);
1879 if (debug_linux_nat)
1880 fprintf_unfiltered (gdb_stdlog,
1881 "LLR: Short circuiting for status 0x%x\n",
1884 restore_child_signals_mask (&prev_mask);
1885 if (target_can_async_p ())
1887 target_async (inferior_event_handler, 0);
1888 /* Tell the event loop we have something to process. */
1894 /* Mark LWP as not stopped to prevent it from being continued by
1899 iterate_over_lwps (ptid, resume_callback, NULL);
1901 /* Convert to something the lower layer understands. */
1902 ptid = pid_to_ptid (GET_LWP (lp->ptid));
1904 linux_ops->to_resume (linux_ops, ptid, step, signo);
1905 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1907 if (debug_linux_nat)
1908 fprintf_unfiltered (gdb_stdlog,
1909 "LLR: %s %s, %s (resume event thread)\n",
1910 step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1911 target_pid_to_str (ptid),
1912 signo ? strsignal (signo) : "0");
1914 restore_child_signals_mask (&prev_mask);
1915 if (target_can_async_p ())
1916 target_async (inferior_event_handler, 0);
1919 /* Issue kill to specified lwp. */
1921 static int tkill_failed;
1924 kill_lwp (int lwpid, int signo)
1928 /* Use tkill, if possible, in case we are using nptl threads. If tkill
1929 fails, then we are not using nptl threads and we should be using kill. */
1931 #ifdef HAVE_TKILL_SYSCALL
1934 int ret = syscall (__NR_tkill, lwpid, signo);
1935 if (errno != ENOSYS)
1942 return kill (lwpid, signo);
1945 /* Handle a GNU/Linux syscall trap wait response. If we see a syscall
1946 event, check if the core is interested in it: if not, ignore the
1947 event, and keep waiting; otherwise, we need to toggle the LWP's
1948 syscall entry/exit status, since the ptrace event itself doesn't
1949 indicate it, and report the trap to higher layers. */
1952 linux_handle_syscall_trap (struct lwp_info *lp, int stopping)
1954 struct target_waitstatus *ourstatus = &lp->waitstatus;
1955 struct gdbarch *gdbarch = target_thread_architecture (lp->ptid);
1956 int syscall_number = (int) gdbarch_get_syscall_number (gdbarch, lp->ptid);
1960 /* If we're stopping threads, there's a SIGSTOP pending, which
1961 makes it so that the LWP reports an immediate syscall return,
1962 followed by the SIGSTOP. Skip seeing that "return" using
1963 PTRACE_CONT directly, and let stop_wait_callback collect the
1964 SIGSTOP. Later when the thread is resumed, a new syscall
1965 entry event. If we didn't do this (and returned 0), we'd
1966 leave a syscall entry pending, and our caller, by using
1967 PTRACE_CONT to collect the SIGSTOP, skips the syscall return
1968 itself. Later, when the user re-resumes this LWP, we'd see
1969 another syscall entry event and we'd mistake it for a return.
1971 If stop_wait_callback didn't force the SIGSTOP out of the LWP
1972 (leaving immediately with LWP->signalled set, without issuing
1973 a PTRACE_CONT), it would still be problematic to leave this
1974 syscall enter pending, as later when the thread is resumed,
1975 it would then see the same syscall exit mentioned above,
1976 followed by the delayed SIGSTOP, while the syscall didn't
1977 actually get to execute. It seems it would be even more
1978 confusing to the user. */
1980 if (debug_linux_nat)
1981 fprintf_unfiltered (gdb_stdlog,
1982 "LHST: ignoring syscall %d "
1983 "for LWP %ld (stopping threads), "
1984 "resuming with PTRACE_CONT for SIGSTOP\n",
1986 GET_LWP (lp->ptid));
1988 lp->syscall_state = TARGET_WAITKIND_IGNORE;
1989 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1993 if (catch_syscall_enabled ())
1995 /* Always update the entry/return state, even if this particular
1996 syscall isn't interesting to the core now. In async mode,
1997 the user could install a new catchpoint for this syscall
1998 between syscall enter/return, and we'll need to know to
1999 report a syscall return if that happens. */
2000 lp->syscall_state = (lp->syscall_state == TARGET_WAITKIND_SYSCALL_ENTRY
2001 ? TARGET_WAITKIND_SYSCALL_RETURN
2002 : TARGET_WAITKIND_SYSCALL_ENTRY);
2004 if (catching_syscall_number (syscall_number))
2006 /* Alright, an event to report. */
2007 ourstatus->kind = lp->syscall_state;
2008 ourstatus->value.syscall_number = syscall_number;
2010 if (debug_linux_nat)
2011 fprintf_unfiltered (gdb_stdlog,
2012 "LHST: stopping for %s of syscall %d"
2014 lp->syscall_state == TARGET_WAITKIND_SYSCALL_ENTRY
2015 ? "entry" : "return",
2017 GET_LWP (lp->ptid));
2021 if (debug_linux_nat)
2022 fprintf_unfiltered (gdb_stdlog,
2023 "LHST: ignoring %s of syscall %d "
2025 lp->syscall_state == TARGET_WAITKIND_SYSCALL_ENTRY
2026 ? "entry" : "return",
2028 GET_LWP (lp->ptid));
2032 /* If we had been syscall tracing, and hence used PT_SYSCALL
2033 before on this LWP, it could happen that the user removes all
2034 syscall catchpoints before we get to process this event.
2035 There are two noteworthy issues here:
2037 - When stopped at a syscall entry event, resuming with
2038 PT_STEP still resumes executing the syscall and reports a
2041 - Only PT_SYSCALL catches syscall enters. If we last
2042 single-stepped this thread, then this event can't be a
2043 syscall enter. If we last single-stepped this thread, this
2044 has to be a syscall exit.
2046 The points above mean that the next resume, be it PT_STEP or
2047 PT_CONTINUE, can not trigger a syscall trace event. */
2048 if (debug_linux_nat)
2049 fprintf_unfiltered (gdb_stdlog,
2050 "LHST: caught syscall event with no syscall catchpoints."
2051 " %d for LWP %ld, ignoring\n",
2053 GET_LWP (lp->ptid));
2054 lp->syscall_state = TARGET_WAITKIND_IGNORE;
2057 /* The core isn't interested in this event. For efficiency, avoid
2058 stopping all threads only to have the core resume them all again.
2059 Since we're not stopping threads, if we're still syscall tracing
2060 and not stepping, we can't use PTRACE_CONT here, as we'd miss any
2061 subsequent syscall. Simply resume using the inf-ptrace layer,
2062 which knows when to use PT_SYSCALL or PT_CONTINUE. */
2064 /* Note that gdbarch_get_syscall_number may access registers, hence
2066 registers_changed ();
2067 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
2068 lp->step, TARGET_SIGNAL_0);
2072 /* Handle a GNU/Linux extended wait response. If we see a clone
2073 event, we need to add the new LWP to our list (and not report the
2074 trap to higher layers). This function returns non-zero if the
2075 event should be ignored and we should wait again. If STOPPING is
2076 true, the new LWP remains stopped, otherwise it is continued. */
2079 linux_handle_extended_wait (struct lwp_info *lp, int status,
2082 int pid = GET_LWP (lp->ptid);
2083 struct target_waitstatus *ourstatus = &lp->waitstatus;
2084 struct lwp_info *new_lp = NULL;
2085 int event = status >> 16;
2087 if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
2088 || event == PTRACE_EVENT_CLONE)
2090 unsigned long new_pid;
2093 ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
2095 /* If we haven't already seen the new PID stop, wait for it now. */
2096 if (! pull_pid_from_list (&stopped_pids, new_pid, &status))
2098 /* The new child has a pending SIGSTOP. We can't affect it until it
2099 hits the SIGSTOP, but we're already attached. */
2100 ret = my_waitpid (new_pid, &status,
2101 (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
2103 perror_with_name (_("waiting for new child"));
2104 else if (ret != new_pid)
2105 internal_error (__FILE__, __LINE__,
2106 _("wait returned unexpected PID %d"), ret);
2107 else if (!WIFSTOPPED (status))
2108 internal_error (__FILE__, __LINE__,
2109 _("wait returned unexpected status 0x%x"), status);
2112 ourstatus->value.related_pid = ptid_build (new_pid, new_pid, 0);
2114 if (event == PTRACE_EVENT_FORK
2115 && linux_fork_checkpointing_p (GET_PID (lp->ptid)))
2117 struct fork_info *fp;
2119 /* Handle checkpointing by linux-fork.c here as a special
2120 case. We don't want the follow-fork-mode or 'catch fork'
2121 to interfere with this. */
2123 /* This won't actually modify the breakpoint list, but will
2124 physically remove the breakpoints from the child. */
2125 detach_breakpoints (new_pid);
2127 /* Retain child fork in ptrace (stopped) state. */
2128 fp = find_fork_pid (new_pid);
2130 fp = add_fork (new_pid);
2132 /* Report as spurious, so that infrun doesn't want to follow
2133 this fork. We're actually doing an infcall in
2135 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
2136 linux_enable_event_reporting (pid_to_ptid (new_pid));
2138 /* Report the stop to the core. */
2142 if (event == PTRACE_EVENT_FORK)
2143 ourstatus->kind = TARGET_WAITKIND_FORKED;
2144 else if (event == PTRACE_EVENT_VFORK)
2145 ourstatus->kind = TARGET_WAITKIND_VFORKED;
2148 struct cleanup *old_chain;
2150 ourstatus->kind = TARGET_WAITKIND_IGNORE;
2151 new_lp = add_lwp (BUILD_LWP (new_pid, GET_PID (lp->ptid)));
2153 new_lp->stopped = 1;
2155 if (WSTOPSIG (status) != SIGSTOP)
2157 /* This can happen if someone starts sending signals to
2158 the new thread before it gets a chance to run, which
2159 have a lower number than SIGSTOP (e.g. SIGUSR1).
2160 This is an unlikely case, and harder to handle for
2161 fork / vfork than for clone, so we do not try - but
2162 we handle it for clone events here. We'll send
2163 the other signal on to the thread below. */
2165 new_lp->signalled = 1;
2172 /* Add the new thread to GDB's lists as soon as possible
2175 1) the frontend doesn't have to wait for a stop to
2178 2) we tag it with the correct running state. */
2180 /* If the thread_db layer is active, let it know about
2181 this new thread, and add it to GDB's list. */
2182 if (!thread_db_attach_lwp (new_lp->ptid))
2184 /* We're not using thread_db. Add it to GDB's
2186 target_post_attach (GET_LWP (new_lp->ptid));
2187 add_thread (new_lp->ptid);
2192 set_running (new_lp->ptid, 1);
2193 set_executing (new_lp->ptid, 1);
2197 /* Note the need to use the low target ops to resume, to
2198 handle resuming with PT_SYSCALL if we have syscall
2204 new_lp->stopped = 0;
2205 new_lp->resumed = 1;
2208 ? target_signal_from_host (WSTOPSIG (status))
2211 linux_ops->to_resume (linux_ops, pid_to_ptid (new_pid),
2215 if (debug_linux_nat)
2216 fprintf_unfiltered (gdb_stdlog,
2217 "LHEW: Got clone event from LWP %ld, resuming\n",
2218 GET_LWP (lp->ptid));
2219 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
2220 0, TARGET_SIGNAL_0);
2228 if (event == PTRACE_EVENT_EXEC)
2230 if (debug_linux_nat)
2231 fprintf_unfiltered (gdb_stdlog,
2232 "LHEW: Got exec event from LWP %ld\n",
2233 GET_LWP (lp->ptid));
2235 ourstatus->kind = TARGET_WAITKIND_EXECD;
2236 ourstatus->value.execd_pathname
2237 = xstrdup (linux_child_pid_to_exec_file (pid));
2239 if (linux_parent_pid)
2241 detach_breakpoints (linux_parent_pid);
2242 ptrace (PTRACE_DETACH, linux_parent_pid, 0, 0);
2244 linux_parent_pid = 0;
2247 /* At this point, all inserted breakpoints are gone. Doing this
2248 as soon as we detect an exec prevents the badness of deleting
2249 a breakpoint writing the current "shadow contents" to lift
2250 the bp. That shadow is NOT valid after an exec.
2252 Note that we have to do this after the detach_breakpoints
2253 call above, otherwise breakpoints wouldn't be lifted from the
2254 parent on a vfork, because detach_breakpoints would think
2255 that breakpoints are not inserted. */
2256 mark_breakpoints_out ();
2260 internal_error (__FILE__, __LINE__,
2261 _("unknown ptrace event %d"), event);
2264 /* Wait for LP to stop. Returns the wait status, or 0 if the LWP has
2268 wait_lwp (struct lwp_info *lp)
2272 int thread_dead = 0;
2274 gdb_assert (!lp->stopped);
2275 gdb_assert (lp->status == 0);
2277 pid = my_waitpid (GET_LWP (lp->ptid), &status, 0);
2278 if (pid == -1 && errno == ECHILD)
2280 pid = my_waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
2281 if (pid == -1 && errno == ECHILD)
2283 /* The thread has previously exited. We need to delete it
2284 now because, for some vendor 2.4 kernels with NPTL
2285 support backported, there won't be an exit event unless
2286 it is the main thread. 2.6 kernels will report an exit
2287 event for each thread that exits, as expected. */
2289 if (debug_linux_nat)
2290 fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
2291 target_pid_to_str (lp->ptid));
2297 gdb_assert (pid == GET_LWP (lp->ptid));
2299 if (debug_linux_nat)
2301 fprintf_unfiltered (gdb_stdlog,
2302 "WL: waitpid %s received %s\n",
2303 target_pid_to_str (lp->ptid),
2304 status_to_str (status));
2308 /* Check if the thread has exited. */
2309 if (WIFEXITED (status) || WIFSIGNALED (status))
2312 if (debug_linux_nat)
2313 fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
2314 target_pid_to_str (lp->ptid));
2323 gdb_assert (WIFSTOPPED (status));
2325 /* Handle GNU/Linux's syscall SIGTRAPs. */
2326 if (WIFSTOPPED (status) && WSTOPSIG (status) == SYSCALL_SIGTRAP)
2328 /* No longer need the sysgood bit. The ptrace event ends up
2329 recorded in lp->waitstatus if we care for it. We can carry
2330 on handling the event like a regular SIGTRAP from here
2332 status = W_STOPCODE (SIGTRAP);
2333 if (linux_handle_syscall_trap (lp, 1))
2334 return wait_lwp (lp);
2337 /* Handle GNU/Linux's extended waitstatus for trace events. */
2338 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2340 if (debug_linux_nat)
2341 fprintf_unfiltered (gdb_stdlog,
2342 "WL: Handling extended status 0x%06x\n",
2344 if (linux_handle_extended_wait (lp, status, 1))
2345 return wait_lwp (lp);
2351 /* Save the most recent siginfo for LP. This is currently only called
2352 for SIGTRAP; some ports use the si_addr field for
2353 target_stopped_data_address. In the future, it may also be used to
2354 restore the siginfo of requeued signals. */
2357 save_siginfo (struct lwp_info *lp)
2360 ptrace (PTRACE_GETSIGINFO, GET_LWP (lp->ptid),
2361 (PTRACE_TYPE_ARG3) 0, &lp->siginfo);
2364 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
2367 /* Send a SIGSTOP to LP. */
2370 stop_callback (struct lwp_info *lp, void *data)
2372 if (!lp->stopped && !lp->signalled)
2376 if (debug_linux_nat)
2378 fprintf_unfiltered (gdb_stdlog,
2379 "SC: kill %s **<SIGSTOP>**\n",
2380 target_pid_to_str (lp->ptid));
2383 ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
2384 if (debug_linux_nat)
2386 fprintf_unfiltered (gdb_stdlog,
2387 "SC: lwp kill %d %s\n",
2389 errno ? safe_strerror (errno) : "ERRNO-OK");
2393 gdb_assert (lp->status == 0);
2399 /* Return non-zero if LWP PID has a pending SIGINT. */
2402 linux_nat_has_pending_sigint (int pid)
2404 sigset_t pending, blocked, ignored;
2407 linux_proc_pending_signals (pid, &pending, &blocked, &ignored);
2409 if (sigismember (&pending, SIGINT)
2410 && !sigismember (&ignored, SIGINT))
2416 /* Set a flag in LP indicating that we should ignore its next SIGINT. */
2419 set_ignore_sigint (struct lwp_info *lp, void *data)
2421 /* If a thread has a pending SIGINT, consume it; otherwise, set a
2422 flag to consume the next one. */
2423 if (lp->stopped && lp->status != 0 && WIFSTOPPED (lp->status)
2424 && WSTOPSIG (lp->status) == SIGINT)
2427 lp->ignore_sigint = 1;
2432 /* If LP does not have a SIGINT pending, then clear the ignore_sigint flag.
2433 This function is called after we know the LWP has stopped; if the LWP
2434 stopped before the expected SIGINT was delivered, then it will never have
2435 arrived. Also, if the signal was delivered to a shared queue and consumed
2436 by a different thread, it will never be delivered to this LWP. */
2439 maybe_clear_ignore_sigint (struct lwp_info *lp)
2441 if (!lp->ignore_sigint)
2444 if (!linux_nat_has_pending_sigint (GET_LWP (lp->ptid)))
2446 if (debug_linux_nat)
2447 fprintf_unfiltered (gdb_stdlog,
2448 "MCIS: Clearing bogus flag for %s\n",
2449 target_pid_to_str (lp->ptid));
2450 lp->ignore_sigint = 0;
2454 /* Wait until LP is stopped. */
2457 stop_wait_callback (struct lwp_info *lp, void *data)
2463 status = wait_lwp (lp);
2467 if (lp->ignore_sigint && WIFSTOPPED (status)
2468 && WSTOPSIG (status) == SIGINT)
2470 lp->ignore_sigint = 0;
2473 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2474 if (debug_linux_nat)
2475 fprintf_unfiltered (gdb_stdlog,
2476 "PTRACE_CONT %s, 0, 0 (%s) (discarding SIGINT)\n",
2477 target_pid_to_str (lp->ptid),
2478 errno ? safe_strerror (errno) : "OK");
2480 return stop_wait_callback (lp, NULL);
2483 maybe_clear_ignore_sigint (lp);
2485 if (WSTOPSIG (status) != SIGSTOP)
2487 if (WSTOPSIG (status) == SIGTRAP)
2489 /* If a LWP other than the LWP that we're reporting an
2490 event for has hit a GDB breakpoint (as opposed to
2491 some random trap signal), then just arrange for it to
2492 hit it again later. We don't keep the SIGTRAP status
2493 and don't forward the SIGTRAP signal to the LWP. We
2494 will handle the current event, eventually we will
2495 resume all LWPs, and this one will get its breakpoint
2498 If we do not do this, then we run the risk that the
2499 user will delete or disable the breakpoint, but the
2500 thread will have already tripped on it. */
2502 /* Save the trap's siginfo in case we need it later. */
2505 /* Now resume this LWP and get the SIGSTOP event. */
2507 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2508 if (debug_linux_nat)
2510 fprintf_unfiltered (gdb_stdlog,
2511 "PTRACE_CONT %s, 0, 0 (%s)\n",
2512 target_pid_to_str (lp->ptid),
2513 errno ? safe_strerror (errno) : "OK");
2515 fprintf_unfiltered (gdb_stdlog,
2516 "SWC: Candidate SIGTRAP event in %s\n",
2517 target_pid_to_str (lp->ptid));
2519 /* Hold this event/waitstatus while we check to see if
2520 there are any more (we still want to get that SIGSTOP). */
2521 stop_wait_callback (lp, NULL);
2523 /* Hold the SIGTRAP for handling by linux_nat_wait. If
2524 there's another event, throw it back into the
2528 if (debug_linux_nat)
2529 fprintf_unfiltered (gdb_stdlog,
2530 "SWC: kill %s, %s\n",
2531 target_pid_to_str (lp->ptid),
2532 status_to_str ((int) status));
2533 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
2536 /* Save the sigtrap event. */
2537 lp->status = status;
2542 /* The thread was stopped with a signal other than
2543 SIGSTOP, and didn't accidentally trip a breakpoint. */
2545 if (debug_linux_nat)
2547 fprintf_unfiltered (gdb_stdlog,
2548 "SWC: Pending event %s in %s\n",
2549 status_to_str ((int) status),
2550 target_pid_to_str (lp->ptid));
2552 /* Now resume this LWP and get the SIGSTOP event. */
2554 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2555 if (debug_linux_nat)
2556 fprintf_unfiltered (gdb_stdlog,
2557 "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
2558 target_pid_to_str (lp->ptid),
2559 errno ? safe_strerror (errno) : "OK");
2561 /* Hold this event/waitstatus while we check to see if
2562 there are any more (we still want to get that SIGSTOP). */
2563 stop_wait_callback (lp, NULL);
2565 /* If the lp->status field is still empty, use it to
2566 hold this event. If not, then this event must be
2567 returned to the event queue of the LWP. */
2570 if (debug_linux_nat)
2572 fprintf_unfiltered (gdb_stdlog,
2573 "SWC: kill %s, %s\n",
2574 target_pid_to_str (lp->ptid),
2575 status_to_str ((int) status));
2577 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
2580 lp->status = status;
2586 /* We caught the SIGSTOP that we intended to catch, so
2587 there's no SIGSTOP pending. */
2596 /* Return non-zero if LP has a wait status pending. */
2599 status_callback (struct lwp_info *lp, void *data)
2601 /* Only report a pending wait status if we pretend that this has
2602 indeed been resumed. */
2606 if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
2608 /* A ptrace event, like PTRACE_FORK|VFORK|EXEC, syscall event,
2609 or a a pending process exit. Note that `W_EXITCODE(0,0) ==
2610 0', so a clean process exit can not be stored pending in
2611 lp->status, it is indistinguishable from
2612 no-pending-status. */
2616 if (lp->status != 0)
2622 /* Return non-zero if LP isn't stopped. */
2625 running_callback (struct lwp_info *lp, void *data)
2627 return (lp->stopped == 0 || (lp->status != 0 && lp->resumed));
2630 /* Count the LWP's that have had events. */
2633 count_events_callback (struct lwp_info *lp, void *data)
2637 gdb_assert (count != NULL);
2639 /* Count only resumed LWPs that have a SIGTRAP event pending. */
2640 if (lp->status != 0 && lp->resumed
2641 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2647 /* Select the LWP (if any) that is currently being single-stepped. */
2650 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
2652 if (lp->step && lp->status != 0)
2658 /* Select the Nth LWP that has had a SIGTRAP event. */
2661 select_event_lwp_callback (struct lwp_info *lp, void *data)
2663 int *selector = data;
2665 gdb_assert (selector != NULL);
2667 /* Select only resumed LWPs that have a SIGTRAP event pending. */
2668 if (lp->status != 0 && lp->resumed
2669 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2670 if ((*selector)-- == 0)
2677 cancel_breakpoint (struct lwp_info *lp)
2679 /* Arrange for a breakpoint to be hit again later. We don't keep
2680 the SIGTRAP status and don't forward the SIGTRAP signal to the
2681 LWP. We will handle the current event, eventually we will resume
2682 this LWP, and this breakpoint will trap again.
2684 If we do not do this, then we run the risk that the user will
2685 delete or disable the breakpoint, but the LWP will have already
2688 struct regcache *regcache = get_thread_regcache (lp->ptid);
2689 struct gdbarch *gdbarch = get_regcache_arch (regcache);
2692 pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
2693 if (breakpoint_inserted_here_p (pc))
2695 if (debug_linux_nat)
2696 fprintf_unfiltered (gdb_stdlog,
2697 "CB: Push back breakpoint for %s\n",
2698 target_pid_to_str (lp->ptid));
2700 /* Back up the PC if necessary. */
2701 if (gdbarch_decr_pc_after_break (gdbarch))
2702 regcache_write_pc (regcache, pc);
2710 cancel_breakpoints_callback (struct lwp_info *lp, void *data)
2712 struct lwp_info *event_lp = data;
2714 /* Leave the LWP that has been elected to receive a SIGTRAP alone. */
2718 /* If a LWP other than the LWP that we're reporting an event for has
2719 hit a GDB breakpoint (as opposed to some random trap signal),
2720 then just arrange for it to hit it again later. We don't keep
2721 the SIGTRAP status and don't forward the SIGTRAP signal to the
2722 LWP. We will handle the current event, eventually we will resume
2723 all LWPs, and this one will get its breakpoint trap again.
2725 If we do not do this, then we run the risk that the user will
2726 delete or disable the breakpoint, but the LWP will have already
2729 if (lp->waitstatus.kind == TARGET_WAITKIND_IGNORE
2731 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
2732 && cancel_breakpoint (lp))
2733 /* Throw away the SIGTRAP. */
2739 /* Select one LWP out of those that have events pending. */
2742 select_event_lwp (ptid_t filter, struct lwp_info **orig_lp, int *status)
2745 int random_selector;
2746 struct lwp_info *event_lp;
2748 /* Record the wait status for the original LWP. */
2749 (*orig_lp)->status = *status;
2751 /* Give preference to any LWP that is being single-stepped. */
2752 event_lp = iterate_over_lwps (filter,
2753 select_singlestep_lwp_callback, NULL);
2754 if (event_lp != NULL)
2756 if (debug_linux_nat)
2757 fprintf_unfiltered (gdb_stdlog,
2758 "SEL: Select single-step %s\n",
2759 target_pid_to_str (event_lp->ptid));
2763 /* No single-stepping LWP. Select one at random, out of those
2764 which have had SIGTRAP events. */
2766 /* First see how many SIGTRAP events we have. */
2767 iterate_over_lwps (filter, count_events_callback, &num_events);
2769 /* Now randomly pick a LWP out of those that have had a SIGTRAP. */
2770 random_selector = (int)
2771 ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
2773 if (debug_linux_nat && num_events > 1)
2774 fprintf_unfiltered (gdb_stdlog,
2775 "SEL: Found %d SIGTRAP events, selecting #%d\n",
2776 num_events, random_selector);
2778 event_lp = iterate_over_lwps (filter,
2779 select_event_lwp_callback,
2783 if (event_lp != NULL)
2785 /* Switch the event LWP. */
2786 *orig_lp = event_lp;
2787 *status = event_lp->status;
2790 /* Flush the wait status for the event LWP. */
2791 (*orig_lp)->status = 0;
2794 /* Return non-zero if LP has been resumed. */
2797 resumed_callback (struct lwp_info *lp, void *data)
2802 /* Stop an active thread, verify it still exists, then resume it. */
2805 stop_and_resume_callback (struct lwp_info *lp, void *data)
2807 struct lwp_info *ptr;
2809 if (!lp->stopped && !lp->signalled)
2811 stop_callback (lp, NULL);
2812 stop_wait_callback (lp, NULL);
2813 /* Resume if the lwp still exists. */
2814 for (ptr = lwp_list; ptr; ptr = ptr->next)
2817 resume_callback (lp, NULL);
2818 resume_set_callback (lp, NULL);
2824 /* Check if we should go on and pass this event to common code.
2825 Return the affected lwp if we are, or NULL otherwise. */
2826 static struct lwp_info *
2827 linux_nat_filter_event (int lwpid, int status, int options)
2829 struct lwp_info *lp;
2831 lp = find_lwp_pid (pid_to_ptid (lwpid));
2833 /* Check for stop events reported by a process we didn't already
2834 know about - anything not already in our LWP list.
2836 If we're expecting to receive stopped processes after
2837 fork, vfork, and clone events, then we'll just add the
2838 new one to our list and go back to waiting for the event
2839 to be reported - the stopped process might be returned
2840 from waitpid before or after the event is. */
2841 if (WIFSTOPPED (status) && !lp)
2843 linux_record_stopped_pid (lwpid, status);
2847 /* Make sure we don't report an event for the exit of an LWP not in
2848 our list, i.e. not part of the current process. This can happen
2849 if we detach from a program we original forked and then it
2851 if (!WIFSTOPPED (status) && !lp)
2854 /* NOTE drow/2003-06-17: This code seems to be meant for debugging
2855 CLONE_PTRACE processes which do not use the thread library -
2856 otherwise we wouldn't find the new LWP this way. That doesn't
2857 currently work, and the following code is currently unreachable
2858 due to the two blocks above. If it's fixed some day, this code
2859 should be broken out into a function so that we can also pick up
2860 LWPs from the new interface. */
2863 lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
2864 if (options & __WCLONE)
2867 gdb_assert (WIFSTOPPED (status)
2868 && WSTOPSIG (status) == SIGSTOP);
2871 if (!in_thread_list (inferior_ptid))
2873 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
2874 GET_PID (inferior_ptid));
2875 add_thread (inferior_ptid);
2878 add_thread (lp->ptid);
2881 /* Handle GNU/Linux's syscall SIGTRAPs. */
2882 if (WIFSTOPPED (status) && WSTOPSIG (status) == SYSCALL_SIGTRAP)
2884 /* No longer need the sysgood bit. The ptrace event ends up
2885 recorded in lp->waitstatus if we care for it. We can carry
2886 on handling the event like a regular SIGTRAP from here
2888 status = W_STOPCODE (SIGTRAP);
2889 if (linux_handle_syscall_trap (lp, 0))
2893 /* Handle GNU/Linux's extended waitstatus for trace events. */
2894 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2896 if (debug_linux_nat)
2897 fprintf_unfiltered (gdb_stdlog,
2898 "LLW: Handling extended status 0x%06x\n",
2900 if (linux_handle_extended_wait (lp, status, 0))
2904 /* Save the trap's siginfo in case we need it later. */
2905 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2908 /* Check if the thread has exited. */
2909 if ((WIFEXITED (status) || WIFSIGNALED (status))
2910 && num_lwps (GET_PID (lp->ptid)) > 1)
2912 /* If this is the main thread, we must stop all threads and verify
2913 if they are still alive. This is because in the nptl thread model
2914 on Linux 2.4, there is no signal issued for exiting LWPs
2915 other than the main thread. We only get the main thread exit
2916 signal once all child threads have already exited. If we
2917 stop all the threads and use the stop_wait_callback to check
2918 if they have exited we can determine whether this signal
2919 should be ignored or whether it means the end of the debugged
2920 application, regardless of which threading model is being
2922 if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
2925 iterate_over_lwps (pid_to_ptid (GET_PID (lp->ptid)),
2926 stop_and_resume_callback, NULL);
2929 if (debug_linux_nat)
2930 fprintf_unfiltered (gdb_stdlog,
2931 "LLW: %s exited.\n",
2932 target_pid_to_str (lp->ptid));
2934 if (num_lwps (GET_PID (lp->ptid)) > 1)
2936 /* If there is at least one more LWP, then the exit signal
2937 was not the end of the debugged application and should be
2944 /* Check if the current LWP has previously exited. In the nptl
2945 thread model, LWPs other than the main thread do not issue
2946 signals when they exit so we must check whenever the thread has
2947 stopped. A similar check is made in stop_wait_callback(). */
2948 if (num_lwps (GET_PID (lp->ptid)) > 1 && !linux_thread_alive (lp->ptid))
2950 ptid_t ptid = pid_to_ptid (GET_PID (lp->ptid));
2952 if (debug_linux_nat)
2953 fprintf_unfiltered (gdb_stdlog,
2954 "LLW: %s exited.\n",
2955 target_pid_to_str (lp->ptid));
2959 /* Make sure there is at least one thread running. */
2960 gdb_assert (iterate_over_lwps (ptid, running_callback, NULL));
2962 /* Discard the event. */
2966 /* Make sure we don't report a SIGSTOP that we sent ourselves in
2967 an attempt to stop an LWP. */
2969 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2971 if (debug_linux_nat)
2972 fprintf_unfiltered (gdb_stdlog,
2973 "LLW: Delayed SIGSTOP caught for %s.\n",
2974 target_pid_to_str (lp->ptid));
2976 /* This is a delayed SIGSTOP. */
2979 registers_changed ();
2981 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
2982 lp->step, TARGET_SIGNAL_0);
2983 if (debug_linux_nat)
2984 fprintf_unfiltered (gdb_stdlog,
2985 "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
2987 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2988 target_pid_to_str (lp->ptid));
2991 gdb_assert (lp->resumed);
2993 /* Discard the event. */
2997 /* Make sure we don't report a SIGINT that we have already displayed
2998 for another thread. */
2999 if (lp->ignore_sigint
3000 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGINT)
3002 if (debug_linux_nat)
3003 fprintf_unfiltered (gdb_stdlog,
3004 "LLW: Delayed SIGINT caught for %s.\n",
3005 target_pid_to_str (lp->ptid));
3007 /* This is a delayed SIGINT. */
3008 lp->ignore_sigint = 0;
3010 registers_changed ();
3011 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
3012 lp->step, TARGET_SIGNAL_0);
3013 if (debug_linux_nat)
3014 fprintf_unfiltered (gdb_stdlog,
3015 "LLW: %s %s, 0, 0 (discard SIGINT)\n",
3017 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
3018 target_pid_to_str (lp->ptid));
3021 gdb_assert (lp->resumed);
3023 /* Discard the event. */
3027 /* An interesting event. */
3029 lp->status = status;
3034 linux_nat_wait_1 (struct target_ops *ops,
3035 ptid_t ptid, struct target_waitstatus *ourstatus,
3038 static sigset_t prev_mask;
3039 struct lwp_info *lp = NULL;
3044 if (debug_linux_nat_async)
3045 fprintf_unfiltered (gdb_stdlog, "LLW: enter\n");
3047 /* The first time we get here after starting a new inferior, we may
3048 not have added it to the LWP list yet - this is the earliest
3049 moment at which we know its PID. */
3050 if (ptid_is_pid (inferior_ptid))
3052 /* Upgrade the main thread's ptid. */
3053 thread_change_ptid (inferior_ptid,
3054 BUILD_LWP (GET_PID (inferior_ptid),
3055 GET_PID (inferior_ptid)));
3057 lp = add_lwp (inferior_ptid);
3061 /* Make sure SIGCHLD is blocked. */
3062 block_child_signals (&prev_mask);
3064 if (ptid_equal (ptid, minus_one_ptid))
3066 else if (ptid_is_pid (ptid))
3067 /* A request to wait for a specific tgid. This is not possible
3068 with waitpid, so instead, we wait for any child, and leave
3069 children we're not interested in right now with a pending
3070 status to report later. */
3073 pid = GET_LWP (ptid);
3079 /* Make sure there is at least one LWP that has been resumed. */
3080 gdb_assert (iterate_over_lwps (ptid, resumed_callback, NULL));
3082 /* First check if there is a LWP with a wait status pending. */
3085 /* Any LWP that's been resumed will do. */
3086 lp = iterate_over_lwps (ptid, status_callback, NULL);
3089 if (debug_linux_nat && lp->status)
3090 fprintf_unfiltered (gdb_stdlog,
3091 "LLW: Using pending wait status %s for %s.\n",
3092 status_to_str (lp->status),
3093 target_pid_to_str (lp->ptid));
3096 /* But if we don't find one, we'll have to wait, and check both
3097 cloned and uncloned processes. We start with the cloned
3099 options = __WCLONE | WNOHANG;
3101 else if (is_lwp (ptid))
3103 if (debug_linux_nat)
3104 fprintf_unfiltered (gdb_stdlog,
3105 "LLW: Waiting for specific LWP %s.\n",
3106 target_pid_to_str (ptid));
3108 /* We have a specific LWP to check. */
3109 lp = find_lwp_pid (ptid);
3112 if (debug_linux_nat && lp->status)
3113 fprintf_unfiltered (gdb_stdlog,
3114 "LLW: Using pending wait status %s for %s.\n",
3115 status_to_str (lp->status),
3116 target_pid_to_str (lp->ptid));
3118 /* If we have to wait, take into account whether PID is a cloned
3119 process or not. And we have to convert it to something that
3120 the layer beneath us can understand. */
3121 options = lp->cloned ? __WCLONE : 0;
3122 pid = GET_LWP (ptid);
3124 /* We check for lp->waitstatus in addition to lp->status,
3125 because we can have pending process exits recorded in
3126 lp->status and W_EXITCODE(0,0) == 0. We should probably have
3127 an additional lp->status_p flag. */
3128 if (lp->status == 0 && lp->waitstatus.kind == TARGET_WAITKIND_IGNORE)
3132 if (lp && lp->signalled)
3134 /* A pending SIGSTOP may interfere with the normal stream of
3135 events. In a typical case where interference is a problem,
3136 we have a SIGSTOP signal pending for LWP A while
3137 single-stepping it, encounter an event in LWP B, and take the
3138 pending SIGSTOP while trying to stop LWP A. After processing
3139 the event in LWP B, LWP A is continued, and we'll never see
3140 the SIGTRAP associated with the last time we were
3141 single-stepping LWP A. */
3143 /* Resume the thread. It should halt immediately returning the
3145 registers_changed ();
3146 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
3147 lp->step, TARGET_SIGNAL_0);
3148 if (debug_linux_nat)
3149 fprintf_unfiltered (gdb_stdlog,
3150 "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
3151 lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
3152 target_pid_to_str (lp->ptid));
3154 gdb_assert (lp->resumed);
3156 /* Catch the pending SIGSTOP. */
3157 status = lp->status;
3160 stop_wait_callback (lp, NULL);
3162 /* If the lp->status field isn't empty, we caught another signal
3163 while flushing the SIGSTOP. Return it back to the event
3164 queue of the LWP, as we already have an event to handle. */
3167 if (debug_linux_nat)
3168 fprintf_unfiltered (gdb_stdlog,
3169 "LLW: kill %s, %s\n",
3170 target_pid_to_str (lp->ptid),
3171 status_to_str (lp->status));
3172 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
3175 lp->status = status;
3178 if (!target_can_async_p ())
3180 /* Causes SIGINT to be passed on to the attached process. */
3184 /* Translate generic target_wait options into waitpid options. */
3185 if (target_options & TARGET_WNOHANG)
3192 lwpid = my_waitpid (pid, &status, options);
3196 gdb_assert (pid == -1 || lwpid == pid);
3198 if (debug_linux_nat)
3200 fprintf_unfiltered (gdb_stdlog,
3201 "LLW: waitpid %ld received %s\n",
3202 (long) lwpid, status_to_str (status));
3205 lp = linux_nat_filter_event (lwpid, status, options);
3208 && ptid_is_pid (ptid)
3209 && ptid_get_pid (lp->ptid) != ptid_get_pid (ptid))
3211 if (debug_linux_nat)
3212 fprintf (stderr, "LWP %ld got an event %06x, leaving pending.\n",
3213 ptid_get_lwp (lp->ptid), status);
3215 if (WIFSTOPPED (lp->status))
3217 if (WSTOPSIG (lp->status) != SIGSTOP)
3219 stop_callback (lp, NULL);
3221 /* Resume in order to collect the sigstop. */
3222 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
3224 stop_wait_callback (lp, NULL);
3232 else if (WIFEXITED (status) || WIFSIGNALED (status))
3234 if (debug_linux_nat)
3235 fprintf (stderr, "Process %ld exited while stopping LWPs\n",
3236 ptid_get_lwp (lp->ptid));
3238 /* This was the last lwp in the process. Since
3239 events are serialized to GDB core, and we can't
3240 report this one right now, but GDB core and the
3241 other target layers will want to be notified
3242 about the exit code/signal, leave the status
3243 pending for the next time we're able to report
3246 /* Prevent trying to stop this thread again. We'll
3247 never try to resume it because it has a pending
3251 /* Dead LWP's aren't expected to reported a pending
3255 /* Store the pending event in the waitstatus as
3256 well, because W_EXITCODE(0,0) == 0. */
3257 store_waitstatus (&lp->waitstatus, lp->status);
3271 /* waitpid did return something. Restart over. */
3272 options |= __WCLONE;
3280 /* Alternate between checking cloned and uncloned processes. */
3281 options ^= __WCLONE;
3283 /* And every time we have checked both:
3284 In async mode, return to event loop;
3285 In sync mode, suspend waiting for a SIGCHLD signal. */
3286 if (options & __WCLONE)
3288 if (target_options & TARGET_WNOHANG)
3290 /* No interesting event. */
3291 ourstatus->kind = TARGET_WAITKIND_IGNORE;
3293 if (debug_linux_nat_async)
3294 fprintf_unfiltered (gdb_stdlog, "LLW: exit (ignore)\n");
3296 restore_child_signals_mask (&prev_mask);
3297 return minus_one_ptid;
3300 sigsuspend (&suspend_mask);
3303 else if (target_options & TARGET_WNOHANG)
3305 /* No interesting event for PID yet. */
3306 ourstatus->kind = TARGET_WAITKIND_IGNORE;
3308 if (debug_linux_nat_async)
3309 fprintf_unfiltered (gdb_stdlog, "LLW: exit (ignore)\n");
3311 restore_child_signals_mask (&prev_mask);
3312 return minus_one_ptid;
3315 /* We shouldn't end up here unless we want to try again. */
3316 gdb_assert (lp == NULL);
3319 if (!target_can_async_p ())
3320 clear_sigint_trap ();
3324 status = lp->status;
3327 /* Don't report signals that GDB isn't interested in, such as
3328 signals that are neither printed nor stopped upon. Stopping all
3329 threads can be a bit time-consuming so if we want decent
3330 performance with heavily multi-threaded programs, especially when
3331 they're using a high frequency timer, we'd better avoid it if we
3334 if (WIFSTOPPED (status))
3336 int signo = target_signal_from_host (WSTOPSIG (status));
3337 struct inferior *inf;
3339 inf = find_inferior_pid (ptid_get_pid (lp->ptid));
3342 /* Defer to common code if we get a signal while
3343 single-stepping, since that may need special care, e.g. to
3344 skip the signal handler, or, if we're gaining control of the
3347 && inf->stop_soon == NO_STOP_QUIETLY
3348 && signal_stop_state (signo) == 0
3349 && signal_print_state (signo) == 0
3350 && signal_pass_state (signo) == 1)
3352 /* FIMXE: kettenis/2001-06-06: Should we resume all threads
3353 here? It is not clear we should. GDB may not expect
3354 other threads to run. On the other hand, not resuming
3355 newly attached threads may cause an unwanted delay in
3356 getting them running. */
3357 registers_changed ();
3358 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
3360 if (debug_linux_nat)
3361 fprintf_unfiltered (gdb_stdlog,
3362 "LLW: %s %s, %s (preempt 'handle')\n",
3364 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
3365 target_pid_to_str (lp->ptid),
3366 signo ? strsignal (signo) : "0");
3373 /* Only do the below in all-stop, as we currently use SIGINT
3374 to implement target_stop (see linux_nat_stop) in
3376 if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
3378 /* If ^C/BREAK is typed at the tty/console, SIGINT gets
3379 forwarded to the entire process group, that is, all LWPs
3380 will receive it - unless they're using CLONE_THREAD to
3381 share signals. Since we only want to report it once, we
3382 mark it as ignored for all LWPs except this one. */
3383 iterate_over_lwps (pid_to_ptid (ptid_get_pid (ptid)),
3384 set_ignore_sigint, NULL);
3385 lp->ignore_sigint = 0;
3388 maybe_clear_ignore_sigint (lp);
3392 /* This LWP is stopped now. */
3395 if (debug_linux_nat)
3396 fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
3397 status_to_str (status), target_pid_to_str (lp->ptid));
3401 /* Now stop all other LWP's ... */
3402 iterate_over_lwps (minus_one_ptid, stop_callback, NULL);
3404 /* ... and wait until all of them have reported back that
3405 they're no longer running. */
3406 iterate_over_lwps (minus_one_ptid, stop_wait_callback, NULL);
3408 /* If we're not waiting for a specific LWP, choose an event LWP
3409 from among those that have had events. Giving equal priority
3410 to all LWPs that have had events helps prevent
3413 select_event_lwp (ptid, &lp, &status);
3416 /* Now that we've selected our final event LWP, cancel any
3417 breakpoints in other LWPs that have hit a GDB breakpoint. See
3418 the comment in cancel_breakpoints_callback to find out why. */
3419 iterate_over_lwps (minus_one_ptid, cancel_breakpoints_callback, lp);
3421 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
3423 if (debug_linux_nat)
3424 fprintf_unfiltered (gdb_stdlog,
3425 "LLW: trap ptid is %s.\n",
3426 target_pid_to_str (lp->ptid));
3429 if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
3431 *ourstatus = lp->waitstatus;
3432 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
3435 store_waitstatus (ourstatus, status);
3437 if (debug_linux_nat_async)
3438 fprintf_unfiltered (gdb_stdlog, "LLW: exit\n");
3440 restore_child_signals_mask (&prev_mask);
3445 linux_nat_wait (struct target_ops *ops,
3446 ptid_t ptid, struct target_waitstatus *ourstatus,
3451 if (debug_linux_nat)
3452 fprintf_unfiltered (gdb_stdlog, "linux_nat_wait: [%s]\n", target_pid_to_str (ptid));
3454 /* Flush the async file first. */
3455 if (target_can_async_p ())
3456 async_file_flush ();
3458 event_ptid = linux_nat_wait_1 (ops, ptid, ourstatus, target_options);
3460 /* If we requested any event, and something came out, assume there
3461 may be more. If we requested a specific lwp or process, also
3462 assume there may be more. */
3463 if (target_can_async_p ()
3464 && (ourstatus->kind != TARGET_WAITKIND_IGNORE
3465 || !ptid_equal (ptid, minus_one_ptid)))
3468 /* Get ready for the next event. */
3469 if (target_can_async_p ())
3470 target_async (inferior_event_handler, 0);
3476 kill_callback (struct lwp_info *lp, void *data)
3479 ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
3480 if (debug_linux_nat)
3481 fprintf_unfiltered (gdb_stdlog,
3482 "KC: PTRACE_KILL %s, 0, 0 (%s)\n",
3483 target_pid_to_str (lp->ptid),
3484 errno ? safe_strerror (errno) : "OK");
3490 kill_wait_callback (struct lwp_info *lp, void *data)
3494 /* We must make sure that there are no pending events (delayed
3495 SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
3496 program doesn't interfere with any following debugging session. */
3498 /* For cloned processes we must check both with __WCLONE and
3499 without, since the exit status of a cloned process isn't reported
3505 pid = my_waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
3506 if (pid != (pid_t) -1)
3508 if (debug_linux_nat)
3509 fprintf_unfiltered (gdb_stdlog,
3510 "KWC: wait %s received unknown.\n",
3511 target_pid_to_str (lp->ptid));
3512 /* The Linux kernel sometimes fails to kill a thread
3513 completely after PTRACE_KILL; that goes from the stop
3514 point in do_fork out to the one in
3515 get_signal_to_deliever and waits again. So kill it
3517 kill_callback (lp, NULL);
3520 while (pid == GET_LWP (lp->ptid));
3522 gdb_assert (pid == -1 && errno == ECHILD);
3527 pid = my_waitpid (GET_LWP (lp->ptid), NULL, 0);
3528 if (pid != (pid_t) -1)
3530 if (debug_linux_nat)
3531 fprintf_unfiltered (gdb_stdlog,
3532 "KWC: wait %s received unk.\n",
3533 target_pid_to_str (lp->ptid));
3534 /* See the call to kill_callback above. */
3535 kill_callback (lp, NULL);
3538 while (pid == GET_LWP (lp->ptid));
3540 gdb_assert (pid == -1 && errno == ECHILD);
3545 linux_nat_kill (struct target_ops *ops)
3547 struct target_waitstatus last;
3551 /* If we're stopped while forking and we haven't followed yet,
3552 kill the other task. We need to do this first because the
3553 parent will be sleeping if this is a vfork. */
3555 get_last_target_status (&last_ptid, &last);
3557 if (last.kind == TARGET_WAITKIND_FORKED
3558 || last.kind == TARGET_WAITKIND_VFORKED)
3560 ptrace (PT_KILL, PIDGET (last.value.related_pid), 0, 0);
3564 if (forks_exist_p ())
3565 linux_fork_killall ();
3568 ptid_t ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
3569 /* Stop all threads before killing them, since ptrace requires
3570 that the thread is stopped to sucessfully PTRACE_KILL. */
3571 iterate_over_lwps (ptid, stop_callback, NULL);
3572 /* ... and wait until all of them have reported back that
3573 they're no longer running. */
3574 iterate_over_lwps (ptid, stop_wait_callback, NULL);
3576 /* Kill all LWP's ... */
3577 iterate_over_lwps (ptid, kill_callback, NULL);
3579 /* ... and wait until we've flushed all events. */
3580 iterate_over_lwps (ptid, kill_wait_callback, NULL);
3583 target_mourn_inferior ();
3587 linux_nat_mourn_inferior (struct target_ops *ops)
3589 purge_lwp_list (ptid_get_pid (inferior_ptid));
3591 if (! forks_exist_p ())
3592 /* Normal case, no other forks available. */
3593 linux_ops->to_mourn_inferior (ops);
3595 /* Multi-fork case. The current inferior_ptid has exited, but
3596 there are other viable forks to debug. Delete the exiting
3597 one and context-switch to the first available. */
3598 linux_fork_mourn_inferior ();
3601 /* Convert a native/host siginfo object, into/from the siginfo in the
3602 layout of the inferiors' architecture. */
3605 siginfo_fixup (struct siginfo *siginfo, gdb_byte *inf_siginfo, int direction)
3609 if (linux_nat_siginfo_fixup != NULL)
3610 done = linux_nat_siginfo_fixup (siginfo, inf_siginfo, direction);
3612 /* If there was no callback, or the callback didn't do anything,
3613 then just do a straight memcpy. */
3617 memcpy (siginfo, inf_siginfo, sizeof (struct siginfo));
3619 memcpy (inf_siginfo, siginfo, sizeof (struct siginfo));
3624 linux_xfer_siginfo (struct target_ops *ops, enum target_object object,
3625 const char *annex, gdb_byte *readbuf,
3626 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
3629 struct siginfo siginfo;
3630 gdb_byte inf_siginfo[sizeof (struct siginfo)];
3632 gdb_assert (object == TARGET_OBJECT_SIGNAL_INFO);
3633 gdb_assert (readbuf || writebuf);
3635 pid = GET_LWP (inferior_ptid);
3637 pid = GET_PID (inferior_ptid);
3639 if (offset > sizeof (siginfo))
3643 ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
3647 /* When GDB is built as a 64-bit application, ptrace writes into
3648 SIGINFO an object with 64-bit layout. Since debugging a 32-bit
3649 inferior with a 64-bit GDB should look the same as debugging it
3650 with a 32-bit GDB, we need to convert it. GDB core always sees
3651 the converted layout, so any read/write will have to be done
3653 siginfo_fixup (&siginfo, inf_siginfo, 0);
3655 if (offset + len > sizeof (siginfo))
3656 len = sizeof (siginfo) - offset;
3658 if (readbuf != NULL)
3659 memcpy (readbuf, inf_siginfo + offset, len);
3662 memcpy (inf_siginfo + offset, writebuf, len);
3664 /* Convert back to ptrace layout before flushing it out. */
3665 siginfo_fixup (&siginfo, inf_siginfo, 1);
3668 ptrace (PTRACE_SETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
3677 linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
3678 const char *annex, gdb_byte *readbuf,
3679 const gdb_byte *writebuf,
3680 ULONGEST offset, LONGEST len)
3682 struct cleanup *old_chain;
3685 if (object == TARGET_OBJECT_SIGNAL_INFO)
3686 return linux_xfer_siginfo (ops, object, annex, readbuf, writebuf,
3689 /* The target is connected but no live inferior is selected. Pass
3690 this request down to a lower stratum (e.g., the executable
3692 if (object == TARGET_OBJECT_MEMORY && ptid_equal (inferior_ptid, null_ptid))
3695 old_chain = save_inferior_ptid ();
3697 if (is_lwp (inferior_ptid))
3698 inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
3700 xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
3703 do_cleanups (old_chain);
3708 linux_thread_alive (ptid_t ptid)
3712 gdb_assert (is_lwp (ptid));
3714 /* Send signal 0 instead of anything ptrace, because ptracing a
3715 running thread errors out claiming that the thread doesn't
3717 err = kill_lwp (GET_LWP (ptid), 0);
3719 if (debug_linux_nat)
3720 fprintf_unfiltered (gdb_stdlog,
3721 "LLTA: KILL(SIG0) %s (%s)\n",
3722 target_pid_to_str (ptid),
3723 err ? safe_strerror (err) : "OK");
3732 linux_nat_thread_alive (struct target_ops *ops, ptid_t ptid)
3734 return linux_thread_alive (ptid);
3738 linux_nat_pid_to_str (struct target_ops *ops, ptid_t ptid)
3740 static char buf[64];
3743 && (GET_PID (ptid) != GET_LWP (ptid)
3744 || num_lwps (GET_PID (ptid)) > 1))
3746 snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
3750 return normal_pid_to_str (ptid);
3753 /* Accepts an integer PID; Returns a string representing a file that
3754 can be opened to get the symbols for the child process. */
3757 linux_child_pid_to_exec_file (int pid)
3759 char *name1, *name2;
3761 name1 = xmalloc (MAXPATHLEN);
3762 name2 = xmalloc (MAXPATHLEN);
3763 make_cleanup (xfree, name1);
3764 make_cleanup (xfree, name2);
3765 memset (name2, 0, MAXPATHLEN);
3767 sprintf (name1, "/proc/%d/exe", pid);
3768 if (readlink (name1, name2, MAXPATHLEN) > 0)
3774 /* Service function for corefiles and info proc. */
3777 read_mapping (FILE *mapfile,
3782 char *device, long long *inode, char *filename)
3784 int ret = fscanf (mapfile, "%llx-%llx %s %llx %s %llx",
3785 addr, endaddr, permissions, offset, device, inode);
3788 if (ret > 0 && ret != EOF)
3790 /* Eat everything up to EOL for the filename. This will prevent
3791 weird filenames (such as one with embedded whitespace) from
3792 confusing this code. It also makes this code more robust in
3793 respect to annotations the kernel may add after the filename.
3795 Note the filename is used for informational purposes
3797 ret += fscanf (mapfile, "%[^\n]\n", filename);
3800 return (ret != 0 && ret != EOF);
3803 /* Fills the "to_find_memory_regions" target vector. Lists the memory
3804 regions in the inferior for a corefile. */
3807 linux_nat_find_memory_regions (int (*func) (CORE_ADDR,
3809 int, int, int, void *), void *obfd)
3811 int pid = PIDGET (inferior_ptid);
3812 char mapsfilename[MAXPATHLEN];
3814 long long addr, endaddr, size, offset, inode;
3815 char permissions[8], device[8], filename[MAXPATHLEN];
3816 int read, write, exec;
3818 struct cleanup *cleanup;
3820 /* Compose the filename for the /proc memory map, and open it. */
3821 sprintf (mapsfilename, "/proc/%d/maps", pid);
3822 if ((mapsfile = fopen (mapsfilename, "r")) == NULL)
3823 error (_("Could not open %s."), mapsfilename);
3824 cleanup = make_cleanup_fclose (mapsfile);
3827 fprintf_filtered (gdb_stdout,
3828 "Reading memory regions from %s\n", mapsfilename);
3830 /* Now iterate until end-of-file. */
3831 while (read_mapping (mapsfile, &addr, &endaddr, &permissions[0],
3832 &offset, &device[0], &inode, &filename[0]))
3834 size = endaddr - addr;
3836 /* Get the segment's permissions. */
3837 read = (strchr (permissions, 'r') != 0);
3838 write = (strchr (permissions, 'w') != 0);
3839 exec = (strchr (permissions, 'x') != 0);
3843 fprintf_filtered (gdb_stdout,
3844 "Save segment, %lld bytes at %s (%c%c%c)",
3845 size, paddress (target_gdbarch, addr),
3847 write ? 'w' : ' ', exec ? 'x' : ' ');
3849 fprintf_filtered (gdb_stdout, " for %s", filename);
3850 fprintf_filtered (gdb_stdout, "\n");
3853 /* Invoke the callback function to create the corefile
3855 func (addr, size, read, write, exec, obfd);
3857 do_cleanups (cleanup);
3862 find_signalled_thread (struct thread_info *info, void *data)
3864 if (info->stop_signal != TARGET_SIGNAL_0
3865 && ptid_get_pid (info->ptid) == ptid_get_pid (inferior_ptid))
3871 static enum target_signal
3872 find_stop_signal (void)
3874 struct thread_info *info =
3875 iterate_over_threads (find_signalled_thread, NULL);
3878 return info->stop_signal;
3880 return TARGET_SIGNAL_0;
3883 /* Records the thread's register state for the corefile note
3887 linux_nat_do_thread_registers (bfd *obfd, ptid_t ptid,
3888 char *note_data, int *note_size,
3889 enum target_signal stop_signal)
3891 gdb_gregset_t gregs;
3892 gdb_fpregset_t fpregs;
3893 unsigned long lwp = ptid_get_lwp (ptid);
3894 struct gdbarch *gdbarch = target_gdbarch;
3895 struct regcache *regcache = get_thread_arch_regcache (ptid, gdbarch);
3896 const struct regset *regset;
3898 struct cleanup *old_chain;
3899 struct core_regset_section *sect_list;
3902 old_chain = save_inferior_ptid ();
3903 inferior_ptid = ptid;
3904 target_fetch_registers (regcache, -1);
3905 do_cleanups (old_chain);
3907 core_regset_p = gdbarch_regset_from_core_section_p (gdbarch);
3908 sect_list = gdbarch_core_regset_sections (gdbarch);
3911 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg",
3912 sizeof (gregs))) != NULL
3913 && regset->collect_regset != NULL)
3914 regset->collect_regset (regset, regcache, -1,
3915 &gregs, sizeof (gregs));
3917 fill_gregset (regcache, &gregs, -1);
3919 note_data = (char *) elfcore_write_prstatus (obfd,
3923 stop_signal, &gregs);
3925 /* The loop below uses the new struct core_regset_section, which stores
3926 the supported section names and sizes for the core file. Note that
3927 note PRSTATUS needs to be treated specially. But the other notes are
3928 structurally the same, so they can benefit from the new struct. */
3929 if (core_regset_p && sect_list != NULL)
3930 while (sect_list->sect_name != NULL)
3932 /* .reg was already handled above. */
3933 if (strcmp (sect_list->sect_name, ".reg") == 0)
3938 regset = gdbarch_regset_from_core_section (gdbarch,
3939 sect_list->sect_name,
3941 gdb_assert (regset && regset->collect_regset);
3942 gdb_regset = xmalloc (sect_list->size);
3943 regset->collect_regset (regset, regcache, -1,
3944 gdb_regset, sect_list->size);
3945 note_data = (char *) elfcore_write_register_note (obfd,
3948 sect_list->sect_name,
3955 /* For architectures that does not have the struct core_regset_section
3956 implemented, we use the old method. When all the architectures have
3957 the new support, the code below should be deleted. */
3961 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg2",
3962 sizeof (fpregs))) != NULL
3963 && regset->collect_regset != NULL)
3964 regset->collect_regset (regset, regcache, -1,
3965 &fpregs, sizeof (fpregs));
3967 fill_fpregset (regcache, &fpregs, -1);
3969 note_data = (char *) elfcore_write_prfpreg (obfd,
3972 &fpregs, sizeof (fpregs));
3978 struct linux_nat_corefile_thread_data
3984 enum target_signal stop_signal;
3987 /* Called by gdbthread.c once per thread. Records the thread's
3988 register state for the corefile note section. */
3991 linux_nat_corefile_thread_callback (struct lwp_info *ti, void *data)
3993 struct linux_nat_corefile_thread_data *args = data;
3995 args->note_data = linux_nat_do_thread_registers (args->obfd,
4005 /* Enumerate spufs IDs for process PID. */
4008 iterate_over_spus (int pid, void (*callback) (void *, int), void *data)
4012 struct dirent *entry;
4014 xsnprintf (path, sizeof path, "/proc/%d/fd", pid);
4015 dir = opendir (path);
4020 while ((entry = readdir (dir)) != NULL)
4026 fd = atoi (entry->d_name);
4030 xsnprintf (path, sizeof path, "/proc/%d/fd/%d", pid, fd);
4031 if (stat (path, &st) != 0)
4033 if (!S_ISDIR (st.st_mode))
4036 if (statfs (path, &stfs) != 0)
4038 if (stfs.f_type != SPUFS_MAGIC)
4041 callback (data, fd);
4047 /* Generate corefile notes for SPU contexts. */
4049 struct linux_spu_corefile_data
4057 linux_spu_corefile_callback (void *data, int fd)
4059 struct linux_spu_corefile_data *args = data;
4062 static const char *spu_files[] =
4084 for (i = 0; i < sizeof (spu_files) / sizeof (spu_files[0]); i++)
4086 char annex[32], note_name[32];
4090 xsnprintf (annex, sizeof annex, "%d/%s", fd, spu_files[i]);
4091 spu_len = target_read_alloc (¤t_target, TARGET_OBJECT_SPU,
4095 xsnprintf (note_name, sizeof note_name, "SPU/%s", annex);
4096 args->note_data = elfcore_write_note (args->obfd, args->note_data,
4097 args->note_size, note_name,
4098 NT_SPU, spu_data, spu_len);
4105 linux_spu_make_corefile_notes (bfd *obfd, char *note_data, int *note_size)
4107 struct linux_spu_corefile_data args;
4109 args.note_data = note_data;
4110 args.note_size = note_size;
4112 iterate_over_spus (PIDGET (inferior_ptid),
4113 linux_spu_corefile_callback, &args);
4115 return args.note_data;
4118 /* Fills the "to_make_corefile_note" target vector. Builds the note
4119 section for a corefile, and returns it in a malloc buffer. */
4122 linux_nat_make_corefile_notes (bfd *obfd, int *note_size)
4124 struct linux_nat_corefile_thread_data thread_args;
4125 struct cleanup *old_chain;
4126 /* The variable size must be >= sizeof (prpsinfo_t.pr_fname). */
4127 char fname[16] = { '\0' };
4128 /* The variable size must be >= sizeof (prpsinfo_t.pr_psargs). */
4129 char psargs[80] = { '\0' };
4130 char *note_data = NULL;
4131 ptid_t current_ptid = inferior_ptid;
4132 ptid_t filter = pid_to_ptid (ptid_get_pid (inferior_ptid));
4136 if (get_exec_file (0))
4138 strncpy (fname, strrchr (get_exec_file (0), '/') + 1, sizeof (fname));
4139 strncpy (psargs, get_exec_file (0), sizeof (psargs));
4140 if (get_inferior_args ())
4143 char *psargs_end = psargs + sizeof (psargs);
4145 /* linux_elfcore_write_prpsinfo () handles zero unterminated
4147 string_end = memchr (psargs, 0, sizeof (psargs));
4148 if (string_end != NULL)
4150 *string_end++ = ' ';
4151 strncpy (string_end, get_inferior_args (),
4152 psargs_end - string_end);
4155 note_data = (char *) elfcore_write_prpsinfo (obfd,
4157 note_size, fname, psargs);
4160 /* Dump information for threads. */
4161 thread_args.obfd = obfd;
4162 thread_args.note_data = note_data;
4163 thread_args.note_size = note_size;
4164 thread_args.num_notes = 0;
4165 thread_args.stop_signal = find_stop_signal ();
4166 iterate_over_lwps (filter, linux_nat_corefile_thread_callback, &thread_args);
4167 gdb_assert (thread_args.num_notes != 0);
4168 note_data = thread_args.note_data;
4170 auxv_len = target_read_alloc (¤t_target, TARGET_OBJECT_AUXV,
4174 note_data = elfcore_write_note (obfd, note_data, note_size,
4175 "CORE", NT_AUXV, auxv, auxv_len);
4179 note_data = linux_spu_make_corefile_notes (obfd, note_data, note_size);
4181 make_cleanup (xfree, note_data);
4185 /* Implement the "info proc" command. */
4188 linux_nat_info_proc_cmd (char *args, int from_tty)
4190 /* A long is used for pid instead of an int to avoid a loss of precision
4191 compiler warning from the output of strtoul. */
4192 long pid = PIDGET (inferior_ptid);
4195 char buffer[MAXPATHLEN];
4196 char fname1[MAXPATHLEN], fname2[MAXPATHLEN];
4209 /* Break up 'args' into an argv array. */
4210 argv = gdb_buildargv (args);
4211 make_cleanup_freeargv (argv);
4213 while (argv != NULL && *argv != NULL)
4215 if (isdigit (argv[0][0]))
4217 pid = strtoul (argv[0], NULL, 10);
4219 else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
4223 else if (strcmp (argv[0], "status") == 0)
4227 else if (strcmp (argv[0], "stat") == 0)
4231 else if (strcmp (argv[0], "cmd") == 0)
4235 else if (strncmp (argv[0], "exe", strlen (argv[0])) == 0)
4239 else if (strcmp (argv[0], "cwd") == 0)
4243 else if (strncmp (argv[0], "all", strlen (argv[0])) == 0)
4249 /* [...] (future options here) */
4254 error (_("No current process: you must name one."));
4256 sprintf (fname1, "/proc/%ld", pid);
4257 if (stat (fname1, &dummy) != 0)
4258 error (_("No /proc directory: '%s'"), fname1);
4260 printf_filtered (_("process %ld\n"), pid);
4261 if (cmdline_f || all)
4263 sprintf (fname1, "/proc/%ld/cmdline", pid);
4264 if ((procfile = fopen (fname1, "r")) != NULL)
4266 struct cleanup *cleanup = make_cleanup_fclose (procfile);
4267 if (fgets (buffer, sizeof (buffer), procfile))
4268 printf_filtered ("cmdline = '%s'\n", buffer);
4270 warning (_("unable to read '%s'"), fname1);
4271 do_cleanups (cleanup);
4274 warning (_("unable to open /proc file '%s'"), fname1);
4278 sprintf (fname1, "/proc/%ld/cwd", pid);
4279 memset (fname2, 0, sizeof (fname2));
4280 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
4281 printf_filtered ("cwd = '%s'\n", fname2);
4283 warning (_("unable to read link '%s'"), fname1);
4287 sprintf (fname1, "/proc/%ld/exe", pid);
4288 memset (fname2, 0, sizeof (fname2));
4289 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
4290 printf_filtered ("exe = '%s'\n", fname2);
4292 warning (_("unable to read link '%s'"), fname1);
4294 if (mappings_f || all)
4296 sprintf (fname1, "/proc/%ld/maps", pid);
4297 if ((procfile = fopen (fname1, "r")) != NULL)
4299 long long addr, endaddr, size, offset, inode;
4300 char permissions[8], device[8], filename[MAXPATHLEN];
4301 struct cleanup *cleanup;
4303 cleanup = make_cleanup_fclose (procfile);
4304 printf_filtered (_("Mapped address spaces:\n\n"));
4305 if (gdbarch_addr_bit (target_gdbarch) == 32)
4307 printf_filtered ("\t%10s %10s %10s %10s %7s\n",
4310 " Size", " Offset", "objfile");
4314 printf_filtered (" %18s %18s %10s %10s %7s\n",
4317 " Size", " Offset", "objfile");
4320 while (read_mapping (procfile, &addr, &endaddr, &permissions[0],
4321 &offset, &device[0], &inode, &filename[0]))
4323 size = endaddr - addr;
4325 /* FIXME: carlton/2003-08-27: Maybe the printf_filtered
4326 calls here (and possibly above) should be abstracted
4327 out into their own functions? Andrew suggests using
4328 a generic local_address_string instead to print out
4329 the addresses; that makes sense to me, too. */
4331 if (gdbarch_addr_bit (target_gdbarch) == 32)
4333 printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
4334 (unsigned long) addr, /* FIXME: pr_addr */
4335 (unsigned long) endaddr,
4337 (unsigned int) offset,
4338 filename[0] ? filename : "");
4342 printf_filtered (" %#18lx %#18lx %#10x %#10x %7s\n",
4343 (unsigned long) addr, /* FIXME: pr_addr */
4344 (unsigned long) endaddr,
4346 (unsigned int) offset,
4347 filename[0] ? filename : "");
4351 do_cleanups (cleanup);
4354 warning (_("unable to open /proc file '%s'"), fname1);
4356 if (status_f || all)
4358 sprintf (fname1, "/proc/%ld/status", pid);
4359 if ((procfile = fopen (fname1, "r")) != NULL)
4361 struct cleanup *cleanup = make_cleanup_fclose (procfile);
4362 while (fgets (buffer, sizeof (buffer), procfile) != NULL)
4363 puts_filtered (buffer);
4364 do_cleanups (cleanup);
4367 warning (_("unable to open /proc file '%s'"), fname1);
4371 sprintf (fname1, "/proc/%ld/stat", pid);
4372 if ((procfile = fopen (fname1, "r")) != NULL)
4377 struct cleanup *cleanup = make_cleanup_fclose (procfile);
4379 if (fscanf (procfile, "%d ", &itmp) > 0)
4380 printf_filtered (_("Process: %d\n"), itmp);
4381 if (fscanf (procfile, "(%[^)]) ", &buffer[0]) > 0)
4382 printf_filtered (_("Exec file: %s\n"), buffer);
4383 if (fscanf (procfile, "%c ", &ctmp) > 0)
4384 printf_filtered (_("State: %c\n"), ctmp);
4385 if (fscanf (procfile, "%d ", &itmp) > 0)
4386 printf_filtered (_("Parent process: %d\n"), itmp);
4387 if (fscanf (procfile, "%d ", &itmp) > 0)
4388 printf_filtered (_("Process group: %d\n"), itmp);
4389 if (fscanf (procfile, "%d ", &itmp) > 0)
4390 printf_filtered (_("Session id: %d\n"), itmp);
4391 if (fscanf (procfile, "%d ", &itmp) > 0)
4392 printf_filtered (_("TTY: %d\n"), itmp);
4393 if (fscanf (procfile, "%d ", &itmp) > 0)
4394 printf_filtered (_("TTY owner process group: %d\n"), itmp);
4395 if (fscanf (procfile, "%lu ", <mp) > 0)
4396 printf_filtered (_("Flags: 0x%lx\n"), ltmp);
4397 if (fscanf (procfile, "%lu ", <mp) > 0)
4398 printf_filtered (_("Minor faults (no memory page): %lu\n"),
4399 (unsigned long) ltmp);
4400 if (fscanf (procfile, "%lu ", <mp) > 0)
4401 printf_filtered (_("Minor faults, children: %lu\n"),
4402 (unsigned long) ltmp);
4403 if (fscanf (procfile, "%lu ", <mp) > 0)
4404 printf_filtered (_("Major faults (memory page faults): %lu\n"),
4405 (unsigned long) ltmp);
4406 if (fscanf (procfile, "%lu ", <mp) > 0)
4407 printf_filtered (_("Major faults, children: %lu\n"),
4408 (unsigned long) ltmp);
4409 if (fscanf (procfile, "%ld ", <mp) > 0)
4410 printf_filtered (_("utime: %ld\n"), ltmp);
4411 if (fscanf (procfile, "%ld ", <mp) > 0)
4412 printf_filtered (_("stime: %ld\n"), ltmp);
4413 if (fscanf (procfile, "%ld ", <mp) > 0)
4414 printf_filtered (_("utime, children: %ld\n"), ltmp);
4415 if (fscanf (procfile, "%ld ", <mp) > 0)
4416 printf_filtered (_("stime, children: %ld\n"), ltmp);
4417 if (fscanf (procfile, "%ld ", <mp) > 0)
4418 printf_filtered (_("jiffies remaining in current time slice: %ld\n"),
4420 if (fscanf (procfile, "%ld ", <mp) > 0)
4421 printf_filtered (_("'nice' value: %ld\n"), ltmp);
4422 if (fscanf (procfile, "%lu ", <mp) > 0)
4423 printf_filtered (_("jiffies until next timeout: %lu\n"),
4424 (unsigned long) ltmp);
4425 if (fscanf (procfile, "%lu ", <mp) > 0)
4426 printf_filtered (_("jiffies until next SIGALRM: %lu\n"),
4427 (unsigned long) ltmp);
4428 if (fscanf (procfile, "%ld ", <mp) > 0)
4429 printf_filtered (_("start time (jiffies since system boot): %ld\n"),
4431 if (fscanf (procfile, "%lu ", <mp) > 0)
4432 printf_filtered (_("Virtual memory size: %lu\n"),
4433 (unsigned long) ltmp);
4434 if (fscanf (procfile, "%lu ", <mp) > 0)
4435 printf_filtered (_("Resident set size: %lu\n"), (unsigned long) ltmp);
4436 if (fscanf (procfile, "%lu ", <mp) > 0)
4437 printf_filtered (_("rlim: %lu\n"), (unsigned long) ltmp);
4438 if (fscanf (procfile, "%lu ", <mp) > 0)
4439 printf_filtered (_("Start of text: 0x%lx\n"), ltmp);
4440 if (fscanf (procfile, "%lu ", <mp) > 0)
4441 printf_filtered (_("End of text: 0x%lx\n"), ltmp);
4442 if (fscanf (procfile, "%lu ", <mp) > 0)
4443 printf_filtered (_("Start of stack: 0x%lx\n"), ltmp);
4444 #if 0 /* Don't know how architecture-dependent the rest is...
4445 Anyway the signal bitmap info is available from "status". */
4446 if (fscanf (procfile, "%lu ", <mp) > 0) /* FIXME arch? */
4447 printf_filtered (_("Kernel stack pointer: 0x%lx\n"), ltmp);
4448 if (fscanf (procfile, "%lu ", <mp) > 0) /* FIXME arch? */
4449 printf_filtered (_("Kernel instr pointer: 0x%lx\n"), ltmp);
4450 if (fscanf (procfile, "%ld ", <mp) > 0)
4451 printf_filtered (_("Pending signals bitmap: 0x%lx\n"), ltmp);
4452 if (fscanf (procfile, "%ld ", <mp) > 0)
4453 printf_filtered (_("Blocked signals bitmap: 0x%lx\n"), ltmp);
4454 if (fscanf (procfile, "%ld ", <mp) > 0)
4455 printf_filtered (_("Ignored signals bitmap: 0x%lx\n"), ltmp);
4456 if (fscanf (procfile, "%ld ", <mp) > 0)
4457 printf_filtered (_("Catched signals bitmap: 0x%lx\n"), ltmp);
4458 if (fscanf (procfile, "%lu ", <mp) > 0) /* FIXME arch? */
4459 printf_filtered (_("wchan (system call): 0x%lx\n"), ltmp);
4461 do_cleanups (cleanup);
4464 warning (_("unable to open /proc file '%s'"), fname1);
4468 /* Implement the to_xfer_partial interface for memory reads using the /proc
4469 filesystem. Because we can use a single read() call for /proc, this
4470 can be much more efficient than banging away at PTRACE_PEEKTEXT,
4471 but it doesn't support writes. */
4474 linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
4475 const char *annex, gdb_byte *readbuf,
4476 const gdb_byte *writebuf,
4477 ULONGEST offset, LONGEST len)
4483 if (object != TARGET_OBJECT_MEMORY || !readbuf)
4486 /* Don't bother for one word. */
4487 if (len < 3 * sizeof (long))
4490 /* We could keep this file open and cache it - possibly one per
4491 thread. That requires some juggling, but is even faster. */
4492 sprintf (filename, "/proc/%d/mem", PIDGET (inferior_ptid));
4493 fd = open (filename, O_RDONLY | O_LARGEFILE);
4497 /* If pread64 is available, use it. It's faster if the kernel
4498 supports it (only one syscall), and it's 64-bit safe even on
4499 32-bit platforms (for instance, SPARC debugging a SPARC64
4502 if (pread64 (fd, readbuf, len, offset) != len)
4504 if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
4515 /* Enumerate spufs IDs for process PID. */
4517 spu_enumerate_spu_ids (int pid, gdb_byte *buf, ULONGEST offset, LONGEST len)
4519 enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch);
4521 LONGEST written = 0;
4524 struct dirent *entry;
4526 xsnprintf (path, sizeof path, "/proc/%d/fd", pid);
4527 dir = opendir (path);
4532 while ((entry = readdir (dir)) != NULL)
4538 fd = atoi (entry->d_name);
4542 xsnprintf (path, sizeof path, "/proc/%d/fd/%d", pid, fd);
4543 if (stat (path, &st) != 0)
4545 if (!S_ISDIR (st.st_mode))
4548 if (statfs (path, &stfs) != 0)
4550 if (stfs.f_type != SPUFS_MAGIC)
4553 if (pos >= offset && pos + 4 <= offset + len)
4555 store_unsigned_integer (buf + pos - offset, 4, byte_order, fd);
4565 /* Implement the to_xfer_partial interface for the TARGET_OBJECT_SPU
4566 object type, using the /proc file system. */
4568 linux_proc_xfer_spu (struct target_ops *ops, enum target_object object,
4569 const char *annex, gdb_byte *readbuf,
4570 const gdb_byte *writebuf,
4571 ULONGEST offset, LONGEST len)
4576 int pid = PIDGET (inferior_ptid);
4583 return spu_enumerate_spu_ids (pid, readbuf, offset, len);
4586 xsnprintf (buf, sizeof buf, "/proc/%d/fd/%s", pid, annex);
4587 fd = open (buf, writebuf? O_WRONLY : O_RDONLY);
4592 && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
4599 ret = write (fd, writebuf, (size_t) len);
4601 ret = read (fd, readbuf, (size_t) len);
4608 /* Parse LINE as a signal set and add its set bits to SIGS. */
4611 add_line_to_sigset (const char *line, sigset_t *sigs)
4613 int len = strlen (line) - 1;
4617 if (line[len] != '\n')
4618 error (_("Could not parse signal set: %s"), line);
4626 if (*p >= '0' && *p <= '9')
4628 else if (*p >= 'a' && *p <= 'f')
4629 digit = *p - 'a' + 10;
4631 error (_("Could not parse signal set: %s"), line);
4636 sigaddset (sigs, signum + 1);
4638 sigaddset (sigs, signum + 2);
4640 sigaddset (sigs, signum + 3);
4642 sigaddset (sigs, signum + 4);
4648 /* Find process PID's pending signals from /proc/pid/status and set
4652 linux_proc_pending_signals (int pid, sigset_t *pending, sigset_t *blocked, sigset_t *ignored)
4655 char buffer[MAXPATHLEN], fname[MAXPATHLEN];
4657 struct cleanup *cleanup;
4659 sigemptyset (pending);
4660 sigemptyset (blocked);
4661 sigemptyset (ignored);
4662 sprintf (fname, "/proc/%d/status", pid);
4663 procfile = fopen (fname, "r");
4664 if (procfile == NULL)
4665 error (_("Could not open %s"), fname);
4666 cleanup = make_cleanup_fclose (procfile);
4668 while (fgets (buffer, MAXPATHLEN, procfile) != NULL)
4670 /* Normal queued signals are on the SigPnd line in the status
4671 file. However, 2.6 kernels also have a "shared" pending
4672 queue for delivering signals to a thread group, so check for
4675 Unfortunately some Red Hat kernels include the shared pending
4676 queue but not the ShdPnd status field. */
4678 if (strncmp (buffer, "SigPnd:\t", 8) == 0)
4679 add_line_to_sigset (buffer + 8, pending);
4680 else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
4681 add_line_to_sigset (buffer + 8, pending);
4682 else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
4683 add_line_to_sigset (buffer + 8, blocked);
4684 else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
4685 add_line_to_sigset (buffer + 8, ignored);
4688 do_cleanups (cleanup);
4692 linux_nat_xfer_osdata (struct target_ops *ops, enum target_object object,
4693 const char *annex, gdb_byte *readbuf,
4694 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
4696 /* We make the process list snapshot when the object starts to be
4698 static const char *buf;
4699 static LONGEST len_avail = -1;
4700 static struct obstack obstack;
4704 gdb_assert (object == TARGET_OBJECT_OSDATA);
4706 if (strcmp (annex, "processes") != 0)
4709 gdb_assert (readbuf && !writebuf);
4713 if (len_avail != -1 && len_avail != 0)
4714 obstack_free (&obstack, NULL);
4717 obstack_init (&obstack);
4718 obstack_grow_str (&obstack, "<osdata type=\"processes\">\n");
4720 dirp = opendir ("/proc");
4724 while ((dp = readdir (dirp)) != NULL)
4726 struct stat statbuf;
4727 char procentry[sizeof ("/proc/4294967295")];
4729 if (!isdigit (dp->d_name[0])
4730 || NAMELEN (dp) > sizeof ("4294967295") - 1)
4733 sprintf (procentry, "/proc/%s", dp->d_name);
4734 if (stat (procentry, &statbuf) == 0
4735 && S_ISDIR (statbuf.st_mode))
4739 char cmd[MAXPATHLEN + 1];
4740 struct passwd *entry;
4742 pathname = xstrprintf ("/proc/%s/cmdline", dp->d_name);
4743 entry = getpwuid (statbuf.st_uid);
4745 if ((f = fopen (pathname, "r")) != NULL)
4747 size_t len = fread (cmd, 1, sizeof (cmd) - 1, f);
4751 for (i = 0; i < len; i++)
4756 obstack_xml_printf (
4759 "<column name=\"pid\">%s</column>"
4760 "<column name=\"user\">%s</column>"
4761 "<column name=\"command\">%s</column>"
4764 entry ? entry->pw_name : "?",
4777 obstack_grow_str0 (&obstack, "</osdata>\n");
4778 buf = obstack_finish (&obstack);
4779 len_avail = strlen (buf);
4782 if (offset >= len_avail)
4784 /* Done. Get rid of the obstack. */
4785 obstack_free (&obstack, NULL);
4791 if (len > len_avail - offset)
4792 len = len_avail - offset;
4793 memcpy (readbuf, buf + offset, len);
4799 linux_xfer_partial (struct target_ops *ops, enum target_object object,
4800 const char *annex, gdb_byte *readbuf,
4801 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
4805 if (object == TARGET_OBJECT_AUXV)
4806 return procfs_xfer_auxv (ops, object, annex, readbuf, writebuf,
4809 if (object == TARGET_OBJECT_OSDATA)
4810 return linux_nat_xfer_osdata (ops, object, annex, readbuf, writebuf,
4813 if (object == TARGET_OBJECT_SPU)
4814 return linux_proc_xfer_spu (ops, object, annex, readbuf, writebuf,
4817 /* GDB calculates all the addresses in possibly larget width of the address.
4818 Address width needs to be masked before its final use - either by
4819 linux_proc_xfer_partial or inf_ptrace_xfer_partial.
4821 Compare ADDR_BIT first to avoid a compiler warning on shift overflow. */
4823 if (object == TARGET_OBJECT_MEMORY)
4825 int addr_bit = gdbarch_addr_bit (target_gdbarch);
4827 if (addr_bit < (sizeof (ULONGEST) * HOST_CHAR_BIT))
4828 offset &= ((ULONGEST) 1 << addr_bit) - 1;
4831 xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
4836 return super_xfer_partial (ops, object, annex, readbuf, writebuf,
4840 /* Create a prototype generic GNU/Linux target. The client can override
4841 it with local methods. */
4844 linux_target_install_ops (struct target_ops *t)
4846 t->to_insert_fork_catchpoint = linux_child_insert_fork_catchpoint;
4847 t->to_insert_vfork_catchpoint = linux_child_insert_vfork_catchpoint;
4848 t->to_insert_exec_catchpoint = linux_child_insert_exec_catchpoint;
4849 t->to_set_syscall_catchpoint = linux_child_set_syscall_catchpoint;
4850 t->to_pid_to_exec_file = linux_child_pid_to_exec_file;
4851 t->to_post_startup_inferior = linux_child_post_startup_inferior;
4852 t->to_post_attach = linux_child_post_attach;
4853 t->to_follow_fork = linux_child_follow_fork;
4854 t->to_find_memory_regions = linux_nat_find_memory_regions;
4855 t->to_make_corefile_notes = linux_nat_make_corefile_notes;
4857 super_xfer_partial = t->to_xfer_partial;
4858 t->to_xfer_partial = linux_xfer_partial;
4864 struct target_ops *t;
4866 t = inf_ptrace_target ();
4867 linux_target_install_ops (t);
4873 linux_trad_target (CORE_ADDR (*register_u_offset)(struct gdbarch *, int, int))
4875 struct target_ops *t;
4877 t = inf_ptrace_trad_target (register_u_offset);
4878 linux_target_install_ops (t);
4883 /* target_is_async_p implementation. */
4886 linux_nat_is_async_p (void)
4888 /* NOTE: palves 2008-03-21: We're only async when the user requests
4889 it explicitly with the "set target-async" command.
4890 Someday, linux will always be async. */
4891 if (!target_async_permitted)
4894 /* See target.h/target_async_mask. */
4895 return linux_nat_async_mask_value;
4898 /* target_can_async_p implementation. */
4901 linux_nat_can_async_p (void)
4903 /* NOTE: palves 2008-03-21: We're only async when the user requests
4904 it explicitly with the "set target-async" command.
4905 Someday, linux will always be async. */
4906 if (!target_async_permitted)
4909 /* See target.h/target_async_mask. */
4910 return linux_nat_async_mask_value;
4914 linux_nat_supports_non_stop (void)
4919 /* True if we want to support multi-process. To be removed when GDB
4920 supports multi-exec. */
4922 int linux_multi_process = 1;
4925 linux_nat_supports_multi_process (void)
4927 return linux_multi_process;
4930 /* target_async_mask implementation. */
4933 linux_nat_async_mask (int new_mask)
4935 int curr_mask = linux_nat_async_mask_value;
4937 if (curr_mask != new_mask)
4941 linux_nat_async (NULL, 0);
4942 linux_nat_async_mask_value = new_mask;
4946 linux_nat_async_mask_value = new_mask;
4948 /* If we're going out of async-mask in all-stop, then the
4949 inferior is stopped. The next resume will call
4950 target_async. In non-stop, the target event source
4951 should be always registered in the event loop. Do so
4954 linux_nat_async (inferior_event_handler, 0);
4961 static int async_terminal_is_ours = 1;
4963 /* target_terminal_inferior implementation. */
4966 linux_nat_terminal_inferior (void)
4968 if (!target_is_async_p ())
4970 /* Async mode is disabled. */
4971 terminal_inferior ();
4975 terminal_inferior ();
4977 /* Calls to target_terminal_*() are meant to be idempotent. */
4978 if (!async_terminal_is_ours)
4981 delete_file_handler (input_fd);
4982 async_terminal_is_ours = 0;
4986 /* target_terminal_ours implementation. */
4989 linux_nat_terminal_ours (void)
4991 if (!target_is_async_p ())
4993 /* Async mode is disabled. */
4998 /* GDB should never give the terminal to the inferior if the
4999 inferior is running in the background (run&, continue&, etc.),
5000 but claiming it sure should. */
5003 if (async_terminal_is_ours)
5006 clear_sigint_trap ();
5007 add_file_handler (input_fd, stdin_event_handler, 0);
5008 async_terminal_is_ours = 1;
5011 static void (*async_client_callback) (enum inferior_event_type event_type,
5013 static void *async_client_context;
5015 /* SIGCHLD handler that serves two purposes: In non-stop/async mode,
5016 so we notice when any child changes state, and notify the
5017 event-loop; it allows us to use sigsuspend in linux_nat_wait_1
5018 above to wait for the arrival of a SIGCHLD. */
5021 sigchld_handler (int signo)
5023 int old_errno = errno;
5025 if (debug_linux_nat_async)
5026 fprintf_unfiltered (gdb_stdlog, "sigchld\n");
5028 if (signo == SIGCHLD
5029 && linux_nat_event_pipe[0] != -1)
5030 async_file_mark (); /* Let the event loop know that there are
5031 events to handle. */
5036 /* Callback registered with the target events file descriptor. */
5039 handle_target_event (int error, gdb_client_data client_data)
5041 (*async_client_callback) (INF_REG_EVENT, async_client_context);
5044 /* Create/destroy the target events pipe. Returns previous state. */
5047 linux_async_pipe (int enable)
5049 int previous = (linux_nat_event_pipe[0] != -1);
5051 if (previous != enable)
5055 block_child_signals (&prev_mask);
5059 if (pipe (linux_nat_event_pipe) == -1)
5060 internal_error (__FILE__, __LINE__,
5061 "creating event pipe failed.");
5063 fcntl (linux_nat_event_pipe[0], F_SETFL, O_NONBLOCK);
5064 fcntl (linux_nat_event_pipe[1], F_SETFL, O_NONBLOCK);
5068 close (linux_nat_event_pipe[0]);
5069 close (linux_nat_event_pipe[1]);
5070 linux_nat_event_pipe[0] = -1;
5071 linux_nat_event_pipe[1] = -1;
5074 restore_child_signals_mask (&prev_mask);
5080 /* target_async implementation. */
5083 linux_nat_async (void (*callback) (enum inferior_event_type event_type,
5084 void *context), void *context)
5086 if (linux_nat_async_mask_value == 0 || !target_async_permitted)
5087 internal_error (__FILE__, __LINE__,
5088 "Calling target_async when async is masked");
5090 if (callback != NULL)
5092 async_client_callback = callback;
5093 async_client_context = context;
5094 if (!linux_async_pipe (1))
5096 add_file_handler (linux_nat_event_pipe[0],
5097 handle_target_event, NULL);
5098 /* There may be pending events to handle. Tell the event loop
5105 async_client_callback = callback;
5106 async_client_context = context;
5107 delete_file_handler (linux_nat_event_pipe[0]);
5108 linux_async_pipe (0);
5113 /* Stop an LWP, and push a TARGET_SIGNAL_0 stop status if no other
5117 linux_nat_stop_lwp (struct lwp_info *lwp, void *data)
5122 ptid_t ptid = lwp->ptid;
5124 if (debug_linux_nat)
5125 fprintf_unfiltered (gdb_stdlog,
5126 "LNSL: running -> suspending %s\n",
5127 target_pid_to_str (lwp->ptid));
5130 stop_callback (lwp, NULL);
5131 stop_wait_callback (lwp, NULL);
5133 /* If the lwp exits while we try to stop it, there's nothing
5135 lwp = find_lwp_pid (ptid);
5139 /* If we didn't collect any signal other than SIGSTOP while
5140 stopping the LWP, push a SIGNAL_0 event. In either case, the
5141 event-loop will end up calling target_wait which will collect
5143 if (lwp->status == 0)
5144 lwp->status = W_STOPCODE (0);
5149 /* Already known to be stopped; do nothing. */
5151 if (debug_linux_nat)
5153 if (find_thread_ptid (lwp->ptid)->stop_requested)
5154 fprintf_unfiltered (gdb_stdlog, "\
5155 LNSL: already stopped/stop_requested %s\n",
5156 target_pid_to_str (lwp->ptid));
5158 fprintf_unfiltered (gdb_stdlog, "\
5159 LNSL: already stopped/no stop_requested yet %s\n",
5160 target_pid_to_str (lwp->ptid));
5167 linux_nat_stop (ptid_t ptid)
5170 iterate_over_lwps (ptid, linux_nat_stop_lwp, NULL);
5172 linux_ops->to_stop (ptid);
5176 linux_nat_close (int quitting)
5178 /* Unregister from the event loop. */
5179 if (target_is_async_p ())
5180 target_async (NULL, 0);
5182 /* Reset the async_masking. */
5183 linux_nat_async_mask_value = 1;
5185 if (linux_ops->to_close)
5186 linux_ops->to_close (quitting);
5190 linux_nat_add_target (struct target_ops *t)
5192 /* Save the provided single-threaded target. We save this in a separate
5193 variable because another target we've inherited from (e.g. inf-ptrace)
5194 may have saved a pointer to T; we want to use it for the final
5195 process stratum target. */
5196 linux_ops_saved = *t;
5197 linux_ops = &linux_ops_saved;
5199 /* Override some methods for multithreading. */
5200 t->to_create_inferior = linux_nat_create_inferior;
5201 t->to_attach = linux_nat_attach;
5202 t->to_detach = linux_nat_detach;
5203 t->to_resume = linux_nat_resume;
5204 t->to_wait = linux_nat_wait;
5205 t->to_xfer_partial = linux_nat_xfer_partial;
5206 t->to_kill = linux_nat_kill;
5207 t->to_mourn_inferior = linux_nat_mourn_inferior;
5208 t->to_thread_alive = linux_nat_thread_alive;
5209 t->to_pid_to_str = linux_nat_pid_to_str;
5210 t->to_has_thread_control = tc_schedlock;
5212 t->to_can_async_p = linux_nat_can_async_p;
5213 t->to_is_async_p = linux_nat_is_async_p;
5214 t->to_supports_non_stop = linux_nat_supports_non_stop;
5215 t->to_async = linux_nat_async;
5216 t->to_async_mask = linux_nat_async_mask;
5217 t->to_terminal_inferior = linux_nat_terminal_inferior;
5218 t->to_terminal_ours = linux_nat_terminal_ours;
5219 t->to_close = linux_nat_close;
5221 /* Methods for non-stop support. */
5222 t->to_stop = linux_nat_stop;
5224 t->to_supports_multi_process = linux_nat_supports_multi_process;
5226 /* We don't change the stratum; this target will sit at
5227 process_stratum and thread_db will set at thread_stratum. This
5228 is a little strange, since this is a multi-threaded-capable
5229 target, but we want to be on the stack below thread_db, and we
5230 also want to be used for single-threaded processes. */
5235 /* Register a method to call whenever a new thread is attached. */
5237 linux_nat_set_new_thread (struct target_ops *t, void (*new_thread) (ptid_t))
5239 /* Save the pointer. We only support a single registered instance
5240 of the GNU/Linux native target, so we do not need to map this to
5242 linux_nat_new_thread = new_thread;
5245 /* Register a method that converts a siginfo object between the layout
5246 that ptrace returns, and the layout in the architecture of the
5249 linux_nat_set_siginfo_fixup (struct target_ops *t,
5250 int (*siginfo_fixup) (struct siginfo *,
5254 /* Save the pointer. */
5255 linux_nat_siginfo_fixup = siginfo_fixup;
5258 /* Return the saved siginfo associated with PTID. */
5260 linux_nat_get_siginfo (ptid_t ptid)
5262 struct lwp_info *lp = find_lwp_pid (ptid);
5264 gdb_assert (lp != NULL);
5266 return &lp->siginfo;
5269 /* Provide a prototype to silence -Wmissing-prototypes. */
5270 extern initialize_file_ftype _initialize_linux_nat;
5273 _initialize_linux_nat (void)
5277 add_info ("proc", linux_nat_info_proc_cmd, _("\
5278 Show /proc process information about any running process.\n\
5279 Specify any process id, or use the program being debugged by default.\n\
5280 Specify any of the following keywords for detailed info:\n\
5281 mappings -- list of mapped memory regions.\n\
5282 stat -- list a bunch of random process info.\n\
5283 status -- list a different bunch of random process info.\n\
5284 all -- list all available /proc info."));
5286 add_setshow_zinteger_cmd ("lin-lwp", class_maintenance,
5287 &debug_linux_nat, _("\
5288 Set debugging of GNU/Linux lwp module."), _("\
5289 Show debugging of GNU/Linux lwp module."), _("\
5290 Enables printf debugging output."),
5292 show_debug_linux_nat,
5293 &setdebuglist, &showdebuglist);
5295 add_setshow_zinteger_cmd ("lin-lwp-async", class_maintenance,
5296 &debug_linux_nat_async, _("\
5297 Set debugging of GNU/Linux async lwp module."), _("\
5298 Show debugging of GNU/Linux async lwp module."), _("\
5299 Enables printf debugging output."),
5301 show_debug_linux_nat_async,
5302 &setdebuglist, &showdebuglist);
5304 /* Save this mask as the default. */
5305 sigprocmask (SIG_SETMASK, NULL, &normal_mask);
5307 /* Install a SIGCHLD handler. */
5308 sigchld_action.sa_handler = sigchld_handler;
5309 sigemptyset (&sigchld_action.sa_mask);
5310 sigchld_action.sa_flags = SA_RESTART;
5312 /* Make it the default. */
5313 sigaction (SIGCHLD, &sigchld_action, NULL);
5315 /* Make sure we don't block SIGCHLD during a sigsuspend. */
5316 sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
5317 sigdelset (&suspend_mask, SIGCHLD);
5319 sigemptyset (&blocked_mask);
5321 add_setshow_boolean_cmd ("disable-randomization", class_support,
5322 &disable_randomization, _("\
5323 Set disabling of debuggee's virtual address space randomization."), _("\
5324 Show disabling of debuggee's virtual address space randomization."), _("\
5325 When this mode is on (which is the default), randomization of the virtual\n\
5326 address space is disabled. Standalone programs run with the randomization\n\
5327 enabled by default on some platforms."),
5328 &set_disable_randomization,
5329 &show_disable_randomization,
5330 &setlist, &showlist);
5334 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
5335 the GNU/Linux Threads library and therefore doesn't really belong
5338 /* Read variable NAME in the target and return its value if found.
5339 Otherwise return zero. It is assumed that the type of the variable
5343 get_signo (const char *name)
5345 struct minimal_symbol *ms;
5348 ms = lookup_minimal_symbol (name, NULL, NULL);
5352 if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
5353 sizeof (signo)) != 0)
5359 /* Return the set of signals used by the threads library in *SET. */
5362 lin_thread_get_thread_signals (sigset_t *set)
5364 struct sigaction action;
5365 int restart, cancel;
5367 sigemptyset (&blocked_mask);
5370 restart = get_signo ("__pthread_sig_restart");
5371 cancel = get_signo ("__pthread_sig_cancel");
5373 /* LinuxThreads normally uses the first two RT signals, but in some legacy
5374 cases may use SIGUSR1/SIGUSR2. NPTL always uses RT signals, but does
5375 not provide any way for the debugger to query the signal numbers -
5376 fortunately they don't change! */
5379 restart = __SIGRTMIN;
5382 cancel = __SIGRTMIN + 1;
5384 sigaddset (set, restart);
5385 sigaddset (set, cancel);
5387 /* The GNU/Linux Threads library makes terminating threads send a
5388 special "cancel" signal instead of SIGCHLD. Make sure we catch
5389 those (to prevent them from terminating GDB itself, which is
5390 likely to be their default action) and treat them the same way as
5393 action.sa_handler = sigchld_handler;
5394 sigemptyset (&action.sa_mask);
5395 action.sa_flags = SA_RESTART;
5396 sigaction (cancel, &action, NULL);
5398 /* We block the "cancel" signal throughout this code ... */
5399 sigaddset (&blocked_mask, cancel);
5400 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
5402 /* ... except during a sigsuspend. */
5403 sigdelset (&suspend_mask, cancel);