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