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