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