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"
57 #ifdef HAVE_PERSONALITY
58 # include <sys/personality.h>
59 # if !HAVE_DECL_ADDR_NO_RANDOMIZE
60 # define ADDR_NO_RANDOMIZE 0x0040000
62 #endif /* HAVE_PERSONALITY */
64 /* This comment documents high-level logic of this file.
66 Waiting for events in sync mode
67 ===============================
69 When waiting for an event in a specific thread, we just use waitpid, passing
70 the specific pid, and not passing WNOHANG.
72 When waiting for an event in all threads, waitpid is not quite good. Prior to
73 version 2.4, Linux can either wait for event in main thread, or in secondary
74 threads. (2.4 has the __WALL flag). So, if we use blocking waitpid, we might
75 miss an event. The solution is to use non-blocking waitpid, together with
76 sigsuspend. First, we use non-blocking waitpid to get an event in the main
77 process, if any. Second, we use non-blocking waitpid with the __WCLONED
78 flag to check for events in cloned processes. If nothing is found, we use
79 sigsuspend to wait for SIGCHLD. When SIGCHLD arrives, it means something
80 happened to a child process -- and SIGCHLD will be delivered both for events
81 in main debugged process and in cloned processes. As soon as we know there's
82 an event, we get back to calling nonblocking waitpid with and without __WCLONED.
84 Note that SIGCHLD should be blocked between waitpid and sigsuspend calls,
85 so that we don't miss a signal. If SIGCHLD arrives in between, when it's
86 blocked, the signal becomes pending and sigsuspend immediately
87 notices it and returns.
89 Waiting for events in async mode
90 ================================
92 In async mode, GDB should always be ready to handle both user input and target
93 events, so neither blocking waitpid nor sigsuspend are viable
94 options. Instead, we should notify the GDB main event loop whenever there's
95 unprocessed event from the target. The only way to notify this event loop is
96 to make it wait on input from a pipe, and write something to the pipe whenever
97 there's event. Obviously, if we fail to notify the event loop if there's
98 target event, it's bad. If we notify the event loop when there's no event
99 from target, linux-nat.c will detect that there's no event, actually, and
100 report event of type TARGET_WAITKIND_IGNORE, but it will waste time and
103 The main design point is that every time GDB is outside linux-nat.c, we have a
104 SIGCHLD handler installed that is called when something happens to the target
105 and notifies the GDB event loop. Also, the event is extracted from the target
106 using waitpid and stored for future use. Whenever GDB core decides to handle
107 the event, and calls into linux-nat.c, we disable SIGCHLD and process things
108 as in sync mode, except that before waitpid call we check if there are any
109 previously read events.
111 It could happen that during event processing, we'll try to get more events
112 than there are events in the local queue, which will result to waitpid call.
113 Those waitpid calls, while blocking, are guarantied to always have
114 something for waitpid to return. E.g., stopping a thread with SIGSTOP, and
115 waiting for the lwp to stop.
117 The event loop is notified about new events using a pipe. SIGCHLD handler does
118 waitpid and writes the results in to a pipe. GDB event loop has the other end
119 of the pipe among the sources. When event loop starts to process the event
120 and calls a function in linux-nat.c, all events from the pipe are transferred
121 into a local queue and SIGCHLD is blocked. Further processing goes as in sync
122 mode. Before we return from linux_nat_wait, we transfer all unprocessed events
123 from local queue back to the pipe, so that when we get back to event loop,
124 event loop will notice there's something more to do.
126 SIGCHLD is blocked when we're inside target_wait, so that should we actually
127 want to wait for some more events, SIGCHLD handler does not steal them from
128 us. Technically, it would be possible to add new events to the local queue but
129 it's about the same amount of work as blocking SIGCHLD.
131 This moving of events from pipe into local queue and back into pipe when we
132 enter/leave linux-nat.c is somewhat ugly. Unfortunately, GDB event loop is
133 home-grown and incapable to wait on any queue.
138 We stop threads by sending a SIGSTOP. The use of SIGSTOP instead of another
139 signal is not entirely significant; we just need for a signal to be delivered,
140 so that we can intercept it. SIGSTOP's advantage is that it can not be
141 blocked. A disadvantage is that it is not a real-time signal, so it can only
142 be queued once; we do not keep track of other sources of SIGSTOP.
144 Two other signals that can't be blocked are SIGCONT and SIGKILL. But we can't
145 use them, because they have special behavior when the signal is generated -
146 not when it is delivered. SIGCONT resumes the entire thread group and SIGKILL
147 kills the entire thread group.
149 A delivered SIGSTOP would stop the entire thread group, not just the thread we
150 tkill'd. But we never let the SIGSTOP be delivered; we always intercept and
151 cancel it (by PTRACE_CONT without passing SIGSTOP).
153 We could use a real-time signal instead. This would solve those problems; we
154 could use PTRACE_GETSIGINFO to locate the specific stop signals sent by GDB.
155 But we would still have to have some support for SIGSTOP, since PTRACE_ATTACH
156 generates it, and there are races with trying to find a signal that is not
160 #define O_LARGEFILE 0
163 /* If the system headers did not provide the constants, hard-code the normal
165 #ifndef PTRACE_EVENT_FORK
167 #define PTRACE_SETOPTIONS 0x4200
168 #define PTRACE_GETEVENTMSG 0x4201
170 /* options set using PTRACE_SETOPTIONS */
171 #define PTRACE_O_TRACESYSGOOD 0x00000001
172 #define PTRACE_O_TRACEFORK 0x00000002
173 #define PTRACE_O_TRACEVFORK 0x00000004
174 #define PTRACE_O_TRACECLONE 0x00000008
175 #define PTRACE_O_TRACEEXEC 0x00000010
176 #define PTRACE_O_TRACEVFORKDONE 0x00000020
177 #define PTRACE_O_TRACEEXIT 0x00000040
179 /* Wait extended result codes for the above trace options. */
180 #define PTRACE_EVENT_FORK 1
181 #define PTRACE_EVENT_VFORK 2
182 #define PTRACE_EVENT_CLONE 3
183 #define PTRACE_EVENT_EXEC 4
184 #define PTRACE_EVENT_VFORK_DONE 5
185 #define PTRACE_EVENT_EXIT 6
187 #endif /* PTRACE_EVENT_FORK */
189 /* We can't always assume that this flag is available, but all systems
190 with the ptrace event handlers also have __WALL, so it's safe to use
193 #define __WALL 0x40000000 /* Wait for any child. */
196 #ifndef PTRACE_GETSIGINFO
197 #define PTRACE_GETSIGINFO 0x4202
200 /* The single-threaded native GNU/Linux target_ops. We save a pointer for
201 the use of the multi-threaded target. */
202 static struct target_ops *linux_ops;
203 static struct target_ops linux_ops_saved;
205 /* The method to call, if any, when a new thread is attached. */
206 static void (*linux_nat_new_thread) (ptid_t);
208 /* The saved to_xfer_partial method, inherited from inf-ptrace.c.
209 Called by our to_xfer_partial. */
210 static LONGEST (*super_xfer_partial) (struct target_ops *,
212 const char *, gdb_byte *,
216 static int debug_linux_nat;
218 show_debug_linux_nat (struct ui_file *file, int from_tty,
219 struct cmd_list_element *c, const char *value)
221 fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
225 static int debug_linux_nat_async = 0;
227 show_debug_linux_nat_async (struct ui_file *file, int from_tty,
228 struct cmd_list_element *c, const char *value)
230 fprintf_filtered (file, _("Debugging of GNU/Linux async lwp module is %s.\n"),
234 static int disable_randomization = 1;
237 show_disable_randomization (struct ui_file *file, int from_tty,
238 struct cmd_list_element *c, const char *value)
240 #ifdef HAVE_PERSONALITY
241 fprintf_filtered (file, _("\
242 Disabling randomization of debuggee's virtual address space is %s.\n"),
244 #else /* !HAVE_PERSONALITY */
246 Disabling randomization of debuggee's virtual address space is unsupported on\n\
247 this platform.\n"), file);
248 #endif /* !HAVE_PERSONALITY */
252 set_disable_randomization (char *args, int from_tty, struct cmd_list_element *c)
254 #ifndef HAVE_PERSONALITY
256 Disabling randomization of debuggee's virtual address space is unsupported on\n\
258 #endif /* !HAVE_PERSONALITY */
261 static int linux_parent_pid;
263 struct simple_pid_list
267 struct simple_pid_list *next;
269 struct simple_pid_list *stopped_pids;
271 /* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACEFORK
272 can not be used, 1 if it can. */
274 static int linux_supports_tracefork_flag = -1;
276 /* If we have PTRACE_O_TRACEFORK, this flag indicates whether we also have
277 PTRACE_O_TRACEVFORKDONE. */
279 static int linux_supports_tracevforkdone_flag = -1;
281 /* Async mode support */
283 /* Zero if the async mode, although enabled, is masked, which means
284 linux_nat_wait should behave as if async mode was off. */
285 static int linux_nat_async_mask_value = 1;
287 /* The read/write ends of the pipe registered as waitable file in the
289 static int linux_nat_event_pipe[2] = { -1, -1 };
291 /* Number of queued events in the pipe. */
292 static volatile int linux_nat_num_queued_events;
294 /* The possible SIGCHLD handling states. */
298 /* SIGCHLD disabled, with action set to sigchld_handler, for the
299 sigsuspend in linux_nat_wait. */
301 /* SIGCHLD enabled, with action set to async_sigchld_handler. */
303 /* Set SIGCHLD to default action. Used while creating an
308 /* The current SIGCHLD handling state. */
309 static enum sigchld_state linux_nat_async_events_state;
311 static enum sigchld_state linux_nat_async_events (enum sigchld_state enable);
312 static void pipe_to_local_event_queue (void);
313 static void local_event_queue_to_pipe (void);
314 static void linux_nat_event_pipe_push (int pid, int status, int options);
315 static int linux_nat_event_pipe_pop (int* ptr_status, int* ptr_options);
316 static void linux_nat_set_async_mode (int on);
317 static void linux_nat_async (void (*callback)
318 (enum inferior_event_type event_type, void *context),
320 static int linux_nat_async_mask (int mask);
321 static int kill_lwp (int lwpid, int signo);
323 static int stop_callback (struct lwp_info *lp, void *data);
325 /* Captures the result of a successful waitpid call, along with the
326 options used in that call. */
327 struct waitpid_result
332 struct waitpid_result *next;
335 /* A singly-linked list of the results of the waitpid calls performed
336 in the async SIGCHLD handler. */
337 static struct waitpid_result *waitpid_queue = NULL;
339 /* Similarly to `waitpid', but check the local event queue instead of
340 querying the kernel queue. If PEEK, don't remove the event found
344 queued_waitpid_1 (int pid, int *status, int flags, int peek)
346 struct waitpid_result *msg = waitpid_queue, *prev = NULL;
348 if (debug_linux_nat_async)
349 fprintf_unfiltered (gdb_stdlog,
351 QWPID: linux_nat_async_events_state(%d), linux_nat_num_queued_events(%d)\n",
352 linux_nat_async_events_state,
353 linux_nat_num_queued_events);
357 for (; msg; prev = msg, msg = msg->next)
358 if (pid == -1 || pid == msg->pid)
361 else if (flags & __WCLONE)
363 for (; msg; prev = msg, msg = msg->next)
364 if (msg->options & __WCLONE
365 && (pid == -1 || pid == msg->pid))
370 for (; msg; prev = msg, msg = msg->next)
371 if ((msg->options & __WCLONE) == 0
372 && (pid == -1 || pid == msg->pid))
381 *status = msg->status;
384 if (debug_linux_nat_async)
385 fprintf_unfiltered (gdb_stdlog, "QWPID: pid(%d), status(%x)\n",
391 prev->next = msg->next;
393 waitpid_queue = msg->next;
402 if (debug_linux_nat_async)
403 fprintf_unfiltered (gdb_stdlog, "QWPID: miss\n");
410 /* Similarly to `waitpid', but check the local event queue. */
413 queued_waitpid (int pid, int *status, int flags)
415 return queued_waitpid_1 (pid, status, flags, 0);
419 push_waitpid (int pid, int status, int options)
421 struct waitpid_result *event, *new_event;
423 new_event = xmalloc (sizeof (*new_event));
424 new_event->pid = pid;
425 new_event->status = status;
426 new_event->options = options;
427 new_event->next = NULL;
431 for (event = waitpid_queue;
432 event && event->next;
436 event->next = new_event;
439 waitpid_queue = new_event;
442 /* Drain all queued events of PID. If PID is -1, the effect is of
443 draining all events. */
445 drain_queued_events (int pid)
447 while (queued_waitpid (pid, NULL, __WALL) != -1)
452 /* Trivial list manipulation functions to keep track of a list of
453 new stopped processes. */
455 add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
457 struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
459 new_pid->status = status;
460 new_pid->next = *listp;
465 pull_pid_from_list (struct simple_pid_list **listp, int pid, int *status)
467 struct simple_pid_list **p;
469 for (p = listp; *p != NULL; p = &(*p)->next)
470 if ((*p)->pid == pid)
472 struct simple_pid_list *next = (*p)->next;
473 *status = (*p)->status;
482 linux_record_stopped_pid (int pid, int status)
484 add_to_pid_list (&stopped_pids, pid, status);
488 /* A helper function for linux_test_for_tracefork, called after fork (). */
491 linux_tracefork_child (void)
495 ptrace (PTRACE_TRACEME, 0, 0, 0);
496 kill (getpid (), SIGSTOP);
501 /* Wrapper function for waitpid which handles EINTR, and checks for
502 locally queued events. */
505 my_waitpid (int pid, int *status, int flags)
509 /* There should be no concurrent calls to waitpid. */
510 gdb_assert (linux_nat_async_events_state == sigchld_sync);
512 ret = queued_waitpid (pid, status, flags);
518 ret = waitpid (pid, status, flags);
520 while (ret == -1 && errno == EINTR);
525 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.
527 First, we try to enable fork tracing on ORIGINAL_PID. If this fails,
528 we know that the feature is not available. This may change the tracing
529 options for ORIGINAL_PID, but we'll be setting them shortly anyway.
531 However, if it succeeds, we don't know for sure that the feature is
532 available; old versions of PTRACE_SETOPTIONS ignored unknown options. We
533 create a child process, attach to it, use PTRACE_SETOPTIONS to enable
534 fork tracing, and let it fork. If the process exits, we assume that we
535 can't use TRACEFORK; if we get the fork notification, and we can extract
536 the new child's PID, then we assume that we can. */
539 linux_test_for_tracefork (int original_pid)
541 int child_pid, ret, status;
543 enum sigchld_state async_events_original_state;
545 async_events_original_state = linux_nat_async_events (sigchld_sync);
547 linux_supports_tracefork_flag = 0;
548 linux_supports_tracevforkdone_flag = 0;
550 ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACEFORK);
556 perror_with_name (("fork"));
559 linux_tracefork_child ();
561 ret = my_waitpid (child_pid, &status, 0);
563 perror_with_name (("waitpid"));
564 else if (ret != child_pid)
565 error (_("linux_test_for_tracefork: waitpid: unexpected result %d."), ret);
566 if (! WIFSTOPPED (status))
567 error (_("linux_test_for_tracefork: waitpid: unexpected status %d."), status);
569 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
572 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
575 warning (_("linux_test_for_tracefork: failed to kill child"));
576 linux_nat_async_events (async_events_original_state);
580 ret = my_waitpid (child_pid, &status, 0);
581 if (ret != child_pid)
582 warning (_("linux_test_for_tracefork: failed to wait for killed child"));
583 else if (!WIFSIGNALED (status))
584 warning (_("linux_test_for_tracefork: unexpected wait status 0x%x from "
585 "killed child"), status);
587 linux_nat_async_events (async_events_original_state);
591 /* Check whether PTRACE_O_TRACEVFORKDONE is available. */
592 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0,
593 PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORKDONE);
594 linux_supports_tracevforkdone_flag = (ret == 0);
596 ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
598 warning (_("linux_test_for_tracefork: failed to resume child"));
600 ret = my_waitpid (child_pid, &status, 0);
602 if (ret == child_pid && WIFSTOPPED (status)
603 && status >> 16 == PTRACE_EVENT_FORK)
606 ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
607 if (ret == 0 && second_pid != 0)
611 linux_supports_tracefork_flag = 1;
612 my_waitpid (second_pid, &second_status, 0);
613 ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
615 warning (_("linux_test_for_tracefork: failed to kill second child"));
616 my_waitpid (second_pid, &status, 0);
620 warning (_("linux_test_for_tracefork: unexpected result from waitpid "
621 "(%d, status 0x%x)"), ret, status);
623 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
625 warning (_("linux_test_for_tracefork: failed to kill child"));
626 my_waitpid (child_pid, &status, 0);
628 linux_nat_async_events (async_events_original_state);
631 /* Return non-zero iff we have tracefork functionality available.
632 This function also sets linux_supports_tracefork_flag. */
635 linux_supports_tracefork (int pid)
637 if (linux_supports_tracefork_flag == -1)
638 linux_test_for_tracefork (pid);
639 return linux_supports_tracefork_flag;
643 linux_supports_tracevforkdone (int pid)
645 if (linux_supports_tracefork_flag == -1)
646 linux_test_for_tracefork (pid);
647 return linux_supports_tracevforkdone_flag;
652 linux_enable_event_reporting (ptid_t ptid)
654 int pid = ptid_get_lwp (ptid);
658 pid = ptid_get_pid (ptid);
660 if (! linux_supports_tracefork (pid))
663 options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEEXEC
664 | PTRACE_O_TRACECLONE;
665 if (linux_supports_tracevforkdone (pid))
666 options |= PTRACE_O_TRACEVFORKDONE;
668 /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to support
669 read-only process state. */
671 ptrace (PTRACE_SETOPTIONS, pid, 0, options);
675 linux_child_post_attach (int pid)
677 linux_enable_event_reporting (pid_to_ptid (pid));
678 check_for_thread_db ();
682 linux_child_post_startup_inferior (ptid_t ptid)
684 linux_enable_event_reporting (ptid);
685 check_for_thread_db ();
689 linux_child_follow_fork (struct target_ops *ops, int follow_child)
692 struct target_waitstatus last_status;
694 int parent_pid, child_pid;
696 if (target_can_async_p ())
697 target_async (NULL, 0);
699 get_last_target_status (&last_ptid, &last_status);
700 has_vforked = (last_status.kind == TARGET_WAITKIND_VFORKED);
701 parent_pid = ptid_get_lwp (last_ptid);
703 parent_pid = ptid_get_pid (last_ptid);
704 child_pid = PIDGET (last_status.value.related_pid);
708 /* We're already attached to the parent, by default. */
710 /* Before detaching from the child, remove all breakpoints from
711 it. (This won't actually modify the breakpoint list, but will
712 physically remove the breakpoints from the child.) */
713 /* If we vforked this will remove the breakpoints from the parent
714 also, but they'll be reinserted below. */
715 detach_breakpoints (child_pid);
717 /* Detach new forked process? */
720 if (info_verbose || debug_linux_nat)
722 target_terminal_ours ();
723 fprintf_filtered (gdb_stdlog,
724 "Detaching after fork from child process %d.\n",
728 ptrace (PTRACE_DETACH, child_pid, 0, 0);
732 struct fork_info *fp;
734 /* Add process to GDB's tables. */
735 add_inferior (child_pid);
737 /* Retain child fork in ptrace (stopped) state. */
738 fp = find_fork_pid (child_pid);
740 fp = add_fork (child_pid);
741 fork_save_infrun_state (fp, 0);
746 gdb_assert (linux_supports_tracefork_flag >= 0);
747 if (linux_supports_tracevforkdone (0))
751 ptrace (PTRACE_CONT, parent_pid, 0, 0);
752 my_waitpid (parent_pid, &status, __WALL);
753 if ((status >> 16) != PTRACE_EVENT_VFORK_DONE)
754 warning (_("Unexpected waitpid result %06x when waiting for "
755 "vfork-done"), status);
759 /* We can't insert breakpoints until the child has
760 finished with the shared memory region. We need to
761 wait until that happens. Ideal would be to just
763 - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
764 - waitpid (parent_pid, &status, __WALL);
765 However, most architectures can't handle a syscall
766 being traced on the way out if it wasn't traced on
769 We might also think to loop, continuing the child
770 until it exits or gets a SIGTRAP. One problem is
771 that the child might call ptrace with PTRACE_TRACEME.
773 There's no simple and reliable way to figure out when
774 the vforked child will be done with its copy of the
775 shared memory. We could step it out of the syscall,
776 two instructions, let it go, and then single-step the
777 parent once. When we have hardware single-step, this
778 would work; with software single-step it could still
779 be made to work but we'd have to be able to insert
780 single-step breakpoints in the child, and we'd have
781 to insert -just- the single-step breakpoint in the
782 parent. Very awkward.
784 In the end, the best we can do is to make sure it
785 runs for a little while. Hopefully it will be out of
786 range of any breakpoints we reinsert. Usually this
787 is only the single-step breakpoint at vfork's return
793 /* Since we vforked, breakpoints were removed in the parent
794 too. Put them back. */
795 reattach_breakpoints (parent_pid);
800 struct thread_info *last_tp = find_thread_pid (last_ptid);
801 struct thread_info *tp;
802 char child_pid_spelling[40];
804 /* Copy user stepping state to the new inferior thread. */
805 struct breakpoint *step_resume_breakpoint = last_tp->step_resume_breakpoint;
806 CORE_ADDR step_range_start = last_tp->step_range_start;
807 CORE_ADDR step_range_end = last_tp->step_range_end;
808 struct frame_id step_frame_id = last_tp->step_frame_id;
810 /* Otherwise, deleting the parent would get rid of this
812 last_tp->step_resume_breakpoint = NULL;
814 /* Needed to keep the breakpoint lists in sync. */
816 detach_breakpoints (child_pid);
818 /* Before detaching from the parent, remove all breakpoints from it. */
819 remove_breakpoints ();
821 if (info_verbose || debug_linux_nat)
823 target_terminal_ours ();
824 fprintf_filtered (gdb_stdlog,
825 "Attaching after fork to child process %d.\n",
829 /* Add the new inferior first, so that the target_detach below
830 doesn't unpush the target. */
832 add_inferior (child_pid);
834 /* If we're vforking, we may want to hold on to the parent until
835 the child exits or execs. At exec time we can remove the old
836 breakpoints from the parent and detach it; at exit time we
837 could do the same (or even, sneakily, resume debugging it - the
838 child's exec has failed, or something similar).
840 This doesn't clean up "properly", because we can't call
841 target_detach, but that's OK; if the current target is "child",
842 then it doesn't need any further cleanups, and lin_lwp will
843 generally not encounter vfork (vfork is defined to fork
846 The holding part is very easy if we have VFORKDONE events;
847 but keeping track of both processes is beyond GDB at the
848 moment. So we don't expose the parent to the rest of GDB.
849 Instead we quietly hold onto it until such time as we can
854 linux_parent_pid = parent_pid;
855 detach_inferior (parent_pid);
857 else if (!detach_fork)
859 struct fork_info *fp;
860 /* Retain parent fork in ptrace (stopped) state. */
861 fp = find_fork_pid (parent_pid);
863 fp = add_fork (parent_pid);
864 fork_save_infrun_state (fp, 0);
866 /* Also add an entry for the child fork. */
867 fp = find_fork_pid (child_pid);
869 fp = add_fork (child_pid);
870 fork_save_infrun_state (fp, 0);
873 target_detach (NULL, 0);
875 inferior_ptid = ptid_build (child_pid, child_pid, 0);
877 linux_nat_switch_fork (inferior_ptid);
878 check_for_thread_db ();
880 tp = inferior_thread ();
881 tp->step_resume_breakpoint = step_resume_breakpoint;
882 tp->step_range_start = step_range_start;
883 tp->step_range_end = step_range_end;
884 tp->step_frame_id = step_frame_id;
886 /* Reset breakpoints in the child as appropriate. */
887 follow_inferior_reset_breakpoints ();
890 if (target_can_async_p ())
891 target_async (inferior_event_handler, 0);
898 linux_child_insert_fork_catchpoint (int pid)
900 if (! linux_supports_tracefork (pid))
901 error (_("Your system does not support fork catchpoints."));
905 linux_child_insert_vfork_catchpoint (int pid)
907 if (!linux_supports_tracefork (pid))
908 error (_("Your system does not support vfork catchpoints."));
912 linux_child_insert_exec_catchpoint (int pid)
914 if (!linux_supports_tracefork (pid))
915 error (_("Your system does not support exec catchpoints."));
918 /* On GNU/Linux there are no real LWP's. The closest thing to LWP's
919 are processes sharing the same VM space. A multi-threaded process
920 is basically a group of such processes. However, such a grouping
921 is almost entirely a user-space issue; the kernel doesn't enforce
922 such a grouping at all (this might change in the future). In
923 general, we'll rely on the threads library (i.e. the GNU/Linux
924 Threads library) to provide such a grouping.
926 It is perfectly well possible to write a multi-threaded application
927 without the assistance of a threads library, by using the clone
928 system call directly. This module should be able to give some
929 rudimentary support for debugging such applications if developers
930 specify the CLONE_PTRACE flag in the clone system call, and are
931 using the Linux kernel 2.4 or above.
933 Note that there are some peculiarities in GNU/Linux that affect
936 - In general one should specify the __WCLONE flag to waitpid in
937 order to make it report events for any of the cloned processes
938 (and leave it out for the initial process). However, if a cloned
939 process has exited the exit status is only reported if the
940 __WCLONE flag is absent. Linux kernel 2.4 has a __WALL flag, but
941 we cannot use it since GDB must work on older systems too.
943 - When a traced, cloned process exits and is waited for by the
944 debugger, the kernel reassigns it to the original parent and
945 keeps it around as a "zombie". Somehow, the GNU/Linux Threads
946 library doesn't notice this, which leads to the "zombie problem":
947 When debugged a multi-threaded process that spawns a lot of
948 threads will run out of processes, even if the threads exit,
949 because the "zombies" stay around. */
951 /* List of known LWPs. */
952 struct lwp_info *lwp_list;
954 /* Number of LWPs in the list. */
958 /* Original signal mask. */
959 static sigset_t normal_mask;
961 /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
962 _initialize_linux_nat. */
963 static sigset_t suspend_mask;
965 /* SIGCHLD action for synchronous mode. */
966 struct sigaction sync_sigchld_action;
968 /* SIGCHLD action for asynchronous mode. */
969 static struct sigaction async_sigchld_action;
971 /* SIGCHLD default action, to pass to new inferiors. */
972 static struct sigaction sigchld_default_action;
975 /* Prototypes for local functions. */
976 static int stop_wait_callback (struct lwp_info *lp, void *data);
977 static int linux_nat_thread_alive (ptid_t ptid);
978 static char *linux_child_pid_to_exec_file (int pid);
979 static int cancel_breakpoint (struct lwp_info *lp);
982 /* Convert wait status STATUS to a string. Used for printing debug
986 status_to_str (int status)
990 if (WIFSTOPPED (status))
991 snprintf (buf, sizeof (buf), "%s (stopped)",
992 strsignal (WSTOPSIG (status)));
993 else if (WIFSIGNALED (status))
994 snprintf (buf, sizeof (buf), "%s (terminated)",
995 strsignal (WSTOPSIG (status)));
997 snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
1002 /* Initialize the list of LWPs. Note that this module, contrary to
1003 what GDB's generic threads layer does for its thread list,
1004 re-initializes the LWP lists whenever we mourn or detach (which
1005 doesn't involve mourning) the inferior. */
1008 init_lwp_list (void)
1010 struct lwp_info *lp, *lpnext;
1012 for (lp = lwp_list; lp; lp = lpnext)
1022 /* Add the LWP specified by PID to the list. Return a pointer to the
1023 structure describing the new LWP. The LWP should already be stopped
1024 (with an exception for the very first LWP). */
1026 static struct lwp_info *
1027 add_lwp (ptid_t ptid)
1029 struct lwp_info *lp;
1031 gdb_assert (is_lwp (ptid));
1033 lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
1035 memset (lp, 0, sizeof (struct lwp_info));
1037 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
1041 lp->next = lwp_list;
1045 if (num_lwps > 1 && linux_nat_new_thread != NULL)
1046 linux_nat_new_thread (ptid);
1051 /* Remove the LWP specified by PID from the list. */
1054 delete_lwp (ptid_t ptid)
1056 struct lwp_info *lp, *lpprev;
1060 for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
1061 if (ptid_equal (lp->ptid, ptid))
1070 lpprev->next = lp->next;
1072 lwp_list = lp->next;
1077 /* Return a pointer to the structure describing the LWP corresponding
1078 to PID. If no corresponding LWP could be found, return NULL. */
1080 static struct lwp_info *
1081 find_lwp_pid (ptid_t ptid)
1083 struct lwp_info *lp;
1087 lwp = GET_LWP (ptid);
1089 lwp = GET_PID (ptid);
1091 for (lp = lwp_list; lp; lp = lp->next)
1092 if (lwp == GET_LWP (lp->ptid))
1098 /* Call CALLBACK with its second argument set to DATA for every LWP in
1099 the list. If CALLBACK returns 1 for a particular LWP, return a
1100 pointer to the structure describing that LWP immediately.
1101 Otherwise return NULL. */
1104 iterate_over_lwps (int (*callback) (struct lwp_info *, void *), void *data)
1106 struct lwp_info *lp, *lpnext;
1108 for (lp = lwp_list; lp; lp = lpnext)
1111 if ((*callback) (lp, data))
1118 /* Update our internal state when changing from one fork (checkpoint,
1119 et cetera) to another indicated by NEW_PTID. We can only switch
1120 single-threaded applications, so we only create one new LWP, and
1121 the previous list is discarded. */
1124 linux_nat_switch_fork (ptid_t new_ptid)
1126 struct lwp_info *lp;
1129 lp = add_lwp (new_ptid);
1132 init_thread_list ();
1133 add_thread_silent (new_ptid);
1136 /* Handle the exit of a single thread LP. */
1139 exit_lwp (struct lwp_info *lp)
1141 struct thread_info *th = find_thread_pid (lp->ptid);
1145 if (print_thread_events)
1146 printf_unfiltered (_("[%s exited]\n"), target_pid_to_str (lp->ptid));
1148 delete_thread (lp->ptid);
1151 delete_lwp (lp->ptid);
1154 /* Detect `T (stopped)' in `/proc/PID/status'.
1155 Other states including `T (tracing stop)' are reported as false. */
1158 pid_is_stopped (pid_t pid)
1164 snprintf (buf, sizeof (buf), "/proc/%d/status", (int) pid);
1165 status_file = fopen (buf, "r");
1166 if (status_file != NULL)
1170 while (fgets (buf, sizeof (buf), status_file))
1172 if (strncmp (buf, "State:", 6) == 0)
1178 if (have_state && strstr (buf, "T (stopped)") != NULL)
1180 fclose (status_file);
1185 /* Wait for the LWP specified by LP, which we have just attached to.
1186 Returns a wait status for that LWP, to cache. */
1189 linux_nat_post_attach_wait (ptid_t ptid, int first, int *cloned,
1192 pid_t new_pid, pid = GET_LWP (ptid);
1195 if (pid_is_stopped (pid))
1197 if (debug_linux_nat)
1198 fprintf_unfiltered (gdb_stdlog,
1199 "LNPAW: Attaching to a stopped process\n");
1201 /* The process is definitely stopped. It is in a job control
1202 stop, unless the kernel predates the TASK_STOPPED /
1203 TASK_TRACED distinction, in which case it might be in a
1204 ptrace stop. Make sure it is in a ptrace stop; from there we
1205 can kill it, signal it, et cetera.
1207 First make sure there is a pending SIGSTOP. Since we are
1208 already attached, the process can not transition from stopped
1209 to running without a PTRACE_CONT; so we know this signal will
1210 go into the queue. The SIGSTOP generated by PTRACE_ATTACH is
1211 probably already in the queue (unless this kernel is old
1212 enough to use TASK_STOPPED for ptrace stops); but since SIGSTOP
1213 is not an RT signal, it can only be queued once. */
1214 kill_lwp (pid, SIGSTOP);
1216 /* Finally, resume the stopped process. This will deliver the SIGSTOP
1217 (or a higher priority signal, just like normal PTRACE_ATTACH). */
1218 ptrace (PTRACE_CONT, pid, 0, 0);
1221 /* Make sure the initial process is stopped. The user-level threads
1222 layer might want to poke around in the inferior, and that won't
1223 work if things haven't stabilized yet. */
1224 new_pid = my_waitpid (pid, &status, 0);
1225 if (new_pid == -1 && errno == ECHILD)
1228 warning (_("%s is a cloned process"), target_pid_to_str (ptid));
1230 /* Try again with __WCLONE to check cloned processes. */
1231 new_pid = my_waitpid (pid, &status, __WCLONE);
1235 gdb_assert (pid == new_pid && WIFSTOPPED (status));
1237 if (WSTOPSIG (status) != SIGSTOP)
1240 if (debug_linux_nat)
1241 fprintf_unfiltered (gdb_stdlog,
1242 "LNPAW: Received %s after attaching\n",
1243 status_to_str (status));
1249 /* Attach to the LWP specified by PID. Return 0 if successful or -1
1250 if the new LWP could not be attached. */
1253 lin_lwp_attach_lwp (ptid_t ptid)
1255 struct lwp_info *lp;
1256 enum sigchld_state async_events_original_state;
1258 gdb_assert (is_lwp (ptid));
1260 async_events_original_state = linux_nat_async_events (sigchld_sync);
1262 lp = find_lwp_pid (ptid);
1264 /* We assume that we're already attached to any LWP that has an id
1265 equal to the overall process id, and to any LWP that is already
1266 in our list of LWPs. If we're not seeing exit events from threads
1267 and we've had PID wraparound since we last tried to stop all threads,
1268 this assumption might be wrong; fortunately, this is very unlikely
1270 if (GET_LWP (ptid) != GET_PID (ptid) && lp == NULL)
1272 int status, cloned = 0, signalled = 0;
1274 if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
1276 /* If we fail to attach to the thread, issue a warning,
1277 but continue. One way this can happen is if thread
1278 creation is interrupted; as of Linux kernel 2.6.19, a
1279 bug may place threads in the thread list and then fail
1281 warning (_("Can't attach %s: %s"), target_pid_to_str (ptid),
1282 safe_strerror (errno));
1286 if (debug_linux_nat)
1287 fprintf_unfiltered (gdb_stdlog,
1288 "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
1289 target_pid_to_str (ptid));
1291 status = linux_nat_post_attach_wait (ptid, 0, &cloned, &signalled);
1292 lp = add_lwp (ptid);
1294 lp->cloned = cloned;
1295 lp->signalled = signalled;
1296 if (WSTOPSIG (status) != SIGSTOP)
1299 lp->status = status;
1302 target_post_attach (GET_LWP (lp->ptid));
1304 if (debug_linux_nat)
1306 fprintf_unfiltered (gdb_stdlog,
1307 "LLAL: waitpid %s received %s\n",
1308 target_pid_to_str (ptid),
1309 status_to_str (status));
1314 /* We assume that the LWP representing the original process is
1315 already stopped. Mark it as stopped in the data structure
1316 that the GNU/linux ptrace layer uses to keep track of
1317 threads. Note that this won't have already been done since
1318 the main thread will have, we assume, been stopped by an
1319 attach from a different layer. */
1321 lp = add_lwp (ptid);
1325 linux_nat_async_events (async_events_original_state);
1330 linux_nat_create_inferior (struct target_ops *ops,
1331 char *exec_file, char *allargs, char **env,
1334 int saved_async = 0;
1335 #ifdef HAVE_PERSONALITY
1336 int personality_orig = 0, personality_set = 0;
1337 #endif /* HAVE_PERSONALITY */
1339 /* The fork_child mechanism is synchronous and calls target_wait, so
1340 we have to mask the async mode. */
1342 if (target_can_async_p ())
1343 /* Mask async mode. Creating a child requires a loop calling
1344 wait_for_inferior currently. */
1345 saved_async = linux_nat_async_mask (0);
1348 /* Restore the original signal mask. */
1349 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1350 /* Make sure we don't block SIGCHLD during a sigsuspend. */
1351 suspend_mask = normal_mask;
1352 sigdelset (&suspend_mask, SIGCHLD);
1355 /* Set SIGCHLD to the default action, until after execing the child,
1356 since the inferior inherits the superior's signal mask. It will
1357 be blocked again in linux_nat_wait, which is only reached after
1358 the inferior execing. */
1359 linux_nat_async_events (sigchld_default);
1361 #ifdef HAVE_PERSONALITY
1362 if (disable_randomization)
1365 personality_orig = personality (0xffffffff);
1366 if (errno == 0 && !(personality_orig & ADDR_NO_RANDOMIZE))
1368 personality_set = 1;
1369 personality (personality_orig | ADDR_NO_RANDOMIZE);
1371 if (errno != 0 || (personality_set
1372 && !(personality (0xffffffff) & ADDR_NO_RANDOMIZE)))
1373 warning (_("Error disabling address space randomization: %s"),
1374 safe_strerror (errno));
1376 #endif /* HAVE_PERSONALITY */
1378 linux_ops->to_create_inferior (ops, exec_file, allargs, env, from_tty);
1380 #ifdef HAVE_PERSONALITY
1381 if (personality_set)
1384 personality (personality_orig);
1386 warning (_("Error restoring address space randomization: %s"),
1387 safe_strerror (errno));
1389 #endif /* HAVE_PERSONALITY */
1392 linux_nat_async_mask (saved_async);
1396 linux_nat_attach (struct target_ops *ops, char *args, int from_tty)
1398 struct lwp_info *lp;
1402 /* FIXME: We should probably accept a list of process id's, and
1403 attach all of them. */
1404 linux_ops->to_attach (ops, args, from_tty);
1406 if (!target_can_async_p ())
1408 /* Restore the original signal mask. */
1409 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1410 /* Make sure we don't block SIGCHLD during a sigsuspend. */
1411 suspend_mask = normal_mask;
1412 sigdelset (&suspend_mask, SIGCHLD);
1415 /* The ptrace base target adds the main thread with (pid,0,0)
1416 format. Decorate it with lwp info. */
1417 ptid = BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid));
1418 thread_change_ptid (inferior_ptid, ptid);
1420 /* Add the initial process as the first LWP to the list. */
1421 lp = add_lwp (ptid);
1423 status = linux_nat_post_attach_wait (lp->ptid, 1, &lp->cloned,
1427 /* Save the wait status to report later. */
1429 if (debug_linux_nat)
1430 fprintf_unfiltered (gdb_stdlog,
1431 "LNA: waitpid %ld, saving status %s\n",
1432 (long) GET_PID (lp->ptid), status_to_str (status));
1434 if (!target_can_async_p ())
1435 lp->status = status;
1438 /* We already waited for this LWP, so put the wait result on the
1439 pipe. The event loop will wake up and gets us to handling
1441 linux_nat_event_pipe_push (GET_PID (lp->ptid), status,
1442 lp->cloned ? __WCLONE : 0);
1443 /* Register in the event loop. */
1444 target_async (inferior_event_handler, 0);
1448 /* Get pending status of LP. */
1450 get_pending_status (struct lwp_info *lp, int *status)
1452 struct target_waitstatus last;
1455 get_last_target_status (&last_ptid, &last);
1457 /* If this lwp is the ptid that GDB is processing an event from, the
1458 signal will be in stop_signal. Otherwise, in all-stop + sync
1459 mode, we may cache pending events in lp->status while trying to
1460 stop all threads (see stop_wait_callback). In async mode, the
1461 events are always cached in waitpid_queue. */
1467 enum target_signal signo = TARGET_SIGNAL_0;
1469 if (is_executing (lp->ptid))
1471 /* If the core thought this lwp was executing --- e.g., the
1472 executing property hasn't been updated yet, but the
1473 thread has been stopped with a stop_callback /
1474 stop_wait_callback sequence (see linux_nat_detach for
1475 example) --- we can only have pending events in the local
1477 if (queued_waitpid (GET_LWP (lp->ptid), status, __WALL) != -1)
1479 if (WIFSTOPPED (*status))
1480 signo = target_signal_from_host (WSTOPSIG (*status));
1482 /* If not stopped, then the lwp is gone, no use in
1483 resending a signal. */
1488 /* If the core knows the thread is not executing, then we
1489 have the last signal recorded in
1490 thread_info->stop_signal. */
1492 struct thread_info *tp = find_thread_pid (lp->ptid);
1493 signo = tp->stop_signal;
1496 if (signo != TARGET_SIGNAL_0
1497 && !signal_pass_state (signo))
1499 if (debug_linux_nat)
1500 fprintf_unfiltered (gdb_stdlog, "\
1501 GPT: lwp %s had signal %s, but it is in no pass state\n",
1502 target_pid_to_str (lp->ptid),
1503 target_signal_to_string (signo));
1507 if (signo != TARGET_SIGNAL_0)
1508 *status = W_STOPCODE (target_signal_to_host (signo));
1510 if (debug_linux_nat)
1511 fprintf_unfiltered (gdb_stdlog,
1512 "GPT: lwp %s as pending signal %s\n",
1513 target_pid_to_str (lp->ptid),
1514 target_signal_to_string (signo));
1519 if (GET_LWP (lp->ptid) == GET_LWP (last_ptid))
1521 struct thread_info *tp = find_thread_pid (lp->ptid);
1522 if (tp->stop_signal != TARGET_SIGNAL_0
1523 && signal_pass_state (tp->stop_signal))
1524 *status = W_STOPCODE (target_signal_to_host (tp->stop_signal));
1526 else if (target_can_async_p ())
1527 queued_waitpid (GET_LWP (lp->ptid), status, __WALL);
1529 *status = lp->status;
1536 detach_callback (struct lwp_info *lp, void *data)
1538 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1540 if (debug_linux_nat && lp->status)
1541 fprintf_unfiltered (gdb_stdlog, "DC: Pending %s for %s on detach.\n",
1542 strsignal (WSTOPSIG (lp->status)),
1543 target_pid_to_str (lp->ptid));
1545 /* If there is a pending SIGSTOP, get rid of it. */
1548 if (debug_linux_nat)
1549 fprintf_unfiltered (gdb_stdlog,
1550 "DC: Sending SIGCONT to %s\n",
1551 target_pid_to_str (lp->ptid));
1553 kill_lwp (GET_LWP (lp->ptid), SIGCONT);
1557 /* We don't actually detach from the LWP that has an id equal to the
1558 overall process id just yet. */
1559 if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
1563 /* Pass on any pending signal for this LWP. */
1564 get_pending_status (lp, &status);
1567 if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
1568 WSTOPSIG (status)) < 0)
1569 error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
1570 safe_strerror (errno));
1572 if (debug_linux_nat)
1573 fprintf_unfiltered (gdb_stdlog,
1574 "PTRACE_DETACH (%s, %s, 0) (OK)\n",
1575 target_pid_to_str (lp->ptid),
1576 strsignal (WSTOPSIG (lp->status)));
1578 delete_lwp (lp->ptid);
1585 linux_nat_detach (struct target_ops *ops, char *args, int from_tty)
1589 enum target_signal sig;
1591 if (target_can_async_p ())
1592 linux_nat_async (NULL, 0);
1594 /* Stop all threads before detaching. ptrace requires that the
1595 thread is stopped to sucessfully detach. */
1596 iterate_over_lwps (stop_callback, NULL);
1597 /* ... and wait until all of them have reported back that
1598 they're no longer running. */
1599 iterate_over_lwps (stop_wait_callback, NULL);
1601 iterate_over_lwps (detach_callback, NULL);
1603 /* Only the initial process should be left right now. */
1604 gdb_assert (num_lwps == 1);
1606 /* Pass on any pending signal for the last LWP. */
1607 if ((args == NULL || *args == '\0')
1608 && get_pending_status (lwp_list, &status) != -1
1609 && WIFSTOPPED (status))
1611 /* Put the signal number in ARGS so that inf_ptrace_detach will
1612 pass it along with PTRACE_DETACH. */
1614 sprintf (args, "%d", (int) WSTOPSIG (status));
1615 fprintf_unfiltered (gdb_stdlog,
1616 "LND: Sending signal %s to %s\n",
1618 target_pid_to_str (lwp_list->ptid));
1621 /* Destroy LWP info; it's no longer valid. */
1624 pid = ptid_get_pid (inferior_ptid);
1626 if (target_can_async_p ())
1627 drain_queued_events (pid);
1629 if (forks_exist_p ())
1631 /* Multi-fork case. The current inferior_ptid is being detached
1632 from, but there are other viable forks to debug. Detach from
1633 the current fork, and context-switch to the first
1635 linux_fork_detach (args, from_tty);
1637 if (non_stop && target_can_async_p ())
1638 target_async (inferior_event_handler, 0);
1641 linux_ops->to_detach (ops, args, from_tty);
1647 resume_callback (struct lwp_info *lp, void *data)
1649 if (lp->stopped && lp->status == 0)
1651 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
1652 0, TARGET_SIGNAL_0);
1653 if (debug_linux_nat)
1654 fprintf_unfiltered (gdb_stdlog,
1655 "RC: PTRACE_CONT %s, 0, 0 (resume sibling)\n",
1656 target_pid_to_str (lp->ptid));
1659 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1661 else if (lp->stopped && debug_linux_nat)
1662 fprintf_unfiltered (gdb_stdlog, "RC: Not resuming sibling %s (has pending)\n",
1663 target_pid_to_str (lp->ptid));
1664 else if (debug_linux_nat)
1665 fprintf_unfiltered (gdb_stdlog, "RC: Not resuming sibling %s (not stopped)\n",
1666 target_pid_to_str (lp->ptid));
1672 resume_clear_callback (struct lwp_info *lp, void *data)
1679 resume_set_callback (struct lwp_info *lp, void *data)
1686 linux_nat_resume (ptid_t ptid, int step, enum target_signal signo)
1688 struct lwp_info *lp;
1691 if (debug_linux_nat)
1692 fprintf_unfiltered (gdb_stdlog,
1693 "LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
1694 step ? "step" : "resume",
1695 target_pid_to_str (ptid),
1696 signo ? strsignal (signo) : "0",
1697 target_pid_to_str (inferior_ptid));
1699 if (target_can_async_p ())
1700 /* Block events while we're here. */
1701 linux_nat_async_events (sigchld_sync);
1703 /* A specific PTID means `step only this process id'. */
1704 resume_all = (PIDGET (ptid) == -1);
1706 if (non_stop && resume_all)
1707 internal_error (__FILE__, __LINE__,
1708 "can't resume all in non-stop mode");
1713 iterate_over_lwps (resume_set_callback, NULL);
1715 iterate_over_lwps (resume_clear_callback, NULL);
1718 /* If PID is -1, it's the current inferior that should be
1719 handled specially. */
1720 if (PIDGET (ptid) == -1)
1721 ptid = inferior_ptid;
1723 lp = find_lwp_pid (ptid);
1724 gdb_assert (lp != NULL);
1726 /* Convert to something the lower layer understands. */
1727 ptid = pid_to_ptid (GET_LWP (lp->ptid));
1729 /* Remember if we're stepping. */
1732 /* Mark this LWP as resumed. */
1735 /* If we have a pending wait status for this thread, there is no
1736 point in resuming the process. But first make sure that
1737 linux_nat_wait won't preemptively handle the event - we
1738 should never take this short-circuit if we are going to
1739 leave LP running, since we have skipped resuming all the
1740 other threads. This bit of code needs to be synchronized
1741 with linux_nat_wait. */
1743 /* In async mode, we never have pending wait status. */
1744 if (target_can_async_p () && lp->status)
1745 internal_error (__FILE__, __LINE__, "Pending status in async mode");
1747 if (lp->status && WIFSTOPPED (lp->status))
1750 struct inferior *inf;
1752 inf = find_inferior_pid (ptid_get_pid (ptid));
1754 saved_signo = target_signal_from_host (WSTOPSIG (lp->status));
1756 /* Defer to common code if we're gaining control of the
1758 if (inf->stop_soon == NO_STOP_QUIETLY
1759 && signal_stop_state (saved_signo) == 0
1760 && signal_print_state (saved_signo) == 0
1761 && signal_pass_state (saved_signo) == 1)
1763 if (debug_linux_nat)
1764 fprintf_unfiltered (gdb_stdlog,
1765 "LLR: Not short circuiting for ignored "
1766 "status 0x%x\n", lp->status);
1768 /* FIXME: What should we do if we are supposed to continue
1769 this thread with a signal? */
1770 gdb_assert (signo == TARGET_SIGNAL_0);
1771 signo = saved_signo;
1778 /* FIXME: What should we do if we are supposed to continue
1779 this thread with a signal? */
1780 gdb_assert (signo == TARGET_SIGNAL_0);
1782 if (debug_linux_nat)
1783 fprintf_unfiltered (gdb_stdlog,
1784 "LLR: Short circuiting for status 0x%x\n",
1790 /* Mark LWP as not stopped to prevent it from being continued by
1795 iterate_over_lwps (resume_callback, NULL);
1797 linux_ops->to_resume (ptid, step, signo);
1798 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1800 if (debug_linux_nat)
1801 fprintf_unfiltered (gdb_stdlog,
1802 "LLR: %s %s, %s (resume event thread)\n",
1803 step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1804 target_pid_to_str (ptid),
1805 signo ? strsignal (signo) : "0");
1807 if (target_can_async_p ())
1808 target_async (inferior_event_handler, 0);
1811 /* Issue kill to specified lwp. */
1813 static int tkill_failed;
1816 kill_lwp (int lwpid, int signo)
1820 /* Use tkill, if possible, in case we are using nptl threads. If tkill
1821 fails, then we are not using nptl threads and we should be using kill. */
1823 #ifdef HAVE_TKILL_SYSCALL
1826 int ret = syscall (__NR_tkill, lwpid, signo);
1827 if (errno != ENOSYS)
1834 return kill (lwpid, signo);
1837 /* Handle a GNU/Linux extended wait response. If we see a clone
1838 event, we need to add the new LWP to our list (and not report the
1839 trap to higher layers). This function returns non-zero if the
1840 event should be ignored and we should wait again. If STOPPING is
1841 true, the new LWP remains stopped, otherwise it is continued. */
1844 linux_handle_extended_wait (struct lwp_info *lp, int status,
1847 int pid = GET_LWP (lp->ptid);
1848 struct target_waitstatus *ourstatus = &lp->waitstatus;
1849 struct lwp_info *new_lp = NULL;
1850 int event = status >> 16;
1852 if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
1853 || event == PTRACE_EVENT_CLONE)
1855 unsigned long new_pid;
1858 ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
1860 /* If we haven't already seen the new PID stop, wait for it now. */
1861 if (! pull_pid_from_list (&stopped_pids, new_pid, &status))
1863 /* The new child has a pending SIGSTOP. We can't affect it until it
1864 hits the SIGSTOP, but we're already attached. */
1865 ret = my_waitpid (new_pid, &status,
1866 (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
1868 perror_with_name (_("waiting for new child"));
1869 else if (ret != new_pid)
1870 internal_error (__FILE__, __LINE__,
1871 _("wait returned unexpected PID %d"), ret);
1872 else if (!WIFSTOPPED (status))
1873 internal_error (__FILE__, __LINE__,
1874 _("wait returned unexpected status 0x%x"), status);
1877 ourstatus->value.related_pid = ptid_build (new_pid, new_pid, 0);
1879 if (event == PTRACE_EVENT_FORK)
1880 ourstatus->kind = TARGET_WAITKIND_FORKED;
1881 else if (event == PTRACE_EVENT_VFORK)
1882 ourstatus->kind = TARGET_WAITKIND_VFORKED;
1885 struct cleanup *old_chain;
1887 ourstatus->kind = TARGET_WAITKIND_IGNORE;
1888 new_lp = add_lwp (BUILD_LWP (new_pid, GET_PID (inferior_ptid)));
1890 new_lp->stopped = 1;
1892 if (WSTOPSIG (status) != SIGSTOP)
1894 /* This can happen if someone starts sending signals to
1895 the new thread before it gets a chance to run, which
1896 have a lower number than SIGSTOP (e.g. SIGUSR1).
1897 This is an unlikely case, and harder to handle for
1898 fork / vfork than for clone, so we do not try - but
1899 we handle it for clone events here. We'll send
1900 the other signal on to the thread below. */
1902 new_lp->signalled = 1;
1909 /* Add the new thread to GDB's lists as soon as possible
1912 1) the frontend doesn't have to wait for a stop to
1915 2) we tag it with the correct running state. */
1917 /* If the thread_db layer is active, let it know about
1918 this new thread, and add it to GDB's list. */
1919 if (!thread_db_attach_lwp (new_lp->ptid))
1921 /* We're not using thread_db. Add it to GDB's
1923 target_post_attach (GET_LWP (new_lp->ptid));
1924 add_thread (new_lp->ptid);
1929 set_running (new_lp->ptid, 1);
1930 set_executing (new_lp->ptid, 1);
1936 new_lp->stopped = 0;
1937 new_lp->resumed = 1;
1938 ptrace (PTRACE_CONT, new_pid, 0,
1939 status ? WSTOPSIG (status) : 0);
1942 if (debug_linux_nat)
1943 fprintf_unfiltered (gdb_stdlog,
1944 "LHEW: Got clone event from LWP %ld, resuming\n",
1945 GET_LWP (lp->ptid));
1946 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1954 if (event == PTRACE_EVENT_EXEC)
1956 ourstatus->kind = TARGET_WAITKIND_EXECD;
1957 ourstatus->value.execd_pathname
1958 = xstrdup (linux_child_pid_to_exec_file (pid));
1960 if (linux_parent_pid)
1962 detach_breakpoints (linux_parent_pid);
1963 ptrace (PTRACE_DETACH, linux_parent_pid, 0, 0);
1965 linux_parent_pid = 0;
1968 /* At this point, all inserted breakpoints are gone. Doing this
1969 as soon as we detect an exec prevents the badness of deleting
1970 a breakpoint writing the current "shadow contents" to lift
1971 the bp. That shadow is NOT valid after an exec.
1973 Note that we have to do this after the detach_breakpoints
1974 call above, otherwise breakpoints wouldn't be lifted from the
1975 parent on a vfork, because detach_breakpoints would think
1976 that breakpoints are not inserted. */
1977 mark_breakpoints_out ();
1981 internal_error (__FILE__, __LINE__,
1982 _("unknown ptrace event %d"), event);
1985 /* Wait for LP to stop. Returns the wait status, or 0 if the LWP has
1989 wait_lwp (struct lwp_info *lp)
1993 int thread_dead = 0;
1995 gdb_assert (!lp->stopped);
1996 gdb_assert (lp->status == 0);
1998 pid = my_waitpid (GET_LWP (lp->ptid), &status, 0);
1999 if (pid == -1 && errno == ECHILD)
2001 pid = my_waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
2002 if (pid == -1 && errno == ECHILD)
2004 /* The thread has previously exited. We need to delete it
2005 now because, for some vendor 2.4 kernels with NPTL
2006 support backported, there won't be an exit event unless
2007 it is the main thread. 2.6 kernels will report an exit
2008 event for each thread that exits, as expected. */
2010 if (debug_linux_nat)
2011 fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
2012 target_pid_to_str (lp->ptid));
2018 gdb_assert (pid == GET_LWP (lp->ptid));
2020 if (debug_linux_nat)
2022 fprintf_unfiltered (gdb_stdlog,
2023 "WL: waitpid %s received %s\n",
2024 target_pid_to_str (lp->ptid),
2025 status_to_str (status));
2029 /* Check if the thread has exited. */
2030 if (WIFEXITED (status) || WIFSIGNALED (status))
2033 if (debug_linux_nat)
2034 fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
2035 target_pid_to_str (lp->ptid));
2044 gdb_assert (WIFSTOPPED (status));
2046 /* Handle GNU/Linux's extended waitstatus for trace events. */
2047 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2049 if (debug_linux_nat)
2050 fprintf_unfiltered (gdb_stdlog,
2051 "WL: Handling extended status 0x%06x\n",
2053 if (linux_handle_extended_wait (lp, status, 1))
2054 return wait_lwp (lp);
2060 /* Save the most recent siginfo for LP. This is currently only called
2061 for SIGTRAP; some ports use the si_addr field for
2062 target_stopped_data_address. In the future, it may also be used to
2063 restore the siginfo of requeued signals. */
2066 save_siginfo (struct lwp_info *lp)
2069 ptrace (PTRACE_GETSIGINFO, GET_LWP (lp->ptid),
2070 (PTRACE_TYPE_ARG3) 0, &lp->siginfo);
2073 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
2076 /* Send a SIGSTOP to LP. */
2079 stop_callback (struct lwp_info *lp, void *data)
2081 if (!lp->stopped && !lp->signalled)
2085 if (debug_linux_nat)
2087 fprintf_unfiltered (gdb_stdlog,
2088 "SC: kill %s **<SIGSTOP>**\n",
2089 target_pid_to_str (lp->ptid));
2092 ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
2093 if (debug_linux_nat)
2095 fprintf_unfiltered (gdb_stdlog,
2096 "SC: lwp kill %d %s\n",
2098 errno ? safe_strerror (errno) : "ERRNO-OK");
2102 gdb_assert (lp->status == 0);
2108 /* Return non-zero if LWP PID has a pending SIGINT. */
2111 linux_nat_has_pending_sigint (int pid)
2113 sigset_t pending, blocked, ignored;
2116 linux_proc_pending_signals (pid, &pending, &blocked, &ignored);
2118 if (sigismember (&pending, SIGINT)
2119 && !sigismember (&ignored, SIGINT))
2125 /* Set a flag in LP indicating that we should ignore its next SIGINT. */
2128 set_ignore_sigint (struct lwp_info *lp, void *data)
2130 /* If a thread has a pending SIGINT, consume it; otherwise, set a
2131 flag to consume the next one. */
2132 if (lp->stopped && lp->status != 0 && WIFSTOPPED (lp->status)
2133 && WSTOPSIG (lp->status) == SIGINT)
2136 lp->ignore_sigint = 1;
2141 /* If LP does not have a SIGINT pending, then clear the ignore_sigint flag.
2142 This function is called after we know the LWP has stopped; if the LWP
2143 stopped before the expected SIGINT was delivered, then it will never have
2144 arrived. Also, if the signal was delivered to a shared queue and consumed
2145 by a different thread, it will never be delivered to this LWP. */
2148 maybe_clear_ignore_sigint (struct lwp_info *lp)
2150 if (!lp->ignore_sigint)
2153 if (!linux_nat_has_pending_sigint (GET_LWP (lp->ptid)))
2155 if (debug_linux_nat)
2156 fprintf_unfiltered (gdb_stdlog,
2157 "MCIS: Clearing bogus flag for %s\n",
2158 target_pid_to_str (lp->ptid));
2159 lp->ignore_sigint = 0;
2163 /* Wait until LP is stopped. */
2166 stop_wait_callback (struct lwp_info *lp, void *data)
2172 status = wait_lwp (lp);
2176 if (lp->ignore_sigint && WIFSTOPPED (status)
2177 && WSTOPSIG (status) == SIGINT)
2179 lp->ignore_sigint = 0;
2182 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2183 if (debug_linux_nat)
2184 fprintf_unfiltered (gdb_stdlog,
2185 "PTRACE_CONT %s, 0, 0 (%s) (discarding SIGINT)\n",
2186 target_pid_to_str (lp->ptid),
2187 errno ? safe_strerror (errno) : "OK");
2189 return stop_wait_callback (lp, NULL);
2192 maybe_clear_ignore_sigint (lp);
2194 if (WSTOPSIG (status) != SIGSTOP)
2196 if (WSTOPSIG (status) == SIGTRAP)
2198 /* If a LWP other than the LWP that we're reporting an
2199 event for has hit a GDB breakpoint (as opposed to
2200 some random trap signal), then just arrange for it to
2201 hit it again later. We don't keep the SIGTRAP status
2202 and don't forward the SIGTRAP signal to the LWP. We
2203 will handle the current event, eventually we will
2204 resume all LWPs, and this one will get its breakpoint
2207 If we do not do this, then we run the risk that the
2208 user will delete or disable the breakpoint, but the
2209 thread will have already tripped on it. */
2211 /* Save the trap's siginfo in case we need it later. */
2214 /* Now resume this LWP and get the SIGSTOP event. */
2216 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2217 if (debug_linux_nat)
2219 fprintf_unfiltered (gdb_stdlog,
2220 "PTRACE_CONT %s, 0, 0 (%s)\n",
2221 target_pid_to_str (lp->ptid),
2222 errno ? safe_strerror (errno) : "OK");
2224 fprintf_unfiltered (gdb_stdlog,
2225 "SWC: Candidate SIGTRAP event in %s\n",
2226 target_pid_to_str (lp->ptid));
2228 /* Hold this event/waitstatus while we check to see if
2229 there are any more (we still want to get that SIGSTOP). */
2230 stop_wait_callback (lp, NULL);
2232 if (target_can_async_p ())
2234 /* Don't leave a pending wait status in async mode.
2235 Retrigger the breakpoint. */
2236 if (!cancel_breakpoint (lp))
2238 /* There was no gdb breakpoint set at pc. Put
2239 the event back in the queue. */
2240 if (debug_linux_nat)
2241 fprintf_unfiltered (gdb_stdlog, "\
2242 SWC: leaving SIGTRAP in local queue of %s\n", target_pid_to_str (lp->ptid));
2243 push_waitpid (GET_LWP (lp->ptid),
2244 W_STOPCODE (SIGTRAP),
2245 lp->cloned ? __WCLONE : 0);
2250 /* Hold the SIGTRAP for handling by
2252 /* If there's another event, throw it back into the
2256 if (debug_linux_nat)
2257 fprintf_unfiltered (gdb_stdlog,
2258 "SWC: kill %s, %s\n",
2259 target_pid_to_str (lp->ptid),
2260 status_to_str ((int) status));
2261 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
2263 /* Save the sigtrap event. */
2264 lp->status = status;
2270 /* The thread was stopped with a signal other than
2271 SIGSTOP, and didn't accidentally trip a breakpoint. */
2273 if (debug_linux_nat)
2275 fprintf_unfiltered (gdb_stdlog,
2276 "SWC: Pending event %s in %s\n",
2277 status_to_str ((int) status),
2278 target_pid_to_str (lp->ptid));
2280 /* Now resume this LWP and get the SIGSTOP event. */
2282 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2283 if (debug_linux_nat)
2284 fprintf_unfiltered (gdb_stdlog,
2285 "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
2286 target_pid_to_str (lp->ptid),
2287 errno ? safe_strerror (errno) : "OK");
2289 /* Hold this event/waitstatus while we check to see if
2290 there are any more (we still want to get that SIGSTOP). */
2291 stop_wait_callback (lp, NULL);
2293 /* If the lp->status field is still empty, use it to
2294 hold this event. If not, then this event must be
2295 returned to the event queue of the LWP. */
2296 if (lp->status || target_can_async_p ())
2298 if (debug_linux_nat)
2300 fprintf_unfiltered (gdb_stdlog,
2301 "SWC: kill %s, %s\n",
2302 target_pid_to_str (lp->ptid),
2303 status_to_str ((int) status));
2305 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
2308 lp->status = status;
2314 /* We caught the SIGSTOP that we intended to catch, so
2315 there's no SIGSTOP pending. */
2324 /* Return non-zero if LP has a wait status pending. */
2327 status_callback (struct lwp_info *lp, void *data)
2329 /* Only report a pending wait status if we pretend that this has
2330 indeed been resumed. */
2331 return (lp->status != 0 && lp->resumed);
2334 /* Return non-zero if LP isn't stopped. */
2337 running_callback (struct lwp_info *lp, void *data)
2339 return (lp->stopped == 0 || (lp->status != 0 && lp->resumed));
2342 /* Count the LWP's that have had events. */
2345 count_events_callback (struct lwp_info *lp, void *data)
2349 gdb_assert (count != NULL);
2351 /* Count only resumed LWPs that have a SIGTRAP event pending. */
2352 if (lp->status != 0 && lp->resumed
2353 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2359 /* Select the LWP (if any) that is currently being single-stepped. */
2362 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
2364 if (lp->step && lp->status != 0)
2370 /* Select the Nth LWP that has had a SIGTRAP event. */
2373 select_event_lwp_callback (struct lwp_info *lp, void *data)
2375 int *selector = data;
2377 gdb_assert (selector != NULL);
2379 /* Select only resumed LWPs that have a SIGTRAP event pending. */
2380 if (lp->status != 0 && lp->resumed
2381 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2382 if ((*selector)-- == 0)
2389 cancel_breakpoint (struct lwp_info *lp)
2391 /* Arrange for a breakpoint to be hit again later. We don't keep
2392 the SIGTRAP status and don't forward the SIGTRAP signal to the
2393 LWP. We will handle the current event, eventually we will resume
2394 this LWP, and this breakpoint will trap again.
2396 If we do not do this, then we run the risk that the user will
2397 delete or disable the breakpoint, but the LWP will have already
2400 struct regcache *regcache = get_thread_regcache (lp->ptid);
2401 struct gdbarch *gdbarch = get_regcache_arch (regcache);
2404 pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
2405 if (breakpoint_inserted_here_p (pc))
2407 if (debug_linux_nat)
2408 fprintf_unfiltered (gdb_stdlog,
2409 "CB: Push back breakpoint for %s\n",
2410 target_pid_to_str (lp->ptid));
2412 /* Back up the PC if necessary. */
2413 if (gdbarch_decr_pc_after_break (gdbarch))
2414 regcache_write_pc (regcache, pc);
2422 cancel_breakpoints_callback (struct lwp_info *lp, void *data)
2424 struct lwp_info *event_lp = data;
2426 /* Leave the LWP that has been elected to receive a SIGTRAP alone. */
2430 /* If a LWP other than the LWP that we're reporting an event for has
2431 hit a GDB breakpoint (as opposed to some random trap signal),
2432 then just arrange for it to hit it again later. We don't keep
2433 the SIGTRAP status and don't forward the SIGTRAP signal to the
2434 LWP. We will handle the current event, eventually we will resume
2435 all LWPs, and this one will get its breakpoint trap again.
2437 If we do not do this, then we run the risk that the user will
2438 delete or disable the breakpoint, but the LWP will have already
2442 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
2443 && cancel_breakpoint (lp))
2444 /* Throw away the SIGTRAP. */
2450 /* Select one LWP out of those that have events pending. */
2453 select_event_lwp (struct lwp_info **orig_lp, int *status)
2456 int random_selector;
2457 struct lwp_info *event_lp;
2459 /* Record the wait status for the original LWP. */
2460 (*orig_lp)->status = *status;
2462 /* Give preference to any LWP that is being single-stepped. */
2463 event_lp = iterate_over_lwps (select_singlestep_lwp_callback, NULL);
2464 if (event_lp != NULL)
2466 if (debug_linux_nat)
2467 fprintf_unfiltered (gdb_stdlog,
2468 "SEL: Select single-step %s\n",
2469 target_pid_to_str (event_lp->ptid));
2473 /* No single-stepping LWP. Select one at random, out of those
2474 which have had SIGTRAP events. */
2476 /* First see how many SIGTRAP events we have. */
2477 iterate_over_lwps (count_events_callback, &num_events);
2479 /* Now randomly pick a LWP out of those that have had a SIGTRAP. */
2480 random_selector = (int)
2481 ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
2483 if (debug_linux_nat && num_events > 1)
2484 fprintf_unfiltered (gdb_stdlog,
2485 "SEL: Found %d SIGTRAP events, selecting #%d\n",
2486 num_events, random_selector);
2488 event_lp = iterate_over_lwps (select_event_lwp_callback,
2492 if (event_lp != NULL)
2494 /* Switch the event LWP. */
2495 *orig_lp = event_lp;
2496 *status = event_lp->status;
2499 /* Flush the wait status for the event LWP. */
2500 (*orig_lp)->status = 0;
2503 /* Return non-zero if LP has been resumed. */
2506 resumed_callback (struct lwp_info *lp, void *data)
2511 /* Stop an active thread, verify it still exists, then resume it. */
2514 stop_and_resume_callback (struct lwp_info *lp, void *data)
2516 struct lwp_info *ptr;
2518 if (!lp->stopped && !lp->signalled)
2520 stop_callback (lp, NULL);
2521 stop_wait_callback (lp, NULL);
2522 /* Resume if the lwp still exists. */
2523 for (ptr = lwp_list; ptr; ptr = ptr->next)
2526 resume_callback (lp, NULL);
2527 resume_set_callback (lp, NULL);
2533 /* Check if we should go on and pass this event to common code.
2534 Return the affected lwp if we are, or NULL otherwise. */
2535 static struct lwp_info *
2536 linux_nat_filter_event (int lwpid, int status, int options)
2538 struct lwp_info *lp;
2540 lp = find_lwp_pid (pid_to_ptid (lwpid));
2542 /* Check for stop events reported by a process we didn't already
2543 know about - anything not already in our LWP list.
2545 If we're expecting to receive stopped processes after
2546 fork, vfork, and clone events, then we'll just add the
2547 new one to our list and go back to waiting for the event
2548 to be reported - the stopped process might be returned
2549 from waitpid before or after the event is. */
2550 if (WIFSTOPPED (status) && !lp)
2552 linux_record_stopped_pid (lwpid, status);
2556 /* Make sure we don't report an event for the exit of an LWP not in
2557 our list, i.e. not part of the current process. This can happen
2558 if we detach from a program we original forked and then it
2560 if (!WIFSTOPPED (status) && !lp)
2563 /* NOTE drow/2003-06-17: This code seems to be meant for debugging
2564 CLONE_PTRACE processes which do not use the thread library -
2565 otherwise we wouldn't find the new LWP this way. That doesn't
2566 currently work, and the following code is currently unreachable
2567 due to the two blocks above. If it's fixed some day, this code
2568 should be broken out into a function so that we can also pick up
2569 LWPs from the new interface. */
2572 lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
2573 if (options & __WCLONE)
2576 gdb_assert (WIFSTOPPED (status)
2577 && WSTOPSIG (status) == SIGSTOP);
2580 if (!in_thread_list (inferior_ptid))
2582 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
2583 GET_PID (inferior_ptid));
2584 add_thread (inferior_ptid);
2587 add_thread (lp->ptid);
2590 /* Save the trap's siginfo in case we need it later. */
2591 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2594 /* Handle GNU/Linux's extended waitstatus for trace events. */
2595 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2597 if (debug_linux_nat)
2598 fprintf_unfiltered (gdb_stdlog,
2599 "LLW: Handling extended status 0x%06x\n",
2601 if (linux_handle_extended_wait (lp, status, 0))
2605 /* Check if the thread has exited. */
2606 if ((WIFEXITED (status) || WIFSIGNALED (status)) && num_lwps > 1)
2608 /* If this is the main thread, we must stop all threads and
2609 verify if they are still alive. This is because in the nptl
2610 thread model, there is no signal issued for exiting LWPs
2611 other than the main thread. We only get the main thread exit
2612 signal once all child threads have already exited. If we
2613 stop all the threads and use the stop_wait_callback to check
2614 if they have exited we can determine whether this signal
2615 should be ignored or whether it means the end of the debugged
2616 application, regardless of which threading model is being
2618 if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
2621 iterate_over_lwps (stop_and_resume_callback, NULL);
2624 if (debug_linux_nat)
2625 fprintf_unfiltered (gdb_stdlog,
2626 "LLW: %s exited.\n",
2627 target_pid_to_str (lp->ptid));
2631 /* If there is at least one more LWP, then the exit signal was
2632 not the end of the debugged application and should be
2638 /* Check if the current LWP has previously exited. In the nptl
2639 thread model, LWPs other than the main thread do not issue
2640 signals when they exit so we must check whenever the thread has
2641 stopped. A similar check is made in stop_wait_callback(). */
2642 if (num_lwps > 1 && !linux_nat_thread_alive (lp->ptid))
2644 if (debug_linux_nat)
2645 fprintf_unfiltered (gdb_stdlog,
2646 "LLW: %s exited.\n",
2647 target_pid_to_str (lp->ptid));
2651 /* Make sure there is at least one thread running. */
2652 gdb_assert (iterate_over_lwps (running_callback, NULL));
2654 /* Discard the event. */
2658 /* Make sure we don't report a SIGSTOP that we sent ourselves in
2659 an attempt to stop an LWP. */
2661 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2663 if (debug_linux_nat)
2664 fprintf_unfiltered (gdb_stdlog,
2665 "LLW: Delayed SIGSTOP caught for %s.\n",
2666 target_pid_to_str (lp->ptid));
2668 /* This is a delayed SIGSTOP. */
2671 registers_changed ();
2673 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2674 lp->step, TARGET_SIGNAL_0);
2675 if (debug_linux_nat)
2676 fprintf_unfiltered (gdb_stdlog,
2677 "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
2679 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2680 target_pid_to_str (lp->ptid));
2683 gdb_assert (lp->resumed);
2685 /* Discard the event. */
2689 /* Make sure we don't report a SIGINT that we have already displayed
2690 for another thread. */
2691 if (lp->ignore_sigint
2692 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGINT)
2694 if (debug_linux_nat)
2695 fprintf_unfiltered (gdb_stdlog,
2696 "LLW: Delayed SIGINT caught for %s.\n",
2697 target_pid_to_str (lp->ptid));
2699 /* This is a delayed SIGINT. */
2700 lp->ignore_sigint = 0;
2702 registers_changed ();
2703 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2704 lp->step, TARGET_SIGNAL_0);
2705 if (debug_linux_nat)
2706 fprintf_unfiltered (gdb_stdlog,
2707 "LLW: %s %s, 0, 0 (discard SIGINT)\n",
2709 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2710 target_pid_to_str (lp->ptid));
2713 gdb_assert (lp->resumed);
2715 /* Discard the event. */
2719 /* An interesting event. */
2724 /* Get the events stored in the pipe into the local queue, so they are
2725 accessible to queued_waitpid. We need to do this, since it is not
2726 always the case that the event at the head of the pipe is the event
2730 pipe_to_local_event_queue (void)
2732 if (debug_linux_nat_async)
2733 fprintf_unfiltered (gdb_stdlog,
2734 "PTLEQ: linux_nat_num_queued_events(%d)\n",
2735 linux_nat_num_queued_events);
2736 while (linux_nat_num_queued_events)
2738 int lwpid, status, options;
2739 lwpid = linux_nat_event_pipe_pop (&status, &options);
2740 gdb_assert (lwpid > 0);
2741 push_waitpid (lwpid, status, options);
2745 /* Get the unprocessed events stored in the local queue back into the
2746 pipe, so the event loop realizes there's something else to
2750 local_event_queue_to_pipe (void)
2752 struct waitpid_result *w = waitpid_queue;
2755 struct waitpid_result *next = w->next;
2756 linux_nat_event_pipe_push (w->pid,
2762 waitpid_queue = NULL;
2764 if (debug_linux_nat_async)
2765 fprintf_unfiltered (gdb_stdlog,
2766 "LEQTP: linux_nat_num_queued_events(%d)\n",
2767 linux_nat_num_queued_events);
2771 linux_nat_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
2773 struct lwp_info *lp = NULL;
2776 pid_t pid = PIDGET (ptid);
2778 if (debug_linux_nat_async)
2779 fprintf_unfiltered (gdb_stdlog, "LLW: enter\n");
2781 /* The first time we get here after starting a new inferior, we may
2782 not have added it to the LWP list yet - this is the earliest
2783 moment at which we know its PID. */
2786 gdb_assert (!is_lwp (inferior_ptid));
2788 /* Upgrade the main thread's ptid. */
2789 thread_change_ptid (inferior_ptid,
2790 BUILD_LWP (GET_PID (inferior_ptid),
2791 GET_PID (inferior_ptid)));
2793 lp = add_lwp (inferior_ptid);
2797 /* Block events while we're here. */
2798 linux_nat_async_events (sigchld_sync);
2802 /* Make sure there is at least one LWP that has been resumed. */
2803 gdb_assert (iterate_over_lwps (resumed_callback, NULL));
2805 /* First check if there is a LWP with a wait status pending. */
2808 /* Any LWP that's been resumed will do. */
2809 lp = iterate_over_lwps (status_callback, NULL);
2812 if (target_can_async_p ())
2813 internal_error (__FILE__, __LINE__,
2814 "Found an LWP with a pending status in async mode.");
2816 status = lp->status;
2819 if (debug_linux_nat && status)
2820 fprintf_unfiltered (gdb_stdlog,
2821 "LLW: Using pending wait status %s for %s.\n",
2822 status_to_str (status),
2823 target_pid_to_str (lp->ptid));
2826 /* But if we don't find one, we'll have to wait, and check both
2827 cloned and uncloned processes. We start with the cloned
2829 options = __WCLONE | WNOHANG;
2831 else if (is_lwp (ptid))
2833 if (debug_linux_nat)
2834 fprintf_unfiltered (gdb_stdlog,
2835 "LLW: Waiting for specific LWP %s.\n",
2836 target_pid_to_str (ptid));
2838 /* We have a specific LWP to check. */
2839 lp = find_lwp_pid (ptid);
2841 status = lp->status;
2844 if (debug_linux_nat && status)
2845 fprintf_unfiltered (gdb_stdlog,
2846 "LLW: Using pending wait status %s for %s.\n",
2847 status_to_str (status),
2848 target_pid_to_str (lp->ptid));
2850 /* If we have to wait, take into account whether PID is a cloned
2851 process or not. And we have to convert it to something that
2852 the layer beneath us can understand. */
2853 options = lp->cloned ? __WCLONE : 0;
2854 pid = GET_LWP (ptid);
2857 if (status && lp->signalled)
2859 /* A pending SIGSTOP may interfere with the normal stream of
2860 events. In a typical case where interference is a problem,
2861 we have a SIGSTOP signal pending for LWP A while
2862 single-stepping it, encounter an event in LWP B, and take the
2863 pending SIGSTOP while trying to stop LWP A. After processing
2864 the event in LWP B, LWP A is continued, and we'll never see
2865 the SIGTRAP associated with the last time we were
2866 single-stepping LWP A. */
2868 /* Resume the thread. It should halt immediately returning the
2870 registers_changed ();
2871 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2872 lp->step, TARGET_SIGNAL_0);
2873 if (debug_linux_nat)
2874 fprintf_unfiltered (gdb_stdlog,
2875 "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
2876 lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2877 target_pid_to_str (lp->ptid));
2879 gdb_assert (lp->resumed);
2881 /* This should catch the pending SIGSTOP. */
2882 stop_wait_callback (lp, NULL);
2885 if (!target_can_async_p ())
2887 /* Causes SIGINT to be passed on to the attached process. */
2895 if (target_can_async_p ())
2896 /* In async mode, don't ever block. Only look at the locally
2898 lwpid = queued_waitpid (pid, &status, options);
2900 lwpid = my_waitpid (pid, &status, options);
2904 gdb_assert (pid == -1 || lwpid == pid);
2906 if (debug_linux_nat)
2908 fprintf_unfiltered (gdb_stdlog,
2909 "LLW: waitpid %ld received %s\n",
2910 (long) lwpid, status_to_str (status));
2913 lp = linux_nat_filter_event (lwpid, status, options);
2916 /* A discarded event. */
2926 /* Alternate between checking cloned and uncloned processes. */
2927 options ^= __WCLONE;
2929 /* And every time we have checked both:
2930 In async mode, return to event loop;
2931 In sync mode, suspend waiting for a SIGCHLD signal. */
2932 if (options & __WCLONE)
2934 if (target_can_async_p ())
2936 /* No interesting event. */
2937 ourstatus->kind = TARGET_WAITKIND_IGNORE;
2939 /* Get ready for the next event. */
2940 target_async (inferior_event_handler, 0);
2942 if (debug_linux_nat_async)
2943 fprintf_unfiltered (gdb_stdlog, "LLW: exit (ignore)\n");
2945 return minus_one_ptid;
2948 sigsuspend (&suspend_mask);
2952 /* We shouldn't end up here unless we want to try again. */
2953 gdb_assert (status == 0);
2956 if (!target_can_async_p ())
2957 clear_sigint_trap ();
2961 /* Don't report signals that GDB isn't interested in, such as
2962 signals that are neither printed nor stopped upon. Stopping all
2963 threads can be a bit time-consuming so if we want decent
2964 performance with heavily multi-threaded programs, especially when
2965 they're using a high frequency timer, we'd better avoid it if we
2968 if (WIFSTOPPED (status))
2970 int signo = target_signal_from_host (WSTOPSIG (status));
2971 struct inferior *inf;
2973 inf = find_inferior_pid (ptid_get_pid (lp->ptid));
2976 /* Defer to common code if we get a signal while
2977 single-stepping, since that may need special care, e.g. to
2978 skip the signal handler, or, if we're gaining control of the
2981 && inf->stop_soon == NO_STOP_QUIETLY
2982 && signal_stop_state (signo) == 0
2983 && signal_print_state (signo) == 0
2984 && signal_pass_state (signo) == 1)
2986 /* FIMXE: kettenis/2001-06-06: Should we resume all threads
2987 here? It is not clear we should. GDB may not expect
2988 other threads to run. On the other hand, not resuming
2989 newly attached threads may cause an unwanted delay in
2990 getting them running. */
2991 registers_changed ();
2992 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2994 if (debug_linux_nat)
2995 fprintf_unfiltered (gdb_stdlog,
2996 "LLW: %s %s, %s (preempt 'handle')\n",
2998 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2999 target_pid_to_str (lp->ptid),
3000 signo ? strsignal (signo) : "0");
3008 /* Only do the below in all-stop, as we currently use SIGINT
3009 to implement target_stop (see linux_nat_stop) in
3011 if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
3013 /* If ^C/BREAK is typed at the tty/console, SIGINT gets
3014 forwarded to the entire process group, that is, all LWPs
3015 will receive it - unless they're using CLONE_THREAD to
3016 share signals. Since we only want to report it once, we
3017 mark it as ignored for all LWPs except this one. */
3018 iterate_over_lwps (set_ignore_sigint, NULL);
3019 lp->ignore_sigint = 0;
3022 maybe_clear_ignore_sigint (lp);
3026 /* This LWP is stopped now. */
3029 if (debug_linux_nat)
3030 fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
3031 status_to_str (status), target_pid_to_str (lp->ptid));
3035 /* Now stop all other LWP's ... */
3036 iterate_over_lwps (stop_callback, NULL);
3038 /* ... and wait until all of them have reported back that
3039 they're no longer running. */
3040 iterate_over_lwps (stop_wait_callback, NULL);
3042 /* If we're not waiting for a specific LWP, choose an event LWP
3043 from among those that have had events. Giving equal priority
3044 to all LWPs that have had events helps prevent
3047 select_event_lwp (&lp, &status);
3050 /* Now that we've selected our final event LWP, cancel any
3051 breakpoints in other LWPs that have hit a GDB breakpoint. See
3052 the comment in cancel_breakpoints_callback to find out why. */
3053 iterate_over_lwps (cancel_breakpoints_callback, lp);
3055 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
3057 if (debug_linux_nat)
3058 fprintf_unfiltered (gdb_stdlog,
3059 "LLW: trap ptid is %s.\n",
3060 target_pid_to_str (lp->ptid));
3063 if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
3065 *ourstatus = lp->waitstatus;
3066 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
3069 store_waitstatus (ourstatus, status);
3071 /* Get ready for the next event. */
3072 if (target_can_async_p ())
3073 target_async (inferior_event_handler, 0);
3075 if (debug_linux_nat_async)
3076 fprintf_unfiltered (gdb_stdlog, "LLW: exit\n");
3082 kill_callback (struct lwp_info *lp, void *data)
3085 ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
3086 if (debug_linux_nat)
3087 fprintf_unfiltered (gdb_stdlog,
3088 "KC: PTRACE_KILL %s, 0, 0 (%s)\n",
3089 target_pid_to_str (lp->ptid),
3090 errno ? safe_strerror (errno) : "OK");
3096 kill_wait_callback (struct lwp_info *lp, void *data)
3100 /* We must make sure that there are no pending events (delayed
3101 SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
3102 program doesn't interfere with any following debugging session. */
3104 /* For cloned processes we must check both with __WCLONE and
3105 without, since the exit status of a cloned process isn't reported
3111 pid = my_waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
3112 if (pid != (pid_t) -1)
3114 if (debug_linux_nat)
3115 fprintf_unfiltered (gdb_stdlog,
3116 "KWC: wait %s received unknown.\n",
3117 target_pid_to_str (lp->ptid));
3118 /* The Linux kernel sometimes fails to kill a thread
3119 completely after PTRACE_KILL; that goes from the stop
3120 point in do_fork out to the one in
3121 get_signal_to_deliever and waits again. So kill it
3123 kill_callback (lp, NULL);
3126 while (pid == GET_LWP (lp->ptid));
3128 gdb_assert (pid == -1 && errno == ECHILD);
3133 pid = my_waitpid (GET_LWP (lp->ptid), NULL, 0);
3134 if (pid != (pid_t) -1)
3136 if (debug_linux_nat)
3137 fprintf_unfiltered (gdb_stdlog,
3138 "KWC: wait %s received unk.\n",
3139 target_pid_to_str (lp->ptid));
3140 /* See the call to kill_callback above. */
3141 kill_callback (lp, NULL);
3144 while (pid == GET_LWP (lp->ptid));
3146 gdb_assert (pid == -1 && errno == ECHILD);
3151 linux_nat_kill (void)
3153 struct target_waitstatus last;
3157 if (target_can_async_p ())
3158 target_async (NULL, 0);
3160 /* If we're stopped while forking and we haven't followed yet,
3161 kill the other task. We need to do this first because the
3162 parent will be sleeping if this is a vfork. */
3164 get_last_target_status (&last_ptid, &last);
3166 if (last.kind == TARGET_WAITKIND_FORKED
3167 || last.kind == TARGET_WAITKIND_VFORKED)
3169 ptrace (PT_KILL, PIDGET (last.value.related_pid), 0, 0);
3173 if (forks_exist_p ())
3175 linux_fork_killall ();
3176 drain_queued_events (-1);
3180 /* Stop all threads before killing them, since ptrace requires
3181 that the thread is stopped to sucessfully PTRACE_KILL. */
3182 iterate_over_lwps (stop_callback, NULL);
3183 /* ... and wait until all of them have reported back that
3184 they're no longer running. */
3185 iterate_over_lwps (stop_wait_callback, NULL);
3187 /* Kill all LWP's ... */
3188 iterate_over_lwps (kill_callback, NULL);
3190 /* ... and wait until we've flushed all events. */
3191 iterate_over_lwps (kill_wait_callback, NULL);
3194 target_mourn_inferior ();
3198 linux_nat_mourn_inferior (struct target_ops *ops)
3200 /* Destroy LWP info; it's no longer valid. */
3203 if (! forks_exist_p ())
3205 /* Normal case, no other forks available. */
3206 if (target_can_async_p ())
3207 linux_nat_async (NULL, 0);
3208 linux_ops->to_mourn_inferior (ops);
3211 /* Multi-fork case. The current inferior_ptid has exited, but
3212 there are other viable forks to debug. Delete the exiting
3213 one and context-switch to the first available. */
3214 linux_fork_mourn_inferior ();
3218 linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
3219 const char *annex, gdb_byte *readbuf,
3220 const gdb_byte *writebuf,
3221 ULONGEST offset, LONGEST len)
3223 struct cleanup *old_chain = save_inferior_ptid ();
3226 if (is_lwp (inferior_ptid))
3227 inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
3229 xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
3232 do_cleanups (old_chain);
3237 linux_nat_thread_alive (ptid_t ptid)
3241 gdb_assert (is_lwp (ptid));
3243 /* Send signal 0 instead of anything ptrace, because ptracing a
3244 running thread errors out claiming that the thread doesn't
3246 err = kill_lwp (GET_LWP (ptid), 0);
3248 if (debug_linux_nat)
3249 fprintf_unfiltered (gdb_stdlog,
3250 "LLTA: KILL(SIG0) %s (%s)\n",
3251 target_pid_to_str (ptid),
3252 err ? safe_strerror (err) : "OK");
3261 linux_nat_pid_to_str (ptid_t ptid)
3263 static char buf[64];
3266 && ((lwp_list && lwp_list->next)
3267 || GET_PID (ptid) != GET_LWP (ptid)))
3269 snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
3273 return normal_pid_to_str (ptid);
3277 sigchld_handler (int signo)
3279 if (target_async_permitted
3280 && linux_nat_async_events_state != sigchld_sync
3281 && signo == SIGCHLD)
3282 /* It is *always* a bug to hit this. */
3283 internal_error (__FILE__, __LINE__,
3284 "sigchld_handler called when async events are enabled");
3286 /* Do nothing. The only reason for this handler is that it allows
3287 us to use sigsuspend in linux_nat_wait above to wait for the
3288 arrival of a SIGCHLD. */
3291 /* Accepts an integer PID; Returns a string representing a file that
3292 can be opened to get the symbols for the child process. */
3295 linux_child_pid_to_exec_file (int pid)
3297 char *name1, *name2;
3299 name1 = xmalloc (MAXPATHLEN);
3300 name2 = xmalloc (MAXPATHLEN);
3301 make_cleanup (xfree, name1);
3302 make_cleanup (xfree, name2);
3303 memset (name2, 0, MAXPATHLEN);
3305 sprintf (name1, "/proc/%d/exe", pid);
3306 if (readlink (name1, name2, MAXPATHLEN) > 0)
3312 /* Service function for corefiles and info proc. */
3315 read_mapping (FILE *mapfile,
3320 char *device, long long *inode, char *filename)
3322 int ret = fscanf (mapfile, "%llx-%llx %s %llx %s %llx",
3323 addr, endaddr, permissions, offset, device, inode);
3326 if (ret > 0 && ret != EOF)
3328 /* Eat everything up to EOL for the filename. This will prevent
3329 weird filenames (such as one with embedded whitespace) from
3330 confusing this code. It also makes this code more robust in
3331 respect to annotations the kernel may add after the filename.
3333 Note the filename is used for informational purposes
3335 ret += fscanf (mapfile, "%[^\n]\n", filename);
3338 return (ret != 0 && ret != EOF);
3341 /* Fills the "to_find_memory_regions" target vector. Lists the memory
3342 regions in the inferior for a corefile. */
3345 linux_nat_find_memory_regions (int (*func) (CORE_ADDR,
3347 int, int, int, void *), void *obfd)
3349 long long pid = PIDGET (inferior_ptid);
3350 char mapsfilename[MAXPATHLEN];
3352 long long addr, endaddr, size, offset, inode;
3353 char permissions[8], device[8], filename[MAXPATHLEN];
3354 int read, write, exec;
3356 struct cleanup *cleanup;
3358 /* Compose the filename for the /proc memory map, and open it. */
3359 sprintf (mapsfilename, "/proc/%lld/maps", pid);
3360 if ((mapsfile = fopen (mapsfilename, "r")) == NULL)
3361 error (_("Could not open %s."), mapsfilename);
3362 cleanup = make_cleanup_fclose (mapsfile);
3365 fprintf_filtered (gdb_stdout,
3366 "Reading memory regions from %s\n", mapsfilename);
3368 /* Now iterate until end-of-file. */
3369 while (read_mapping (mapsfile, &addr, &endaddr, &permissions[0],
3370 &offset, &device[0], &inode, &filename[0]))
3372 size = endaddr - addr;
3374 /* Get the segment's permissions. */
3375 read = (strchr (permissions, 'r') != 0);
3376 write = (strchr (permissions, 'w') != 0);
3377 exec = (strchr (permissions, 'x') != 0);
3381 fprintf_filtered (gdb_stdout,
3382 "Save segment, %lld bytes at 0x%s (%c%c%c)",
3383 size, paddr_nz (addr),
3385 write ? 'w' : ' ', exec ? 'x' : ' ');
3387 fprintf_filtered (gdb_stdout, " for %s", filename);
3388 fprintf_filtered (gdb_stdout, "\n");
3391 /* Invoke the callback function to create the corefile
3393 func (addr, size, read, write, exec, obfd);
3395 do_cleanups (cleanup);
3400 find_signalled_thread (struct thread_info *info, void *data)
3402 if (info->stop_signal != TARGET_SIGNAL_0
3403 && ptid_get_pid (info->ptid) == ptid_get_pid (inferior_ptid))
3409 static enum target_signal
3410 find_stop_signal (void)
3412 struct thread_info *info =
3413 iterate_over_threads (find_signalled_thread, NULL);
3416 return info->stop_signal;
3418 return TARGET_SIGNAL_0;
3421 /* Records the thread's register state for the corefile note
3425 linux_nat_do_thread_registers (bfd *obfd, ptid_t ptid,
3426 char *note_data, int *note_size,
3427 enum target_signal stop_signal)
3429 gdb_gregset_t gregs;
3430 gdb_fpregset_t fpregs;
3431 unsigned long lwp = ptid_get_lwp (ptid);
3432 struct regcache *regcache = get_thread_regcache (ptid);
3433 struct gdbarch *gdbarch = get_regcache_arch (regcache);
3434 const struct regset *regset;
3436 struct cleanup *old_chain;
3437 struct core_regset_section *sect_list;
3440 old_chain = save_inferior_ptid ();
3441 inferior_ptid = ptid;
3442 target_fetch_registers (regcache, -1);
3443 do_cleanups (old_chain);
3445 core_regset_p = gdbarch_regset_from_core_section_p (gdbarch);
3446 sect_list = gdbarch_core_regset_sections (gdbarch);
3449 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg",
3450 sizeof (gregs))) != NULL
3451 && regset->collect_regset != NULL)
3452 regset->collect_regset (regset, regcache, -1,
3453 &gregs, sizeof (gregs));
3455 fill_gregset (regcache, &gregs, -1);
3457 note_data = (char *) elfcore_write_prstatus (obfd,
3461 stop_signal, &gregs);
3463 /* The loop below uses the new struct core_regset_section, which stores
3464 the supported section names and sizes for the core file. Note that
3465 note PRSTATUS needs to be treated specially. But the other notes are
3466 structurally the same, so they can benefit from the new struct. */
3467 if (core_regset_p && sect_list != NULL)
3468 while (sect_list->sect_name != NULL)
3470 /* .reg was already handled above. */
3471 if (strcmp (sect_list->sect_name, ".reg") == 0)
3476 regset = gdbarch_regset_from_core_section (gdbarch,
3477 sect_list->sect_name,
3479 gdb_assert (regset && regset->collect_regset);
3480 gdb_regset = xmalloc (sect_list->size);
3481 regset->collect_regset (regset, regcache, -1,
3482 gdb_regset, sect_list->size);
3483 note_data = (char *) elfcore_write_register_note (obfd,
3486 sect_list->sect_name,
3493 /* For architectures that does not have the struct core_regset_section
3494 implemented, we use the old method. When all the architectures have
3495 the new support, the code below should be deleted. */
3499 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg2",
3500 sizeof (fpregs))) != NULL
3501 && regset->collect_regset != NULL)
3502 regset->collect_regset (regset, regcache, -1,
3503 &fpregs, sizeof (fpregs));
3505 fill_fpregset (regcache, &fpregs, -1);
3507 note_data = (char *) elfcore_write_prfpreg (obfd,
3510 &fpregs, sizeof (fpregs));
3516 struct linux_nat_corefile_thread_data
3522 enum target_signal stop_signal;
3525 /* Called by gdbthread.c once per thread. Records the thread's
3526 register state for the corefile note section. */
3529 linux_nat_corefile_thread_callback (struct lwp_info *ti, void *data)
3531 struct linux_nat_corefile_thread_data *args = data;
3533 args->note_data = linux_nat_do_thread_registers (args->obfd,
3543 /* Fills the "to_make_corefile_note" target vector. Builds the note
3544 section for a corefile, and returns it in a malloc buffer. */
3547 linux_nat_make_corefile_notes (bfd *obfd, int *note_size)
3549 struct linux_nat_corefile_thread_data thread_args;
3550 struct cleanup *old_chain;
3551 /* The variable size must be >= sizeof (prpsinfo_t.pr_fname). */
3552 char fname[16] = { '\0' };
3553 /* The variable size must be >= sizeof (prpsinfo_t.pr_psargs). */
3554 char psargs[80] = { '\0' };
3555 char *note_data = NULL;
3556 ptid_t current_ptid = inferior_ptid;
3560 if (get_exec_file (0))
3562 strncpy (fname, strrchr (get_exec_file (0), '/') + 1, sizeof (fname));
3563 strncpy (psargs, get_exec_file (0), sizeof (psargs));
3564 if (get_inferior_args ())
3567 char *psargs_end = psargs + sizeof (psargs);
3569 /* linux_elfcore_write_prpsinfo () handles zero unterminated
3571 string_end = memchr (psargs, 0, sizeof (psargs));
3572 if (string_end != NULL)
3574 *string_end++ = ' ';
3575 strncpy (string_end, get_inferior_args (),
3576 psargs_end - string_end);
3579 note_data = (char *) elfcore_write_prpsinfo (obfd,
3581 note_size, fname, psargs);
3584 /* Dump information for threads. */
3585 thread_args.obfd = obfd;
3586 thread_args.note_data = note_data;
3587 thread_args.note_size = note_size;
3588 thread_args.num_notes = 0;
3589 thread_args.stop_signal = find_stop_signal ();
3590 iterate_over_lwps (linux_nat_corefile_thread_callback, &thread_args);
3591 gdb_assert (thread_args.num_notes != 0);
3592 note_data = thread_args.note_data;
3594 auxv_len = target_read_alloc (¤t_target, TARGET_OBJECT_AUXV,
3598 note_data = elfcore_write_note (obfd, note_data, note_size,
3599 "CORE", NT_AUXV, auxv, auxv_len);
3603 make_cleanup (xfree, note_data);
3607 /* Implement the "info proc" command. */
3610 linux_nat_info_proc_cmd (char *args, int from_tty)
3612 long long pid = PIDGET (inferior_ptid);
3615 char buffer[MAXPATHLEN];
3616 char fname1[MAXPATHLEN], fname2[MAXPATHLEN];
3629 /* Break up 'args' into an argv array. */
3630 argv = gdb_buildargv (args);
3631 make_cleanup_freeargv (argv);
3633 while (argv != NULL && *argv != NULL)
3635 if (isdigit (argv[0][0]))
3637 pid = strtoul (argv[0], NULL, 10);
3639 else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
3643 else if (strcmp (argv[0], "status") == 0)
3647 else if (strcmp (argv[0], "stat") == 0)
3651 else if (strcmp (argv[0], "cmd") == 0)
3655 else if (strncmp (argv[0], "exe", strlen (argv[0])) == 0)
3659 else if (strcmp (argv[0], "cwd") == 0)
3663 else if (strncmp (argv[0], "all", strlen (argv[0])) == 0)
3669 /* [...] (future options here) */
3674 error (_("No current process: you must name one."));
3676 sprintf (fname1, "/proc/%lld", pid);
3677 if (stat (fname1, &dummy) != 0)
3678 error (_("No /proc directory: '%s'"), fname1);
3680 printf_filtered (_("process %lld\n"), pid);
3681 if (cmdline_f || all)
3683 sprintf (fname1, "/proc/%lld/cmdline", pid);
3684 if ((procfile = fopen (fname1, "r")) != NULL)
3686 struct cleanup *cleanup = make_cleanup_fclose (procfile);
3687 fgets (buffer, sizeof (buffer), procfile);
3688 printf_filtered ("cmdline = '%s'\n", buffer);
3689 do_cleanups (cleanup);
3692 warning (_("unable to open /proc file '%s'"), fname1);
3696 sprintf (fname1, "/proc/%lld/cwd", pid);
3697 memset (fname2, 0, sizeof (fname2));
3698 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
3699 printf_filtered ("cwd = '%s'\n", fname2);
3701 warning (_("unable to read link '%s'"), fname1);
3705 sprintf (fname1, "/proc/%lld/exe", pid);
3706 memset (fname2, 0, sizeof (fname2));
3707 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
3708 printf_filtered ("exe = '%s'\n", fname2);
3710 warning (_("unable to read link '%s'"), fname1);
3712 if (mappings_f || all)
3714 sprintf (fname1, "/proc/%lld/maps", pid);
3715 if ((procfile = fopen (fname1, "r")) != NULL)
3717 long long addr, endaddr, size, offset, inode;
3718 char permissions[8], device[8], filename[MAXPATHLEN];
3719 struct cleanup *cleanup;
3721 cleanup = make_cleanup_fclose (procfile);
3722 printf_filtered (_("Mapped address spaces:\n\n"));
3723 if (gdbarch_addr_bit (current_gdbarch) == 32)
3725 printf_filtered ("\t%10s %10s %10s %10s %7s\n",
3728 " Size", " Offset", "objfile");
3732 printf_filtered (" %18s %18s %10s %10s %7s\n",
3735 " Size", " Offset", "objfile");
3738 while (read_mapping (procfile, &addr, &endaddr, &permissions[0],
3739 &offset, &device[0], &inode, &filename[0]))
3741 size = endaddr - addr;
3743 /* FIXME: carlton/2003-08-27: Maybe the printf_filtered
3744 calls here (and possibly above) should be abstracted
3745 out into their own functions? Andrew suggests using
3746 a generic local_address_string instead to print out
3747 the addresses; that makes sense to me, too. */
3749 if (gdbarch_addr_bit (current_gdbarch) == 32)
3751 printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
3752 (unsigned long) addr, /* FIXME: pr_addr */
3753 (unsigned long) endaddr,
3755 (unsigned int) offset,
3756 filename[0] ? filename : "");
3760 printf_filtered (" %#18lx %#18lx %#10x %#10x %7s\n",
3761 (unsigned long) addr, /* FIXME: pr_addr */
3762 (unsigned long) endaddr,
3764 (unsigned int) offset,
3765 filename[0] ? filename : "");
3769 do_cleanups (cleanup);
3772 warning (_("unable to open /proc file '%s'"), fname1);
3774 if (status_f || all)
3776 sprintf (fname1, "/proc/%lld/status", pid);
3777 if ((procfile = fopen (fname1, "r")) != NULL)
3779 struct cleanup *cleanup = make_cleanup_fclose (procfile);
3780 while (fgets (buffer, sizeof (buffer), procfile) != NULL)
3781 puts_filtered (buffer);
3782 do_cleanups (cleanup);
3785 warning (_("unable to open /proc file '%s'"), fname1);
3789 sprintf (fname1, "/proc/%lld/stat", pid);
3790 if ((procfile = fopen (fname1, "r")) != NULL)
3795 struct cleanup *cleanup = make_cleanup_fclose (procfile);
3797 if (fscanf (procfile, "%d ", &itmp) > 0)
3798 printf_filtered (_("Process: %d\n"), itmp);
3799 if (fscanf (procfile, "(%[^)]) ", &buffer[0]) > 0)
3800 printf_filtered (_("Exec file: %s\n"), buffer);
3801 if (fscanf (procfile, "%c ", &ctmp) > 0)
3802 printf_filtered (_("State: %c\n"), ctmp);
3803 if (fscanf (procfile, "%d ", &itmp) > 0)
3804 printf_filtered (_("Parent process: %d\n"), itmp);
3805 if (fscanf (procfile, "%d ", &itmp) > 0)
3806 printf_filtered (_("Process group: %d\n"), itmp);
3807 if (fscanf (procfile, "%d ", &itmp) > 0)
3808 printf_filtered (_("Session id: %d\n"), itmp);
3809 if (fscanf (procfile, "%d ", &itmp) > 0)
3810 printf_filtered (_("TTY: %d\n"), itmp);
3811 if (fscanf (procfile, "%d ", &itmp) > 0)
3812 printf_filtered (_("TTY owner process group: %d\n"), itmp);
3813 if (fscanf (procfile, "%lu ", <mp) > 0)
3814 printf_filtered (_("Flags: 0x%lx\n"), ltmp);
3815 if (fscanf (procfile, "%lu ", <mp) > 0)
3816 printf_filtered (_("Minor faults (no memory page): %lu\n"),
3817 (unsigned long) ltmp);
3818 if (fscanf (procfile, "%lu ", <mp) > 0)
3819 printf_filtered (_("Minor faults, children: %lu\n"),
3820 (unsigned long) ltmp);
3821 if (fscanf (procfile, "%lu ", <mp) > 0)
3822 printf_filtered (_("Major faults (memory page faults): %lu\n"),
3823 (unsigned long) ltmp);
3824 if (fscanf (procfile, "%lu ", <mp) > 0)
3825 printf_filtered (_("Major faults, children: %lu\n"),
3826 (unsigned long) ltmp);
3827 if (fscanf (procfile, "%ld ", <mp) > 0)
3828 printf_filtered (_("utime: %ld\n"), ltmp);
3829 if (fscanf (procfile, "%ld ", <mp) > 0)
3830 printf_filtered (_("stime: %ld\n"), ltmp);
3831 if (fscanf (procfile, "%ld ", <mp) > 0)
3832 printf_filtered (_("utime, children: %ld\n"), ltmp);
3833 if (fscanf (procfile, "%ld ", <mp) > 0)
3834 printf_filtered (_("stime, children: %ld\n"), ltmp);
3835 if (fscanf (procfile, "%ld ", <mp) > 0)
3836 printf_filtered (_("jiffies remaining in current time slice: %ld\n"),
3838 if (fscanf (procfile, "%ld ", <mp) > 0)
3839 printf_filtered (_("'nice' value: %ld\n"), ltmp);
3840 if (fscanf (procfile, "%lu ", <mp) > 0)
3841 printf_filtered (_("jiffies until next timeout: %lu\n"),
3842 (unsigned long) ltmp);
3843 if (fscanf (procfile, "%lu ", <mp) > 0)
3844 printf_filtered (_("jiffies until next SIGALRM: %lu\n"),
3845 (unsigned long) ltmp);
3846 if (fscanf (procfile, "%ld ", <mp) > 0)
3847 printf_filtered (_("start time (jiffies since system boot): %ld\n"),
3849 if (fscanf (procfile, "%lu ", <mp) > 0)
3850 printf_filtered (_("Virtual memory size: %lu\n"),
3851 (unsigned long) ltmp);
3852 if (fscanf (procfile, "%lu ", <mp) > 0)
3853 printf_filtered (_("Resident set size: %lu\n"), (unsigned long) ltmp);
3854 if (fscanf (procfile, "%lu ", <mp) > 0)
3855 printf_filtered (_("rlim: %lu\n"), (unsigned long) ltmp);
3856 if (fscanf (procfile, "%lu ", <mp) > 0)
3857 printf_filtered (_("Start of text: 0x%lx\n"), ltmp);
3858 if (fscanf (procfile, "%lu ", <mp) > 0)
3859 printf_filtered (_("End of text: 0x%lx\n"), ltmp);
3860 if (fscanf (procfile, "%lu ", <mp) > 0)
3861 printf_filtered (_("Start of stack: 0x%lx\n"), ltmp);
3862 #if 0 /* Don't know how architecture-dependent the rest is...
3863 Anyway the signal bitmap info is available from "status". */
3864 if (fscanf (procfile, "%lu ", <mp) > 0) /* FIXME arch? */
3865 printf_filtered (_("Kernel stack pointer: 0x%lx\n"), ltmp);
3866 if (fscanf (procfile, "%lu ", <mp) > 0) /* FIXME arch? */
3867 printf_filtered (_("Kernel instr pointer: 0x%lx\n"), ltmp);
3868 if (fscanf (procfile, "%ld ", <mp) > 0)
3869 printf_filtered (_("Pending signals bitmap: 0x%lx\n"), ltmp);
3870 if (fscanf (procfile, "%ld ", <mp) > 0)
3871 printf_filtered (_("Blocked signals bitmap: 0x%lx\n"), ltmp);
3872 if (fscanf (procfile, "%ld ", <mp) > 0)
3873 printf_filtered (_("Ignored signals bitmap: 0x%lx\n"), ltmp);
3874 if (fscanf (procfile, "%ld ", <mp) > 0)
3875 printf_filtered (_("Catched signals bitmap: 0x%lx\n"), ltmp);
3876 if (fscanf (procfile, "%lu ", <mp) > 0) /* FIXME arch? */
3877 printf_filtered (_("wchan (system call): 0x%lx\n"), ltmp);
3879 do_cleanups (cleanup);
3882 warning (_("unable to open /proc file '%s'"), fname1);
3886 /* Implement the to_xfer_partial interface for memory reads using the /proc
3887 filesystem. Because we can use a single read() call for /proc, this
3888 can be much more efficient than banging away at PTRACE_PEEKTEXT,
3889 but it doesn't support writes. */
3892 linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
3893 const char *annex, gdb_byte *readbuf,
3894 const gdb_byte *writebuf,
3895 ULONGEST offset, LONGEST len)
3901 if (object != TARGET_OBJECT_MEMORY || !readbuf)
3904 /* Don't bother for one word. */
3905 if (len < 3 * sizeof (long))
3908 /* We could keep this file open and cache it - possibly one per
3909 thread. That requires some juggling, but is even faster. */
3910 sprintf (filename, "/proc/%d/mem", PIDGET (inferior_ptid));
3911 fd = open (filename, O_RDONLY | O_LARGEFILE);
3915 /* If pread64 is available, use it. It's faster if the kernel
3916 supports it (only one syscall), and it's 64-bit safe even on
3917 32-bit platforms (for instance, SPARC debugging a SPARC64
3920 if (pread64 (fd, readbuf, len, offset) != len)
3922 if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
3932 /* Parse LINE as a signal set and add its set bits to SIGS. */
3935 add_line_to_sigset (const char *line, sigset_t *sigs)
3937 int len = strlen (line) - 1;
3941 if (line[len] != '\n')
3942 error (_("Could not parse signal set: %s"), line);
3950 if (*p >= '0' && *p <= '9')
3952 else if (*p >= 'a' && *p <= 'f')
3953 digit = *p - 'a' + 10;
3955 error (_("Could not parse signal set: %s"), line);
3960 sigaddset (sigs, signum + 1);
3962 sigaddset (sigs, signum + 2);
3964 sigaddset (sigs, signum + 3);
3966 sigaddset (sigs, signum + 4);
3972 /* Find process PID's pending signals from /proc/pid/status and set
3976 linux_proc_pending_signals (int pid, sigset_t *pending, sigset_t *blocked, sigset_t *ignored)
3979 char buffer[MAXPATHLEN], fname[MAXPATHLEN];
3981 struct cleanup *cleanup;
3983 sigemptyset (pending);
3984 sigemptyset (blocked);
3985 sigemptyset (ignored);
3986 sprintf (fname, "/proc/%d/status", pid);
3987 procfile = fopen (fname, "r");
3988 if (procfile == NULL)
3989 error (_("Could not open %s"), fname);
3990 cleanup = make_cleanup_fclose (procfile);
3992 while (fgets (buffer, MAXPATHLEN, procfile) != NULL)
3994 /* Normal queued signals are on the SigPnd line in the status
3995 file. However, 2.6 kernels also have a "shared" pending
3996 queue for delivering signals to a thread group, so check for
3999 Unfortunately some Red Hat kernels include the shared pending
4000 queue but not the ShdPnd status field. */
4002 if (strncmp (buffer, "SigPnd:\t", 8) == 0)
4003 add_line_to_sigset (buffer + 8, pending);
4004 else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
4005 add_line_to_sigset (buffer + 8, pending);
4006 else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
4007 add_line_to_sigset (buffer + 8, blocked);
4008 else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
4009 add_line_to_sigset (buffer + 8, ignored);
4012 do_cleanups (cleanup);
4016 linux_nat_xfer_osdata (struct target_ops *ops, enum target_object object,
4017 const char *annex, gdb_byte *readbuf,
4018 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
4020 /* We make the process list snapshot when the object starts to be
4022 static const char *buf;
4023 static LONGEST len_avail = -1;
4024 static struct obstack obstack;
4028 gdb_assert (object == TARGET_OBJECT_OSDATA);
4030 if (strcmp (annex, "processes") != 0)
4033 gdb_assert (readbuf && !writebuf);
4037 if (len_avail != -1 && len_avail != 0)
4038 obstack_free (&obstack, NULL);
4041 obstack_init (&obstack);
4042 obstack_grow_str (&obstack, "<osdata type=\"processes\">\n");
4044 dirp = opendir ("/proc");
4048 while ((dp = readdir (dirp)) != NULL)
4050 struct stat statbuf;
4051 char procentry[sizeof ("/proc/4294967295")];
4053 if (!isdigit (dp->d_name[0])
4054 || strlen (dp->d_name) > sizeof ("4294967295") - 1)
4057 sprintf (procentry, "/proc/%s", dp->d_name);
4058 if (stat (procentry, &statbuf) == 0
4059 && S_ISDIR (statbuf.st_mode))
4063 char cmd[MAXPATHLEN + 1];
4064 struct passwd *entry;
4066 pathname = xstrprintf ("/proc/%s/cmdline", dp->d_name);
4067 entry = getpwuid (statbuf.st_uid);
4069 if ((f = fopen (pathname, "r")) != NULL)
4071 size_t len = fread (cmd, 1, sizeof (cmd) - 1, f);
4075 for (i = 0; i < len; i++)
4080 obstack_xml_printf (
4083 "<column name=\"pid\">%s</column>"
4084 "<column name=\"user\">%s</column>"
4085 "<column name=\"command\">%s</column>"
4088 entry ? entry->pw_name : "?",
4101 obstack_grow_str0 (&obstack, "</osdata>\n");
4102 buf = obstack_finish (&obstack);
4103 len_avail = strlen (buf);
4106 if (offset >= len_avail)
4108 /* Done. Get rid of the obstack. */
4109 obstack_free (&obstack, NULL);
4115 if (len > len_avail - offset)
4116 len = len_avail - offset;
4117 memcpy (readbuf, buf + offset, len);
4123 linux_xfer_partial (struct target_ops *ops, enum target_object object,
4124 const char *annex, gdb_byte *readbuf,
4125 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
4129 if (object == TARGET_OBJECT_AUXV)
4130 return procfs_xfer_auxv (ops, object, annex, readbuf, writebuf,
4133 if (object == TARGET_OBJECT_OSDATA)
4134 return linux_nat_xfer_osdata (ops, object, annex, readbuf, writebuf,
4137 xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
4142 return super_xfer_partial (ops, object, annex, readbuf, writebuf,
4146 /* Create a prototype generic GNU/Linux target. The client can override
4147 it with local methods. */
4150 linux_target_install_ops (struct target_ops *t)
4152 t->to_insert_fork_catchpoint = linux_child_insert_fork_catchpoint;
4153 t->to_insert_vfork_catchpoint = linux_child_insert_vfork_catchpoint;
4154 t->to_insert_exec_catchpoint = linux_child_insert_exec_catchpoint;
4155 t->to_pid_to_exec_file = linux_child_pid_to_exec_file;
4156 t->to_post_startup_inferior = linux_child_post_startup_inferior;
4157 t->to_post_attach = linux_child_post_attach;
4158 t->to_follow_fork = linux_child_follow_fork;
4159 t->to_find_memory_regions = linux_nat_find_memory_regions;
4160 t->to_make_corefile_notes = linux_nat_make_corefile_notes;
4162 super_xfer_partial = t->to_xfer_partial;
4163 t->to_xfer_partial = linux_xfer_partial;
4169 struct target_ops *t;
4171 t = inf_ptrace_target ();
4172 linux_target_install_ops (t);
4178 linux_trad_target (CORE_ADDR (*register_u_offset)(struct gdbarch *, int, int))
4180 struct target_ops *t;
4182 t = inf_ptrace_trad_target (register_u_offset);
4183 linux_target_install_ops (t);
4188 /* target_is_async_p implementation. */
4191 linux_nat_is_async_p (void)
4193 /* NOTE: palves 2008-03-21: We're only async when the user requests
4194 it explicitly with the "maintenance set target-async" command.
4195 Someday, linux will always be async. */
4196 if (!target_async_permitted)
4202 /* target_can_async_p implementation. */
4205 linux_nat_can_async_p (void)
4207 /* NOTE: palves 2008-03-21: We're only async when the user requests
4208 it explicitly with the "maintenance set target-async" command.
4209 Someday, linux will always be async. */
4210 if (!target_async_permitted)
4213 /* See target.h/target_async_mask. */
4214 return linux_nat_async_mask_value;
4218 linux_nat_supports_non_stop (void)
4223 /* target_async_mask implementation. */
4226 linux_nat_async_mask (int mask)
4229 current_state = linux_nat_async_mask_value;
4231 if (current_state != mask)
4235 linux_nat_async (NULL, 0);
4236 linux_nat_async_mask_value = mask;
4240 linux_nat_async_mask_value = mask;
4241 linux_nat_async (inferior_event_handler, 0);
4245 return current_state;
4248 /* Pop an event from the event pipe. */
4251 linux_nat_event_pipe_pop (int* ptr_status, int* ptr_options)
4253 struct waitpid_result event = {0};
4258 ret = read (linux_nat_event_pipe[0], &event, sizeof (event));
4260 while (ret == -1 && errno == EINTR);
4262 gdb_assert (ret == sizeof (event));
4264 *ptr_status = event.status;
4265 *ptr_options = event.options;
4267 linux_nat_num_queued_events--;
4272 /* Push an event into the event pipe. */
4275 linux_nat_event_pipe_push (int pid, int status, int options)
4278 struct waitpid_result event = {0};
4280 event.status = status;
4281 event.options = options;
4285 ret = write (linux_nat_event_pipe[1], &event, sizeof (event));
4286 gdb_assert ((ret == -1 && errno == EINTR) || ret == sizeof (event));
4287 } while (ret == -1 && errno == EINTR);
4289 linux_nat_num_queued_events++;
4293 get_pending_events (void)
4295 int status, options, pid;
4297 if (!target_async_permitted
4298 || linux_nat_async_events_state != sigchld_async)
4299 internal_error (__FILE__, __LINE__,
4300 "get_pending_events called with async masked");
4305 options = __WCLONE | WNOHANG;
4309 pid = waitpid (-1, &status, options);
4311 while (pid == -1 && errno == EINTR);
4318 pid = waitpid (-1, &status, options);
4320 while (pid == -1 && errno == EINTR);
4324 /* No more children reporting events. */
4327 if (debug_linux_nat_async)
4328 fprintf_unfiltered (gdb_stdlog, "\
4329 get_pending_events: pid(%d), status(%x), options (%x)\n",
4330 pid, status, options);
4332 linux_nat_event_pipe_push (pid, status, options);
4335 if (debug_linux_nat_async)
4336 fprintf_unfiltered (gdb_stdlog, "\
4337 get_pending_events: linux_nat_num_queued_events(%d)\n",
4338 linux_nat_num_queued_events);
4341 /* SIGCHLD handler for async mode. */
4344 async_sigchld_handler (int signo)
4346 if (debug_linux_nat_async)
4347 fprintf_unfiltered (gdb_stdlog, "async_sigchld_handler\n");
4349 get_pending_events ();
4352 /* Set SIGCHLD handling state to STATE. Returns previous state. */
4354 static enum sigchld_state
4355 linux_nat_async_events (enum sigchld_state state)
4357 enum sigchld_state current_state = linux_nat_async_events_state;
4359 if (debug_linux_nat_async)
4360 fprintf_unfiltered (gdb_stdlog,
4361 "LNAE: state(%d): linux_nat_async_events_state(%d), "
4362 "linux_nat_num_queued_events(%d)\n",
4363 state, linux_nat_async_events_state,
4364 linux_nat_num_queued_events);
4366 if (current_state != state)
4369 sigemptyset (&mask);
4370 sigaddset (&mask, SIGCHLD);
4372 /* Always block before changing state. */
4373 sigprocmask (SIG_BLOCK, &mask, NULL);
4375 /* Set new state. */
4376 linux_nat_async_events_state = state;
4382 /* Block target events. */
4383 sigprocmask (SIG_BLOCK, &mask, NULL);
4384 sigaction (SIGCHLD, &sync_sigchld_action, NULL);
4385 /* Get events out of queue, and make them available to
4386 queued_waitpid / my_waitpid. */
4387 pipe_to_local_event_queue ();
4392 /* Unblock target events for async mode. */
4394 sigprocmask (SIG_BLOCK, &mask, NULL);
4396 /* Put events we already waited on, in the pipe first, so
4398 local_event_queue_to_pipe ();
4399 /* While in masked async, we may have not collected all
4400 the pending events. Get them out now. */
4401 get_pending_events ();
4404 sigaction (SIGCHLD, &async_sigchld_action, NULL);
4405 sigprocmask (SIG_UNBLOCK, &mask, NULL);
4408 case sigchld_default:
4410 /* SIGCHLD default mode. */
4411 sigaction (SIGCHLD, &sigchld_default_action, NULL);
4413 /* Get events out of queue, and make them available to
4414 queued_waitpid / my_waitpid. */
4415 pipe_to_local_event_queue ();
4417 /* Unblock SIGCHLD. */
4418 sigprocmask (SIG_UNBLOCK, &mask, NULL);
4424 return current_state;
4427 static int async_terminal_is_ours = 1;
4429 /* target_terminal_inferior implementation. */
4432 linux_nat_terminal_inferior (void)
4434 if (!target_is_async_p ())
4436 /* Async mode is disabled. */
4437 terminal_inferior ();
4441 /* GDB should never give the terminal to the inferior, if the
4442 inferior is running in the background (run&, continue&, etc.).
4443 This check can be removed when the common code is fixed. */
4444 if (!sync_execution)
4447 terminal_inferior ();
4449 if (!async_terminal_is_ours)
4452 delete_file_handler (input_fd);
4453 async_terminal_is_ours = 0;
4457 /* target_terminal_ours implementation. */
4460 linux_nat_terminal_ours (void)
4462 if (!target_is_async_p ())
4464 /* Async mode is disabled. */
4469 /* GDB should never give the terminal to the inferior if the
4470 inferior is running in the background (run&, continue&, etc.),
4471 but claiming it sure should. */
4474 if (!sync_execution)
4477 if (async_terminal_is_ours)
4480 clear_sigint_trap ();
4481 add_file_handler (input_fd, stdin_event_handler, 0);
4482 async_terminal_is_ours = 1;
4485 static void (*async_client_callback) (enum inferior_event_type event_type,
4487 static void *async_client_context;
4490 linux_nat_async_file_handler (int error, gdb_client_data client_data)
4492 async_client_callback (INF_REG_EVENT, async_client_context);
4495 /* target_async implementation. */
4498 linux_nat_async (void (*callback) (enum inferior_event_type event_type,
4499 void *context), void *context)
4501 if (linux_nat_async_mask_value == 0 || !target_async_permitted)
4502 internal_error (__FILE__, __LINE__,
4503 "Calling target_async when async is masked");
4505 if (callback != NULL)
4507 async_client_callback = callback;
4508 async_client_context = context;
4509 add_file_handler (linux_nat_event_pipe[0],
4510 linux_nat_async_file_handler, NULL);
4512 linux_nat_async_events (sigchld_async);
4516 async_client_callback = callback;
4517 async_client_context = context;
4519 linux_nat_async_events (sigchld_sync);
4520 delete_file_handler (linux_nat_event_pipe[0]);
4525 /* Stop an LWP, and push a TARGET_SIGNAL_0 stop status if no other
4529 linux_nat_stop_lwp (struct lwp_info *lwp, void *data)
4531 ptid_t ptid = * (ptid_t *) data;
4533 if (ptid_equal (lwp->ptid, ptid)
4534 || ptid_equal (minus_one_ptid, ptid)
4535 || (ptid_is_pid (ptid)
4536 && ptid_get_pid (ptid) == ptid_get_pid (lwp->ptid)))
4542 if (debug_linux_nat)
4543 fprintf_unfiltered (gdb_stdlog,
4544 "LNSL: running -> suspending %s\n",
4545 target_pid_to_str (lwp->ptid));
4547 /* Peek once, to check if we've already waited for this
4549 pid = queued_waitpid_1 (ptid_get_lwp (lwp->ptid), &status,
4550 lwp->cloned ? __WCLONE : 0, 1 /* peek */);
4554 ptid_t ptid = lwp->ptid;
4556 stop_callback (lwp, NULL);
4557 stop_wait_callback (lwp, NULL);
4559 /* If the lwp exits while we try to stop it, there's
4560 nothing else to do. */
4561 lwp = find_lwp_pid (ptid);
4565 pid = queued_waitpid_1 (ptid_get_lwp (lwp->ptid), &status,
4566 lwp->cloned ? __WCLONE : 0,
4570 /* If we didn't collect any signal other than SIGSTOP while
4571 stopping the LWP, push a SIGNAL_0 event. In either case,
4572 the event-loop will end up calling target_wait which will
4575 push_waitpid (ptid_get_lwp (lwp->ptid), W_STOPCODE (0),
4576 lwp->cloned ? __WCLONE : 0);
4580 /* Already known to be stopped; do nothing. */
4582 if (debug_linux_nat)
4584 if (find_thread_pid (lwp->ptid)->stop_requested)
4585 fprintf_unfiltered (gdb_stdlog, "\
4586 LNSL: already stopped/stop_requested %s\n",
4587 target_pid_to_str (lwp->ptid));
4589 fprintf_unfiltered (gdb_stdlog, "\
4590 LNSL: already stopped/no stop_requested yet %s\n",
4591 target_pid_to_str (lwp->ptid));
4599 linux_nat_stop (ptid_t ptid)
4603 linux_nat_async_events (sigchld_sync);
4604 iterate_over_lwps (linux_nat_stop_lwp, &ptid);
4605 target_async (inferior_event_handler, 0);
4608 linux_ops->to_stop (ptid);
4612 linux_nat_add_target (struct target_ops *t)
4614 /* Save the provided single-threaded target. We save this in a separate
4615 variable because another target we've inherited from (e.g. inf-ptrace)
4616 may have saved a pointer to T; we want to use it for the final
4617 process stratum target. */
4618 linux_ops_saved = *t;
4619 linux_ops = &linux_ops_saved;
4621 /* Override some methods for multithreading. */
4622 t->to_create_inferior = linux_nat_create_inferior;
4623 t->to_attach = linux_nat_attach;
4624 t->to_detach = linux_nat_detach;
4625 t->to_resume = linux_nat_resume;
4626 t->to_wait = linux_nat_wait;
4627 t->to_xfer_partial = linux_nat_xfer_partial;
4628 t->to_kill = linux_nat_kill;
4629 t->to_mourn_inferior = linux_nat_mourn_inferior;
4630 t->to_thread_alive = linux_nat_thread_alive;
4631 t->to_pid_to_str = linux_nat_pid_to_str;
4632 t->to_has_thread_control = tc_schedlock;
4634 t->to_can_async_p = linux_nat_can_async_p;
4635 t->to_is_async_p = linux_nat_is_async_p;
4636 t->to_supports_non_stop = linux_nat_supports_non_stop;
4637 t->to_async = linux_nat_async;
4638 t->to_async_mask = linux_nat_async_mask;
4639 t->to_terminal_inferior = linux_nat_terminal_inferior;
4640 t->to_terminal_ours = linux_nat_terminal_ours;
4642 /* Methods for non-stop support. */
4643 t->to_stop = linux_nat_stop;
4645 /* We don't change the stratum; this target will sit at
4646 process_stratum and thread_db will set at thread_stratum. This
4647 is a little strange, since this is a multi-threaded-capable
4648 target, but we want to be on the stack below thread_db, and we
4649 also want to be used for single-threaded processes. */
4653 /* TODO: Eliminate this and have libthread_db use
4654 find_target_beneath. */
4658 /* Register a method to call whenever a new thread is attached. */
4660 linux_nat_set_new_thread (struct target_ops *t, void (*new_thread) (ptid_t))
4662 /* Save the pointer. We only support a single registered instance
4663 of the GNU/Linux native target, so we do not need to map this to
4665 linux_nat_new_thread = new_thread;
4668 /* Return the saved siginfo associated with PTID. */
4670 linux_nat_get_siginfo (ptid_t ptid)
4672 struct lwp_info *lp = find_lwp_pid (ptid);
4674 gdb_assert (lp != NULL);
4676 return &lp->siginfo;
4679 /* Enable/Disable async mode. */
4682 linux_nat_setup_async (void)
4684 if (pipe (linux_nat_event_pipe) == -1)
4685 internal_error (__FILE__, __LINE__,
4686 "creating event pipe failed.");
4687 fcntl (linux_nat_event_pipe[0], F_SETFL, O_NONBLOCK);
4688 fcntl (linux_nat_event_pipe[1], F_SETFL, O_NONBLOCK);
4692 _initialize_linux_nat (void)
4696 add_info ("proc", linux_nat_info_proc_cmd, _("\
4697 Show /proc process information about any running process.\n\
4698 Specify any process id, or use the program being debugged by default.\n\
4699 Specify any of the following keywords for detailed info:\n\
4700 mappings -- list of mapped memory regions.\n\
4701 stat -- list a bunch of random process info.\n\
4702 status -- list a different bunch of random process info.\n\
4703 all -- list all available /proc info."));
4705 add_setshow_zinteger_cmd ("lin-lwp", class_maintenance,
4706 &debug_linux_nat, _("\
4707 Set debugging of GNU/Linux lwp module."), _("\
4708 Show debugging of GNU/Linux lwp module."), _("\
4709 Enables printf debugging output."),
4711 show_debug_linux_nat,
4712 &setdebuglist, &showdebuglist);
4714 add_setshow_zinteger_cmd ("lin-lwp-async", class_maintenance,
4715 &debug_linux_nat_async, _("\
4716 Set debugging of GNU/Linux async lwp module."), _("\
4717 Show debugging of GNU/Linux async lwp module."), _("\
4718 Enables printf debugging output."),
4720 show_debug_linux_nat_async,
4721 &setdebuglist, &showdebuglist);
4723 /* Get the default SIGCHLD action. Used while forking an inferior
4724 (see linux_nat_create_inferior/linux_nat_async_events). */
4725 sigaction (SIGCHLD, NULL, &sigchld_default_action);
4727 /* Block SIGCHLD by default. Doing this early prevents it getting
4728 unblocked if an exception is thrown due to an error while the
4729 inferior is starting (sigsetjmp/siglongjmp). */
4730 sigemptyset (&mask);
4731 sigaddset (&mask, SIGCHLD);
4732 sigprocmask (SIG_BLOCK, &mask, NULL);
4734 /* Save this mask as the default. */
4735 sigprocmask (SIG_SETMASK, NULL, &normal_mask);
4737 /* The synchronous SIGCHLD handler. */
4738 sync_sigchld_action.sa_handler = sigchld_handler;
4739 sigemptyset (&sync_sigchld_action.sa_mask);
4740 sync_sigchld_action.sa_flags = SA_RESTART;
4742 /* Make it the default. */
4743 sigaction (SIGCHLD, &sync_sigchld_action, NULL);
4745 /* Make sure we don't block SIGCHLD during a sigsuspend. */
4746 sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
4747 sigdelset (&suspend_mask, SIGCHLD);
4749 /* SIGCHLD handler for async mode. */
4750 async_sigchld_action.sa_handler = async_sigchld_handler;
4751 sigemptyset (&async_sigchld_action.sa_mask);
4752 async_sigchld_action.sa_flags = SA_RESTART;
4754 linux_nat_setup_async ();
4756 add_setshow_boolean_cmd ("disable-randomization", class_support,
4757 &disable_randomization, _("\
4758 Set disabling of debuggee's virtual address space randomization."), _("\
4759 Show disabling of debuggee's virtual address space randomization."), _("\
4760 When this mode is on (which is the default), randomization of the virtual\n\
4761 address space is disabled. Standalone programs run with the randomization\n\
4762 enabled by default on some platforms."),
4763 &set_disable_randomization,
4764 &show_disable_randomization,
4765 &setlist, &showlist);
4769 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
4770 the GNU/Linux Threads library and therefore doesn't really belong
4773 /* Read variable NAME in the target and return its value if found.
4774 Otherwise return zero. It is assumed that the type of the variable
4778 get_signo (const char *name)
4780 struct minimal_symbol *ms;
4783 ms = lookup_minimal_symbol (name, NULL, NULL);
4787 if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
4788 sizeof (signo)) != 0)
4794 /* Return the set of signals used by the threads library in *SET. */
4797 lin_thread_get_thread_signals (sigset_t *set)
4799 struct sigaction action;
4800 int restart, cancel;
4801 sigset_t blocked_mask;
4803 sigemptyset (&blocked_mask);
4806 restart = get_signo ("__pthread_sig_restart");
4807 cancel = get_signo ("__pthread_sig_cancel");
4809 /* LinuxThreads normally uses the first two RT signals, but in some legacy
4810 cases may use SIGUSR1/SIGUSR2. NPTL always uses RT signals, but does
4811 not provide any way for the debugger to query the signal numbers -
4812 fortunately they don't change! */
4815 restart = __SIGRTMIN;
4818 cancel = __SIGRTMIN + 1;
4820 sigaddset (set, restart);
4821 sigaddset (set, cancel);
4823 /* The GNU/Linux Threads library makes terminating threads send a
4824 special "cancel" signal instead of SIGCHLD. Make sure we catch
4825 those (to prevent them from terminating GDB itself, which is
4826 likely to be their default action) and treat them the same way as
4829 action.sa_handler = sigchld_handler;
4830 sigemptyset (&action.sa_mask);
4831 action.sa_flags = SA_RESTART;
4832 sigaction (cancel, &action, NULL);
4834 /* We block the "cancel" signal throughout this code ... */
4835 sigaddset (&blocked_mask, cancel);
4836 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
4838 /* ... except during a sigsuspend. */
4839 sigdelset (&suspend_mask, cancel);