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