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