]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/linux-nat.c
* target.h (TARGET_WNOHANG): New.
[thirdparty/binutils-gdb.git] / gdb / linux-nat.c
CommitLineData
3993f6b1 1/* GNU/Linux native-dependent code common to multiple platforms.
dba24537 2
0fb0cc75 3 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
e26af52f 4 Free Software Foundation, Inc.
3993f6b1
DJ
5
6 This file is part of GDB.
7
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
a9762ec7 10 the Free Software Foundation; either version 3 of the License, or
3993f6b1
DJ
11 (at your option) any later version.
12
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.
17
18 You should have received a copy of the GNU General Public License
a9762ec7 19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
3993f6b1
DJ
20
21#include "defs.h"
22#include "inferior.h"
23#include "target.h"
d6b0e80f 24#include "gdb_string.h"
3993f6b1 25#include "gdb_wait.h"
d6b0e80f
AC
26#include "gdb_assert.h"
27#ifdef HAVE_TKILL_SYSCALL
28#include <unistd.h>
29#include <sys/syscall.h>
30#endif
3993f6b1 31#include <sys/ptrace.h>
0274a8ce 32#include "linux-nat.h"
ac264b3b 33#include "linux-fork.h"
d6b0e80f
AC
34#include "gdbthread.h"
35#include "gdbcmd.h"
36#include "regcache.h"
4f844a66 37#include "regset.h"
10d6c8cd
DJ
38#include "inf-ptrace.h"
39#include "auxv.h"
dba24537
AC
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 */
b84876c2
PA
49#include "inf-loop.h"
50#include "event-loop.h"
51#include "event-top.h"
07e059b5
VP
52#include <pwd.h>
53#include <sys/types.h>
54#include "gdb_dirent.h"
55#include "xml-support.h"
191c4426 56#include "terminal.h"
dba24537 57
10568435
JK
58#ifdef HAVE_PERSONALITY
59# include <sys/personality.h>
60# if !HAVE_DECL_ADDR_NO_RANDOMIZE
61# define ADDR_NO_RANDOMIZE 0x0040000
62# endif
63#endif /* HAVE_PERSONALITY */
64
8a77dff3
VP
65/* This comment documents high-level logic of this file.
66
67Waiting for events in sync mode
68===============================
69
70When waiting for an event in a specific thread, we just use waitpid, passing
71the specific pid, and not passing WNOHANG.
72
73When waiting for an event in all threads, waitpid is not quite good. Prior to
74version 2.4, Linux can either wait for event in main thread, or in secondary
75threads. (2.4 has the __WALL flag). So, if we use blocking waitpid, we might
76miss an event. The solution is to use non-blocking waitpid, together with
77sigsuspend. First, we use non-blocking waitpid to get an event in the main
78process, if any. Second, we use non-blocking waitpid with the __WCLONED
79flag to check for events in cloned processes. If nothing is found, we use
80sigsuspend to wait for SIGCHLD. When SIGCHLD arrives, it means something
81happened to a child process -- and SIGCHLD will be delivered both for events
82in main debugged process and in cloned processes. As soon as we know there's
83an event, we get back to calling nonblocking waitpid with and without __WCLONED.
84
85Note that SIGCHLD should be blocked between waitpid and sigsuspend calls,
86so that we don't miss a signal. If SIGCHLD arrives in between, when it's
87blocked, the signal becomes pending and sigsuspend immediately
88notices it and returns.
89
90Waiting for events in async mode
91================================
92
7feb7d06
PA
93In async mode, GDB should always be ready to handle both user input
94and target events, so neither blocking waitpid nor sigsuspend are
95viable options. Instead, we should asynchronously notify the GDB main
96event loop whenever there's an unprocessed event from the target. We
97detect asynchronous target events by handling SIGCHLD signals. To
98notify the event loop about target events, the self-pipe trick is used
99--- a pipe is registered as waitable event source in the event loop,
100the event loop select/poll's on the read end of this pipe (as well on
101other event sources, e.g., stdin), and the SIGCHLD handler writes a
102byte to this pipe. This is more portable than relying on
103pselect/ppoll, since on kernels that lack those syscalls, libc
104emulates them with select/poll+sigprocmask, and that is racy
105(a.k.a. plain broken).
106
107Obviously, if we fail to notify the event loop if there's a target
108event, it's bad. OTOH, if we notify the event loop when there's no
109event from the target, linux_nat_wait will detect that there's no real
110event to report, and return event of type TARGET_WAITKIND_IGNORE.
111This is mostly harmless, but it will waste time and is better avoided.
112
113The main design point is that every time GDB is outside linux-nat.c,
114we have a SIGCHLD handler installed that is called when something
115happens to the target and notifies the GDB event loop. Whenever GDB
116core decides to handle the event, and calls into linux-nat.c, we
117process things as in sync mode, except that the we never block in
118sigsuspend.
119
120While processing an event, we may end up momentarily blocked in
121waitpid calls. Those waitpid calls, while blocking, are guarantied to
122return quickly. E.g., in all-stop mode, before reporting to the core
123that an LWP hit a breakpoint, all LWPs are stopped by sending them
124SIGSTOP, and synchronously waiting for the SIGSTOP to be reported.
125Note that this is different from blocking indefinitely waiting for the
126next event --- here, we're already handling an event.
8a77dff3
VP
127
128Use of signals
129==============
130
131We stop threads by sending a SIGSTOP. The use of SIGSTOP instead of another
132signal is not entirely significant; we just need for a signal to be delivered,
133so that we can intercept it. SIGSTOP's advantage is that it can not be
134blocked. A disadvantage is that it is not a real-time signal, so it can only
135be queued once; we do not keep track of other sources of SIGSTOP.
136
137Two other signals that can't be blocked are SIGCONT and SIGKILL. But we can't
138use them, because they have special behavior when the signal is generated -
139not when it is delivered. SIGCONT resumes the entire thread group and SIGKILL
140kills the entire thread group.
141
142A delivered SIGSTOP would stop the entire thread group, not just the thread we
143tkill'd. But we never let the SIGSTOP be delivered; we always intercept and
144cancel it (by PTRACE_CONT without passing SIGSTOP).
145
146We could use a real-time signal instead. This would solve those problems; we
147could use PTRACE_GETSIGINFO to locate the specific stop signals sent by GDB.
148But we would still have to have some support for SIGSTOP, since PTRACE_ATTACH
149generates it, and there are races with trying to find a signal that is not
150blocked. */
a0ef4274 151
dba24537
AC
152#ifndef O_LARGEFILE
153#define O_LARGEFILE 0
154#endif
0274a8ce 155
3993f6b1
DJ
156/* If the system headers did not provide the constants, hard-code the normal
157 values. */
158#ifndef PTRACE_EVENT_FORK
159
160#define PTRACE_SETOPTIONS 0x4200
161#define PTRACE_GETEVENTMSG 0x4201
162
163/* options set using PTRACE_SETOPTIONS */
164#define PTRACE_O_TRACESYSGOOD 0x00000001
165#define PTRACE_O_TRACEFORK 0x00000002
166#define PTRACE_O_TRACEVFORK 0x00000004
167#define PTRACE_O_TRACECLONE 0x00000008
168#define PTRACE_O_TRACEEXEC 0x00000010
9016a515
DJ
169#define PTRACE_O_TRACEVFORKDONE 0x00000020
170#define PTRACE_O_TRACEEXIT 0x00000040
3993f6b1
DJ
171
172/* Wait extended result codes for the above trace options. */
173#define PTRACE_EVENT_FORK 1
174#define PTRACE_EVENT_VFORK 2
175#define PTRACE_EVENT_CLONE 3
176#define PTRACE_EVENT_EXEC 4
c874c7fc 177#define PTRACE_EVENT_VFORK_DONE 5
9016a515 178#define PTRACE_EVENT_EXIT 6
3993f6b1
DJ
179
180#endif /* PTRACE_EVENT_FORK */
181
182/* We can't always assume that this flag is available, but all systems
183 with the ptrace event handlers also have __WALL, so it's safe to use
184 here. */
185#ifndef __WALL
186#define __WALL 0x40000000 /* Wait for any child. */
187#endif
188
02d3ff8c 189#ifndef PTRACE_GETSIGINFO
1ef18d08
PA
190# define PTRACE_GETSIGINFO 0x4202
191# define PTRACE_SETSIGINFO 0x4203
02d3ff8c
UW
192#endif
193
10d6c8cd
DJ
194/* The single-threaded native GNU/Linux target_ops. We save a pointer for
195 the use of the multi-threaded target. */
196static struct target_ops *linux_ops;
f973ed9c 197static struct target_ops linux_ops_saved;
10d6c8cd 198
9f0bdab8
DJ
199/* The method to call, if any, when a new thread is attached. */
200static void (*linux_nat_new_thread) (ptid_t);
201
5b009018
PA
202/* The method to call, if any, when the siginfo object needs to be
203 converted between the layout returned by ptrace, and the layout in
204 the architecture of the inferior. */
205static int (*linux_nat_siginfo_fixup) (struct siginfo *,
206 gdb_byte *,
207 int);
208
ac264b3b
MS
209/* The saved to_xfer_partial method, inherited from inf-ptrace.c.
210 Called by our to_xfer_partial. */
211static LONGEST (*super_xfer_partial) (struct target_ops *,
212 enum target_object,
213 const char *, gdb_byte *,
214 const gdb_byte *,
10d6c8cd
DJ
215 ULONGEST, LONGEST);
216
d6b0e80f 217static int debug_linux_nat;
920d2a44
AC
218static void
219show_debug_linux_nat (struct ui_file *file, int from_tty,
220 struct cmd_list_element *c, const char *value)
221{
222 fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
223 value);
224}
d6b0e80f 225
b84876c2
PA
226static int debug_linux_nat_async = 0;
227static void
228show_debug_linux_nat_async (struct ui_file *file, int from_tty,
229 struct cmd_list_element *c, const char *value)
230{
231 fprintf_filtered (file, _("Debugging of GNU/Linux async lwp module is %s.\n"),
232 value);
233}
234
10568435
JK
235static int disable_randomization = 1;
236
237static void
238show_disable_randomization (struct ui_file *file, int from_tty,
239 struct cmd_list_element *c, const char *value)
240{
241#ifdef HAVE_PERSONALITY
242 fprintf_filtered (file, _("\
243Disabling randomization of debuggee's virtual address space is %s.\n"),
244 value);
245#else /* !HAVE_PERSONALITY */
246 fputs_filtered (_("\
247Disabling randomization of debuggee's virtual address space is unsupported on\n\
248this platform.\n"), file);
249#endif /* !HAVE_PERSONALITY */
250}
251
252static void
253set_disable_randomization (char *args, int from_tty, struct cmd_list_element *c)
254{
255#ifndef HAVE_PERSONALITY
256 error (_("\
257Disabling randomization of debuggee's virtual address space is unsupported on\n\
258this platform."));
259#endif /* !HAVE_PERSONALITY */
260}
261
9016a515
DJ
262static int linux_parent_pid;
263
ae087d01
DJ
264struct simple_pid_list
265{
266 int pid;
3d799a95 267 int status;
ae087d01
DJ
268 struct simple_pid_list *next;
269};
270struct simple_pid_list *stopped_pids;
271
3993f6b1
DJ
272/* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACEFORK
273 can not be used, 1 if it can. */
274
275static int linux_supports_tracefork_flag = -1;
276
9016a515
DJ
277/* If we have PTRACE_O_TRACEFORK, this flag indicates whether we also have
278 PTRACE_O_TRACEVFORKDONE. */
279
280static int linux_supports_tracevforkdone_flag = -1;
281
b84876c2
PA
282/* Async mode support */
283
b84876c2
PA
284/* Zero if the async mode, although enabled, is masked, which means
285 linux_nat_wait should behave as if async mode was off. */
286static int linux_nat_async_mask_value = 1;
287
288/* The read/write ends of the pipe registered as waitable file in the
289 event loop. */
290static int linux_nat_event_pipe[2] = { -1, -1 };
291
7feb7d06 292/* Flush the event pipe. */
b84876c2 293
7feb7d06
PA
294static void
295async_file_flush (void)
b84876c2 296{
7feb7d06
PA
297 int ret;
298 char buf;
b84876c2 299
7feb7d06 300 do
b84876c2 301 {
7feb7d06 302 ret = read (linux_nat_event_pipe[0], &buf, 1);
b84876c2 303 }
7feb7d06 304 while (ret >= 0 || (ret == -1 && errno == EINTR));
b84876c2
PA
305}
306
7feb7d06
PA
307/* Put something (anything, doesn't matter what, or how much) in event
308 pipe, so that the select/poll in the event-loop realizes we have
309 something to process. */
252fbfc8 310
b84876c2 311static void
7feb7d06 312async_file_mark (void)
b84876c2 313{
7feb7d06 314 int ret;
b84876c2 315
7feb7d06
PA
316 /* It doesn't really matter what the pipe contains, as long we end
317 up with something in it. Might as well flush the previous
318 left-overs. */
319 async_file_flush ();
b84876c2 320
7feb7d06 321 do
b84876c2 322 {
7feb7d06 323 ret = write (linux_nat_event_pipe[1], "+", 1);
b84876c2 324 }
7feb7d06 325 while (ret == -1 && errno == EINTR);
b84876c2 326
7feb7d06
PA
327 /* Ignore EAGAIN. If the pipe is full, the event loop will already
328 be awakened anyway. */
b84876c2
PA
329}
330
7feb7d06
PA
331static void linux_nat_async (void (*callback)
332 (enum inferior_event_type event_type, void *context),
333 void *context);
334static int linux_nat_async_mask (int mask);
335static int kill_lwp (int lwpid, int signo);
336
337static int stop_callback (struct lwp_info *lp, void *data);
338
339static void block_child_signals (sigset_t *prev_mask);
340static void restore_child_signals_mask (sigset_t *prev_mask);
ae087d01
DJ
341\f
342/* Trivial list manipulation functions to keep track of a list of
343 new stopped processes. */
344static void
3d799a95 345add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
ae087d01
DJ
346{
347 struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
348 new_pid->pid = pid;
3d799a95 349 new_pid->status = status;
ae087d01
DJ
350 new_pid->next = *listp;
351 *listp = new_pid;
352}
353
354static int
3d799a95 355pull_pid_from_list (struct simple_pid_list **listp, int pid, int *status)
ae087d01
DJ
356{
357 struct simple_pid_list **p;
358
359 for (p = listp; *p != NULL; p = &(*p)->next)
360 if ((*p)->pid == pid)
361 {
362 struct simple_pid_list *next = (*p)->next;
3d799a95 363 *status = (*p)->status;
ae087d01
DJ
364 xfree (*p);
365 *p = next;
366 return 1;
367 }
368 return 0;
369}
370
3d799a95
DJ
371static void
372linux_record_stopped_pid (int pid, int status)
ae087d01 373{
3d799a95 374 add_to_pid_list (&stopped_pids, pid, status);
ae087d01
DJ
375}
376
3993f6b1
DJ
377\f
378/* A helper function for linux_test_for_tracefork, called after fork (). */
379
380static void
381linux_tracefork_child (void)
382{
383 int ret;
384
385 ptrace (PTRACE_TRACEME, 0, 0, 0);
386 kill (getpid (), SIGSTOP);
387 fork ();
48bb3cce 388 _exit (0);
3993f6b1
DJ
389}
390
7feb7d06 391/* Wrapper function for waitpid which handles EINTR. */
b957e937
DJ
392
393static int
394my_waitpid (int pid, int *status, int flags)
395{
396 int ret;
b84876c2 397
b957e937
DJ
398 do
399 {
400 ret = waitpid (pid, status, flags);
401 }
402 while (ret == -1 && errno == EINTR);
403
404 return ret;
405}
406
407/* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.
408
409 First, we try to enable fork tracing on ORIGINAL_PID. If this fails,
410 we know that the feature is not available. This may change the tracing
411 options for ORIGINAL_PID, but we'll be setting them shortly anyway.
412
413 However, if it succeeds, we don't know for sure that the feature is
414 available; old versions of PTRACE_SETOPTIONS ignored unknown options. We
3993f6b1 415 create a child process, attach to it, use PTRACE_SETOPTIONS to enable
b957e937
DJ
416 fork tracing, and let it fork. If the process exits, we assume that we
417 can't use TRACEFORK; if we get the fork notification, and we can extract
418 the new child's PID, then we assume that we can. */
3993f6b1
DJ
419
420static void
b957e937 421linux_test_for_tracefork (int original_pid)
3993f6b1
DJ
422{
423 int child_pid, ret, status;
424 long second_pid;
7feb7d06 425 sigset_t prev_mask;
4c28f408 426
7feb7d06
PA
427 /* We don't want those ptrace calls to be interrupted. */
428 block_child_signals (&prev_mask);
3993f6b1 429
b957e937
DJ
430 linux_supports_tracefork_flag = 0;
431 linux_supports_tracevforkdone_flag = 0;
432
433 ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACEFORK);
434 if (ret != 0)
7feb7d06
PA
435 {
436 restore_child_signals_mask (&prev_mask);
437 return;
438 }
b957e937 439
3993f6b1
DJ
440 child_pid = fork ();
441 if (child_pid == -1)
e2e0b3e5 442 perror_with_name (("fork"));
3993f6b1
DJ
443
444 if (child_pid == 0)
445 linux_tracefork_child ();
446
b957e937 447 ret = my_waitpid (child_pid, &status, 0);
3993f6b1 448 if (ret == -1)
e2e0b3e5 449 perror_with_name (("waitpid"));
3993f6b1 450 else if (ret != child_pid)
8a3fe4f8 451 error (_("linux_test_for_tracefork: waitpid: unexpected result %d."), ret);
3993f6b1 452 if (! WIFSTOPPED (status))
8a3fe4f8 453 error (_("linux_test_for_tracefork: waitpid: unexpected status %d."), status);
3993f6b1 454
3993f6b1
DJ
455 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
456 if (ret != 0)
457 {
b957e937
DJ
458 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
459 if (ret != 0)
460 {
8a3fe4f8 461 warning (_("linux_test_for_tracefork: failed to kill child"));
7feb7d06 462 restore_child_signals_mask (&prev_mask);
b957e937
DJ
463 return;
464 }
465
466 ret = my_waitpid (child_pid, &status, 0);
467 if (ret != child_pid)
8a3fe4f8 468 warning (_("linux_test_for_tracefork: failed to wait for killed child"));
b957e937 469 else if (!WIFSIGNALED (status))
8a3fe4f8
AC
470 warning (_("linux_test_for_tracefork: unexpected wait status 0x%x from "
471 "killed child"), status);
b957e937 472
7feb7d06 473 restore_child_signals_mask (&prev_mask);
3993f6b1
DJ
474 return;
475 }
476
9016a515
DJ
477 /* Check whether PTRACE_O_TRACEVFORKDONE is available. */
478 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0,
479 PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORKDONE);
480 linux_supports_tracevforkdone_flag = (ret == 0);
481
b957e937
DJ
482 ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
483 if (ret != 0)
8a3fe4f8 484 warning (_("linux_test_for_tracefork: failed to resume child"));
b957e937
DJ
485
486 ret = my_waitpid (child_pid, &status, 0);
487
3993f6b1
DJ
488 if (ret == child_pid && WIFSTOPPED (status)
489 && status >> 16 == PTRACE_EVENT_FORK)
490 {
491 second_pid = 0;
492 ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
493 if (ret == 0 && second_pid != 0)
494 {
495 int second_status;
496
497 linux_supports_tracefork_flag = 1;
b957e937
DJ
498 my_waitpid (second_pid, &second_status, 0);
499 ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
500 if (ret != 0)
8a3fe4f8 501 warning (_("linux_test_for_tracefork: failed to kill second child"));
97725dc4 502 my_waitpid (second_pid, &status, 0);
3993f6b1
DJ
503 }
504 }
b957e937 505 else
8a3fe4f8
AC
506 warning (_("linux_test_for_tracefork: unexpected result from waitpid "
507 "(%d, status 0x%x)"), ret, status);
3993f6b1 508
b957e937
DJ
509 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
510 if (ret != 0)
8a3fe4f8 511 warning (_("linux_test_for_tracefork: failed to kill child"));
b957e937 512 my_waitpid (child_pid, &status, 0);
4c28f408 513
7feb7d06 514 restore_child_signals_mask (&prev_mask);
3993f6b1
DJ
515}
516
517/* Return non-zero iff we have tracefork functionality available.
518 This function also sets linux_supports_tracefork_flag. */
519
520static int
b957e937 521linux_supports_tracefork (int pid)
3993f6b1
DJ
522{
523 if (linux_supports_tracefork_flag == -1)
b957e937 524 linux_test_for_tracefork (pid);
3993f6b1
DJ
525 return linux_supports_tracefork_flag;
526}
527
9016a515 528static int
b957e937 529linux_supports_tracevforkdone (int pid)
9016a515
DJ
530{
531 if (linux_supports_tracefork_flag == -1)
b957e937 532 linux_test_for_tracefork (pid);
9016a515
DJ
533 return linux_supports_tracevforkdone_flag;
534}
535
3993f6b1 536\f
4de4c07c
DJ
537void
538linux_enable_event_reporting (ptid_t ptid)
539{
d3587048 540 int pid = ptid_get_lwp (ptid);
4de4c07c
DJ
541 int options;
542
d3587048
DJ
543 if (pid == 0)
544 pid = ptid_get_pid (ptid);
545
b957e937 546 if (! linux_supports_tracefork (pid))
4de4c07c
DJ
547 return;
548
a2f23071
DJ
549 options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEEXEC
550 | PTRACE_O_TRACECLONE;
b957e937 551 if (linux_supports_tracevforkdone (pid))
9016a515
DJ
552 options |= PTRACE_O_TRACEVFORKDONE;
553
554 /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to support
555 read-only process state. */
4de4c07c
DJ
556
557 ptrace (PTRACE_SETOPTIONS, pid, 0, options);
558}
559
6d8fd2b7
UW
560static void
561linux_child_post_attach (int pid)
4de4c07c
DJ
562{
563 linux_enable_event_reporting (pid_to_ptid (pid));
0ec9a092 564 check_for_thread_db ();
4de4c07c
DJ
565}
566
10d6c8cd 567static void
4de4c07c
DJ
568linux_child_post_startup_inferior (ptid_t ptid)
569{
570 linux_enable_event_reporting (ptid);
0ec9a092 571 check_for_thread_db ();
4de4c07c
DJ
572}
573
6d8fd2b7
UW
574static int
575linux_child_follow_fork (struct target_ops *ops, int follow_child)
3993f6b1 576{
7feb7d06 577 sigset_t prev_mask;
4de4c07c
DJ
578 ptid_t last_ptid;
579 struct target_waitstatus last_status;
9016a515 580 int has_vforked;
4de4c07c
DJ
581 int parent_pid, child_pid;
582
7feb7d06 583 block_child_signals (&prev_mask);
b84876c2 584
4de4c07c 585 get_last_target_status (&last_ptid, &last_status);
9016a515 586 has_vforked = (last_status.kind == TARGET_WAITKIND_VFORKED);
d3587048
DJ
587 parent_pid = ptid_get_lwp (last_ptid);
588 if (parent_pid == 0)
589 parent_pid = ptid_get_pid (last_ptid);
3a3e9ee3 590 child_pid = PIDGET (last_status.value.related_pid);
4de4c07c
DJ
591
592 if (! follow_child)
593 {
594 /* We're already attached to the parent, by default. */
595
596 /* Before detaching from the child, remove all breakpoints from
b242c3c2
PA
597 it. If we forked, then this has already been taken care of
598 by infrun.c. If we vforked however, any breakpoint inserted
599 in the parent is visible in the child, even those added while
600 stopped in a vfork catchpoint. This won't actually modify
601 the breakpoint list, but will physically remove the
602 breakpoints from the child. This will remove the breakpoints
603 from the parent also, but they'll be reinserted below. */
604 if (has_vforked)
605 detach_breakpoints (child_pid);
4de4c07c 606
ac264b3b
MS
607 /* Detach new forked process? */
608 if (detach_fork)
f75c00e4 609 {
e85a822c 610 if (info_verbose || debug_linux_nat)
ac264b3b
MS
611 {
612 target_terminal_ours ();
613 fprintf_filtered (gdb_stdlog,
614 "Detaching after fork from child process %d.\n",
615 child_pid);
616 }
4de4c07c 617
ac264b3b
MS
618 ptrace (PTRACE_DETACH, child_pid, 0, 0);
619 }
620 else
621 {
622 struct fork_info *fp;
77435e4c 623 struct inferior *parent_inf, *child_inf;
7f9f62ba
PA
624
625 /* Add process to GDB's tables. */
77435e4c
PA
626 child_inf = add_inferior (child_pid);
627
628 parent_inf = find_inferior_pid (GET_PID (last_ptid));
629 child_inf->attach_flag = parent_inf->attach_flag;
191c4426 630 copy_terminal_info (child_inf, parent_inf);
7f9f62ba 631
ac264b3b
MS
632 /* Retain child fork in ptrace (stopped) state. */
633 fp = find_fork_pid (child_pid);
634 if (!fp)
635 fp = add_fork (child_pid);
636 fork_save_infrun_state (fp, 0);
637 }
9016a515
DJ
638
639 if (has_vforked)
640 {
b957e937
DJ
641 gdb_assert (linux_supports_tracefork_flag >= 0);
642 if (linux_supports_tracevforkdone (0))
9016a515
DJ
643 {
644 int status;
645
646 ptrace (PTRACE_CONT, parent_pid, 0, 0);
58aecb61 647 my_waitpid (parent_pid, &status, __WALL);
c874c7fc 648 if ((status >> 16) != PTRACE_EVENT_VFORK_DONE)
8a3fe4f8
AC
649 warning (_("Unexpected waitpid result %06x when waiting for "
650 "vfork-done"), status);
9016a515
DJ
651 }
652 else
653 {
654 /* We can't insert breakpoints until the child has
655 finished with the shared memory region. We need to
656 wait until that happens. Ideal would be to just
657 call:
658 - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
659 - waitpid (parent_pid, &status, __WALL);
660 However, most architectures can't handle a syscall
661 being traced on the way out if it wasn't traced on
662 the way in.
663
664 We might also think to loop, continuing the child
665 until it exits or gets a SIGTRAP. One problem is
666 that the child might call ptrace with PTRACE_TRACEME.
667
668 There's no simple and reliable way to figure out when
669 the vforked child will be done with its copy of the
670 shared memory. We could step it out of the syscall,
671 two instructions, let it go, and then single-step the
672 parent once. When we have hardware single-step, this
673 would work; with software single-step it could still
674 be made to work but we'd have to be able to insert
675 single-step breakpoints in the child, and we'd have
676 to insert -just- the single-step breakpoint in the
677 parent. Very awkward.
678
679 In the end, the best we can do is to make sure it
680 runs for a little while. Hopefully it will be out of
681 range of any breakpoints we reinsert. Usually this
682 is only the single-step breakpoint at vfork's return
683 point. */
684
685 usleep (10000);
686 }
687
688 /* Since we vforked, breakpoints were removed in the parent
689 too. Put them back. */
690 reattach_breakpoints (parent_pid);
691 }
4de4c07c 692 }
3993f6b1 693 else
4de4c07c 694 {
4e1c45ea
PA
695 struct thread_info *last_tp = find_thread_pid (last_ptid);
696 struct thread_info *tp;
4de4c07c 697 char child_pid_spelling[40];
77435e4c 698 struct inferior *parent_inf, *child_inf;
4de4c07c 699
4e1c45ea
PA
700 /* Copy user stepping state to the new inferior thread. */
701 struct breakpoint *step_resume_breakpoint = last_tp->step_resume_breakpoint;
702 CORE_ADDR step_range_start = last_tp->step_range_start;
703 CORE_ADDR step_range_end = last_tp->step_range_end;
704 struct frame_id step_frame_id = last_tp->step_frame_id;
705
706 /* Otherwise, deleting the parent would get rid of this
707 breakpoint. */
708 last_tp->step_resume_breakpoint = NULL;
709
4de4c07c
DJ
710 /* Before detaching from the parent, remove all breakpoints from it. */
711 remove_breakpoints ();
712
e85a822c 713 if (info_verbose || debug_linux_nat)
f75c00e4
DJ
714 {
715 target_terminal_ours ();
ac264b3b
MS
716 fprintf_filtered (gdb_stdlog,
717 "Attaching after fork to child process %d.\n",
718 child_pid);
f75c00e4 719 }
4de4c07c 720
7a7d3353
PA
721 /* Add the new inferior first, so that the target_detach below
722 doesn't unpush the target. */
723
77435e4c
PA
724 child_inf = add_inferior (child_pid);
725
726 parent_inf = find_inferior_pid (GET_PID (last_ptid));
727 child_inf->attach_flag = parent_inf->attach_flag;
191c4426 728 copy_terminal_info (child_inf, parent_inf);
7a7d3353 729
9016a515
DJ
730 /* If we're vforking, we may want to hold on to the parent until
731 the child exits or execs. At exec time we can remove the old
732 breakpoints from the parent and detach it; at exit time we
733 could do the same (or even, sneakily, resume debugging it - the
734 child's exec has failed, or something similar).
735
736 This doesn't clean up "properly", because we can't call
737 target_detach, but that's OK; if the current target is "child",
738 then it doesn't need any further cleanups, and lin_lwp will
739 generally not encounter vfork (vfork is defined to fork
740 in libpthread.so).
741
742 The holding part is very easy if we have VFORKDONE events;
743 but keeping track of both processes is beyond GDB at the
744 moment. So we don't expose the parent to the rest of GDB.
745 Instead we quietly hold onto it until such time as we can
746 safely resume it. */
747
748 if (has_vforked)
7f9f62ba
PA
749 {
750 linux_parent_pid = parent_pid;
751 detach_inferior (parent_pid);
752 }
ac264b3b
MS
753 else if (!detach_fork)
754 {
755 struct fork_info *fp;
756 /* Retain parent fork in ptrace (stopped) state. */
757 fp = find_fork_pid (parent_pid);
758 if (!fp)
759 fp = add_fork (parent_pid);
760 fork_save_infrun_state (fp, 0);
0d14fc63
PA
761
762 /* Also add an entry for the child fork. */
763 fp = find_fork_pid (child_pid);
764 if (!fp)
765 fp = add_fork (child_pid);
766 fork_save_infrun_state (fp, 0);
ac264b3b 767 }
9016a515 768 else
b84876c2 769 target_detach (NULL, 0);
4de4c07c 770
9f0bdab8 771 inferior_ptid = ptid_build (child_pid, child_pid, 0);
ac264b3b 772
9f0bdab8 773 linux_nat_switch_fork (inferior_ptid);
ef29ce1a 774 check_for_thread_db ();
4de4c07c 775
4e1c45ea
PA
776 tp = inferior_thread ();
777 tp->step_resume_breakpoint = step_resume_breakpoint;
778 tp->step_range_start = step_range_start;
779 tp->step_range_end = step_range_end;
780 tp->step_frame_id = step_frame_id;
781
4de4c07c
DJ
782 /* Reset breakpoints in the child as appropriate. */
783 follow_inferior_reset_breakpoints ();
784 }
785
7feb7d06 786 restore_child_signals_mask (&prev_mask);
4de4c07c
DJ
787 return 0;
788}
789
4de4c07c 790\f
6d8fd2b7
UW
791static void
792linux_child_insert_fork_catchpoint (int pid)
4de4c07c 793{
b957e937 794 if (! linux_supports_tracefork (pid))
8a3fe4f8 795 error (_("Your system does not support fork catchpoints."));
3993f6b1
DJ
796}
797
6d8fd2b7
UW
798static void
799linux_child_insert_vfork_catchpoint (int pid)
3993f6b1 800{
b957e937 801 if (!linux_supports_tracefork (pid))
8a3fe4f8 802 error (_("Your system does not support vfork catchpoints."));
3993f6b1
DJ
803}
804
6d8fd2b7
UW
805static void
806linux_child_insert_exec_catchpoint (int pid)
3993f6b1 807{
b957e937 808 if (!linux_supports_tracefork (pid))
8a3fe4f8 809 error (_("Your system does not support exec catchpoints."));
3993f6b1
DJ
810}
811
d6b0e80f
AC
812/* On GNU/Linux there are no real LWP's. The closest thing to LWP's
813 are processes sharing the same VM space. A multi-threaded process
814 is basically a group of such processes. However, such a grouping
815 is almost entirely a user-space issue; the kernel doesn't enforce
816 such a grouping at all (this might change in the future). In
817 general, we'll rely on the threads library (i.e. the GNU/Linux
818 Threads library) to provide such a grouping.
819
820 It is perfectly well possible to write a multi-threaded application
821 without the assistance of a threads library, by using the clone
822 system call directly. This module should be able to give some
823 rudimentary support for debugging such applications if developers
824 specify the CLONE_PTRACE flag in the clone system call, and are
825 using the Linux kernel 2.4 or above.
826
827 Note that there are some peculiarities in GNU/Linux that affect
828 this code:
829
830 - In general one should specify the __WCLONE flag to waitpid in
831 order to make it report events for any of the cloned processes
832 (and leave it out for the initial process). However, if a cloned
833 process has exited the exit status is only reported if the
834 __WCLONE flag is absent. Linux kernel 2.4 has a __WALL flag, but
835 we cannot use it since GDB must work on older systems too.
836
837 - When a traced, cloned process exits and is waited for by the
838 debugger, the kernel reassigns it to the original parent and
839 keeps it around as a "zombie". Somehow, the GNU/Linux Threads
840 library doesn't notice this, which leads to the "zombie problem":
841 When debugged a multi-threaded process that spawns a lot of
842 threads will run out of processes, even if the threads exit,
843 because the "zombies" stay around. */
844
845/* List of known LWPs. */
9f0bdab8 846struct lwp_info *lwp_list;
d6b0e80f
AC
847\f
848
d6b0e80f
AC
849/* Original signal mask. */
850static sigset_t normal_mask;
851
852/* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
853 _initialize_linux_nat. */
854static sigset_t suspend_mask;
855
7feb7d06
PA
856/* Signals to block to make that sigsuspend work. */
857static sigset_t blocked_mask;
858
859/* SIGCHLD action. */
860struct sigaction sigchld_action;
b84876c2 861
7feb7d06
PA
862/* Block child signals (SIGCHLD and linux threads signals), and store
863 the previous mask in PREV_MASK. */
84e46146 864
7feb7d06
PA
865static void
866block_child_signals (sigset_t *prev_mask)
867{
868 /* Make sure SIGCHLD is blocked. */
869 if (!sigismember (&blocked_mask, SIGCHLD))
870 sigaddset (&blocked_mask, SIGCHLD);
871
872 sigprocmask (SIG_BLOCK, &blocked_mask, prev_mask);
873}
874
875/* Restore child signals mask, previously returned by
876 block_child_signals. */
877
878static void
879restore_child_signals_mask (sigset_t *prev_mask)
880{
881 sigprocmask (SIG_SETMASK, prev_mask, NULL);
882}
d6b0e80f
AC
883\f
884
885/* Prototypes for local functions. */
886static int stop_wait_callback (struct lwp_info *lp, void *data);
28439f5e 887static int linux_thread_alive (ptid_t ptid);
6d8fd2b7 888static char *linux_child_pid_to_exec_file (int pid);
710151dd
PA
889static int cancel_breakpoint (struct lwp_info *lp);
890
d6b0e80f
AC
891\f
892/* Convert wait status STATUS to a string. Used for printing debug
893 messages only. */
894
895static char *
896status_to_str (int status)
897{
898 static char buf[64];
899
900 if (WIFSTOPPED (status))
901 snprintf (buf, sizeof (buf), "%s (stopped)",
902 strsignal (WSTOPSIG (status)));
903 else if (WIFSIGNALED (status))
904 snprintf (buf, sizeof (buf), "%s (terminated)",
905 strsignal (WSTOPSIG (status)));
906 else
907 snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
908
909 return buf;
910}
911
912/* Initialize the list of LWPs. Note that this module, contrary to
913 what GDB's generic threads layer does for its thread list,
914 re-initializes the LWP lists whenever we mourn or detach (which
915 doesn't involve mourning) the inferior. */
916
917static void
918init_lwp_list (void)
919{
920 struct lwp_info *lp, *lpnext;
921
922 for (lp = lwp_list; lp; lp = lpnext)
923 {
924 lpnext = lp->next;
925 xfree (lp);
926 }
927
928 lwp_list = NULL;
d90e17a7
PA
929}
930
931/* Remove all LWPs belong to PID from the lwp list. */
932
933static void
934purge_lwp_list (int pid)
935{
936 struct lwp_info *lp, *lpprev, *lpnext;
937
938 lpprev = NULL;
939
940 for (lp = lwp_list; lp; lp = lpnext)
941 {
942 lpnext = lp->next;
943
944 if (ptid_get_pid (lp->ptid) == pid)
945 {
946 if (lp == lwp_list)
947 lwp_list = lp->next;
948 else
949 lpprev->next = lp->next;
950
951 xfree (lp);
952 }
953 else
954 lpprev = lp;
955 }
956}
957
958/* Return the number of known LWPs in the tgid given by PID. */
959
960static int
961num_lwps (int pid)
962{
963 int count = 0;
964 struct lwp_info *lp;
965
966 for (lp = lwp_list; lp; lp = lp->next)
967 if (ptid_get_pid (lp->ptid) == pid)
968 count++;
969
970 return count;
d6b0e80f
AC
971}
972
f973ed9c 973/* Add the LWP specified by PID to the list. Return a pointer to the
9f0bdab8
DJ
974 structure describing the new LWP. The LWP should already be stopped
975 (with an exception for the very first LWP). */
d6b0e80f
AC
976
977static struct lwp_info *
978add_lwp (ptid_t ptid)
979{
980 struct lwp_info *lp;
981
982 gdb_assert (is_lwp (ptid));
983
984 lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
985
986 memset (lp, 0, sizeof (struct lwp_info));
987
988 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
989
990 lp->ptid = ptid;
991
992 lp->next = lwp_list;
993 lwp_list = lp;
d6b0e80f 994
d90e17a7 995 if (num_lwps (GET_PID (ptid)) > 1 && linux_nat_new_thread != NULL)
9f0bdab8
DJ
996 linux_nat_new_thread (ptid);
997
d6b0e80f
AC
998 return lp;
999}
1000
1001/* Remove the LWP specified by PID from the list. */
1002
1003static void
1004delete_lwp (ptid_t ptid)
1005{
1006 struct lwp_info *lp, *lpprev;
1007
1008 lpprev = NULL;
1009
1010 for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
1011 if (ptid_equal (lp->ptid, ptid))
1012 break;
1013
1014 if (!lp)
1015 return;
1016
d6b0e80f
AC
1017 if (lpprev)
1018 lpprev->next = lp->next;
1019 else
1020 lwp_list = lp->next;
1021
1022 xfree (lp);
1023}
1024
1025/* Return a pointer to the structure describing the LWP corresponding
1026 to PID. If no corresponding LWP could be found, return NULL. */
1027
1028static struct lwp_info *
1029find_lwp_pid (ptid_t ptid)
1030{
1031 struct lwp_info *lp;
1032 int lwp;
1033
1034 if (is_lwp (ptid))
1035 lwp = GET_LWP (ptid);
1036 else
1037 lwp = GET_PID (ptid);
1038
1039 for (lp = lwp_list; lp; lp = lp->next)
1040 if (lwp == GET_LWP (lp->ptid))
1041 return lp;
1042
1043 return NULL;
1044}
1045
d90e17a7
PA
1046/* Returns true if PTID matches filter FILTER. FILTER can be the wild
1047 card MINUS_ONE_PTID (all ptid match it); can be a ptid representing
1048 a process (ptid_is_pid returns true), in which case, all lwps of
1049 that give process match, lwps of other process do not; or, it can
1050 represent a specific thread, in which case, only that thread will
1051 match true. PTID must represent an LWP, it can never be a wild
1052 card. */
1053
1054static int
1055ptid_match (ptid_t ptid, ptid_t filter)
1056{
1057 /* Since both parameters have the same type, prevent easy mistakes
1058 from happening. */
1059 gdb_assert (!ptid_equal (ptid, minus_one_ptid)
1060 && !ptid_equal (ptid, null_ptid));
1061
1062 if (ptid_equal (filter, minus_one_ptid))
1063 return 1;
1064 if (ptid_is_pid (filter)
1065 && ptid_get_pid (ptid) == ptid_get_pid (filter))
1066 return 1;
1067 else if (ptid_equal (ptid, filter))
1068 return 1;
1069
1070 return 0;
1071}
1072
d6b0e80f
AC
1073/* Call CALLBACK with its second argument set to DATA for every LWP in
1074 the list. If CALLBACK returns 1 for a particular LWP, return a
1075 pointer to the structure describing that LWP immediately.
1076 Otherwise return NULL. */
1077
1078struct lwp_info *
d90e17a7
PA
1079iterate_over_lwps (ptid_t filter,
1080 int (*callback) (struct lwp_info *, void *),
1081 void *data)
d6b0e80f
AC
1082{
1083 struct lwp_info *lp, *lpnext;
1084
1085 for (lp = lwp_list; lp; lp = lpnext)
1086 {
1087 lpnext = lp->next;
d90e17a7
PA
1088
1089 if (ptid_match (lp->ptid, filter))
1090 {
1091 if ((*callback) (lp, data))
1092 return lp;
1093 }
d6b0e80f
AC
1094 }
1095
1096 return NULL;
1097}
1098
f973ed9c
DJ
1099/* Update our internal state when changing from one fork (checkpoint,
1100 et cetera) to another indicated by NEW_PTID. We can only switch
1101 single-threaded applications, so we only create one new LWP, and
1102 the previous list is discarded. */
1103
1104void
1105linux_nat_switch_fork (ptid_t new_ptid)
1106{
1107 struct lwp_info *lp;
1108
1109 init_lwp_list ();
1110 lp = add_lwp (new_ptid);
1111 lp->stopped = 1;
e26af52f 1112
4f8d22e3
PA
1113 init_thread_list ();
1114 add_thread_silent (new_ptid);
e26af52f
DJ
1115}
1116
e26af52f
DJ
1117/* Handle the exit of a single thread LP. */
1118
1119static void
1120exit_lwp (struct lwp_info *lp)
1121{
063bfe2e
VP
1122 struct thread_info *th = find_thread_pid (lp->ptid);
1123
1124 if (th)
e26af52f 1125 {
17faa917
DJ
1126 if (print_thread_events)
1127 printf_unfiltered (_("[%s exited]\n"), target_pid_to_str (lp->ptid));
1128
4f8d22e3 1129 delete_thread (lp->ptid);
e26af52f
DJ
1130 }
1131
1132 delete_lwp (lp->ptid);
1133}
1134
4d062f1a
PA
1135/* Return an lwp's tgid, found in `/proc/PID/status'. */
1136
1137int
1138linux_proc_get_tgid (int lwpid)
1139{
1140 FILE *status_file;
1141 char buf[100];
1142 int tgid = -1;
1143
1144 snprintf (buf, sizeof (buf), "/proc/%d/status", (int) lwpid);
1145 status_file = fopen (buf, "r");
1146 if (status_file != NULL)
1147 {
1148 while (fgets (buf, sizeof (buf), status_file))
1149 {
1150 if (strncmp (buf, "Tgid:", 5) == 0)
1151 {
1152 tgid = strtoul (buf + strlen ("Tgid:"), NULL, 10);
1153 break;
1154 }
1155 }
1156
1157 fclose (status_file);
1158 }
1159
1160 return tgid;
1161}
1162
a0ef4274
DJ
1163/* Detect `T (stopped)' in `/proc/PID/status'.
1164 Other states including `T (tracing stop)' are reported as false. */
1165
1166static int
1167pid_is_stopped (pid_t pid)
1168{
1169 FILE *status_file;
1170 char buf[100];
1171 int retval = 0;
1172
1173 snprintf (buf, sizeof (buf), "/proc/%d/status", (int) pid);
1174 status_file = fopen (buf, "r");
1175 if (status_file != NULL)
1176 {
1177 int have_state = 0;
1178
1179 while (fgets (buf, sizeof (buf), status_file))
1180 {
1181 if (strncmp (buf, "State:", 6) == 0)
1182 {
1183 have_state = 1;
1184 break;
1185 }
1186 }
1187 if (have_state && strstr (buf, "T (stopped)") != NULL)
1188 retval = 1;
1189 fclose (status_file);
1190 }
1191 return retval;
1192}
1193
1194/* Wait for the LWP specified by LP, which we have just attached to.
1195 Returns a wait status for that LWP, to cache. */
1196
1197static int
1198linux_nat_post_attach_wait (ptid_t ptid, int first, int *cloned,
1199 int *signalled)
1200{
1201 pid_t new_pid, pid = GET_LWP (ptid);
1202 int status;
1203
1204 if (pid_is_stopped (pid))
1205 {
1206 if (debug_linux_nat)
1207 fprintf_unfiltered (gdb_stdlog,
1208 "LNPAW: Attaching to a stopped process\n");
1209
1210 /* The process is definitely stopped. It is in a job control
1211 stop, unless the kernel predates the TASK_STOPPED /
1212 TASK_TRACED distinction, in which case it might be in a
1213 ptrace stop. Make sure it is in a ptrace stop; from there we
1214 can kill it, signal it, et cetera.
1215
1216 First make sure there is a pending SIGSTOP. Since we are
1217 already attached, the process can not transition from stopped
1218 to running without a PTRACE_CONT; so we know this signal will
1219 go into the queue. The SIGSTOP generated by PTRACE_ATTACH is
1220 probably already in the queue (unless this kernel is old
1221 enough to use TASK_STOPPED for ptrace stops); but since SIGSTOP
1222 is not an RT signal, it can only be queued once. */
1223 kill_lwp (pid, SIGSTOP);
1224
1225 /* Finally, resume the stopped process. This will deliver the SIGSTOP
1226 (or a higher priority signal, just like normal PTRACE_ATTACH). */
1227 ptrace (PTRACE_CONT, pid, 0, 0);
1228 }
1229
1230 /* Make sure the initial process is stopped. The user-level threads
1231 layer might want to poke around in the inferior, and that won't
1232 work if things haven't stabilized yet. */
1233 new_pid = my_waitpid (pid, &status, 0);
1234 if (new_pid == -1 && errno == ECHILD)
1235 {
1236 if (first)
1237 warning (_("%s is a cloned process"), target_pid_to_str (ptid));
1238
1239 /* Try again with __WCLONE to check cloned processes. */
1240 new_pid = my_waitpid (pid, &status, __WCLONE);
1241 *cloned = 1;
1242 }
1243
1244 gdb_assert (pid == new_pid && WIFSTOPPED (status));
1245
1246 if (WSTOPSIG (status) != SIGSTOP)
1247 {
1248 *signalled = 1;
1249 if (debug_linux_nat)
1250 fprintf_unfiltered (gdb_stdlog,
1251 "LNPAW: Received %s after attaching\n",
1252 status_to_str (status));
1253 }
1254
1255 return status;
1256}
1257
1258/* Attach to the LWP specified by PID. Return 0 if successful or -1
1259 if the new LWP could not be attached. */
d6b0e80f 1260
9ee57c33 1261int
93815fbf 1262lin_lwp_attach_lwp (ptid_t ptid)
d6b0e80f 1263{
9ee57c33 1264 struct lwp_info *lp;
7feb7d06 1265 sigset_t prev_mask;
d6b0e80f
AC
1266
1267 gdb_assert (is_lwp (ptid));
1268
7feb7d06 1269 block_child_signals (&prev_mask);
d6b0e80f 1270
9ee57c33 1271 lp = find_lwp_pid (ptid);
d6b0e80f
AC
1272
1273 /* We assume that we're already attached to any LWP that has an id
1274 equal to the overall process id, and to any LWP that is already
1275 in our list of LWPs. If we're not seeing exit events from threads
1276 and we've had PID wraparound since we last tried to stop all threads,
1277 this assumption might be wrong; fortunately, this is very unlikely
1278 to happen. */
9ee57c33 1279 if (GET_LWP (ptid) != GET_PID (ptid) && lp == NULL)
d6b0e80f 1280 {
a0ef4274 1281 int status, cloned = 0, signalled = 0;
d6b0e80f
AC
1282
1283 if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
9ee57c33
DJ
1284 {
1285 /* If we fail to attach to the thread, issue a warning,
1286 but continue. One way this can happen is if thread
e9efe249 1287 creation is interrupted; as of Linux kernel 2.6.19, a
9ee57c33
DJ
1288 bug may place threads in the thread list and then fail
1289 to create them. */
1290 warning (_("Can't attach %s: %s"), target_pid_to_str (ptid),
1291 safe_strerror (errno));
7feb7d06 1292 restore_child_signals_mask (&prev_mask);
9ee57c33
DJ
1293 return -1;
1294 }
1295
d6b0e80f
AC
1296 if (debug_linux_nat)
1297 fprintf_unfiltered (gdb_stdlog,
1298 "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
1299 target_pid_to_str (ptid));
1300
a0ef4274
DJ
1301 status = linux_nat_post_attach_wait (ptid, 0, &cloned, &signalled);
1302 lp = add_lwp (ptid);
1303 lp->stopped = 1;
1304 lp->cloned = cloned;
1305 lp->signalled = signalled;
1306 if (WSTOPSIG (status) != SIGSTOP)
d6b0e80f 1307 {
a0ef4274
DJ
1308 lp->resumed = 1;
1309 lp->status = status;
d6b0e80f
AC
1310 }
1311
a0ef4274 1312 target_post_attach (GET_LWP (lp->ptid));
d6b0e80f
AC
1313
1314 if (debug_linux_nat)
1315 {
1316 fprintf_unfiltered (gdb_stdlog,
1317 "LLAL: waitpid %s received %s\n",
1318 target_pid_to_str (ptid),
1319 status_to_str (status));
1320 }
1321 }
1322 else
1323 {
1324 /* We assume that the LWP representing the original process is
1325 already stopped. Mark it as stopped in the data structure
155bd5d1
AC
1326 that the GNU/linux ptrace layer uses to keep track of
1327 threads. Note that this won't have already been done since
1328 the main thread will have, we assume, been stopped by an
1329 attach from a different layer. */
9ee57c33
DJ
1330 if (lp == NULL)
1331 lp = add_lwp (ptid);
d6b0e80f
AC
1332 lp->stopped = 1;
1333 }
9ee57c33 1334
7feb7d06 1335 restore_child_signals_mask (&prev_mask);
9ee57c33 1336 return 0;
d6b0e80f
AC
1337}
1338
b84876c2 1339static void
136d6dae
VP
1340linux_nat_create_inferior (struct target_ops *ops,
1341 char *exec_file, char *allargs, char **env,
b84876c2
PA
1342 int from_tty)
1343{
10568435
JK
1344#ifdef HAVE_PERSONALITY
1345 int personality_orig = 0, personality_set = 0;
1346#endif /* HAVE_PERSONALITY */
b84876c2
PA
1347
1348 /* The fork_child mechanism is synchronous and calls target_wait, so
1349 we have to mask the async mode. */
1350
10568435
JK
1351#ifdef HAVE_PERSONALITY
1352 if (disable_randomization)
1353 {
1354 errno = 0;
1355 personality_orig = personality (0xffffffff);
1356 if (errno == 0 && !(personality_orig & ADDR_NO_RANDOMIZE))
1357 {
1358 personality_set = 1;
1359 personality (personality_orig | ADDR_NO_RANDOMIZE);
1360 }
1361 if (errno != 0 || (personality_set
1362 && !(personality (0xffffffff) & ADDR_NO_RANDOMIZE)))
1363 warning (_("Error disabling address space randomization: %s"),
1364 safe_strerror (errno));
1365 }
1366#endif /* HAVE_PERSONALITY */
1367
136d6dae 1368 linux_ops->to_create_inferior (ops, exec_file, allargs, env, from_tty);
b84876c2 1369
10568435
JK
1370#ifdef HAVE_PERSONALITY
1371 if (personality_set)
1372 {
1373 errno = 0;
1374 personality (personality_orig);
1375 if (errno != 0)
1376 warning (_("Error restoring address space randomization: %s"),
1377 safe_strerror (errno));
1378 }
1379#endif /* HAVE_PERSONALITY */
b84876c2
PA
1380}
1381
d6b0e80f 1382static void
136d6dae 1383linux_nat_attach (struct target_ops *ops, char *args, int from_tty)
d6b0e80f
AC
1384{
1385 struct lwp_info *lp;
d6b0e80f 1386 int status;
af990527 1387 ptid_t ptid;
d6b0e80f 1388
136d6dae 1389 linux_ops->to_attach (ops, args, from_tty);
d6b0e80f 1390
af990527
PA
1391 /* The ptrace base target adds the main thread with (pid,0,0)
1392 format. Decorate it with lwp info. */
1393 ptid = BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid));
1394 thread_change_ptid (inferior_ptid, ptid);
1395
9f0bdab8 1396 /* Add the initial process as the first LWP to the list. */
af990527 1397 lp = add_lwp (ptid);
a0ef4274
DJ
1398
1399 status = linux_nat_post_attach_wait (lp->ptid, 1, &lp->cloned,
1400 &lp->signalled);
1401 lp->stopped = 1;
9f0bdab8 1402
a0ef4274 1403 /* Save the wait status to report later. */
d6b0e80f 1404 lp->resumed = 1;
a0ef4274
DJ
1405 if (debug_linux_nat)
1406 fprintf_unfiltered (gdb_stdlog,
1407 "LNA: waitpid %ld, saving status %s\n",
1408 (long) GET_PID (lp->ptid), status_to_str (status));
710151dd 1409
7feb7d06
PA
1410 lp->status = status;
1411
1412 if (target_can_async_p ())
1413 target_async (inferior_event_handler, 0);
d6b0e80f
AC
1414}
1415
a0ef4274
DJ
1416/* Get pending status of LP. */
1417static int
1418get_pending_status (struct lwp_info *lp, int *status)
1419{
1420 struct target_waitstatus last;
1421 ptid_t last_ptid;
1422
1423 get_last_target_status (&last_ptid, &last);
1424
1425 /* If this lwp is the ptid that GDB is processing an event from, the
7feb7d06
PA
1426 signal will be in stop_signal. Otherwise, we may cache pending
1427 events in lp->status while trying to stop all threads (see
1428 stop_wait_callback). */
a0ef4274
DJ
1429
1430 *status = 0;
4c28f408
PA
1431
1432 if (non_stop)
a0ef4274 1433 {
4c28f408
PA
1434 enum target_signal signo = TARGET_SIGNAL_0;
1435
1436 if (is_executing (lp->ptid))
1437 {
1438 /* If the core thought this lwp was executing --- e.g., the
1439 executing property hasn't been updated yet, but the
1440 thread has been stopped with a stop_callback /
1441 stop_wait_callback sequence (see linux_nat_detach for
1442 example) --- we can only have pending events in the local
1443 queue. */
7feb7d06 1444 signo = target_signal_from_host (WSTOPSIG (lp->status));
4c28f408
PA
1445 }
1446 else
1447 {
1448 /* If the core knows the thread is not executing, then we
1449 have the last signal recorded in
2020b7ab 1450 thread_info->stop_signal. */
4c28f408 1451
2020b7ab
PA
1452 struct thread_info *tp = find_thread_pid (lp->ptid);
1453 signo = tp->stop_signal;
4c28f408
PA
1454 }
1455
1456 if (signo != TARGET_SIGNAL_0
1457 && !signal_pass_state (signo))
1458 {
1459 if (debug_linux_nat)
1460 fprintf_unfiltered (gdb_stdlog, "\
1461GPT: lwp %s had signal %s, but it is in no pass state\n",
1462 target_pid_to_str (lp->ptid),
1463 target_signal_to_string (signo));
1464 }
1465 else
1466 {
1467 if (signo != TARGET_SIGNAL_0)
1468 *status = W_STOPCODE (target_signal_to_host (signo));
1469
1470 if (debug_linux_nat)
1471 fprintf_unfiltered (gdb_stdlog,
1472 "GPT: lwp %s as pending signal %s\n",
1473 target_pid_to_str (lp->ptid),
1474 target_signal_to_string (signo));
1475 }
a0ef4274 1476 }
a0ef4274 1477 else
4c28f408
PA
1478 {
1479 if (GET_LWP (lp->ptid) == GET_LWP (last_ptid))
1480 {
2020b7ab
PA
1481 struct thread_info *tp = find_thread_pid (lp->ptid);
1482 if (tp->stop_signal != TARGET_SIGNAL_0
1483 && signal_pass_state (tp->stop_signal))
1484 *status = W_STOPCODE (target_signal_to_host (tp->stop_signal));
4c28f408 1485 }
4c28f408
PA
1486 else
1487 *status = lp->status;
1488 }
a0ef4274
DJ
1489
1490 return 0;
1491}
1492
d6b0e80f
AC
1493static int
1494detach_callback (struct lwp_info *lp, void *data)
1495{
1496 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1497
1498 if (debug_linux_nat && lp->status)
1499 fprintf_unfiltered (gdb_stdlog, "DC: Pending %s for %s on detach.\n",
1500 strsignal (WSTOPSIG (lp->status)),
1501 target_pid_to_str (lp->ptid));
1502
a0ef4274
DJ
1503 /* If there is a pending SIGSTOP, get rid of it. */
1504 if (lp->signalled)
d6b0e80f 1505 {
d6b0e80f
AC
1506 if (debug_linux_nat)
1507 fprintf_unfiltered (gdb_stdlog,
a0ef4274
DJ
1508 "DC: Sending SIGCONT to %s\n",
1509 target_pid_to_str (lp->ptid));
d6b0e80f 1510
a0ef4274 1511 kill_lwp (GET_LWP (lp->ptid), SIGCONT);
d6b0e80f 1512 lp->signalled = 0;
d6b0e80f
AC
1513 }
1514
1515 /* We don't actually detach from the LWP that has an id equal to the
1516 overall process id just yet. */
1517 if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
1518 {
a0ef4274
DJ
1519 int status = 0;
1520
1521 /* Pass on any pending signal for this LWP. */
1522 get_pending_status (lp, &status);
1523
d6b0e80f
AC
1524 errno = 0;
1525 if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
a0ef4274 1526 WSTOPSIG (status)) < 0)
8a3fe4f8 1527 error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
d6b0e80f
AC
1528 safe_strerror (errno));
1529
1530 if (debug_linux_nat)
1531 fprintf_unfiltered (gdb_stdlog,
1532 "PTRACE_DETACH (%s, %s, 0) (OK)\n",
1533 target_pid_to_str (lp->ptid),
7feb7d06 1534 strsignal (WSTOPSIG (status)));
d6b0e80f
AC
1535
1536 delete_lwp (lp->ptid);
1537 }
1538
1539 return 0;
1540}
1541
1542static void
136d6dae 1543linux_nat_detach (struct target_ops *ops, char *args, int from_tty)
d6b0e80f 1544{
b84876c2 1545 int pid;
a0ef4274
DJ
1546 int status;
1547 enum target_signal sig;
d90e17a7
PA
1548 struct lwp_info *main_lwp;
1549
1550 pid = GET_PID (inferior_ptid);
a0ef4274 1551
b84876c2
PA
1552 if (target_can_async_p ())
1553 linux_nat_async (NULL, 0);
1554
4c28f408
PA
1555 /* Stop all threads before detaching. ptrace requires that the
1556 thread is stopped to sucessfully detach. */
d90e17a7 1557 iterate_over_lwps (pid_to_ptid (pid), stop_callback, NULL);
4c28f408
PA
1558 /* ... and wait until all of them have reported back that
1559 they're no longer running. */
d90e17a7 1560 iterate_over_lwps (pid_to_ptid (pid), stop_wait_callback, NULL);
4c28f408 1561
d90e17a7 1562 iterate_over_lwps (pid_to_ptid (pid), detach_callback, NULL);
d6b0e80f
AC
1563
1564 /* Only the initial process should be left right now. */
d90e17a7
PA
1565 gdb_assert (num_lwps (GET_PID (inferior_ptid)) == 1);
1566
1567 main_lwp = find_lwp_pid (pid_to_ptid (pid));
d6b0e80f 1568
a0ef4274
DJ
1569 /* Pass on any pending signal for the last LWP. */
1570 if ((args == NULL || *args == '\0')
d90e17a7 1571 && get_pending_status (main_lwp, &status) != -1
a0ef4274
DJ
1572 && WIFSTOPPED (status))
1573 {
1574 /* Put the signal number in ARGS so that inf_ptrace_detach will
1575 pass it along with PTRACE_DETACH. */
1576 args = alloca (8);
1577 sprintf (args, "%d", (int) WSTOPSIG (status));
1578 fprintf_unfiltered (gdb_stdlog,
1579 "LND: Sending signal %s to %s\n",
1580 args,
d90e17a7 1581 target_pid_to_str (main_lwp->ptid));
a0ef4274
DJ
1582 }
1583
d90e17a7 1584 delete_lwp (main_lwp->ptid);
b84876c2 1585
7a7d3353
PA
1586 if (forks_exist_p ())
1587 {
1588 /* Multi-fork case. The current inferior_ptid is being detached
1589 from, but there are other viable forks to debug. Detach from
1590 the current fork, and context-switch to the first
1591 available. */
1592 linux_fork_detach (args, from_tty);
1593
1594 if (non_stop && target_can_async_p ())
1595 target_async (inferior_event_handler, 0);
1596 }
1597 else
1598 linux_ops->to_detach (ops, args, from_tty);
d6b0e80f
AC
1599}
1600
1601/* Resume LP. */
1602
1603static int
1604resume_callback (struct lwp_info *lp, void *data)
1605{
1606 if (lp->stopped && lp->status == 0)
1607 {
d90e17a7
PA
1608 if (debug_linux_nat)
1609 fprintf_unfiltered (gdb_stdlog,
1610 "RC: PTRACE_CONT %s, 0, 0 (resuming sibling)\n",
1611 target_pid_to_str (lp->ptid));
1612
28439f5e
PA
1613 linux_ops->to_resume (linux_ops,
1614 pid_to_ptid (GET_LWP (lp->ptid)),
10d6c8cd 1615 0, TARGET_SIGNAL_0);
d6b0e80f
AC
1616 if (debug_linux_nat)
1617 fprintf_unfiltered (gdb_stdlog,
1618 "RC: PTRACE_CONT %s, 0, 0 (resume sibling)\n",
1619 target_pid_to_str (lp->ptid));
1620 lp->stopped = 0;
1621 lp->step = 0;
9f0bdab8 1622 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
d6b0e80f 1623 }
57380f4e
DJ
1624 else if (lp->stopped && debug_linux_nat)
1625 fprintf_unfiltered (gdb_stdlog, "RC: Not resuming sibling %s (has pending)\n",
1626 target_pid_to_str (lp->ptid));
1627 else if (debug_linux_nat)
1628 fprintf_unfiltered (gdb_stdlog, "RC: Not resuming sibling %s (not stopped)\n",
1629 target_pid_to_str (lp->ptid));
d6b0e80f
AC
1630
1631 return 0;
1632}
1633
1634static int
1635resume_clear_callback (struct lwp_info *lp, void *data)
1636{
1637 lp->resumed = 0;
1638 return 0;
1639}
1640
1641static int
1642resume_set_callback (struct lwp_info *lp, void *data)
1643{
1644 lp->resumed = 1;
1645 return 0;
1646}
1647
1648static void
28439f5e
PA
1649linux_nat_resume (struct target_ops *ops,
1650 ptid_t ptid, int step, enum target_signal signo)
d6b0e80f 1651{
7feb7d06 1652 sigset_t prev_mask;
d6b0e80f 1653 struct lwp_info *lp;
d90e17a7 1654 int resume_many;
d6b0e80f 1655
76f50ad1
DJ
1656 if (debug_linux_nat)
1657 fprintf_unfiltered (gdb_stdlog,
1658 "LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
1659 step ? "step" : "resume",
1660 target_pid_to_str (ptid),
1661 signo ? strsignal (signo) : "0",
1662 target_pid_to_str (inferior_ptid));
1663
7feb7d06 1664 block_child_signals (&prev_mask);
b84876c2 1665
d6b0e80f 1666 /* A specific PTID means `step only this process id'. */
d90e17a7
PA
1667 resume_many = (ptid_equal (minus_one_ptid, ptid)
1668 || ptid_is_pid (ptid));
4c28f408
PA
1669
1670 if (!non_stop)
1671 {
d90e17a7
PA
1672 /* Mark the lwps we're resuming as resumed. */
1673 iterate_over_lwps (minus_one_ptid, resume_clear_callback, NULL);
1674 iterate_over_lwps (ptid, resume_set_callback, NULL);
4c28f408 1675 }
d90e17a7
PA
1676 else
1677 iterate_over_lwps (minus_one_ptid, resume_set_callback, NULL);
d6b0e80f 1678
d90e17a7
PA
1679 /* See if it's the current inferior that should be handled
1680 specially. */
1681 if (resume_many)
1682 lp = find_lwp_pid (inferior_ptid);
1683 else
1684 lp = find_lwp_pid (ptid);
9f0bdab8 1685 gdb_assert (lp != NULL);
d6b0e80f 1686
9f0bdab8
DJ
1687 /* Remember if we're stepping. */
1688 lp->step = step;
d6b0e80f 1689
9f0bdab8
DJ
1690 /* If we have a pending wait status for this thread, there is no
1691 point in resuming the process. But first make sure that
1692 linux_nat_wait won't preemptively handle the event - we
1693 should never take this short-circuit if we are going to
1694 leave LP running, since we have skipped resuming all the
1695 other threads. This bit of code needs to be synchronized
1696 with linux_nat_wait. */
76f50ad1 1697
9f0bdab8
DJ
1698 if (lp->status && WIFSTOPPED (lp->status))
1699 {
d6b48e9c
PA
1700 int saved_signo;
1701 struct inferior *inf;
76f50ad1 1702
d90e17a7 1703 inf = find_inferior_pid (ptid_get_pid (lp->ptid));
d6b48e9c
PA
1704 gdb_assert (inf);
1705 saved_signo = target_signal_from_host (WSTOPSIG (lp->status));
1706
1707 /* Defer to common code if we're gaining control of the
1708 inferior. */
1709 if (inf->stop_soon == NO_STOP_QUIETLY
1710 && signal_stop_state (saved_signo) == 0
9f0bdab8
DJ
1711 && signal_print_state (saved_signo) == 0
1712 && signal_pass_state (saved_signo) == 1)
d6b0e80f 1713 {
9f0bdab8
DJ
1714 if (debug_linux_nat)
1715 fprintf_unfiltered (gdb_stdlog,
1716 "LLR: Not short circuiting for ignored "
1717 "status 0x%x\n", lp->status);
1718
d6b0e80f
AC
1719 /* FIXME: What should we do if we are supposed to continue
1720 this thread with a signal? */
1721 gdb_assert (signo == TARGET_SIGNAL_0);
9f0bdab8
DJ
1722 signo = saved_signo;
1723 lp->status = 0;
1724 }
1725 }
76f50ad1 1726
9f0bdab8
DJ
1727 if (lp->status)
1728 {
1729 /* FIXME: What should we do if we are supposed to continue
1730 this thread with a signal? */
1731 gdb_assert (signo == TARGET_SIGNAL_0);
76f50ad1 1732
9f0bdab8
DJ
1733 if (debug_linux_nat)
1734 fprintf_unfiltered (gdb_stdlog,
1735 "LLR: Short circuiting for status 0x%x\n",
1736 lp->status);
d6b0e80f 1737
7feb7d06
PA
1738 restore_child_signals_mask (&prev_mask);
1739 if (target_can_async_p ())
1740 {
1741 target_async (inferior_event_handler, 0);
1742 /* Tell the event loop we have something to process. */
1743 async_file_mark ();
1744 }
9f0bdab8 1745 return;
d6b0e80f
AC
1746 }
1747
9f0bdab8
DJ
1748 /* Mark LWP as not stopped to prevent it from being continued by
1749 resume_callback. */
1750 lp->stopped = 0;
1751
d90e17a7
PA
1752 if (resume_many)
1753 iterate_over_lwps (ptid, resume_callback, NULL);
1754
1755 /* Convert to something the lower layer understands. */
1756 ptid = pid_to_ptid (GET_LWP (lp->ptid));
d6b0e80f 1757
28439f5e 1758 linux_ops->to_resume (linux_ops, ptid, step, signo);
9f0bdab8
DJ
1759 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1760
d6b0e80f
AC
1761 if (debug_linux_nat)
1762 fprintf_unfiltered (gdb_stdlog,
1763 "LLR: %s %s, %s (resume event thread)\n",
1764 step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1765 target_pid_to_str (ptid),
1766 signo ? strsignal (signo) : "0");
b84876c2 1767
7feb7d06 1768 restore_child_signals_mask (&prev_mask);
b84876c2 1769 if (target_can_async_p ())
8ea051c5 1770 target_async (inferior_event_handler, 0);
d6b0e80f
AC
1771}
1772
1773/* Issue kill to specified lwp. */
1774
1775static int tkill_failed;
1776
1777static int
1778kill_lwp (int lwpid, int signo)
1779{
1780 errno = 0;
1781
1782/* Use tkill, if possible, in case we are using nptl threads. If tkill
1783 fails, then we are not using nptl threads and we should be using kill. */
1784
1785#ifdef HAVE_TKILL_SYSCALL
1786 if (!tkill_failed)
1787 {
1788 int ret = syscall (__NR_tkill, lwpid, signo);
1789 if (errno != ENOSYS)
1790 return ret;
1791 errno = 0;
1792 tkill_failed = 1;
1793 }
1794#endif
1795
1796 return kill (lwpid, signo);
1797}
1798
3d799a95
DJ
1799/* Handle a GNU/Linux extended wait response. If we see a clone
1800 event, we need to add the new LWP to our list (and not report the
1801 trap to higher layers). This function returns non-zero if the
1802 event should be ignored and we should wait again. If STOPPING is
1803 true, the new LWP remains stopped, otherwise it is continued. */
d6b0e80f
AC
1804
1805static int
3d799a95
DJ
1806linux_handle_extended_wait (struct lwp_info *lp, int status,
1807 int stopping)
d6b0e80f 1808{
3d799a95
DJ
1809 int pid = GET_LWP (lp->ptid);
1810 struct target_waitstatus *ourstatus = &lp->waitstatus;
1811 struct lwp_info *new_lp = NULL;
1812 int event = status >> 16;
d6b0e80f 1813
3d799a95
DJ
1814 if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
1815 || event == PTRACE_EVENT_CLONE)
d6b0e80f 1816 {
3d799a95
DJ
1817 unsigned long new_pid;
1818 int ret;
1819
1820 ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
6fc19103 1821
3d799a95
DJ
1822 /* If we haven't already seen the new PID stop, wait for it now. */
1823 if (! pull_pid_from_list (&stopped_pids, new_pid, &status))
1824 {
1825 /* The new child has a pending SIGSTOP. We can't affect it until it
1826 hits the SIGSTOP, but we're already attached. */
1827 ret = my_waitpid (new_pid, &status,
1828 (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
1829 if (ret == -1)
1830 perror_with_name (_("waiting for new child"));
1831 else if (ret != new_pid)
1832 internal_error (__FILE__, __LINE__,
1833 _("wait returned unexpected PID %d"), ret);
1834 else if (!WIFSTOPPED (status))
1835 internal_error (__FILE__, __LINE__,
1836 _("wait returned unexpected status 0x%x"), status);
1837 }
1838
3a3e9ee3 1839 ourstatus->value.related_pid = ptid_build (new_pid, new_pid, 0);
3d799a95
DJ
1840
1841 if (event == PTRACE_EVENT_FORK)
1842 ourstatus->kind = TARGET_WAITKIND_FORKED;
1843 else if (event == PTRACE_EVENT_VFORK)
1844 ourstatus->kind = TARGET_WAITKIND_VFORKED;
6fc19103 1845 else
3d799a95 1846 {
4c28f408
PA
1847 struct cleanup *old_chain;
1848
3d799a95 1849 ourstatus->kind = TARGET_WAITKIND_IGNORE;
d90e17a7 1850 new_lp = add_lwp (BUILD_LWP (new_pid, GET_PID (lp->ptid)));
3d799a95 1851 new_lp->cloned = 1;
4c28f408 1852 new_lp->stopped = 1;
d6b0e80f 1853
3d799a95
DJ
1854 if (WSTOPSIG (status) != SIGSTOP)
1855 {
1856 /* This can happen if someone starts sending signals to
1857 the new thread before it gets a chance to run, which
1858 have a lower number than SIGSTOP (e.g. SIGUSR1).
1859 This is an unlikely case, and harder to handle for
1860 fork / vfork than for clone, so we do not try - but
1861 we handle it for clone events here. We'll send
1862 the other signal on to the thread below. */
1863
1864 new_lp->signalled = 1;
1865 }
1866 else
1867 status = 0;
d6b0e80f 1868
4c28f408 1869 if (non_stop)
3d799a95 1870 {
4c28f408
PA
1871 /* Add the new thread to GDB's lists as soon as possible
1872 so that:
1873
1874 1) the frontend doesn't have to wait for a stop to
1875 display them, and,
1876
1877 2) we tag it with the correct running state. */
1878
1879 /* If the thread_db layer is active, let it know about
1880 this new thread, and add it to GDB's list. */
1881 if (!thread_db_attach_lwp (new_lp->ptid))
1882 {
1883 /* We're not using thread_db. Add it to GDB's
1884 list. */
1885 target_post_attach (GET_LWP (new_lp->ptid));
1886 add_thread (new_lp->ptid);
1887 }
1888
1889 if (!stopping)
1890 {
1891 set_running (new_lp->ptid, 1);
1892 set_executing (new_lp->ptid, 1);
1893 }
1894 }
1895
1896 if (!stopping)
1897 {
1898 new_lp->stopped = 0;
3d799a95 1899 new_lp->resumed = 1;
4c28f408 1900 ptrace (PTRACE_CONT, new_pid, 0,
3d799a95
DJ
1901 status ? WSTOPSIG (status) : 0);
1902 }
d6b0e80f 1903
3d799a95
DJ
1904 if (debug_linux_nat)
1905 fprintf_unfiltered (gdb_stdlog,
1906 "LHEW: Got clone event from LWP %ld, resuming\n",
1907 GET_LWP (lp->ptid));
1908 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1909
1910 return 1;
1911 }
1912
1913 return 0;
d6b0e80f
AC
1914 }
1915
3d799a95
DJ
1916 if (event == PTRACE_EVENT_EXEC)
1917 {
1918 ourstatus->kind = TARGET_WAITKIND_EXECD;
1919 ourstatus->value.execd_pathname
6d8fd2b7 1920 = xstrdup (linux_child_pid_to_exec_file (pid));
3d799a95
DJ
1921
1922 if (linux_parent_pid)
1923 {
1924 detach_breakpoints (linux_parent_pid);
1925 ptrace (PTRACE_DETACH, linux_parent_pid, 0, 0);
1926
1927 linux_parent_pid = 0;
1928 }
1929
25b22b0a
PA
1930 /* At this point, all inserted breakpoints are gone. Doing this
1931 as soon as we detect an exec prevents the badness of deleting
1932 a breakpoint writing the current "shadow contents" to lift
1933 the bp. That shadow is NOT valid after an exec.
1934
1935 Note that we have to do this after the detach_breakpoints
1936 call above, otherwise breakpoints wouldn't be lifted from the
1937 parent on a vfork, because detach_breakpoints would think
1938 that breakpoints are not inserted. */
1939 mark_breakpoints_out ();
3d799a95
DJ
1940 return 0;
1941 }
1942
1943 internal_error (__FILE__, __LINE__,
1944 _("unknown ptrace event %d"), event);
d6b0e80f
AC
1945}
1946
1947/* Wait for LP to stop. Returns the wait status, or 0 if the LWP has
1948 exited. */
1949
1950static int
1951wait_lwp (struct lwp_info *lp)
1952{
1953 pid_t pid;
1954 int status;
1955 int thread_dead = 0;
1956
1957 gdb_assert (!lp->stopped);
1958 gdb_assert (lp->status == 0);
1959
58aecb61 1960 pid = my_waitpid (GET_LWP (lp->ptid), &status, 0);
d6b0e80f
AC
1961 if (pid == -1 && errno == ECHILD)
1962 {
58aecb61 1963 pid = my_waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
d6b0e80f
AC
1964 if (pid == -1 && errno == ECHILD)
1965 {
1966 /* The thread has previously exited. We need to delete it
1967 now because, for some vendor 2.4 kernels with NPTL
1968 support backported, there won't be an exit event unless
1969 it is the main thread. 2.6 kernels will report an exit
1970 event for each thread that exits, as expected. */
1971 thread_dead = 1;
1972 if (debug_linux_nat)
1973 fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
1974 target_pid_to_str (lp->ptid));
1975 }
1976 }
1977
1978 if (!thread_dead)
1979 {
1980 gdb_assert (pid == GET_LWP (lp->ptid));
1981
1982 if (debug_linux_nat)
1983 {
1984 fprintf_unfiltered (gdb_stdlog,
1985 "WL: waitpid %s received %s\n",
1986 target_pid_to_str (lp->ptid),
1987 status_to_str (status));
1988 }
1989 }
1990
1991 /* Check if the thread has exited. */
1992 if (WIFEXITED (status) || WIFSIGNALED (status))
1993 {
1994 thread_dead = 1;
1995 if (debug_linux_nat)
1996 fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
1997 target_pid_to_str (lp->ptid));
1998 }
1999
2000 if (thread_dead)
2001 {
e26af52f 2002 exit_lwp (lp);
d6b0e80f
AC
2003 return 0;
2004 }
2005
2006 gdb_assert (WIFSTOPPED (status));
2007
2008 /* Handle GNU/Linux's extended waitstatus for trace events. */
2009 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2010 {
2011 if (debug_linux_nat)
2012 fprintf_unfiltered (gdb_stdlog,
2013 "WL: Handling extended status 0x%06x\n",
2014 status);
3d799a95 2015 if (linux_handle_extended_wait (lp, status, 1))
d6b0e80f
AC
2016 return wait_lwp (lp);
2017 }
2018
2019 return status;
2020}
2021
9f0bdab8
DJ
2022/* Save the most recent siginfo for LP. This is currently only called
2023 for SIGTRAP; some ports use the si_addr field for
2024 target_stopped_data_address. In the future, it may also be used to
2025 restore the siginfo of requeued signals. */
2026
2027static void
2028save_siginfo (struct lwp_info *lp)
2029{
2030 errno = 0;
2031 ptrace (PTRACE_GETSIGINFO, GET_LWP (lp->ptid),
2032 (PTRACE_TYPE_ARG3) 0, &lp->siginfo);
2033
2034 if (errno != 0)
2035 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
2036}
2037
d6b0e80f
AC
2038/* Send a SIGSTOP to LP. */
2039
2040static int
2041stop_callback (struct lwp_info *lp, void *data)
2042{
2043 if (!lp->stopped && !lp->signalled)
2044 {
2045 int ret;
2046
2047 if (debug_linux_nat)
2048 {
2049 fprintf_unfiltered (gdb_stdlog,
2050 "SC: kill %s **<SIGSTOP>**\n",
2051 target_pid_to_str (lp->ptid));
2052 }
2053 errno = 0;
2054 ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
2055 if (debug_linux_nat)
2056 {
2057 fprintf_unfiltered (gdb_stdlog,
2058 "SC: lwp kill %d %s\n",
2059 ret,
2060 errno ? safe_strerror (errno) : "ERRNO-OK");
2061 }
2062
2063 lp->signalled = 1;
2064 gdb_assert (lp->status == 0);
2065 }
2066
2067 return 0;
2068}
2069
57380f4e 2070/* Return non-zero if LWP PID has a pending SIGINT. */
d6b0e80f
AC
2071
2072static int
57380f4e
DJ
2073linux_nat_has_pending_sigint (int pid)
2074{
2075 sigset_t pending, blocked, ignored;
2076 int i;
2077
2078 linux_proc_pending_signals (pid, &pending, &blocked, &ignored);
2079
2080 if (sigismember (&pending, SIGINT)
2081 && !sigismember (&ignored, SIGINT))
2082 return 1;
2083
2084 return 0;
2085}
2086
2087/* Set a flag in LP indicating that we should ignore its next SIGINT. */
2088
2089static int
2090set_ignore_sigint (struct lwp_info *lp, void *data)
d6b0e80f 2091{
57380f4e
DJ
2092 /* If a thread has a pending SIGINT, consume it; otherwise, set a
2093 flag to consume the next one. */
2094 if (lp->stopped && lp->status != 0 && WIFSTOPPED (lp->status)
2095 && WSTOPSIG (lp->status) == SIGINT)
2096 lp->status = 0;
2097 else
2098 lp->ignore_sigint = 1;
2099
2100 return 0;
2101}
2102
2103/* If LP does not have a SIGINT pending, then clear the ignore_sigint flag.
2104 This function is called after we know the LWP has stopped; if the LWP
2105 stopped before the expected SIGINT was delivered, then it will never have
2106 arrived. Also, if the signal was delivered to a shared queue and consumed
2107 by a different thread, it will never be delivered to this LWP. */
d6b0e80f 2108
57380f4e
DJ
2109static void
2110maybe_clear_ignore_sigint (struct lwp_info *lp)
2111{
2112 if (!lp->ignore_sigint)
2113 return;
2114
2115 if (!linux_nat_has_pending_sigint (GET_LWP (lp->ptid)))
2116 {
2117 if (debug_linux_nat)
2118 fprintf_unfiltered (gdb_stdlog,
2119 "MCIS: Clearing bogus flag for %s\n",
2120 target_pid_to_str (lp->ptid));
2121 lp->ignore_sigint = 0;
2122 }
2123}
2124
2125/* Wait until LP is stopped. */
2126
2127static int
2128stop_wait_callback (struct lwp_info *lp, void *data)
2129{
d6b0e80f
AC
2130 if (!lp->stopped)
2131 {
2132 int status;
2133
2134 status = wait_lwp (lp);
2135 if (status == 0)
2136 return 0;
2137
57380f4e
DJ
2138 if (lp->ignore_sigint && WIFSTOPPED (status)
2139 && WSTOPSIG (status) == SIGINT)
d6b0e80f 2140 {
57380f4e 2141 lp->ignore_sigint = 0;
d6b0e80f
AC
2142
2143 errno = 0;
2144 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2145 if (debug_linux_nat)
2146 fprintf_unfiltered (gdb_stdlog,
57380f4e 2147 "PTRACE_CONT %s, 0, 0 (%s) (discarding SIGINT)\n",
d6b0e80f
AC
2148 target_pid_to_str (lp->ptid),
2149 errno ? safe_strerror (errno) : "OK");
2150
57380f4e 2151 return stop_wait_callback (lp, NULL);
d6b0e80f
AC
2152 }
2153
57380f4e
DJ
2154 maybe_clear_ignore_sigint (lp);
2155
d6b0e80f
AC
2156 if (WSTOPSIG (status) != SIGSTOP)
2157 {
2158 if (WSTOPSIG (status) == SIGTRAP)
2159 {
2160 /* If a LWP other than the LWP that we're reporting an
2161 event for has hit a GDB breakpoint (as opposed to
2162 some random trap signal), then just arrange for it to
2163 hit it again later. We don't keep the SIGTRAP status
2164 and don't forward the SIGTRAP signal to the LWP. We
2165 will handle the current event, eventually we will
2166 resume all LWPs, and this one will get its breakpoint
2167 trap again.
2168
2169 If we do not do this, then we run the risk that the
2170 user will delete or disable the breakpoint, but the
2171 thread will have already tripped on it. */
2172
9f0bdab8
DJ
2173 /* Save the trap's siginfo in case we need it later. */
2174 save_siginfo (lp);
2175
d6b0e80f
AC
2176 /* Now resume this LWP and get the SIGSTOP event. */
2177 errno = 0;
2178 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2179 if (debug_linux_nat)
2180 {
2181 fprintf_unfiltered (gdb_stdlog,
2182 "PTRACE_CONT %s, 0, 0 (%s)\n",
2183 target_pid_to_str (lp->ptid),
2184 errno ? safe_strerror (errno) : "OK");
2185
2186 fprintf_unfiltered (gdb_stdlog,
2187 "SWC: Candidate SIGTRAP event in %s\n",
2188 target_pid_to_str (lp->ptid));
2189 }
710151dd
PA
2190 /* Hold this event/waitstatus while we check to see if
2191 there are any more (we still want to get that SIGSTOP). */
57380f4e 2192 stop_wait_callback (lp, NULL);
710151dd 2193
7feb7d06
PA
2194 /* Hold the SIGTRAP for handling by linux_nat_wait. If
2195 there's another event, throw it back into the
2196 queue. */
2197 if (lp->status)
710151dd 2198 {
7feb7d06
PA
2199 if (debug_linux_nat)
2200 fprintf_unfiltered (gdb_stdlog,
2201 "SWC: kill %s, %s\n",
2202 target_pid_to_str (lp->ptid),
2203 status_to_str ((int) status));
2204 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
d6b0e80f 2205 }
7feb7d06
PA
2206
2207 /* Save the sigtrap event. */
2208 lp->status = status;
d6b0e80f
AC
2209 return 0;
2210 }
2211 else
2212 {
2213 /* The thread was stopped with a signal other than
2214 SIGSTOP, and didn't accidentally trip a breakpoint. */
2215
2216 if (debug_linux_nat)
2217 {
2218 fprintf_unfiltered (gdb_stdlog,
2219 "SWC: Pending event %s in %s\n",
2220 status_to_str ((int) status),
2221 target_pid_to_str (lp->ptid));
2222 }
2223 /* Now resume this LWP and get the SIGSTOP event. */
2224 errno = 0;
2225 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2226 if (debug_linux_nat)
2227 fprintf_unfiltered (gdb_stdlog,
2228 "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
2229 target_pid_to_str (lp->ptid),
2230 errno ? safe_strerror (errno) : "OK");
2231
2232 /* Hold this event/waitstatus while we check to see if
2233 there are any more (we still want to get that SIGSTOP). */
57380f4e 2234 stop_wait_callback (lp, NULL);
710151dd
PA
2235
2236 /* If the lp->status field is still empty, use it to
2237 hold this event. If not, then this event must be
2238 returned to the event queue of the LWP. */
7feb7d06 2239 if (lp->status)
d6b0e80f
AC
2240 {
2241 if (debug_linux_nat)
2242 {
2243 fprintf_unfiltered (gdb_stdlog,
2244 "SWC: kill %s, %s\n",
2245 target_pid_to_str (lp->ptid),
2246 status_to_str ((int) status));
2247 }
2248 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
2249 }
710151dd
PA
2250 else
2251 lp->status = status;
d6b0e80f
AC
2252 return 0;
2253 }
2254 }
2255 else
2256 {
2257 /* We caught the SIGSTOP that we intended to catch, so
2258 there's no SIGSTOP pending. */
2259 lp->stopped = 1;
2260 lp->signalled = 0;
2261 }
2262 }
2263
2264 return 0;
2265}
2266
d6b0e80f
AC
2267/* Return non-zero if LP has a wait status pending. */
2268
2269static int
2270status_callback (struct lwp_info *lp, void *data)
2271{
2272 /* Only report a pending wait status if we pretend that this has
2273 indeed been resumed. */
d90e17a7
PA
2274 /* We check for lp->waitstatus in addition to lp->status, because we
2275 can have pending process exits recorded in lp->waitstatus, and
2276 W_EXITCODE(0,0) == 0. */
2277 return ((lp->status != 0
2278 || lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
2279 && lp->resumed);
d6b0e80f
AC
2280}
2281
2282/* Return non-zero if LP isn't stopped. */
2283
2284static int
2285running_callback (struct lwp_info *lp, void *data)
2286{
2287 return (lp->stopped == 0 || (lp->status != 0 && lp->resumed));
2288}
2289
2290/* Count the LWP's that have had events. */
2291
2292static int
2293count_events_callback (struct lwp_info *lp, void *data)
2294{
2295 int *count = data;
2296
2297 gdb_assert (count != NULL);
2298
e09490f1
DJ
2299 /* Count only resumed LWPs that have a SIGTRAP event pending. */
2300 if (lp->status != 0 && lp->resumed
d6b0e80f
AC
2301 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2302 (*count)++;
2303
2304 return 0;
2305}
2306
2307/* Select the LWP (if any) that is currently being single-stepped. */
2308
2309static int
2310select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
2311{
2312 if (lp->step && lp->status != 0)
2313 return 1;
2314 else
2315 return 0;
2316}
2317
2318/* Select the Nth LWP that has had a SIGTRAP event. */
2319
2320static int
2321select_event_lwp_callback (struct lwp_info *lp, void *data)
2322{
2323 int *selector = data;
2324
2325 gdb_assert (selector != NULL);
2326
e09490f1
DJ
2327 /* Select only resumed LWPs that have a SIGTRAP event pending. */
2328 if (lp->status != 0 && lp->resumed
d6b0e80f
AC
2329 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2330 if ((*selector)-- == 0)
2331 return 1;
2332
2333 return 0;
2334}
2335
710151dd
PA
2336static int
2337cancel_breakpoint (struct lwp_info *lp)
2338{
2339 /* Arrange for a breakpoint to be hit again later. We don't keep
2340 the SIGTRAP status and don't forward the SIGTRAP signal to the
2341 LWP. We will handle the current event, eventually we will resume
2342 this LWP, and this breakpoint will trap again.
2343
2344 If we do not do this, then we run the risk that the user will
2345 delete or disable the breakpoint, but the LWP will have already
2346 tripped on it. */
2347
515630c5
UW
2348 struct regcache *regcache = get_thread_regcache (lp->ptid);
2349 struct gdbarch *gdbarch = get_regcache_arch (regcache);
2350 CORE_ADDR pc;
2351
2352 pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
2353 if (breakpoint_inserted_here_p (pc))
710151dd
PA
2354 {
2355 if (debug_linux_nat)
2356 fprintf_unfiltered (gdb_stdlog,
2357 "CB: Push back breakpoint for %s\n",
2358 target_pid_to_str (lp->ptid));
2359
2360 /* Back up the PC if necessary. */
515630c5
UW
2361 if (gdbarch_decr_pc_after_break (gdbarch))
2362 regcache_write_pc (regcache, pc);
2363
710151dd
PA
2364 return 1;
2365 }
2366 return 0;
2367}
2368
d6b0e80f
AC
2369static int
2370cancel_breakpoints_callback (struct lwp_info *lp, void *data)
2371{
2372 struct lwp_info *event_lp = data;
2373
2374 /* Leave the LWP that has been elected to receive a SIGTRAP alone. */
2375 if (lp == event_lp)
2376 return 0;
2377
2378 /* If a LWP other than the LWP that we're reporting an event for has
2379 hit a GDB breakpoint (as opposed to some random trap signal),
2380 then just arrange for it to hit it again later. We don't keep
2381 the SIGTRAP status and don't forward the SIGTRAP signal to the
2382 LWP. We will handle the current event, eventually we will resume
2383 all LWPs, and this one will get its breakpoint trap again.
2384
2385 If we do not do this, then we run the risk that the user will
2386 delete or disable the breakpoint, but the LWP will have already
2387 tripped on it. */
2388
2389 if (lp->status != 0
2390 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
710151dd
PA
2391 && cancel_breakpoint (lp))
2392 /* Throw away the SIGTRAP. */
2393 lp->status = 0;
d6b0e80f
AC
2394
2395 return 0;
2396}
2397
2398/* Select one LWP out of those that have events pending. */
2399
2400static void
d90e17a7 2401select_event_lwp (ptid_t filter, struct lwp_info **orig_lp, int *status)
d6b0e80f
AC
2402{
2403 int num_events = 0;
2404 int random_selector;
2405 struct lwp_info *event_lp;
2406
ac264b3b 2407 /* Record the wait status for the original LWP. */
d6b0e80f
AC
2408 (*orig_lp)->status = *status;
2409
2410 /* Give preference to any LWP that is being single-stepped. */
d90e17a7
PA
2411 event_lp = iterate_over_lwps (filter,
2412 select_singlestep_lwp_callback, NULL);
d6b0e80f
AC
2413 if (event_lp != NULL)
2414 {
2415 if (debug_linux_nat)
2416 fprintf_unfiltered (gdb_stdlog,
2417 "SEL: Select single-step %s\n",
2418 target_pid_to_str (event_lp->ptid));
2419 }
2420 else
2421 {
2422 /* No single-stepping LWP. Select one at random, out of those
2423 which have had SIGTRAP events. */
2424
2425 /* First see how many SIGTRAP events we have. */
d90e17a7 2426 iterate_over_lwps (filter, count_events_callback, &num_events);
d6b0e80f
AC
2427
2428 /* Now randomly pick a LWP out of those that have had a SIGTRAP. */
2429 random_selector = (int)
2430 ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
2431
2432 if (debug_linux_nat && num_events > 1)
2433 fprintf_unfiltered (gdb_stdlog,
2434 "SEL: Found %d SIGTRAP events, selecting #%d\n",
2435 num_events, random_selector);
2436
d90e17a7
PA
2437 event_lp = iterate_over_lwps (filter,
2438 select_event_lwp_callback,
d6b0e80f
AC
2439 &random_selector);
2440 }
2441
2442 if (event_lp != NULL)
2443 {
2444 /* Switch the event LWP. */
2445 *orig_lp = event_lp;
2446 *status = event_lp->status;
2447 }
2448
2449 /* Flush the wait status for the event LWP. */
2450 (*orig_lp)->status = 0;
2451}
2452
2453/* Return non-zero if LP has been resumed. */
2454
2455static int
2456resumed_callback (struct lwp_info *lp, void *data)
2457{
2458 return lp->resumed;
2459}
2460
d6b0e80f
AC
2461/* Stop an active thread, verify it still exists, then resume it. */
2462
2463static int
2464stop_and_resume_callback (struct lwp_info *lp, void *data)
2465{
2466 struct lwp_info *ptr;
2467
2468 if (!lp->stopped && !lp->signalled)
2469 {
2470 stop_callback (lp, NULL);
2471 stop_wait_callback (lp, NULL);
2472 /* Resume if the lwp still exists. */
2473 for (ptr = lwp_list; ptr; ptr = ptr->next)
2474 if (lp == ptr)
2475 {
2476 resume_callback (lp, NULL);
2477 resume_set_callback (lp, NULL);
2478 }
2479 }
2480 return 0;
2481}
2482
02f3fc28 2483/* Check if we should go on and pass this event to common code.
fa2c6a57 2484 Return the affected lwp if we are, or NULL otherwise. */
02f3fc28
PA
2485static struct lwp_info *
2486linux_nat_filter_event (int lwpid, int status, int options)
2487{
2488 struct lwp_info *lp;
2489
2490 lp = find_lwp_pid (pid_to_ptid (lwpid));
2491
2492 /* Check for stop events reported by a process we didn't already
2493 know about - anything not already in our LWP list.
2494
2495 If we're expecting to receive stopped processes after
2496 fork, vfork, and clone events, then we'll just add the
2497 new one to our list and go back to waiting for the event
2498 to be reported - the stopped process might be returned
2499 from waitpid before or after the event is. */
2500 if (WIFSTOPPED (status) && !lp)
2501 {
2502 linux_record_stopped_pid (lwpid, status);
2503 return NULL;
2504 }
2505
2506 /* Make sure we don't report an event for the exit of an LWP not in
2507 our list, i.e. not part of the current process. This can happen
2508 if we detach from a program we original forked and then it
2509 exits. */
2510 if (!WIFSTOPPED (status) && !lp)
2511 return NULL;
2512
2513 /* NOTE drow/2003-06-17: This code seems to be meant for debugging
2514 CLONE_PTRACE processes which do not use the thread library -
2515 otherwise we wouldn't find the new LWP this way. That doesn't
2516 currently work, and the following code is currently unreachable
2517 due to the two blocks above. If it's fixed some day, this code
2518 should be broken out into a function so that we can also pick up
2519 LWPs from the new interface. */
2520 if (!lp)
2521 {
2522 lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
2523 if (options & __WCLONE)
2524 lp->cloned = 1;
2525
2526 gdb_assert (WIFSTOPPED (status)
2527 && WSTOPSIG (status) == SIGSTOP);
2528 lp->signalled = 1;
2529
2530 if (!in_thread_list (inferior_ptid))
2531 {
2532 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
2533 GET_PID (inferior_ptid));
2534 add_thread (inferior_ptid);
2535 }
2536
2537 add_thread (lp->ptid);
2538 }
2539
2540 /* Save the trap's siginfo in case we need it later. */
2541 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2542 save_siginfo (lp);
2543
2544 /* Handle GNU/Linux's extended waitstatus for trace events. */
2545 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2546 {
2547 if (debug_linux_nat)
2548 fprintf_unfiltered (gdb_stdlog,
2549 "LLW: Handling extended status 0x%06x\n",
2550 status);
2551 if (linux_handle_extended_wait (lp, status, 0))
2552 return NULL;
2553 }
2554
2555 /* Check if the thread has exited. */
d90e17a7
PA
2556 if ((WIFEXITED (status) || WIFSIGNALED (status))
2557 && num_lwps (GET_PID (lp->ptid)) > 1)
02f3fc28 2558 {
9db03742
JB
2559 /* If this is the main thread, we must stop all threads and verify
2560 if they are still alive. This is because in the nptl thread model
2561 on Linux 2.4, there is no signal issued for exiting LWPs
02f3fc28
PA
2562 other than the main thread. We only get the main thread exit
2563 signal once all child threads have already exited. If we
2564 stop all the threads and use the stop_wait_callback to check
2565 if they have exited we can determine whether this signal
2566 should be ignored or whether it means the end of the debugged
2567 application, regardless of which threading model is being
5d3b6af6 2568 used. */
02f3fc28
PA
2569 if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
2570 {
2571 lp->stopped = 1;
d90e17a7
PA
2572 iterate_over_lwps (pid_to_ptid (GET_PID (lp->ptid)),
2573 stop_and_resume_callback, NULL);
02f3fc28
PA
2574 }
2575
2576 if (debug_linux_nat)
2577 fprintf_unfiltered (gdb_stdlog,
2578 "LLW: %s exited.\n",
2579 target_pid_to_str (lp->ptid));
2580
d90e17a7 2581 if (num_lwps (GET_PID (lp->ptid)) > 1)
9db03742
JB
2582 {
2583 /* If there is at least one more LWP, then the exit signal
2584 was not the end of the debugged application and should be
2585 ignored. */
2586 exit_lwp (lp);
2587 return NULL;
2588 }
02f3fc28
PA
2589 }
2590
2591 /* Check if the current LWP has previously exited. In the nptl
2592 thread model, LWPs other than the main thread do not issue
2593 signals when they exit so we must check whenever the thread has
2594 stopped. A similar check is made in stop_wait_callback(). */
d90e17a7 2595 if (num_lwps (GET_PID (lp->ptid)) > 1 && !linux_thread_alive (lp->ptid))
02f3fc28 2596 {
d90e17a7
PA
2597 ptid_t ptid = pid_to_ptid (GET_PID (lp->ptid));
2598
02f3fc28
PA
2599 if (debug_linux_nat)
2600 fprintf_unfiltered (gdb_stdlog,
2601 "LLW: %s exited.\n",
2602 target_pid_to_str (lp->ptid));
2603
2604 exit_lwp (lp);
2605
2606 /* Make sure there is at least one thread running. */
d90e17a7 2607 gdb_assert (iterate_over_lwps (ptid, running_callback, NULL));
02f3fc28
PA
2608
2609 /* Discard the event. */
2610 return NULL;
2611 }
2612
2613 /* Make sure we don't report a SIGSTOP that we sent ourselves in
2614 an attempt to stop an LWP. */
2615 if (lp->signalled
2616 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2617 {
2618 if (debug_linux_nat)
2619 fprintf_unfiltered (gdb_stdlog,
2620 "LLW: Delayed SIGSTOP caught for %s.\n",
2621 target_pid_to_str (lp->ptid));
2622
2623 /* This is a delayed SIGSTOP. */
2624 lp->signalled = 0;
2625
2626 registers_changed ();
2627
28439f5e 2628 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
02f3fc28
PA
2629 lp->step, TARGET_SIGNAL_0);
2630 if (debug_linux_nat)
2631 fprintf_unfiltered (gdb_stdlog,
2632 "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
2633 lp->step ?
2634 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2635 target_pid_to_str (lp->ptid));
2636
2637 lp->stopped = 0;
2638 gdb_assert (lp->resumed);
2639
2640 /* Discard the event. */
2641 return NULL;
2642 }
2643
57380f4e
DJ
2644 /* Make sure we don't report a SIGINT that we have already displayed
2645 for another thread. */
2646 if (lp->ignore_sigint
2647 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGINT)
2648 {
2649 if (debug_linux_nat)
2650 fprintf_unfiltered (gdb_stdlog,
2651 "LLW: Delayed SIGINT caught for %s.\n",
2652 target_pid_to_str (lp->ptid));
2653
2654 /* This is a delayed SIGINT. */
2655 lp->ignore_sigint = 0;
2656
2657 registers_changed ();
28439f5e 2658 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
57380f4e
DJ
2659 lp->step, TARGET_SIGNAL_0);
2660 if (debug_linux_nat)
2661 fprintf_unfiltered (gdb_stdlog,
2662 "LLW: %s %s, 0, 0 (discard SIGINT)\n",
2663 lp->step ?
2664 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2665 target_pid_to_str (lp->ptid));
2666
2667 lp->stopped = 0;
2668 gdb_assert (lp->resumed);
2669
2670 /* Discard the event. */
2671 return NULL;
2672 }
2673
02f3fc28
PA
2674 /* An interesting event. */
2675 gdb_assert (lp);
2676 return lp;
2677}
2678
d6b0e80f 2679static ptid_t
7feb7d06 2680linux_nat_wait_1 (struct target_ops *ops,
47608cb1
PA
2681 ptid_t ptid, struct target_waitstatus *ourstatus,
2682 int target_options)
d6b0e80f 2683{
7feb7d06 2684 static sigset_t prev_mask;
d6b0e80f
AC
2685 struct lwp_info *lp = NULL;
2686 int options = 0;
2687 int status = 0;
d90e17a7 2688 pid_t pid;
d6b0e80f 2689
b84876c2
PA
2690 if (debug_linux_nat_async)
2691 fprintf_unfiltered (gdb_stdlog, "LLW: enter\n");
2692
f973ed9c
DJ
2693 /* The first time we get here after starting a new inferior, we may
2694 not have added it to the LWP list yet - this is the earliest
2695 moment at which we know its PID. */
d90e17a7 2696 if (ptid_is_pid (inferior_ptid))
f973ed9c 2697 {
27c9d204
PA
2698 /* Upgrade the main thread's ptid. */
2699 thread_change_ptid (inferior_ptid,
2700 BUILD_LWP (GET_PID (inferior_ptid),
2701 GET_PID (inferior_ptid)));
2702
f973ed9c
DJ
2703 lp = add_lwp (inferior_ptid);
2704 lp->resumed = 1;
2705 }
2706
7feb7d06
PA
2707 /* Make sure SIGCHLD is blocked. */
2708 block_child_signals (&prev_mask);
d6b0e80f 2709
d90e17a7
PA
2710 if (ptid_equal (ptid, minus_one_ptid))
2711 pid = -1;
2712 else if (ptid_is_pid (ptid))
2713 /* A request to wait for a specific tgid. This is not possible
2714 with waitpid, so instead, we wait for any child, and leave
2715 children we're not interested in right now with a pending
2716 status to report later. */
2717 pid = -1;
2718 else
2719 pid = GET_LWP (ptid);
2720
d6b0e80f 2721retry:
d90e17a7
PA
2722 lp = NULL;
2723 status = 0;
d6b0e80f 2724
f973ed9c 2725 /* Make sure there is at least one LWP that has been resumed. */
d90e17a7 2726 gdb_assert (iterate_over_lwps (ptid, resumed_callback, NULL));
d6b0e80f
AC
2727
2728 /* First check if there is a LWP with a wait status pending. */
2729 if (pid == -1)
2730 {
2731 /* Any LWP that's been resumed will do. */
d90e17a7 2732 lp = iterate_over_lwps (ptid, status_callback, NULL);
d6b0e80f
AC
2733 if (lp)
2734 {
2735 status = lp->status;
2736 lp->status = 0;
2737
2738 if (debug_linux_nat && status)
2739 fprintf_unfiltered (gdb_stdlog,
2740 "LLW: Using pending wait status %s for %s.\n",
2741 status_to_str (status),
2742 target_pid_to_str (lp->ptid));
2743 }
2744
b84876c2 2745 /* But if we don't find one, we'll have to wait, and check both
7feb7d06
PA
2746 cloned and uncloned processes. We start with the cloned
2747 processes. */
d6b0e80f
AC
2748 options = __WCLONE | WNOHANG;
2749 }
2750 else if (is_lwp (ptid))
2751 {
2752 if (debug_linux_nat)
2753 fprintf_unfiltered (gdb_stdlog,
2754 "LLW: Waiting for specific LWP %s.\n",
2755 target_pid_to_str (ptid));
2756
2757 /* We have a specific LWP to check. */
2758 lp = find_lwp_pid (ptid);
2759 gdb_assert (lp);
2760 status = lp->status;
2761 lp->status = 0;
2762
2763 if (debug_linux_nat && status)
2764 fprintf_unfiltered (gdb_stdlog,
2765 "LLW: Using pending wait status %s for %s.\n",
2766 status_to_str (status),
2767 target_pid_to_str (lp->ptid));
2768
2769 /* If we have to wait, take into account whether PID is a cloned
2770 process or not. And we have to convert it to something that
2771 the layer beneath us can understand. */
2772 options = lp->cloned ? __WCLONE : 0;
2773 pid = GET_LWP (ptid);
d90e17a7
PA
2774
2775 /* We check for lp->waitstatus in addition to lp->status,
2776 because we can have pending process exits recorded in
2777 lp->status and W_EXITCODE(0,0) == 0. We should probably have
2778 an additional lp->status_p flag. */
2779 if (status == 0 && lp->waitstatus.kind == TARGET_WAITKIND_IGNORE)
2780 lp = NULL;
d6b0e80f
AC
2781 }
2782
d90e17a7 2783 if (lp && lp->signalled)
d6b0e80f
AC
2784 {
2785 /* A pending SIGSTOP may interfere with the normal stream of
2786 events. In a typical case where interference is a problem,
2787 we have a SIGSTOP signal pending for LWP A while
2788 single-stepping it, encounter an event in LWP B, and take the
2789 pending SIGSTOP while trying to stop LWP A. After processing
2790 the event in LWP B, LWP A is continued, and we'll never see
2791 the SIGTRAP associated with the last time we were
2792 single-stepping LWP A. */
2793
2794 /* Resume the thread. It should halt immediately returning the
2795 pending SIGSTOP. */
2796 registers_changed ();
28439f5e 2797 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
10d6c8cd 2798 lp->step, TARGET_SIGNAL_0);
d6b0e80f
AC
2799 if (debug_linux_nat)
2800 fprintf_unfiltered (gdb_stdlog,
2801 "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
2802 lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2803 target_pid_to_str (lp->ptid));
2804 lp->stopped = 0;
2805 gdb_assert (lp->resumed);
2806
2807 /* This should catch the pending SIGSTOP. */
2808 stop_wait_callback (lp, NULL);
2809 }
2810
b84876c2
PA
2811 if (!target_can_async_p ())
2812 {
2813 /* Causes SIGINT to be passed on to the attached process. */
2814 set_sigint_trap ();
b84876c2 2815 }
d6b0e80f 2816
47608cb1
PA
2817 /* Translate generic target_wait options into waitpid options. */
2818 if (target_options & TARGET_WNOHANG)
2819 options |= WNOHANG;
7feb7d06 2820
d90e17a7 2821 while (lp == NULL)
d6b0e80f
AC
2822 {
2823 pid_t lwpid;
2824
7feb7d06 2825 lwpid = my_waitpid (pid, &status, options);
b84876c2 2826
d6b0e80f
AC
2827 if (lwpid > 0)
2828 {
2829 gdb_assert (pid == -1 || lwpid == pid);
2830
2831 if (debug_linux_nat)
2832 {
2833 fprintf_unfiltered (gdb_stdlog,
2834 "LLW: waitpid %ld received %s\n",
2835 (long) lwpid, status_to_str (status));
2836 }
2837
02f3fc28 2838 lp = linux_nat_filter_event (lwpid, status, options);
d90e17a7
PA
2839
2840 if (lp
2841 && ptid_is_pid (ptid)
2842 && ptid_get_pid (lp->ptid) != ptid_get_pid (ptid))
d6b0e80f 2843 {
d90e17a7
PA
2844 if (debug_linux_nat)
2845 fprintf (stderr, "LWP %ld got an event %06x, leaving pending.\n",
2846 ptid_get_lwp (lp->ptid), status);
2847
2848 if (WIFSTOPPED (status))
2849 {
2850 if (WSTOPSIG (status) != SIGSTOP)
2851 {
2852 lp->status = status;
2853
2854 stop_callback (lp, NULL);
2855
2856 /* Resume in order to collect the sigstop. */
2857 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2858
2859 stop_wait_callback (lp, NULL);
2860 }
2861 else
2862 {
2863 lp->stopped = 1;
2864 lp->signalled = 0;
2865 }
2866 }
2867 else if (WIFEXITED (status) || WIFSIGNALED (status))
2868 {
2869 if (debug_linux_nat)
2870 fprintf (stderr, "Process %ld exited while stopping LWPs\n",
2871 ptid_get_lwp (lp->ptid));
2872
2873 /* This was the last lwp in the process. Since
2874 events are serialized to GDB core, and we can't
2875 report this one right now, but GDB core and the
2876 other target layers will want to be notified
2877 about the exit code/signal, leave the status
2878 pending for the next time we're able to report
2879 it. */
2880 lp->status = status;
2881
2882 /* Prevent trying to stop this thread again. We'll
2883 never try to resume it because it has a pending
2884 status. */
2885 lp->stopped = 1;
2886
2887 /* Dead LWP's aren't expected to reported a pending
2888 sigstop. */
2889 lp->signalled = 0;
2890
2891 /* Store the pending event in the waitstatus as
2892 well, because W_EXITCODE(0,0) == 0. */
2893 store_waitstatus (&lp->waitstatus, status);
2894 }
2895
2896 /* Keep looking. */
2897 lp = NULL;
d6b0e80f
AC
2898 continue;
2899 }
2900
d90e17a7
PA
2901 if (lp)
2902 break;
2903 else
2904 {
2905 if (pid == -1)
2906 {
2907 /* waitpid did return something. Restart over. */
2908 options |= __WCLONE;
2909 }
2910 continue;
2911 }
d6b0e80f
AC
2912 }
2913
2914 if (pid == -1)
2915 {
2916 /* Alternate between checking cloned and uncloned processes. */
2917 options ^= __WCLONE;
2918
b84876c2
PA
2919 /* And every time we have checked both:
2920 In async mode, return to event loop;
2921 In sync mode, suspend waiting for a SIGCHLD signal. */
d6b0e80f 2922 if (options & __WCLONE)
b84876c2 2923 {
47608cb1 2924 if (target_options & TARGET_WNOHANG)
b84876c2
PA
2925 {
2926 /* No interesting event. */
2927 ourstatus->kind = TARGET_WAITKIND_IGNORE;
2928
b84876c2
PA
2929 if (debug_linux_nat_async)
2930 fprintf_unfiltered (gdb_stdlog, "LLW: exit (ignore)\n");
2931
7feb7d06 2932 restore_child_signals_mask (&prev_mask);
b84876c2
PA
2933 return minus_one_ptid;
2934 }
2935
2936 sigsuspend (&suspend_mask);
2937 }
d6b0e80f
AC
2938 }
2939
2940 /* We shouldn't end up here unless we want to try again. */
d90e17a7 2941 gdb_assert (lp == NULL);
d6b0e80f
AC
2942 }
2943
b84876c2 2944 if (!target_can_async_p ())
d26b5354 2945 clear_sigint_trap ();
d6b0e80f
AC
2946
2947 gdb_assert (lp);
2948
2949 /* Don't report signals that GDB isn't interested in, such as
2950 signals that are neither printed nor stopped upon. Stopping all
2951 threads can be a bit time-consuming so if we want decent
2952 performance with heavily multi-threaded programs, especially when
2953 they're using a high frequency timer, we'd better avoid it if we
2954 can. */
2955
2956 if (WIFSTOPPED (status))
2957 {
2958 int signo = target_signal_from_host (WSTOPSIG (status));
d6b48e9c
PA
2959 struct inferior *inf;
2960
2961 inf = find_inferior_pid (ptid_get_pid (lp->ptid));
2962 gdb_assert (inf);
d6b0e80f 2963
d6b48e9c
PA
2964 /* Defer to common code if we get a signal while
2965 single-stepping, since that may need special care, e.g. to
2966 skip the signal handler, or, if we're gaining control of the
2967 inferior. */
d539ed7e 2968 if (!lp->step
d6b48e9c 2969 && inf->stop_soon == NO_STOP_QUIETLY
d539ed7e 2970 && signal_stop_state (signo) == 0
d6b0e80f
AC
2971 && signal_print_state (signo) == 0
2972 && signal_pass_state (signo) == 1)
2973 {
2974 /* FIMXE: kettenis/2001-06-06: Should we resume all threads
2975 here? It is not clear we should. GDB may not expect
2976 other threads to run. On the other hand, not resuming
2977 newly attached threads may cause an unwanted delay in
2978 getting them running. */
2979 registers_changed ();
28439f5e 2980 linux_ops->to_resume (linux_ops, pid_to_ptid (GET_LWP (lp->ptid)),
10d6c8cd 2981 lp->step, signo);
d6b0e80f
AC
2982 if (debug_linux_nat)
2983 fprintf_unfiltered (gdb_stdlog,
2984 "LLW: %s %s, %s (preempt 'handle')\n",
2985 lp->step ?
2986 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2987 target_pid_to_str (lp->ptid),
2988 signo ? strsignal (signo) : "0");
2989 lp->stopped = 0;
d6b0e80f
AC
2990 goto retry;
2991 }
2992
1ad15515 2993 if (!non_stop)
d6b0e80f 2994 {
1ad15515
PA
2995 /* Only do the below in all-stop, as we currently use SIGINT
2996 to implement target_stop (see linux_nat_stop) in
2997 non-stop. */
2998 if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
2999 {
3000 /* If ^C/BREAK is typed at the tty/console, SIGINT gets
3001 forwarded to the entire process group, that is, all LWPs
3002 will receive it - unless they're using CLONE_THREAD to
3003 share signals. Since we only want to report it once, we
3004 mark it as ignored for all LWPs except this one. */
d90e17a7
PA
3005 iterate_over_lwps (pid_to_ptid (ptid_get_pid (ptid)),
3006 set_ignore_sigint, NULL);
1ad15515
PA
3007 lp->ignore_sigint = 0;
3008 }
3009 else
3010 maybe_clear_ignore_sigint (lp);
d6b0e80f
AC
3011 }
3012 }
3013
3014 /* This LWP is stopped now. */
3015 lp->stopped = 1;
3016
3017 if (debug_linux_nat)
3018 fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
3019 status_to_str (status), target_pid_to_str (lp->ptid));
3020
4c28f408
PA
3021 if (!non_stop)
3022 {
3023 /* Now stop all other LWP's ... */
d90e17a7 3024 iterate_over_lwps (minus_one_ptid, stop_callback, NULL);
4c28f408
PA
3025
3026 /* ... and wait until all of them have reported back that
3027 they're no longer running. */
d90e17a7 3028 iterate_over_lwps (minus_one_ptid, stop_wait_callback, NULL);
4c28f408
PA
3029
3030 /* If we're not waiting for a specific LWP, choose an event LWP
3031 from among those that have had events. Giving equal priority
3032 to all LWPs that have had events helps prevent
3033 starvation. */
3034 if (pid == -1)
d90e17a7 3035 select_event_lwp (ptid, &lp, &status);
4c28f408 3036 }
d6b0e80f
AC
3037
3038 /* Now that we've selected our final event LWP, cancel any
3039 breakpoints in other LWPs that have hit a GDB breakpoint. See
3040 the comment in cancel_breakpoints_callback to find out why. */
d90e17a7 3041 iterate_over_lwps (minus_one_ptid, cancel_breakpoints_callback, lp);
d6b0e80f 3042
d6b0e80f
AC
3043 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
3044 {
d6b0e80f
AC
3045 if (debug_linux_nat)
3046 fprintf_unfiltered (gdb_stdlog,
4fdebdd0
PA
3047 "LLW: trap ptid is %s.\n",
3048 target_pid_to_str (lp->ptid));
d6b0e80f 3049 }
d6b0e80f
AC
3050
3051 if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
3052 {
3053 *ourstatus = lp->waitstatus;
3054 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
3055 }
3056 else
3057 store_waitstatus (ourstatus, status);
3058
b84876c2
PA
3059 if (debug_linux_nat_async)
3060 fprintf_unfiltered (gdb_stdlog, "LLW: exit\n");
3061
7feb7d06 3062 restore_child_signals_mask (&prev_mask);
f973ed9c 3063 return lp->ptid;
d6b0e80f
AC
3064}
3065
7feb7d06
PA
3066static ptid_t
3067linux_nat_wait (struct target_ops *ops,
47608cb1
PA
3068 ptid_t ptid, struct target_waitstatus *ourstatus,
3069 int target_options)
7feb7d06
PA
3070{
3071 ptid_t event_ptid;
3072
3073 if (debug_linux_nat)
3074 fprintf_unfiltered (gdb_stdlog, "linux_nat_wait: [%s]\n", target_pid_to_str (ptid));
3075
3076 /* Flush the async file first. */
3077 if (target_can_async_p ())
3078 async_file_flush ();
3079
47608cb1 3080 event_ptid = linux_nat_wait_1 (ops, ptid, ourstatus, target_options);
7feb7d06
PA
3081
3082 /* If we requested any event, and something came out, assume there
3083 may be more. If we requested a specific lwp or process, also
3084 assume there may be more. */
3085 if (target_can_async_p ()
3086 && (ourstatus->kind != TARGET_WAITKIND_IGNORE
3087 || !ptid_equal (ptid, minus_one_ptid)))
3088 async_file_mark ();
3089
3090 /* Get ready for the next event. */
3091 if (target_can_async_p ())
3092 target_async (inferior_event_handler, 0);
3093
3094 return event_ptid;
3095}
3096
d6b0e80f
AC
3097static int
3098kill_callback (struct lwp_info *lp, void *data)
3099{
3100 errno = 0;
3101 ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
3102 if (debug_linux_nat)
3103 fprintf_unfiltered (gdb_stdlog,
3104 "KC: PTRACE_KILL %s, 0, 0 (%s)\n",
3105 target_pid_to_str (lp->ptid),
3106 errno ? safe_strerror (errno) : "OK");
3107
3108 return 0;
3109}
3110
3111static int
3112kill_wait_callback (struct lwp_info *lp, void *data)
3113{
3114 pid_t pid;
3115
3116 /* We must make sure that there are no pending events (delayed
3117 SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
3118 program doesn't interfere with any following debugging session. */
3119
3120 /* For cloned processes we must check both with __WCLONE and
3121 without, since the exit status of a cloned process isn't reported
3122 with __WCLONE. */
3123 if (lp->cloned)
3124 {
3125 do
3126 {
58aecb61 3127 pid = my_waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
e85a822c 3128 if (pid != (pid_t) -1)
d6b0e80f 3129 {
e85a822c
DJ
3130 if (debug_linux_nat)
3131 fprintf_unfiltered (gdb_stdlog,
3132 "KWC: wait %s received unknown.\n",
3133 target_pid_to_str (lp->ptid));
3134 /* The Linux kernel sometimes fails to kill a thread
3135 completely after PTRACE_KILL; that goes from the stop
3136 point in do_fork out to the one in
3137 get_signal_to_deliever and waits again. So kill it
3138 again. */
3139 kill_callback (lp, NULL);
d6b0e80f
AC
3140 }
3141 }
3142 while (pid == GET_LWP (lp->ptid));
3143
3144 gdb_assert (pid == -1 && errno == ECHILD);
3145 }
3146
3147 do
3148 {
58aecb61 3149 pid = my_waitpid (GET_LWP (lp->ptid), NULL, 0);
e85a822c 3150 if (pid != (pid_t) -1)
d6b0e80f 3151 {
e85a822c
DJ
3152 if (debug_linux_nat)
3153 fprintf_unfiltered (gdb_stdlog,
3154 "KWC: wait %s received unk.\n",
3155 target_pid_to_str (lp->ptid));
3156 /* See the call to kill_callback above. */
3157 kill_callback (lp, NULL);
d6b0e80f
AC
3158 }
3159 }
3160 while (pid == GET_LWP (lp->ptid));
3161
3162 gdb_assert (pid == -1 && errno == ECHILD);
3163 return 0;
3164}
3165
3166static void
7d85a9c0 3167linux_nat_kill (struct target_ops *ops)
d6b0e80f 3168{
f973ed9c
DJ
3169 struct target_waitstatus last;
3170 ptid_t last_ptid;
3171 int status;
d6b0e80f 3172
f973ed9c
DJ
3173 /* If we're stopped while forking and we haven't followed yet,
3174 kill the other task. We need to do this first because the
3175 parent will be sleeping if this is a vfork. */
d6b0e80f 3176
f973ed9c 3177 get_last_target_status (&last_ptid, &last);
d6b0e80f 3178
f973ed9c
DJ
3179 if (last.kind == TARGET_WAITKIND_FORKED
3180 || last.kind == TARGET_WAITKIND_VFORKED)
3181 {
3a3e9ee3 3182 ptrace (PT_KILL, PIDGET (last.value.related_pid), 0, 0);
f973ed9c
DJ
3183 wait (&status);
3184 }
3185
3186 if (forks_exist_p ())
7feb7d06 3187 linux_fork_killall ();
f973ed9c
DJ
3188 else
3189 {
d90e17a7 3190 ptid_t ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
4c28f408
PA
3191 /* Stop all threads before killing them, since ptrace requires
3192 that the thread is stopped to sucessfully PTRACE_KILL. */
d90e17a7 3193 iterate_over_lwps (ptid, stop_callback, NULL);
4c28f408
PA
3194 /* ... and wait until all of them have reported back that
3195 they're no longer running. */
d90e17a7 3196 iterate_over_lwps (ptid, stop_wait_callback, NULL);
4c28f408 3197
f973ed9c 3198 /* Kill all LWP's ... */
d90e17a7 3199 iterate_over_lwps (ptid, kill_callback, NULL);
f973ed9c
DJ
3200
3201 /* ... and wait until we've flushed all events. */
d90e17a7 3202 iterate_over_lwps (ptid, kill_wait_callback, NULL);
f973ed9c
DJ
3203 }
3204
3205 target_mourn_inferior ();
d6b0e80f
AC
3206}
3207
3208static void
136d6dae 3209linux_nat_mourn_inferior (struct target_ops *ops)
d6b0e80f 3210{
d90e17a7 3211 purge_lwp_list (ptid_get_pid (inferior_ptid));
d6b0e80f 3212
f973ed9c 3213 if (! forks_exist_p ())
d90e17a7
PA
3214 /* Normal case, no other forks available. */
3215 linux_ops->to_mourn_inferior (ops);
f973ed9c
DJ
3216 else
3217 /* Multi-fork case. The current inferior_ptid has exited, but
3218 there are other viable forks to debug. Delete the exiting
3219 one and context-switch to the first available. */
3220 linux_fork_mourn_inferior ();
d6b0e80f
AC
3221}
3222
5b009018
PA
3223/* Convert a native/host siginfo object, into/from the siginfo in the
3224 layout of the inferiors' architecture. */
3225
3226static void
3227siginfo_fixup (struct siginfo *siginfo, gdb_byte *inf_siginfo, int direction)
3228{
3229 int done = 0;
3230
3231 if (linux_nat_siginfo_fixup != NULL)
3232 done = linux_nat_siginfo_fixup (siginfo, inf_siginfo, direction);
3233
3234 /* If there was no callback, or the callback didn't do anything,
3235 then just do a straight memcpy. */
3236 if (!done)
3237 {
3238 if (direction == 1)
3239 memcpy (siginfo, inf_siginfo, sizeof (struct siginfo));
3240 else
3241 memcpy (inf_siginfo, siginfo, sizeof (struct siginfo));
3242 }
3243}
3244
4aa995e1
PA
3245static LONGEST
3246linux_xfer_siginfo (struct target_ops *ops, enum target_object object,
3247 const char *annex, gdb_byte *readbuf,
3248 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
3249{
4aa995e1
PA
3250 int pid;
3251 struct siginfo siginfo;
5b009018 3252 gdb_byte inf_siginfo[sizeof (struct siginfo)];
4aa995e1
PA
3253
3254 gdb_assert (object == TARGET_OBJECT_SIGNAL_INFO);
3255 gdb_assert (readbuf || writebuf);
3256
3257 pid = GET_LWP (inferior_ptid);
3258 if (pid == 0)
3259 pid = GET_PID (inferior_ptid);
3260
3261 if (offset > sizeof (siginfo))
3262 return -1;
3263
3264 errno = 0;
3265 ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
3266 if (errno != 0)
3267 return -1;
3268
5b009018
PA
3269 /* When GDB is built as a 64-bit application, ptrace writes into
3270 SIGINFO an object with 64-bit layout. Since debugging a 32-bit
3271 inferior with a 64-bit GDB should look the same as debugging it
3272 with a 32-bit GDB, we need to convert it. GDB core always sees
3273 the converted layout, so any read/write will have to be done
3274 post-conversion. */
3275 siginfo_fixup (&siginfo, inf_siginfo, 0);
3276
4aa995e1
PA
3277 if (offset + len > sizeof (siginfo))
3278 len = sizeof (siginfo) - offset;
3279
3280 if (readbuf != NULL)
5b009018 3281 memcpy (readbuf, inf_siginfo + offset, len);
4aa995e1
PA
3282 else
3283 {
5b009018
PA
3284 memcpy (inf_siginfo + offset, writebuf, len);
3285
3286 /* Convert back to ptrace layout before flushing it out. */
3287 siginfo_fixup (&siginfo, inf_siginfo, 1);
3288
4aa995e1
PA
3289 errno = 0;
3290 ptrace (PTRACE_SETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
3291 if (errno != 0)
3292 return -1;
3293 }
3294
3295 return len;
3296}
3297
10d6c8cd
DJ
3298static LONGEST
3299linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
3300 const char *annex, gdb_byte *readbuf,
3301 const gdb_byte *writebuf,
3302 ULONGEST offset, LONGEST len)
d6b0e80f 3303{
4aa995e1 3304 struct cleanup *old_chain;
10d6c8cd 3305 LONGEST xfer;
d6b0e80f 3306
4aa995e1
PA
3307 if (object == TARGET_OBJECT_SIGNAL_INFO)
3308 return linux_xfer_siginfo (ops, object, annex, readbuf, writebuf,
3309 offset, len);
3310
3311 old_chain = save_inferior_ptid ();
3312
d6b0e80f
AC
3313 if (is_lwp (inferior_ptid))
3314 inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
3315
10d6c8cd
DJ
3316 xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
3317 offset, len);
d6b0e80f
AC
3318
3319 do_cleanups (old_chain);
3320 return xfer;
3321}
3322
3323static int
28439f5e 3324linux_thread_alive (ptid_t ptid)
d6b0e80f 3325{
4c28f408
PA
3326 int err;
3327
d6b0e80f
AC
3328 gdb_assert (is_lwp (ptid));
3329
4c28f408
PA
3330 /* Send signal 0 instead of anything ptrace, because ptracing a
3331 running thread errors out claiming that the thread doesn't
3332 exist. */
3333 err = kill_lwp (GET_LWP (ptid), 0);
3334
d6b0e80f
AC
3335 if (debug_linux_nat)
3336 fprintf_unfiltered (gdb_stdlog,
4c28f408 3337 "LLTA: KILL(SIG0) %s (%s)\n",
d6b0e80f 3338 target_pid_to_str (ptid),
4c28f408 3339 err ? safe_strerror (err) : "OK");
9c0dd46b 3340
4c28f408 3341 if (err != 0)
d6b0e80f
AC
3342 return 0;
3343
3344 return 1;
3345}
3346
28439f5e
PA
3347static int
3348linux_nat_thread_alive (struct target_ops *ops, ptid_t ptid)
3349{
3350 return linux_thread_alive (ptid);
3351}
3352
d6b0e80f 3353static char *
117de6a9 3354linux_nat_pid_to_str (struct target_ops *ops, ptid_t ptid)
d6b0e80f
AC
3355{
3356 static char buf[64];
3357
a0ef4274 3358 if (is_lwp (ptid)
d90e17a7
PA
3359 && (GET_PID (ptid) != GET_LWP (ptid)
3360 || num_lwps (GET_PID (ptid)) > 1))
d6b0e80f
AC
3361 {
3362 snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
3363 return buf;
3364 }
3365
3366 return normal_pid_to_str (ptid);
3367}
3368
dba24537
AC
3369/* Accepts an integer PID; Returns a string representing a file that
3370 can be opened to get the symbols for the child process. */
3371
6d8fd2b7
UW
3372static char *
3373linux_child_pid_to_exec_file (int pid)
dba24537
AC
3374{
3375 char *name1, *name2;
3376
3377 name1 = xmalloc (MAXPATHLEN);
3378 name2 = xmalloc (MAXPATHLEN);
3379 make_cleanup (xfree, name1);
3380 make_cleanup (xfree, name2);
3381 memset (name2, 0, MAXPATHLEN);
3382
3383 sprintf (name1, "/proc/%d/exe", pid);
3384 if (readlink (name1, name2, MAXPATHLEN) > 0)
3385 return name2;
3386 else
3387 return name1;
3388}
3389
3390/* Service function for corefiles and info proc. */
3391
3392static int
3393read_mapping (FILE *mapfile,
3394 long long *addr,
3395 long long *endaddr,
3396 char *permissions,
3397 long long *offset,
3398 char *device, long long *inode, char *filename)
3399{
3400 int ret = fscanf (mapfile, "%llx-%llx %s %llx %s %llx",
3401 addr, endaddr, permissions, offset, device, inode);
3402
2e14c2ea
MS
3403 filename[0] = '\0';
3404 if (ret > 0 && ret != EOF)
dba24537
AC
3405 {
3406 /* Eat everything up to EOL for the filename. This will prevent
3407 weird filenames (such as one with embedded whitespace) from
3408 confusing this code. It also makes this code more robust in
3409 respect to annotations the kernel may add after the filename.
3410
3411 Note the filename is used for informational purposes
3412 only. */
3413 ret += fscanf (mapfile, "%[^\n]\n", filename);
3414 }
2e14c2ea 3415
dba24537
AC
3416 return (ret != 0 && ret != EOF);
3417}
3418
3419/* Fills the "to_find_memory_regions" target vector. Lists the memory
3420 regions in the inferior for a corefile. */
3421
3422static int
3423linux_nat_find_memory_regions (int (*func) (CORE_ADDR,
3424 unsigned long,
3425 int, int, int, void *), void *obfd)
3426{
89ecc4f5 3427 int pid = PIDGET (inferior_ptid);
dba24537
AC
3428 char mapsfilename[MAXPATHLEN];
3429 FILE *mapsfile;
3430 long long addr, endaddr, size, offset, inode;
3431 char permissions[8], device[8], filename[MAXPATHLEN];
3432 int read, write, exec;
3433 int ret;
7c8a8b04 3434 struct cleanup *cleanup;
dba24537
AC
3435
3436 /* Compose the filename for the /proc memory map, and open it. */
89ecc4f5 3437 sprintf (mapsfilename, "/proc/%d/maps", pid);
dba24537 3438 if ((mapsfile = fopen (mapsfilename, "r")) == NULL)
8a3fe4f8 3439 error (_("Could not open %s."), mapsfilename);
7c8a8b04 3440 cleanup = make_cleanup_fclose (mapsfile);
dba24537
AC
3441
3442 if (info_verbose)
3443 fprintf_filtered (gdb_stdout,
3444 "Reading memory regions from %s\n", mapsfilename);
3445
3446 /* Now iterate until end-of-file. */
3447 while (read_mapping (mapsfile, &addr, &endaddr, &permissions[0],
3448 &offset, &device[0], &inode, &filename[0]))
3449 {
3450 size = endaddr - addr;
3451
3452 /* Get the segment's permissions. */
3453 read = (strchr (permissions, 'r') != 0);
3454 write = (strchr (permissions, 'w') != 0);
3455 exec = (strchr (permissions, 'x') != 0);
3456
3457 if (info_verbose)
3458 {
3459 fprintf_filtered (gdb_stdout,
3460 "Save segment, %lld bytes at 0x%s (%c%c%c)",
3461 size, paddr_nz (addr),
3462 read ? 'r' : ' ',
3463 write ? 'w' : ' ', exec ? 'x' : ' ');
b260b6c1 3464 if (filename[0])
dba24537
AC
3465 fprintf_filtered (gdb_stdout, " for %s", filename);
3466 fprintf_filtered (gdb_stdout, "\n");
3467 }
3468
3469 /* Invoke the callback function to create the corefile
3470 segment. */
3471 func (addr, size, read, write, exec, obfd);
3472 }
7c8a8b04 3473 do_cleanups (cleanup);
dba24537
AC
3474 return 0;
3475}
3476
2020b7ab
PA
3477static int
3478find_signalled_thread (struct thread_info *info, void *data)
3479{
3480 if (info->stop_signal != TARGET_SIGNAL_0
3481 && ptid_get_pid (info->ptid) == ptid_get_pid (inferior_ptid))
3482 return 1;
3483
3484 return 0;
3485}
3486
3487static enum target_signal
3488find_stop_signal (void)
3489{
3490 struct thread_info *info =
3491 iterate_over_threads (find_signalled_thread, NULL);
3492
3493 if (info)
3494 return info->stop_signal;
3495 else
3496 return TARGET_SIGNAL_0;
3497}
3498
dba24537
AC
3499/* Records the thread's register state for the corefile note
3500 section. */
3501
3502static char *
3503linux_nat_do_thread_registers (bfd *obfd, ptid_t ptid,
2020b7ab
PA
3504 char *note_data, int *note_size,
3505 enum target_signal stop_signal)
dba24537
AC
3506{
3507 gdb_gregset_t gregs;
3508 gdb_fpregset_t fpregs;
dba24537 3509 unsigned long lwp = ptid_get_lwp (ptid);
594f7785
UW
3510 struct regcache *regcache = get_thread_regcache (ptid);
3511 struct gdbarch *gdbarch = get_regcache_arch (regcache);
4f844a66 3512 const struct regset *regset;
55e969c1 3513 int core_regset_p;
594f7785 3514 struct cleanup *old_chain;
17ea7499
CES
3515 struct core_regset_section *sect_list;
3516 char *gdb_regset;
594f7785
UW
3517
3518 old_chain = save_inferior_ptid ();
3519 inferior_ptid = ptid;
3520 target_fetch_registers (regcache, -1);
3521 do_cleanups (old_chain);
4f844a66
DM
3522
3523 core_regset_p = gdbarch_regset_from_core_section_p (gdbarch);
17ea7499
CES
3524 sect_list = gdbarch_core_regset_sections (gdbarch);
3525
55e969c1
DM
3526 if (core_regset_p
3527 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg",
3528 sizeof (gregs))) != NULL
3529 && regset->collect_regset != NULL)
594f7785 3530 regset->collect_regset (regset, regcache, -1,
55e969c1 3531 &gregs, sizeof (gregs));
4f844a66 3532 else
594f7785 3533 fill_gregset (regcache, &gregs, -1);
4f844a66 3534
55e969c1
DM
3535 note_data = (char *) elfcore_write_prstatus (obfd,
3536 note_data,
3537 note_size,
3538 lwp,
3539 stop_signal, &gregs);
3540
17ea7499
CES
3541 /* The loop below uses the new struct core_regset_section, which stores
3542 the supported section names and sizes for the core file. Note that
3543 note PRSTATUS needs to be treated specially. But the other notes are
3544 structurally the same, so they can benefit from the new struct. */
3545 if (core_regset_p && sect_list != NULL)
3546 while (sect_list->sect_name != NULL)
3547 {
3548 /* .reg was already handled above. */
3549 if (strcmp (sect_list->sect_name, ".reg") == 0)
3550 {
3551 sect_list++;
3552 continue;
3553 }
3554 regset = gdbarch_regset_from_core_section (gdbarch,
3555 sect_list->sect_name,
3556 sect_list->size);
3557 gdb_assert (regset && regset->collect_regset);
3558 gdb_regset = xmalloc (sect_list->size);
3559 regset->collect_regset (regset, regcache, -1,
3560 gdb_regset, sect_list->size);
3561 note_data = (char *) elfcore_write_register_note (obfd,
3562 note_data,
3563 note_size,
3564 sect_list->sect_name,
3565 gdb_regset,
3566 sect_list->size);
3567 xfree (gdb_regset);
3568 sect_list++;
3569 }
dba24537 3570
17ea7499
CES
3571 /* For architectures that does not have the struct core_regset_section
3572 implemented, we use the old method. When all the architectures have
3573 the new support, the code below should be deleted. */
4f844a66 3574 else
17ea7499
CES
3575 {
3576 if (core_regset_p
3577 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg2",
3578 sizeof (fpregs))) != NULL
3579 && regset->collect_regset != NULL)
3580 regset->collect_regset (regset, regcache, -1,
3581 &fpregs, sizeof (fpregs));
3582 else
3583 fill_fpregset (regcache, &fpregs, -1);
3584
3585 note_data = (char *) elfcore_write_prfpreg (obfd,
3586 note_data,
3587 note_size,
3588 &fpregs, sizeof (fpregs));
3589 }
4f844a66 3590
dba24537
AC
3591 return note_data;
3592}
3593
3594struct linux_nat_corefile_thread_data
3595{
3596 bfd *obfd;
3597 char *note_data;
3598 int *note_size;
3599 int num_notes;
2020b7ab 3600 enum target_signal stop_signal;
dba24537
AC
3601};
3602
3603/* Called by gdbthread.c once per thread. Records the thread's
3604 register state for the corefile note section. */
3605
3606static int
3607linux_nat_corefile_thread_callback (struct lwp_info *ti, void *data)
3608{
3609 struct linux_nat_corefile_thread_data *args = data;
dba24537 3610
dba24537
AC
3611 args->note_data = linux_nat_do_thread_registers (args->obfd,
3612 ti->ptid,
3613 args->note_data,
2020b7ab
PA
3614 args->note_size,
3615 args->stop_signal);
dba24537 3616 args->num_notes++;
56be3814 3617
dba24537
AC
3618 return 0;
3619}
3620
dba24537
AC
3621/* Fills the "to_make_corefile_note" target vector. Builds the note
3622 section for a corefile, and returns it in a malloc buffer. */
3623
3624static char *
3625linux_nat_make_corefile_notes (bfd *obfd, int *note_size)
3626{
3627 struct linux_nat_corefile_thread_data thread_args;
3628 struct cleanup *old_chain;
d99148ef 3629 /* The variable size must be >= sizeof (prpsinfo_t.pr_fname). */
dba24537 3630 char fname[16] = { '\0' };
d99148ef 3631 /* The variable size must be >= sizeof (prpsinfo_t.pr_psargs). */
dba24537
AC
3632 char psargs[80] = { '\0' };
3633 char *note_data = NULL;
3634 ptid_t current_ptid = inferior_ptid;
d90e17a7 3635 ptid_t filter = pid_to_ptid (ptid_get_pid (inferior_ptid));
c6826062 3636 gdb_byte *auxv;
dba24537
AC
3637 int auxv_len;
3638
3639 if (get_exec_file (0))
3640 {
3641 strncpy (fname, strrchr (get_exec_file (0), '/') + 1, sizeof (fname));
3642 strncpy (psargs, get_exec_file (0), sizeof (psargs));
3643 if (get_inferior_args ())
3644 {
d99148ef
JK
3645 char *string_end;
3646 char *psargs_end = psargs + sizeof (psargs);
3647
3648 /* linux_elfcore_write_prpsinfo () handles zero unterminated
3649 strings fine. */
3650 string_end = memchr (psargs, 0, sizeof (psargs));
3651 if (string_end != NULL)
3652 {
3653 *string_end++ = ' ';
3654 strncpy (string_end, get_inferior_args (),
3655 psargs_end - string_end);
3656 }
dba24537
AC
3657 }
3658 note_data = (char *) elfcore_write_prpsinfo (obfd,
3659 note_data,
3660 note_size, fname, psargs);
3661 }
3662
3663 /* Dump information for threads. */
3664 thread_args.obfd = obfd;
3665 thread_args.note_data = note_data;
3666 thread_args.note_size = note_size;
3667 thread_args.num_notes = 0;
2020b7ab 3668 thread_args.stop_signal = find_stop_signal ();
d90e17a7 3669 iterate_over_lwps (filter, linux_nat_corefile_thread_callback, &thread_args);
2020b7ab
PA
3670 gdb_assert (thread_args.num_notes != 0);
3671 note_data = thread_args.note_data;
dba24537 3672
13547ab6
DJ
3673 auxv_len = target_read_alloc (&current_target, TARGET_OBJECT_AUXV,
3674 NULL, &auxv);
dba24537
AC
3675 if (auxv_len > 0)
3676 {
3677 note_data = elfcore_write_note (obfd, note_data, note_size,
3678 "CORE", NT_AUXV, auxv, auxv_len);
3679 xfree (auxv);
3680 }
3681
3682 make_cleanup (xfree, note_data);
3683 return note_data;
3684}
3685
3686/* Implement the "info proc" command. */
3687
3688static void
3689linux_nat_info_proc_cmd (char *args, int from_tty)
3690{
89ecc4f5
DE
3691 /* A long is used for pid instead of an int to avoid a loss of precision
3692 compiler warning from the output of strtoul. */
3693 long pid = PIDGET (inferior_ptid);
dba24537
AC
3694 FILE *procfile;
3695 char **argv = NULL;
3696 char buffer[MAXPATHLEN];
3697 char fname1[MAXPATHLEN], fname2[MAXPATHLEN];
3698 int cmdline_f = 1;
3699 int cwd_f = 1;
3700 int exe_f = 1;
3701 int mappings_f = 0;
3702 int environ_f = 0;
3703 int status_f = 0;
3704 int stat_f = 0;
3705 int all = 0;
3706 struct stat dummy;
3707
3708 if (args)
3709 {
3710 /* Break up 'args' into an argv array. */
d1a41061
PP
3711 argv = gdb_buildargv (args);
3712 make_cleanup_freeargv (argv);
dba24537
AC
3713 }
3714 while (argv != NULL && *argv != NULL)
3715 {
3716 if (isdigit (argv[0][0]))
3717 {
3718 pid = strtoul (argv[0], NULL, 10);
3719 }
3720 else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
3721 {
3722 mappings_f = 1;
3723 }
3724 else if (strcmp (argv[0], "status") == 0)
3725 {
3726 status_f = 1;
3727 }
3728 else if (strcmp (argv[0], "stat") == 0)
3729 {
3730 stat_f = 1;
3731 }
3732 else if (strcmp (argv[0], "cmd") == 0)
3733 {
3734 cmdline_f = 1;
3735 }
3736 else if (strncmp (argv[0], "exe", strlen (argv[0])) == 0)
3737 {
3738 exe_f = 1;
3739 }
3740 else if (strcmp (argv[0], "cwd") == 0)
3741 {
3742 cwd_f = 1;
3743 }
3744 else if (strncmp (argv[0], "all", strlen (argv[0])) == 0)
3745 {
3746 all = 1;
3747 }
3748 else
3749 {
3750 /* [...] (future options here) */
3751 }
3752 argv++;
3753 }
3754 if (pid == 0)
8a3fe4f8 3755 error (_("No current process: you must name one."));
dba24537 3756
89ecc4f5 3757 sprintf (fname1, "/proc/%ld", pid);
dba24537 3758 if (stat (fname1, &dummy) != 0)
8a3fe4f8 3759 error (_("No /proc directory: '%s'"), fname1);
dba24537 3760
89ecc4f5 3761 printf_filtered (_("process %ld\n"), pid);
dba24537
AC
3762 if (cmdline_f || all)
3763 {
89ecc4f5 3764 sprintf (fname1, "/proc/%ld/cmdline", pid);
d5d6fca5 3765 if ((procfile = fopen (fname1, "r")) != NULL)
dba24537 3766 {
7c8a8b04 3767 struct cleanup *cleanup = make_cleanup_fclose (procfile);
bf1d7d9c
JB
3768 if (fgets (buffer, sizeof (buffer), procfile))
3769 printf_filtered ("cmdline = '%s'\n", buffer);
3770 else
3771 warning (_("unable to read '%s'"), fname1);
7c8a8b04 3772 do_cleanups (cleanup);
dba24537
AC
3773 }
3774 else
8a3fe4f8 3775 warning (_("unable to open /proc file '%s'"), fname1);
dba24537
AC
3776 }
3777 if (cwd_f || all)
3778 {
89ecc4f5 3779 sprintf (fname1, "/proc/%ld/cwd", pid);
dba24537
AC
3780 memset (fname2, 0, sizeof (fname2));
3781 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
3782 printf_filtered ("cwd = '%s'\n", fname2);
3783 else
8a3fe4f8 3784 warning (_("unable to read link '%s'"), fname1);
dba24537
AC
3785 }
3786 if (exe_f || all)
3787 {
89ecc4f5 3788 sprintf (fname1, "/proc/%ld/exe", pid);
dba24537
AC
3789 memset (fname2, 0, sizeof (fname2));
3790 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
3791 printf_filtered ("exe = '%s'\n", fname2);
3792 else
8a3fe4f8 3793 warning (_("unable to read link '%s'"), fname1);
dba24537
AC
3794 }
3795 if (mappings_f || all)
3796 {
89ecc4f5 3797 sprintf (fname1, "/proc/%ld/maps", pid);
d5d6fca5 3798 if ((procfile = fopen (fname1, "r")) != NULL)
dba24537
AC
3799 {
3800 long long addr, endaddr, size, offset, inode;
3801 char permissions[8], device[8], filename[MAXPATHLEN];
7c8a8b04 3802 struct cleanup *cleanup;
dba24537 3803
7c8a8b04 3804 cleanup = make_cleanup_fclose (procfile);
a3f17187 3805 printf_filtered (_("Mapped address spaces:\n\n"));
17a912b6 3806 if (gdbarch_addr_bit (current_gdbarch) == 32)
dba24537
AC
3807 {
3808 printf_filtered ("\t%10s %10s %10s %10s %7s\n",
3809 "Start Addr",
3810 " End Addr",
3811 " Size", " Offset", "objfile");
3812 }
3813 else
3814 {
3815 printf_filtered (" %18s %18s %10s %10s %7s\n",
3816 "Start Addr",
3817 " End Addr",
3818 " Size", " Offset", "objfile");
3819 }
3820
3821 while (read_mapping (procfile, &addr, &endaddr, &permissions[0],
3822 &offset, &device[0], &inode, &filename[0]))
3823 {
3824 size = endaddr - addr;
3825
3826 /* FIXME: carlton/2003-08-27: Maybe the printf_filtered
3827 calls here (and possibly above) should be abstracted
3828 out into their own functions? Andrew suggests using
3829 a generic local_address_string instead to print out
3830 the addresses; that makes sense to me, too. */
3831
17a912b6 3832 if (gdbarch_addr_bit (current_gdbarch) == 32)
dba24537
AC
3833 {
3834 printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
3835 (unsigned long) addr, /* FIXME: pr_addr */
3836 (unsigned long) endaddr,
3837 (int) size,
3838 (unsigned int) offset,
3839 filename[0] ? filename : "");
3840 }
3841 else
3842 {
3843 printf_filtered (" %#18lx %#18lx %#10x %#10x %7s\n",
3844 (unsigned long) addr, /* FIXME: pr_addr */
3845 (unsigned long) endaddr,
3846 (int) size,
3847 (unsigned int) offset,
3848 filename[0] ? filename : "");
3849 }
3850 }
3851
7c8a8b04 3852 do_cleanups (cleanup);
dba24537
AC
3853 }
3854 else
8a3fe4f8 3855 warning (_("unable to open /proc file '%s'"), fname1);
dba24537
AC
3856 }
3857 if (status_f || all)
3858 {
89ecc4f5 3859 sprintf (fname1, "/proc/%ld/status", pid);
d5d6fca5 3860 if ((procfile = fopen (fname1, "r")) != NULL)
dba24537 3861 {
7c8a8b04 3862 struct cleanup *cleanup = make_cleanup_fclose (procfile);
dba24537
AC
3863 while (fgets (buffer, sizeof (buffer), procfile) != NULL)
3864 puts_filtered (buffer);
7c8a8b04 3865 do_cleanups (cleanup);
dba24537
AC
3866 }
3867 else
8a3fe4f8 3868 warning (_("unable to open /proc file '%s'"), fname1);
dba24537
AC
3869 }
3870 if (stat_f || all)
3871 {
89ecc4f5 3872 sprintf (fname1, "/proc/%ld/stat", pid);
d5d6fca5 3873 if ((procfile = fopen (fname1, "r")) != NULL)
dba24537
AC
3874 {
3875 int itmp;
3876 char ctmp;
a25694b4 3877 long ltmp;
7c8a8b04 3878 struct cleanup *cleanup = make_cleanup_fclose (procfile);
dba24537
AC
3879
3880 if (fscanf (procfile, "%d ", &itmp) > 0)
a3f17187 3881 printf_filtered (_("Process: %d\n"), itmp);
a25694b4 3882 if (fscanf (procfile, "(%[^)]) ", &buffer[0]) > 0)
a3f17187 3883 printf_filtered (_("Exec file: %s\n"), buffer);
dba24537 3884 if (fscanf (procfile, "%c ", &ctmp) > 0)
a3f17187 3885 printf_filtered (_("State: %c\n"), ctmp);
dba24537 3886 if (fscanf (procfile, "%d ", &itmp) > 0)
a3f17187 3887 printf_filtered (_("Parent process: %d\n"), itmp);
dba24537 3888 if (fscanf (procfile, "%d ", &itmp) > 0)
a3f17187 3889 printf_filtered (_("Process group: %d\n"), itmp);
dba24537 3890 if (fscanf (procfile, "%d ", &itmp) > 0)
a3f17187 3891 printf_filtered (_("Session id: %d\n"), itmp);
dba24537 3892 if (fscanf (procfile, "%d ", &itmp) > 0)
a3f17187 3893 printf_filtered (_("TTY: %d\n"), itmp);
dba24537 3894 if (fscanf (procfile, "%d ", &itmp) > 0)
a3f17187 3895 printf_filtered (_("TTY owner process group: %d\n"), itmp);
a25694b4
AS
3896 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3897 printf_filtered (_("Flags: 0x%lx\n"), ltmp);
3898 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3899 printf_filtered (_("Minor faults (no memory page): %lu\n"),
3900 (unsigned long) ltmp);
3901 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3902 printf_filtered (_("Minor faults, children: %lu\n"),
3903 (unsigned long) ltmp);
3904 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3905 printf_filtered (_("Major faults (memory page faults): %lu\n"),
3906 (unsigned long) ltmp);
3907 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3908 printf_filtered (_("Major faults, children: %lu\n"),
3909 (unsigned long) ltmp);
3910 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3911 printf_filtered (_("utime: %ld\n"), ltmp);
3912 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3913 printf_filtered (_("stime: %ld\n"), ltmp);
3914 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3915 printf_filtered (_("utime, children: %ld\n"), ltmp);
3916 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3917 printf_filtered (_("stime, children: %ld\n"), ltmp);
3918 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3919 printf_filtered (_("jiffies remaining in current time slice: %ld\n"),
3920 ltmp);
3921 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3922 printf_filtered (_("'nice' value: %ld\n"), ltmp);
3923 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3924 printf_filtered (_("jiffies until next timeout: %lu\n"),
3925 (unsigned long) ltmp);
3926 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3927 printf_filtered (_("jiffies until next SIGALRM: %lu\n"),
3928 (unsigned long) ltmp);
3929 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3930 printf_filtered (_("start time (jiffies since system boot): %ld\n"),
3931 ltmp);
3932 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3933 printf_filtered (_("Virtual memory size: %lu\n"),
3934 (unsigned long) ltmp);
3935 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3936 printf_filtered (_("Resident set size: %lu\n"), (unsigned long) ltmp);
3937 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3938 printf_filtered (_("rlim: %lu\n"), (unsigned long) ltmp);
3939 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3940 printf_filtered (_("Start of text: 0x%lx\n"), ltmp);
3941 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3942 printf_filtered (_("End of text: 0x%lx\n"), ltmp);
3943 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3944 printf_filtered (_("Start of stack: 0x%lx\n"), ltmp);
dba24537
AC
3945#if 0 /* Don't know how architecture-dependent the rest is...
3946 Anyway the signal bitmap info is available from "status". */
a25694b4
AS
3947 if (fscanf (procfile, "%lu ", &ltmp) > 0) /* FIXME arch? */
3948 printf_filtered (_("Kernel stack pointer: 0x%lx\n"), ltmp);
3949 if (fscanf (procfile, "%lu ", &ltmp) > 0) /* FIXME arch? */
3950 printf_filtered (_("Kernel instr pointer: 0x%lx\n"), ltmp);
3951 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3952 printf_filtered (_("Pending signals bitmap: 0x%lx\n"), ltmp);
3953 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3954 printf_filtered (_("Blocked signals bitmap: 0x%lx\n"), ltmp);
3955 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3956 printf_filtered (_("Ignored signals bitmap: 0x%lx\n"), ltmp);
3957 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3958 printf_filtered (_("Catched signals bitmap: 0x%lx\n"), ltmp);
3959 if (fscanf (procfile, "%lu ", &ltmp) > 0) /* FIXME arch? */
3960 printf_filtered (_("wchan (system call): 0x%lx\n"), ltmp);
dba24537 3961#endif
7c8a8b04 3962 do_cleanups (cleanup);
dba24537
AC
3963 }
3964 else
8a3fe4f8 3965 warning (_("unable to open /proc file '%s'"), fname1);
dba24537
AC
3966 }
3967}
3968
10d6c8cd
DJ
3969/* Implement the to_xfer_partial interface for memory reads using the /proc
3970 filesystem. Because we can use a single read() call for /proc, this
3971 can be much more efficient than banging away at PTRACE_PEEKTEXT,
3972 but it doesn't support writes. */
3973
3974static LONGEST
3975linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
3976 const char *annex, gdb_byte *readbuf,
3977 const gdb_byte *writebuf,
3978 ULONGEST offset, LONGEST len)
dba24537 3979{
10d6c8cd
DJ
3980 LONGEST ret;
3981 int fd;
dba24537
AC
3982 char filename[64];
3983
10d6c8cd 3984 if (object != TARGET_OBJECT_MEMORY || !readbuf)
dba24537
AC
3985 return 0;
3986
3987 /* Don't bother for one word. */
3988 if (len < 3 * sizeof (long))
3989 return 0;
3990
3991 /* We could keep this file open and cache it - possibly one per
3992 thread. That requires some juggling, but is even faster. */
3993 sprintf (filename, "/proc/%d/mem", PIDGET (inferior_ptid));
3994 fd = open (filename, O_RDONLY | O_LARGEFILE);
3995 if (fd == -1)
3996 return 0;
3997
3998 /* If pread64 is available, use it. It's faster if the kernel
3999 supports it (only one syscall), and it's 64-bit safe even on
4000 32-bit platforms (for instance, SPARC debugging a SPARC64
4001 application). */
4002#ifdef HAVE_PREAD64
10d6c8cd 4003 if (pread64 (fd, readbuf, len, offset) != len)
dba24537 4004#else
10d6c8cd 4005 if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
dba24537
AC
4006#endif
4007 ret = 0;
4008 else
4009 ret = len;
4010
4011 close (fd);
4012 return ret;
4013}
4014
4015/* Parse LINE as a signal set and add its set bits to SIGS. */
4016
4017static void
4018add_line_to_sigset (const char *line, sigset_t *sigs)
4019{
4020 int len = strlen (line) - 1;
4021 const char *p;
4022 int signum;
4023
4024 if (line[len] != '\n')
8a3fe4f8 4025 error (_("Could not parse signal set: %s"), line);
dba24537
AC
4026
4027 p = line;
4028 signum = len * 4;
4029 while (len-- > 0)
4030 {
4031 int digit;
4032
4033 if (*p >= '0' && *p <= '9')
4034 digit = *p - '0';
4035 else if (*p >= 'a' && *p <= 'f')
4036 digit = *p - 'a' + 10;
4037 else
8a3fe4f8 4038 error (_("Could not parse signal set: %s"), line);
dba24537
AC
4039
4040 signum -= 4;
4041
4042 if (digit & 1)
4043 sigaddset (sigs, signum + 1);
4044 if (digit & 2)
4045 sigaddset (sigs, signum + 2);
4046 if (digit & 4)
4047 sigaddset (sigs, signum + 3);
4048 if (digit & 8)
4049 sigaddset (sigs, signum + 4);
4050
4051 p++;
4052 }
4053}
4054
4055/* Find process PID's pending signals from /proc/pid/status and set
4056 SIGS to match. */
4057
4058void
4059linux_proc_pending_signals (int pid, sigset_t *pending, sigset_t *blocked, sigset_t *ignored)
4060{
4061 FILE *procfile;
4062 char buffer[MAXPATHLEN], fname[MAXPATHLEN];
4063 int signum;
7c8a8b04 4064 struct cleanup *cleanup;
dba24537
AC
4065
4066 sigemptyset (pending);
4067 sigemptyset (blocked);
4068 sigemptyset (ignored);
4069 sprintf (fname, "/proc/%d/status", pid);
4070 procfile = fopen (fname, "r");
4071 if (procfile == NULL)
8a3fe4f8 4072 error (_("Could not open %s"), fname);
7c8a8b04 4073 cleanup = make_cleanup_fclose (procfile);
dba24537
AC
4074
4075 while (fgets (buffer, MAXPATHLEN, procfile) != NULL)
4076 {
4077 /* Normal queued signals are on the SigPnd line in the status
4078 file. However, 2.6 kernels also have a "shared" pending
4079 queue for delivering signals to a thread group, so check for
4080 a ShdPnd line also.
4081
4082 Unfortunately some Red Hat kernels include the shared pending
4083 queue but not the ShdPnd status field. */
4084
4085 if (strncmp (buffer, "SigPnd:\t", 8) == 0)
4086 add_line_to_sigset (buffer + 8, pending);
4087 else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
4088 add_line_to_sigset (buffer + 8, pending);
4089 else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
4090 add_line_to_sigset (buffer + 8, blocked);
4091 else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
4092 add_line_to_sigset (buffer + 8, ignored);
4093 }
4094
7c8a8b04 4095 do_cleanups (cleanup);
dba24537
AC
4096}
4097
07e059b5
VP
4098static LONGEST
4099linux_nat_xfer_osdata (struct target_ops *ops, enum target_object object,
4100 const char *annex, gdb_byte *readbuf,
4101 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
4102{
4103 /* We make the process list snapshot when the object starts to be
4104 read. */
4105 static const char *buf;
4106 static LONGEST len_avail = -1;
4107 static struct obstack obstack;
4108
4109 DIR *dirp;
4110
4111 gdb_assert (object == TARGET_OBJECT_OSDATA);
4112
4113 if (strcmp (annex, "processes") != 0)
4114 return 0;
4115
4116 gdb_assert (readbuf && !writebuf);
4117
4118 if (offset == 0)
4119 {
4120 if (len_avail != -1 && len_avail != 0)
4121 obstack_free (&obstack, NULL);
4122 len_avail = 0;
4123 buf = NULL;
4124 obstack_init (&obstack);
4125 obstack_grow_str (&obstack, "<osdata type=\"processes\">\n");
4126
4127 dirp = opendir ("/proc");
4128 if (dirp)
4129 {
4130 struct dirent *dp;
4131 while ((dp = readdir (dirp)) != NULL)
4132 {
4133 struct stat statbuf;
4134 char procentry[sizeof ("/proc/4294967295")];
4135
4136 if (!isdigit (dp->d_name[0])
1a6d2f2f 4137 || NAMELEN (dp) > sizeof ("4294967295") - 1)
07e059b5
VP
4138 continue;
4139
4140 sprintf (procentry, "/proc/%s", dp->d_name);
4141 if (stat (procentry, &statbuf) == 0
4142 && S_ISDIR (statbuf.st_mode))
4143 {
4144 char *pathname;
4145 FILE *f;
4146 char cmd[MAXPATHLEN + 1];
4147 struct passwd *entry;
4148
4149 pathname = xstrprintf ("/proc/%s/cmdline", dp->d_name);
4150 entry = getpwuid (statbuf.st_uid);
4151
4152 if ((f = fopen (pathname, "r")) != NULL)
4153 {
4154 size_t len = fread (cmd, 1, sizeof (cmd) - 1, f);
4155 if (len > 0)
4156 {
4157 int i;
4158 for (i = 0; i < len; i++)
4159 if (cmd[i] == '\0')
4160 cmd[i] = ' ';
4161 cmd[len] = '\0';
4162
4163 obstack_xml_printf (
4164 &obstack,
4165 "<item>"
4166 "<column name=\"pid\">%s</column>"
4167 "<column name=\"user\">%s</column>"
4168 "<column name=\"command\">%s</column>"
4169 "</item>",
4170 dp->d_name,
4171 entry ? entry->pw_name : "?",
4172 cmd);
4173 }
4174 fclose (f);
4175 }
4176
4177 xfree (pathname);
4178 }
4179 }
4180
4181 closedir (dirp);
4182 }
4183
4184 obstack_grow_str0 (&obstack, "</osdata>\n");
4185 buf = obstack_finish (&obstack);
4186 len_avail = strlen (buf);
4187 }
4188
4189 if (offset >= len_avail)
4190 {
4191 /* Done. Get rid of the obstack. */
4192 obstack_free (&obstack, NULL);
4193 buf = NULL;
4194 len_avail = 0;
4195 return 0;
4196 }
4197
4198 if (len > len_avail - offset)
4199 len = len_avail - offset;
4200 memcpy (readbuf, buf + offset, len);
4201
4202 return len;
4203}
4204
10d6c8cd
DJ
4205static LONGEST
4206linux_xfer_partial (struct target_ops *ops, enum target_object object,
4207 const char *annex, gdb_byte *readbuf,
4208 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
4209{
4210 LONGEST xfer;
4211
4212 if (object == TARGET_OBJECT_AUXV)
4213 return procfs_xfer_auxv (ops, object, annex, readbuf, writebuf,
4214 offset, len);
4215
07e059b5
VP
4216 if (object == TARGET_OBJECT_OSDATA)
4217 return linux_nat_xfer_osdata (ops, object, annex, readbuf, writebuf,
4218 offset, len);
4219
10d6c8cd
DJ
4220 xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
4221 offset, len);
4222 if (xfer != 0)
4223 return xfer;
4224
4225 return super_xfer_partial (ops, object, annex, readbuf, writebuf,
4226 offset, len);
4227}
4228
e9efe249 4229/* Create a prototype generic GNU/Linux target. The client can override
10d6c8cd
DJ
4230 it with local methods. */
4231
910122bf
UW
4232static void
4233linux_target_install_ops (struct target_ops *t)
10d6c8cd 4234{
6d8fd2b7
UW
4235 t->to_insert_fork_catchpoint = linux_child_insert_fork_catchpoint;
4236 t->to_insert_vfork_catchpoint = linux_child_insert_vfork_catchpoint;
4237 t->to_insert_exec_catchpoint = linux_child_insert_exec_catchpoint;
4238 t->to_pid_to_exec_file = linux_child_pid_to_exec_file;
10d6c8cd 4239 t->to_post_startup_inferior = linux_child_post_startup_inferior;
6d8fd2b7
UW
4240 t->to_post_attach = linux_child_post_attach;
4241 t->to_follow_fork = linux_child_follow_fork;
10d6c8cd
DJ
4242 t->to_find_memory_regions = linux_nat_find_memory_regions;
4243 t->to_make_corefile_notes = linux_nat_make_corefile_notes;
4244
4245 super_xfer_partial = t->to_xfer_partial;
4246 t->to_xfer_partial = linux_xfer_partial;
910122bf
UW
4247}
4248
4249struct target_ops *
4250linux_target (void)
4251{
4252 struct target_ops *t;
4253
4254 t = inf_ptrace_target ();
4255 linux_target_install_ops (t);
4256
4257 return t;
4258}
4259
4260struct target_ops *
7714d83a 4261linux_trad_target (CORE_ADDR (*register_u_offset)(struct gdbarch *, int, int))
910122bf
UW
4262{
4263 struct target_ops *t;
4264
4265 t = inf_ptrace_trad_target (register_u_offset);
4266 linux_target_install_ops (t);
10d6c8cd 4267
10d6c8cd
DJ
4268 return t;
4269}
4270
b84876c2
PA
4271/* target_is_async_p implementation. */
4272
4273static int
4274linux_nat_is_async_p (void)
4275{
4276 /* NOTE: palves 2008-03-21: We're only async when the user requests
7feb7d06 4277 it explicitly with the "set target-async" command.
b84876c2 4278 Someday, linux will always be async. */
c6ebd6cf 4279 if (!target_async_permitted)
b84876c2
PA
4280 return 0;
4281
d90e17a7
PA
4282 /* See target.h/target_async_mask. */
4283 return linux_nat_async_mask_value;
b84876c2
PA
4284}
4285
4286/* target_can_async_p implementation. */
4287
4288static int
4289linux_nat_can_async_p (void)
4290{
4291 /* NOTE: palves 2008-03-21: We're only async when the user requests
7feb7d06 4292 it explicitly with the "set target-async" command.
b84876c2 4293 Someday, linux will always be async. */
c6ebd6cf 4294 if (!target_async_permitted)
b84876c2
PA
4295 return 0;
4296
4297 /* See target.h/target_async_mask. */
4298 return linux_nat_async_mask_value;
4299}
4300
9908b566
VP
4301static int
4302linux_nat_supports_non_stop (void)
4303{
4304 return 1;
4305}
4306
d90e17a7
PA
4307/* True if we want to support multi-process. To be removed when GDB
4308 supports multi-exec. */
4309
4310int linux_multi_process = 0;
4311
4312static int
4313linux_nat_supports_multi_process (void)
4314{
4315 return linux_multi_process;
4316}
4317
b84876c2
PA
4318/* target_async_mask implementation. */
4319
4320static int
7feb7d06 4321linux_nat_async_mask (int new_mask)
b84876c2 4322{
7feb7d06 4323 int curr_mask = linux_nat_async_mask_value;
b84876c2 4324
7feb7d06 4325 if (curr_mask != new_mask)
b84876c2 4326 {
7feb7d06 4327 if (new_mask == 0)
b84876c2
PA
4328 {
4329 linux_nat_async (NULL, 0);
7feb7d06 4330 linux_nat_async_mask_value = new_mask;
b84876c2
PA
4331 }
4332 else
4333 {
7feb7d06 4334 linux_nat_async_mask_value = new_mask;
84e46146 4335
7feb7d06
PA
4336 /* If we're going out of async-mask in all-stop, then the
4337 inferior is stopped. The next resume will call
4338 target_async. In non-stop, the target event source
4339 should be always registered in the event loop. Do so
4340 now. */
4341 if (non_stop)
4342 linux_nat_async (inferior_event_handler, 0);
b84876c2
PA
4343 }
4344 }
4345
7feb7d06 4346 return curr_mask;
b84876c2
PA
4347}
4348
4349static int async_terminal_is_ours = 1;
4350
4351/* target_terminal_inferior implementation. */
4352
4353static void
4354linux_nat_terminal_inferior (void)
4355{
4356 if (!target_is_async_p ())
4357 {
4358 /* Async mode is disabled. */
4359 terminal_inferior ();
4360 return;
4361 }
4362
4363 /* GDB should never give the terminal to the inferior, if the
4364 inferior is running in the background (run&, continue&, etc.).
4365 This check can be removed when the common code is fixed. */
4366 if (!sync_execution)
4367 return;
4368
4369 terminal_inferior ();
4370
4371 if (!async_terminal_is_ours)
4372 return;
4373
4374 delete_file_handler (input_fd);
4375 async_terminal_is_ours = 0;
4376 set_sigint_trap ();
4377}
4378
4379/* target_terminal_ours implementation. */
4380
2c0b251b 4381static void
b84876c2
PA
4382linux_nat_terminal_ours (void)
4383{
4384 if (!target_is_async_p ())
4385 {
4386 /* Async mode is disabled. */
4387 terminal_ours ();
4388 return;
4389 }
4390
4391 /* GDB should never give the terminal to the inferior if the
4392 inferior is running in the background (run&, continue&, etc.),
4393 but claiming it sure should. */
4394 terminal_ours ();
4395
4396 if (!sync_execution)
4397 return;
4398
4399 if (async_terminal_is_ours)
4400 return;
4401
4402 clear_sigint_trap ();
4403 add_file_handler (input_fd, stdin_event_handler, 0);
4404 async_terminal_is_ours = 1;
4405}
4406
4407static void (*async_client_callback) (enum inferior_event_type event_type,
4408 void *context);
4409static void *async_client_context;
4410
7feb7d06
PA
4411/* SIGCHLD handler that serves two purposes: In non-stop/async mode,
4412 so we notice when any child changes state, and notify the
4413 event-loop; it allows us to use sigsuspend in linux_nat_wait_1
4414 above to wait for the arrival of a SIGCHLD. */
4415
b84876c2 4416static void
7feb7d06 4417sigchld_handler (int signo)
b84876c2 4418{
7feb7d06
PA
4419 int old_errno = errno;
4420
4421 if (debug_linux_nat_async)
4422 fprintf_unfiltered (gdb_stdlog, "sigchld\n");
4423
4424 if (signo == SIGCHLD
4425 && linux_nat_event_pipe[0] != -1)
4426 async_file_mark (); /* Let the event loop know that there are
4427 events to handle. */
4428
4429 errno = old_errno;
4430}
4431
4432/* Callback registered with the target events file descriptor. */
4433
4434static void
4435handle_target_event (int error, gdb_client_data client_data)
4436{
4437 (*async_client_callback) (INF_REG_EVENT, async_client_context);
4438}
4439
4440/* Create/destroy the target events pipe. Returns previous state. */
4441
4442static int
4443linux_async_pipe (int enable)
4444{
4445 int previous = (linux_nat_event_pipe[0] != -1);
4446
4447 if (previous != enable)
4448 {
4449 sigset_t prev_mask;
4450
4451 block_child_signals (&prev_mask);
4452
4453 if (enable)
4454 {
4455 if (pipe (linux_nat_event_pipe) == -1)
4456 internal_error (__FILE__, __LINE__,
4457 "creating event pipe failed.");
4458
4459 fcntl (linux_nat_event_pipe[0], F_SETFL, O_NONBLOCK);
4460 fcntl (linux_nat_event_pipe[1], F_SETFL, O_NONBLOCK);
4461 }
4462 else
4463 {
4464 close (linux_nat_event_pipe[0]);
4465 close (linux_nat_event_pipe[1]);
4466 linux_nat_event_pipe[0] = -1;
4467 linux_nat_event_pipe[1] = -1;
4468 }
4469
4470 restore_child_signals_mask (&prev_mask);
4471 }
4472
4473 return previous;
b84876c2
PA
4474}
4475
4476/* target_async implementation. */
4477
4478static void
4479linux_nat_async (void (*callback) (enum inferior_event_type event_type,
4480 void *context), void *context)
4481{
c6ebd6cf 4482 if (linux_nat_async_mask_value == 0 || !target_async_permitted)
b84876c2
PA
4483 internal_error (__FILE__, __LINE__,
4484 "Calling target_async when async is masked");
4485
4486 if (callback != NULL)
4487 {
4488 async_client_callback = callback;
4489 async_client_context = context;
7feb7d06
PA
4490 if (!linux_async_pipe (1))
4491 {
4492 add_file_handler (linux_nat_event_pipe[0],
4493 handle_target_event, NULL);
4494 /* There may be pending events to handle. Tell the event loop
4495 to poll them. */
4496 async_file_mark ();
4497 }
b84876c2
PA
4498 }
4499 else
4500 {
4501 async_client_callback = callback;
4502 async_client_context = context;
b84876c2 4503 delete_file_handler (linux_nat_event_pipe[0]);
7feb7d06 4504 linux_async_pipe (0);
b84876c2
PA
4505 }
4506 return;
4507}
4508
252fbfc8
PA
4509/* Stop an LWP, and push a TARGET_SIGNAL_0 stop status if no other
4510 event came out. */
4511
4c28f408 4512static int
252fbfc8 4513linux_nat_stop_lwp (struct lwp_info *lwp, void *data)
4c28f408 4514{
d90e17a7 4515 if (!lwp->stopped)
252fbfc8 4516 {
d90e17a7
PA
4517 int pid, status;
4518 ptid_t ptid = lwp->ptid;
252fbfc8 4519
d90e17a7
PA
4520 if (debug_linux_nat)
4521 fprintf_unfiltered (gdb_stdlog,
4522 "LNSL: running -> suspending %s\n",
4523 target_pid_to_str (lwp->ptid));
252fbfc8 4524
252fbfc8 4525
d90e17a7
PA
4526 stop_callback (lwp, NULL);
4527 stop_wait_callback (lwp, NULL);
252fbfc8 4528
d90e17a7
PA
4529 /* If the lwp exits while we try to stop it, there's nothing
4530 else to do. */
4531 lwp = find_lwp_pid (ptid);
4532 if (lwp == NULL)
4533 return 0;
252fbfc8 4534
d90e17a7
PA
4535 /* If we didn't collect any signal other than SIGSTOP while
4536 stopping the LWP, push a SIGNAL_0 event. In either case, the
4537 event-loop will end up calling target_wait which will collect
4538 these. */
4539 if (lwp->status == 0)
4540 lwp->status = W_STOPCODE (0);
4541 async_file_mark ();
4542 }
4543 else
4544 {
4545 /* Already known to be stopped; do nothing. */
252fbfc8 4546
d90e17a7
PA
4547 if (debug_linux_nat)
4548 {
4549 if (find_thread_pid (lwp->ptid)->stop_requested)
4550 fprintf_unfiltered (gdb_stdlog, "\
252fbfc8 4551LNSL: already stopped/stop_requested %s\n",
d90e17a7
PA
4552 target_pid_to_str (lwp->ptid));
4553 else
4554 fprintf_unfiltered (gdb_stdlog, "\
252fbfc8 4555LNSL: already stopped/no stop_requested yet %s\n",
d90e17a7 4556 target_pid_to_str (lwp->ptid));
252fbfc8
PA
4557 }
4558 }
4c28f408
PA
4559 return 0;
4560}
4561
4562static void
4563linux_nat_stop (ptid_t ptid)
4564{
4565 if (non_stop)
d90e17a7 4566 iterate_over_lwps (ptid, linux_nat_stop_lwp, NULL);
4c28f408
PA
4567 else
4568 linux_ops->to_stop (ptid);
4569}
4570
d90e17a7
PA
4571static void
4572linux_nat_close (int quitting)
4573{
4574 /* Unregister from the event loop. */
4575 if (target_is_async_p ())
4576 target_async (NULL, 0);
4577
4578 /* Reset the async_masking. */
4579 linux_nat_async_mask_value = 1;
4580
4581 if (linux_ops->to_close)
4582 linux_ops->to_close (quitting);
4583}
4584
f973ed9c
DJ
4585void
4586linux_nat_add_target (struct target_ops *t)
4587{
f973ed9c
DJ
4588 /* Save the provided single-threaded target. We save this in a separate
4589 variable because another target we've inherited from (e.g. inf-ptrace)
4590 may have saved a pointer to T; we want to use it for the final
4591 process stratum target. */
4592 linux_ops_saved = *t;
4593 linux_ops = &linux_ops_saved;
4594
4595 /* Override some methods for multithreading. */
b84876c2 4596 t->to_create_inferior = linux_nat_create_inferior;
f973ed9c
DJ
4597 t->to_attach = linux_nat_attach;
4598 t->to_detach = linux_nat_detach;
4599 t->to_resume = linux_nat_resume;
4600 t->to_wait = linux_nat_wait;
4601 t->to_xfer_partial = linux_nat_xfer_partial;
4602 t->to_kill = linux_nat_kill;
4603 t->to_mourn_inferior = linux_nat_mourn_inferior;
4604 t->to_thread_alive = linux_nat_thread_alive;
4605 t->to_pid_to_str = linux_nat_pid_to_str;
4606 t->to_has_thread_control = tc_schedlock;
4607
b84876c2
PA
4608 t->to_can_async_p = linux_nat_can_async_p;
4609 t->to_is_async_p = linux_nat_is_async_p;
9908b566 4610 t->to_supports_non_stop = linux_nat_supports_non_stop;
b84876c2
PA
4611 t->to_async = linux_nat_async;
4612 t->to_async_mask = linux_nat_async_mask;
4613 t->to_terminal_inferior = linux_nat_terminal_inferior;
4614 t->to_terminal_ours = linux_nat_terminal_ours;
d90e17a7 4615 t->to_close = linux_nat_close;
b84876c2 4616
4c28f408
PA
4617 /* Methods for non-stop support. */
4618 t->to_stop = linux_nat_stop;
4619
d90e17a7
PA
4620 t->to_supports_multi_process = linux_nat_supports_multi_process;
4621
f973ed9c
DJ
4622 /* We don't change the stratum; this target will sit at
4623 process_stratum and thread_db will set at thread_stratum. This
4624 is a little strange, since this is a multi-threaded-capable
4625 target, but we want to be on the stack below thread_db, and we
4626 also want to be used for single-threaded processes. */
4627
4628 add_target (t);
f973ed9c
DJ
4629}
4630
9f0bdab8
DJ
4631/* Register a method to call whenever a new thread is attached. */
4632void
4633linux_nat_set_new_thread (struct target_ops *t, void (*new_thread) (ptid_t))
4634{
4635 /* Save the pointer. We only support a single registered instance
4636 of the GNU/Linux native target, so we do not need to map this to
4637 T. */
4638 linux_nat_new_thread = new_thread;
4639}
4640
5b009018
PA
4641/* Register a method that converts a siginfo object between the layout
4642 that ptrace returns, and the layout in the architecture of the
4643 inferior. */
4644void
4645linux_nat_set_siginfo_fixup (struct target_ops *t,
4646 int (*siginfo_fixup) (struct siginfo *,
4647 gdb_byte *,
4648 int))
4649{
4650 /* Save the pointer. */
4651 linux_nat_siginfo_fixup = siginfo_fixup;
4652}
4653
9f0bdab8
DJ
4654/* Return the saved siginfo associated with PTID. */
4655struct siginfo *
4656linux_nat_get_siginfo (ptid_t ptid)
4657{
4658 struct lwp_info *lp = find_lwp_pid (ptid);
4659
4660 gdb_assert (lp != NULL);
4661
4662 return &lp->siginfo;
4663}
4664
2c0b251b
PA
4665/* Provide a prototype to silence -Wmissing-prototypes. */
4666extern initialize_file_ftype _initialize_linux_nat;
4667
d6b0e80f
AC
4668void
4669_initialize_linux_nat (void)
4670{
b84876c2 4671 sigset_t mask;
dba24537 4672
1bedd215
AC
4673 add_info ("proc", linux_nat_info_proc_cmd, _("\
4674Show /proc process information about any running process.\n\
dba24537
AC
4675Specify any process id, or use the program being debugged by default.\n\
4676Specify any of the following keywords for detailed info:\n\
4677 mappings -- list of mapped memory regions.\n\
4678 stat -- list a bunch of random process info.\n\
4679 status -- list a different bunch of random process info.\n\
1bedd215 4680 all -- list all available /proc info."));
d6b0e80f 4681
b84876c2
PA
4682 add_setshow_zinteger_cmd ("lin-lwp", class_maintenance,
4683 &debug_linux_nat, _("\
4684Set debugging of GNU/Linux lwp module."), _("\
4685Show debugging of GNU/Linux lwp module."), _("\
4686Enables printf debugging output."),
4687 NULL,
4688 show_debug_linux_nat,
4689 &setdebuglist, &showdebuglist);
4690
4691 add_setshow_zinteger_cmd ("lin-lwp-async", class_maintenance,
4692 &debug_linux_nat_async, _("\
4693Set debugging of GNU/Linux async lwp module."), _("\
4694Show debugging of GNU/Linux async lwp module."), _("\
4695Enables printf debugging output."),
4696 NULL,
4697 show_debug_linux_nat_async,
4698 &setdebuglist, &showdebuglist);
4699
b84876c2 4700 /* Save this mask as the default. */
d6b0e80f
AC
4701 sigprocmask (SIG_SETMASK, NULL, &normal_mask);
4702
7feb7d06
PA
4703 /* Install a SIGCHLD handler. */
4704 sigchld_action.sa_handler = sigchld_handler;
4705 sigemptyset (&sigchld_action.sa_mask);
4706 sigchld_action.sa_flags = SA_RESTART;
b84876c2
PA
4707
4708 /* Make it the default. */
7feb7d06 4709 sigaction (SIGCHLD, &sigchld_action, NULL);
d6b0e80f
AC
4710
4711 /* Make sure we don't block SIGCHLD during a sigsuspend. */
4712 sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
4713 sigdelset (&suspend_mask, SIGCHLD);
4714
7feb7d06 4715 sigemptyset (&blocked_mask);
10568435
JK
4716
4717 add_setshow_boolean_cmd ("disable-randomization", class_support,
4718 &disable_randomization, _("\
4719Set disabling of debuggee's virtual address space randomization."), _("\
4720Show disabling of debuggee's virtual address space randomization."), _("\
4721When this mode is on (which is the default), randomization of the virtual\n\
4722address space is disabled. Standalone programs run with the randomization\n\
4723enabled by default on some platforms."),
4724 &set_disable_randomization,
4725 &show_disable_randomization,
4726 &setlist, &showlist);
d6b0e80f
AC
4727}
4728\f
4729
4730/* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
4731 the GNU/Linux Threads library and therefore doesn't really belong
4732 here. */
4733
4734/* Read variable NAME in the target and return its value if found.
4735 Otherwise return zero. It is assumed that the type of the variable
4736 is `int'. */
4737
4738static int
4739get_signo (const char *name)
4740{
4741 struct minimal_symbol *ms;
4742 int signo;
4743
4744 ms = lookup_minimal_symbol (name, NULL, NULL);
4745 if (ms == NULL)
4746 return 0;
4747
8e70166d 4748 if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
d6b0e80f
AC
4749 sizeof (signo)) != 0)
4750 return 0;
4751
4752 return signo;
4753}
4754
4755/* Return the set of signals used by the threads library in *SET. */
4756
4757void
4758lin_thread_get_thread_signals (sigset_t *set)
4759{
4760 struct sigaction action;
4761 int restart, cancel;
4762
b84876c2 4763 sigemptyset (&blocked_mask);
d6b0e80f
AC
4764 sigemptyset (set);
4765
4766 restart = get_signo ("__pthread_sig_restart");
17fbb0bd
DJ
4767 cancel = get_signo ("__pthread_sig_cancel");
4768
4769 /* LinuxThreads normally uses the first two RT signals, but in some legacy
4770 cases may use SIGUSR1/SIGUSR2. NPTL always uses RT signals, but does
4771 not provide any way for the debugger to query the signal numbers -
4772 fortunately they don't change! */
4773
d6b0e80f 4774 if (restart == 0)
17fbb0bd 4775 restart = __SIGRTMIN;
d6b0e80f 4776
d6b0e80f 4777 if (cancel == 0)
17fbb0bd 4778 cancel = __SIGRTMIN + 1;
d6b0e80f
AC
4779
4780 sigaddset (set, restart);
4781 sigaddset (set, cancel);
4782
4783 /* The GNU/Linux Threads library makes terminating threads send a
4784 special "cancel" signal instead of SIGCHLD. Make sure we catch
4785 those (to prevent them from terminating GDB itself, which is
4786 likely to be their default action) and treat them the same way as
4787 SIGCHLD. */
4788
4789 action.sa_handler = sigchld_handler;
4790 sigemptyset (&action.sa_mask);
58aecb61 4791 action.sa_flags = SA_RESTART;
d6b0e80f
AC
4792 sigaction (cancel, &action, NULL);
4793
4794 /* We block the "cancel" signal throughout this code ... */
4795 sigaddset (&blocked_mask, cancel);
4796 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
4797
4798 /* ... except during a sigsuspend. */
4799 sigdelset (&suspend_mask, cancel);
4800}