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