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