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