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