gdb/linux-nat.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* GNU/Linux native-dependent code common to multiple platforms.

  2.    Copyright (C) 2001-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "inferior.h"
  16. #include "infrun.h"
  17. #include "target.h"
  18. #include "nat/linux-nat.h"
  19. #include "nat/linux-waitpid.h"
  20. #include "gdb_wait.h"
  21. #ifdef HAVE_TKILL_SYSCALL
  22. #include <unistd.h>
  23. #include <sys/syscall.h>
  24. #endif
  25. #include <sys/ptrace.h>
  26. #include "linux-nat.h"
  27. #include "nat/linux-ptrace.h"
  28. #include "nat/linux-procfs.h"
  29. #include "linux-fork.h"
  30. #include "gdbthread.h"
  31. #include "gdbcmd.h"
  32. #include "regcache.h"
  33. #include "regset.h"
  34. #include "inf-child.h"
  35. #include "inf-ptrace.h"
  36. #include "auxv.h"
  37. #include <sys/procfs.h>                /* for elf_gregset etc.  */
  38. #include "elf-bfd.h"                /* for elfcore_write_* */
  39. #include "gregset.h"                /* for gregset */
  40. #include "gdbcore.h"                /* for get_exec_file */
  41. #include <ctype.h>                /* for isdigit */
  42. #include <sys/stat.h>                /* for struct stat */
  43. #include <fcntl.h>                /* for O_RDONLY */
  44. #include "inf-loop.h"
  45. #include "event-loop.h"
  46. #include "event-top.h"
  47. #include <pwd.h>
  48. #include <sys/types.h>
  49. #include <dirent.h>
  50. #include "xml-support.h"
  51. #include <sys/vfs.h>
  52. #include "solib.h"
  53. #include "nat/linux-osdata.h"
  54. #include "linux-tdep.h"
  55. #include "symfile.h"
  56. #include "agent.h"
  57. #include "tracepoint.h"
  58. #include "buffer.h"
  59. #include "target-descriptions.h"
  60. #include "filestuff.h"
  61. #include "objfiles.h"

  62. #ifndef SPUFS_MAGIC
  63. #define SPUFS_MAGIC 0x23c9b64e
  64. #endif

  65. #ifdef HAVE_PERSONALITY
  66. # include <sys/personality.h>
  67. # if !HAVE_DECL_ADDR_NO_RANDOMIZE
  68. #  define ADDR_NO_RANDOMIZE 0x0040000
  69. # endif
  70. #endif /* HAVE_PERSONALITY */

  71. /* This comment documents high-level logic of this file.

  72. Waiting for events in sync mode
  73. ===============================

  74. When waiting for an event in a specific thread, we just use waitpid, passing
  75. the specific pid, and not passing WNOHANG.

  76. When waiting for an event in all threads, waitpid is not quite good.  Prior to
  77. version 2.4, Linux can either wait for event in main thread, or in secondary
  78. threads.  (2.4 has the __WALL flag).  So, if we use blocking waitpid, we might
  79. miss an event.  The solution is to use non-blocking waitpid, together with
  80. sigsuspend.  First, we use non-blocking waitpid to get an event in the main
  81. process, if any.  Second, we use non-blocking waitpid with the __WCLONED
  82. flag to check for events in cloned processes.  If nothing is found, we use
  83. sigsuspend to wait for SIGCHLD.  When SIGCHLD arrives, it means something
  84. happened to a child process -- and SIGCHLD will be delivered both for events
  85. in main debugged process and in cloned processes.  As soon as we know there's
  86. an event, we get back to calling nonblocking waitpid with and without
  87. __WCLONED.

  88. Note that SIGCHLD should be blocked between waitpid and sigsuspend calls,
  89. so that we don't miss a signal.  If SIGCHLD arrives in between, when it's
  90. blocked, the signal becomes pending and sigsuspend immediately
  91. notices it and returns.

  92. Waiting for events in async mode
  93. ================================

  94. In async mode, GDB should always be ready to handle both user input
  95. and target events, so neither blocking waitpid nor sigsuspend are
  96. viable options.  Instead, we should asynchronously notify the GDB main
  97. event loop whenever there's an unprocessed event from the target.  We
  98. detect asynchronous target events by handling SIGCHLD signals.  To
  99. notify the event loop about target events, the self-pipe trick is used
  100. --- a pipe is registered as waitable event source in the event loop,
  101. the event loop select/poll's on the read end of this pipe (as well on
  102. other event sources, e.g., stdin), and the SIGCHLD handler writes a
  103. byte to this pipe.  This is more portable than relying on
  104. pselect/ppoll, since on kernels that lack those syscalls, libc
  105. emulates them with select/poll+sigprocmask, and that is racy
  106. (a.k.a. plain broken).

  107. Obviously, if we fail to notify the event loop if there's a target
  108. event, it's bad.  OTOH, if we notify the event loop when there's no
  109. event from the target, linux_nat_wait will detect that there's no real
  110. event to report, and return event of type TARGET_WAITKIND_IGNORE.
  111. This is mostly harmless, but it will waste time and is better avoided.

  112. The main design point is that every time GDB is outside linux-nat.c,
  113. we have a SIGCHLD handler installed that is called when something
  114. happens to the target and notifies the GDB event loop.  Whenever GDB
  115. core decides to handle the event, and calls into linux-nat.c, we
  116. process things as in sync mode, except that the we never block in
  117. sigsuspend.

  118. While processing an event, we may end up momentarily blocked in
  119. waitpid calls.  Those waitpid calls, while blocking, are guarantied to
  120. return quickly.  E.g., in all-stop mode, before reporting to the core
  121. that an LWP hit a breakpoint, all LWPs are stopped by sending them
  122. SIGSTOP, and synchronously waiting for the SIGSTOP to be reported.
  123. Note that this is different from blocking indefinitely waiting for the
  124. next event --- here, we're already handling an event.

  125. Use of signals
  126. ==============

  127. We stop threads by sending a SIGSTOP.  The use of SIGSTOP instead of another
  128. signal is not entirely significant; we just need for a signal to be delivered,
  129. so that we can intercept it.  SIGSTOP's advantage is that it can not be
  130. blocked.  A disadvantage is that it is not a real-time signal, so it can only
  131. be queued once; we do not keep track of other sources of SIGSTOP.

  132. Two other signals that can't be blocked are SIGCONT and SIGKILL.  But we can't
  133. use them, because they have special behavior when the signal is generated -
  134. not when it is delivered.  SIGCONT resumes the entire thread group and SIGKILL
  135. kills the entire thread group.

  136. A delivered SIGSTOP would stop the entire thread group, not just the thread we
  137. tkill'd.  But we never let the SIGSTOP be delivered; we always intercept and
  138. cancel it (by PTRACE_CONT without passing SIGSTOP).

  139. We could use a real-time signal instead.  This would solve those problems; we
  140. could use PTRACE_GETSIGINFO to locate the specific stop signals sent by GDB.
  141. But we would still have to have some support for SIGSTOP, since PTRACE_ATTACH
  142. generates it, and there are races with trying to find a signal that is not
  143. blocked.  */

  144. #ifndef O_LARGEFILE
  145. #define O_LARGEFILE 0
  146. #endif

  147. /* The single-threaded native GNU/Linux target_ops.  We save a pointer for
  148.    the use of the multi-threaded target.  */
  149. static struct target_ops *linux_ops;
  150. static struct target_ops linux_ops_saved;

  151. /* The method to call, if any, when a new thread is attached.  */
  152. static void (*linux_nat_new_thread) (struct lwp_info *);

  153. /* The method to call, if any, when a new fork is attached.  */
  154. static linux_nat_new_fork_ftype *linux_nat_new_fork;

  155. /* The method to call, if any, when a process is no longer
  156.    attached.  */
  157. static linux_nat_forget_process_ftype *linux_nat_forget_process_hook;

  158. /* Hook to call prior to resuming a thread.  */
  159. static void (*linux_nat_prepare_to_resume) (struct lwp_info *);

  160. /* The method to call, if any, when the siginfo object needs to be
  161.    converted between the layout returned by ptrace, and the layout in
  162.    the architecture of the inferior.  */
  163. static int (*linux_nat_siginfo_fixup) (siginfo_t *,
  164.                                        gdb_byte *,
  165.                                        int);

  166. /* The saved to_xfer_partial method, inherited from inf-ptrace.c.
  167.    Called by our to_xfer_partial.  */
  168. static target_xfer_partial_ftype *super_xfer_partial;

  169. /* The saved to_close method, inherited from inf-ptrace.c.
  170.    Called by our to_close.  */
  171. static void (*super_close) (struct target_ops *);

  172. static unsigned int debug_linux_nat;
  173. static void
  174. show_debug_linux_nat (struct ui_file *file, int from_tty,
  175.                       struct cmd_list_element *c, const char *value)
  176. {
  177.   fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
  178.                     value);
  179. }

  180. struct simple_pid_list
  181. {
  182.   int pid;
  183.   int status;
  184.   struct simple_pid_list *next;
  185. };
  186. struct simple_pid_list *stopped_pids;

  187. /* Async mode support.  */

  188. /* The read/write ends of the pipe registered as waitable file in the
  189.    event loop.  */
  190. static int linux_nat_event_pipe[2] = { -1, -1 };

  191. /* Flush the event pipe.  */

  192. static void
  193. async_file_flush (void)
  194. {
  195.   int ret;
  196.   char buf;

  197.   do
  198.     {
  199.       ret = read (linux_nat_event_pipe[0], &buf, 1);
  200.     }
  201.   while (ret >= 0 || (ret == -1 && errno == EINTR));
  202. }

  203. /* Put something (anything, doesn't matter what, or how much) in event
  204.    pipe, so that the select/poll in the event-loop realizes we have
  205.    something to process.  */

  206. static void
  207. async_file_mark (void)
  208. {
  209.   int ret;

  210.   /* It doesn't really matter what the pipe contains, as long we end
  211.      up with something in it.  Might as well flush the previous
  212.      left-overs.  */
  213.   async_file_flush ();

  214.   do
  215.     {
  216.       ret = write (linux_nat_event_pipe[1], "+", 1);
  217.     }
  218.   while (ret == -1 && errno == EINTR);

  219.   /* Ignore EAGAIN.  If the pipe is full, the event loop will already
  220.      be awakened anyway.  */
  221. }

  222. static int kill_lwp (int lwpid, int signo);

  223. static int stop_callback (struct lwp_info *lp, void *data);

  224. static void block_child_signals (sigset_t *prev_mask);
  225. static void restore_child_signals_mask (sigset_t *prev_mask);

  226. struct lwp_info;
  227. static struct lwp_info *add_lwp (ptid_t ptid);
  228. static void purge_lwp_list (int pid);
  229. static void delete_lwp (ptid_t ptid);
  230. static struct lwp_info *find_lwp_pid (ptid_t ptid);

  231. static int lwp_status_pending_p (struct lwp_info *lp);

  232. static int check_stopped_by_breakpoint (struct lwp_info *lp);
  233. static int sigtrap_is_event (int status);
  234. static int (*linux_nat_status_is_event) (int status) = sigtrap_is_event;


  235. /* Trivial list manipulation functions to keep track of a list of
  236.    new stopped processes.  */
  237. static void
  238. add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
  239. {
  240.   struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));

  241.   new_pid->pid = pid;
  242.   new_pid->status = status;
  243.   new_pid->next = *listp;
  244.   *listp = new_pid;
  245. }

  246. static int
  247. in_pid_list_p (struct simple_pid_list *list, int pid)
  248. {
  249.   struct simple_pid_list *p;

  250.   for (p = list; p != NULL; p = p->next)
  251.     if (p->pid == pid)
  252.       return 1;
  253.   return 0;
  254. }

  255. static int
  256. pull_pid_from_list (struct simple_pid_list **listp, int pid, int *statusp)
  257. {
  258.   struct simple_pid_list **p;

  259.   for (p = listp; *p != NULL; p = &(*p)->next)
  260.     if ((*p)->pid == pid)
  261.       {
  262.         struct simple_pid_list *next = (*p)->next;

  263.         *statusp = (*p)->status;
  264.         xfree (*p);
  265.         *p = next;
  266.         return 1;
  267.       }
  268.   return 0;
  269. }

  270. /* Initialize ptrace warnings and check for supported ptrace
  271.    features given PID.

  272.    ATTACHED should be nonzero iff we attached to the inferior.  */

  273. static void
  274. linux_init_ptrace (pid_t pid, int attached)
  275. {
  276.   linux_enable_event_reporting (pid, attached);
  277.   linux_ptrace_init_warnings ();
  278. }

  279. static void
  280. linux_child_post_attach (struct target_ops *self, int pid)
  281. {
  282.   linux_init_ptrace (pid, 1);
  283. }

  284. static void
  285. linux_child_post_startup_inferior (struct target_ops *self, ptid_t ptid)
  286. {
  287.   linux_init_ptrace (ptid_get_pid (ptid), 0);
  288. }

  289. /* Return the number of known LWPs in the tgid given by PID.  */

  290. static int
  291. num_lwps (int pid)
  292. {
  293.   int count = 0;
  294.   struct lwp_info *lp;

  295.   for (lp = lwp_list; lp; lp = lp->next)
  296.     if (ptid_get_pid (lp->ptid) == pid)
  297.       count++;

  298.   return count;
  299. }

  300. /* Call delete_lwp with prototype compatible for make_cleanup.  */

  301. static void
  302. delete_lwp_cleanup (void *lp_voidp)
  303. {
  304.   struct lwp_info *lp = lp_voidp;

  305.   delete_lwp (lp->ptid);
  306. }

  307. /* Target hook for follow_fork.  On entry inferior_ptid must be the
  308.    ptid of the followed inferior.  At return, inferior_ptid will be
  309.    unchanged.  */

  310. static int
  311. linux_child_follow_fork (struct target_ops *ops, int follow_child,
  312.                          int detach_fork)
  313. {
  314.   if (!follow_child)
  315.     {
  316.       struct lwp_info *child_lp = NULL;
  317.       int status = W_STOPCODE (0);
  318.       struct cleanup *old_chain;
  319.       int has_vforked;
  320.       int parent_pid, child_pid;

  321.       has_vforked = (inferior_thread ()->pending_follow.kind
  322.                      == TARGET_WAITKIND_VFORKED);
  323.       parent_pid = ptid_get_lwp (inferior_ptid);
  324.       if (parent_pid == 0)
  325.         parent_pid = ptid_get_pid (inferior_ptid);
  326.       child_pid
  327.         = ptid_get_pid (inferior_thread ()->pending_follow.value.related_pid);


  328.       /* We're already attached to the parent, by default.  */
  329.       old_chain = save_inferior_ptid ();
  330.       inferior_ptid = ptid_build (child_pid, child_pid, 0);
  331.       child_lp = add_lwp (inferior_ptid);
  332.       child_lp->stopped = 1;
  333.       child_lp->last_resume_kind = resume_stop;

  334.       /* Detach new forked process?  */
  335.       if (detach_fork)
  336.         {
  337.           make_cleanup (delete_lwp_cleanup, child_lp);

  338.           if (linux_nat_prepare_to_resume != NULL)
  339.             linux_nat_prepare_to_resume (child_lp);

  340.           /* When debugging an inferior in an architecture that supports
  341.              hardware single stepping on a kernel without commit
  342.              6580807da14c423f0d0a708108e6df6ebc8bc83d, the vfork child
  343.              process starts with the TIF_SINGLESTEP/X86_EFLAGS_TF bits
  344.              set if the parent process had them set.
  345.              To work around this, single step the child process
  346.              once before detaching to clear the flags.  */

  347.           if (!gdbarch_software_single_step_p (target_thread_architecture
  348.                                                    (child_lp->ptid)))
  349.             {
  350.               linux_disable_event_reporting (child_pid);
  351.               if (ptrace (PTRACE_SINGLESTEP, child_pid, 0, 0) < 0)
  352.                 perror_with_name (_("Couldn't do single step"));
  353.               if (my_waitpid (child_pid, &status, 0) < 0)
  354.                 perror_with_name (_("Couldn't wait vfork process"));
  355.             }

  356.           if (WIFSTOPPED (status))
  357.             {
  358.               int signo;

  359.               signo = WSTOPSIG (status);
  360.               if (signo != 0
  361.                   && !signal_pass_state (gdb_signal_from_host (signo)))
  362.                 signo = 0;
  363.               ptrace (PTRACE_DETACH, child_pid, 0, signo);
  364.             }

  365.           /* Resets value of inferior_ptid to parent ptid.  */
  366.           do_cleanups (old_chain);
  367.         }
  368.       else
  369.         {
  370.           /* Let the thread_db layer learn about this new process.  */
  371.           check_for_thread_db ();
  372.         }

  373.       do_cleanups (old_chain);

  374.       if (has_vforked)
  375.         {
  376.           struct lwp_info *parent_lp;

  377.           parent_lp = find_lwp_pid (pid_to_ptid (parent_pid));
  378.           gdb_assert (linux_supports_tracefork () >= 0);

  379.           if (linux_supports_tracevforkdone ())
  380.             {
  381.                 if (debug_linux_nat)
  382.                   fprintf_unfiltered (gdb_stdlog,
  383.                                       "LCFF: waiting for VFORK_DONE on %d\n",
  384.                                       parent_pid);
  385.               parent_lp->stopped = 1;

  386.               /* We'll handle the VFORK_DONE event like any other
  387.                  event, in target_wait.  */
  388.             }
  389.           else
  390.             {
  391.               /* We can't insert breakpoints until the child has
  392.                  finished with the shared memory region.  We need to
  393.                  wait until that happens.  Ideal would be to just
  394.                  call:
  395.                  - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
  396.                  - waitpid (parent_pid, &status, __WALL);
  397.                  However, most architectures can't handle a syscall
  398.                  being traced on the way out if it wasn't traced on
  399.                  the way in.

  400.                  We might also think to loop, continuing the child
  401.                  until it exits or gets a SIGTRAP.  One problem is
  402.                  that the child might call ptrace with PTRACE_TRACEME.

  403.                  There's no simple and reliable way to figure out when
  404.                  the vforked child will be done with its copy of the
  405.                  shared memory.  We could step it out of the syscall,
  406.                  two instructions, let it go, and then single-step the
  407.                  parent once.  When we have hardware single-step, this
  408.                  would work; with software single-step it could still
  409.                  be made to work but we'd have to be able to insert
  410.                  single-step breakpoints in the child, and we'd have
  411.                  to insert -just- the single-step breakpoint in the
  412.                  parent.  Very awkward.

  413.                  In the end, the best we can do is to make sure it
  414.                  runs for a little while.  Hopefully it will be out of
  415.                  range of any breakpoints we reinsert.  Usually this
  416.                  is only the single-step breakpoint at vfork's return
  417.                  point.  */

  418.                 if (debug_linux_nat)
  419.                   fprintf_unfiltered (gdb_stdlog,
  420.                                     "LCFF: no VFORK_DONE "
  421.                                     "support, sleeping a bit\n");

  422.               usleep (10000);

  423.               /* Pretend we've seen a PTRACE_EVENT_VFORK_DONE event,
  424.                  and leave it pending.  The next linux_nat_resume call
  425.                  will notice a pending event, and bypasses actually
  426.                  resuming the inferior.  */
  427.               parent_lp->status = 0;
  428.               parent_lp->waitstatus.kind = TARGET_WAITKIND_VFORK_DONE;
  429.               parent_lp->stopped = 1;

  430.               /* If we're in async mode, need to tell the event loop
  431.                  there's something here to process.  */
  432.               if (target_can_async_p ())
  433.                 async_file_mark ();
  434.             }
  435.         }
  436.     }
  437.   else
  438.     {
  439.       struct lwp_info *child_lp;

  440.       child_lp = add_lwp (inferior_ptid);
  441.       child_lp->stopped = 1;
  442.       child_lp->last_resume_kind = resume_stop;

  443.       /* Let the thread_db layer learn about this new process.  */
  444.       check_for_thread_db ();
  445.     }

  446.   return 0;
  447. }


  448. static int
  449. linux_child_insert_fork_catchpoint (struct target_ops *self, int pid)
  450. {
  451.   return !linux_supports_tracefork ();
  452. }

  453. static int
  454. linux_child_remove_fork_catchpoint (struct target_ops *self, int pid)
  455. {
  456.   return 0;
  457. }

  458. static int
  459. linux_child_insert_vfork_catchpoint (struct target_ops *self, int pid)
  460. {
  461.   return !linux_supports_tracefork ();
  462. }

  463. static int
  464. linux_child_remove_vfork_catchpoint (struct target_ops *self, int pid)
  465. {
  466.   return 0;
  467. }

  468. static int
  469. linux_child_insert_exec_catchpoint (struct target_ops *self, int pid)
  470. {
  471.   return !linux_supports_tracefork ();
  472. }

  473. static int
  474. linux_child_remove_exec_catchpoint (struct target_ops *self, int pid)
  475. {
  476.   return 0;
  477. }

  478. static int
  479. linux_child_set_syscall_catchpoint (struct target_ops *self,
  480.                                     int pid, int needed, int any_count,
  481.                                     int table_size, int *table)
  482. {
  483.   if (!linux_supports_tracesysgood ())
  484.     return 1;

  485.   /* On GNU/Linux, we ignore the arguments.  It means that we only
  486.      enable the syscall catchpoints, but do not disable them.

  487.      Also, we do not use the `table' information because we do not
  488.      filter system calls here.  We let GDB do the logic for us.  */
  489.   return 0;
  490. }

  491. /* On GNU/Linux there are no real LWP's.  The closest thing to LWP's
  492.    are processes sharing the same VM space.  A multi-threaded process
  493.    is basically a group of such processes.  However, such a grouping
  494.    is almost entirely a user-space issue; the kernel doesn't enforce
  495.    such a grouping at all (this might change in the future).  In
  496.    general, we'll rely on the threads library (i.e. the GNU/Linux
  497.    Threads library) to provide such a grouping.

  498.    It is perfectly well possible to write a multi-threaded application
  499.    without the assistance of a threads library, by using the clone
  500.    system call directly.  This module should be able to give some
  501.    rudimentary support for debugging such applications if developers
  502.    specify the CLONE_PTRACE flag in the clone system call, and are
  503.    using the Linux kernel 2.4 or above.

  504.    Note that there are some peculiarities in GNU/Linux that affect
  505.    this code:

  506.    - In general one should specify the __WCLONE flag to waitpid in
  507.      order to make it report events for any of the cloned processes
  508.      (and leave it out for the initial process).  However, if a cloned
  509.      process has exited the exit status is only reported if the
  510.      __WCLONE flag is absent.  Linux kernel 2.4 has a __WALL flag, but
  511.      we cannot use it since GDB must work on older systems too.

  512.    - When a traced, cloned process exits and is waited for by the
  513.      debugger, the kernel reassigns it to the original parent and
  514.      keeps it around as a "zombie".  Somehow, the GNU/Linux Threads
  515.      library doesn't notice this, which leads to the "zombie problem":
  516.      When debugged a multi-threaded process that spawns a lot of
  517.      threads will run out of processes, even if the threads exit,
  518.      because the "zombies" stay around.  */

  519. /* List of known LWPs.  */
  520. struct lwp_info *lwp_list;


  521. /* Original signal mask.  */
  522. static sigset_t normal_mask;

  523. /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
  524.    _initialize_linux_nat.  */
  525. static sigset_t suspend_mask;

  526. /* Signals to block to make that sigsuspend work.  */
  527. static sigset_t blocked_mask;

  528. /* SIGCHLD action.  */
  529. struct sigaction sigchld_action;

  530. /* Block child signals (SIGCHLD and linux threads signals), and store
  531.    the previous mask in PREV_MASK.  */

  532. static void
  533. block_child_signals (sigset_t *prev_mask)
  534. {
  535.   /* Make sure SIGCHLD is blocked.  */
  536.   if (!sigismember (&blocked_mask, SIGCHLD))
  537.     sigaddset (&blocked_mask, SIGCHLD);

  538.   sigprocmask (SIG_BLOCK, &blocked_mask, prev_mask);
  539. }

  540. /* Restore child signals mask, previously returned by
  541.    block_child_signals.  */

  542. static void
  543. restore_child_signals_mask (sigset_t *prev_mask)
  544. {
  545.   sigprocmask (SIG_SETMASK, prev_mask, NULL);
  546. }

  547. /* Mask of signals to pass directly to the inferior.  */
  548. static sigset_t pass_mask;

  549. /* Update signals to pass to the inferior.  */
  550. static void
  551. linux_nat_pass_signals (struct target_ops *self,
  552.                         int numsigs, unsigned char *pass_signals)
  553. {
  554.   int signo;

  555.   sigemptyset (&pass_mask);

  556.   for (signo = 1; signo < NSIG; signo++)
  557.     {
  558.       int target_signo = gdb_signal_from_host (signo);
  559.       if (target_signo < numsigs && pass_signals[target_signo])
  560.         sigaddset (&pass_mask, signo);
  561.     }
  562. }



  563. /* Prototypes for local functions.  */
  564. static int stop_wait_callback (struct lwp_info *lp, void *data);
  565. static int linux_thread_alive (ptid_t ptid);
  566. static char *linux_child_pid_to_exec_file (struct target_ops *self, int pid);



  567. /* Destroy and free LP.  */

  568. static void
  569. lwp_free (struct lwp_info *lp)
  570. {
  571.   xfree (lp->arch_private);
  572.   xfree (lp);
  573. }

  574. /* Remove all LWPs belong to PID from the lwp list.  */

  575. static void
  576. purge_lwp_list (int pid)
  577. {
  578.   struct lwp_info *lp, *lpprev, *lpnext;

  579.   lpprev = NULL;

  580.   for (lp = lwp_list; lp; lp = lpnext)
  581.     {
  582.       lpnext = lp->next;

  583.       if (ptid_get_pid (lp->ptid) == pid)
  584.         {
  585.           if (lp == lwp_list)
  586.             lwp_list = lp->next;
  587.           else
  588.             lpprev->next = lp->next;

  589.           lwp_free (lp);
  590.         }
  591.       else
  592.         lpprev = lp;
  593.     }
  594. }

  595. /* Add the LWP specified by PTID to the list.  PTID is the first LWP
  596.    in the process.  Return a pointer to the structure describing the
  597.    new LWP.

  598.    This differs from add_lwp in that we don't let the arch specific
  599.    bits know about this new thread.  Current clients of this callback
  600.    take the opportunity to install watchpoints in the new thread, and
  601.    we shouldn't do that for the first thread.  If we're spawning a
  602.    child ("run"), the thread executes the shell wrapper first, and we
  603.    shouldn't touch it until it execs the program we want to debug.
  604.    For "attach", it'd be okay to call the callback, but it's not
  605.    necessary, because watchpoints can't yet have been inserted into
  606.    the inferior.  */

  607. static struct lwp_info *
  608. add_initial_lwp (ptid_t ptid)
  609. {
  610.   struct lwp_info *lp;

  611.   gdb_assert (ptid_lwp_p (ptid));

  612.   lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));

  613.   memset (lp, 0, sizeof (struct lwp_info));

  614.   lp->last_resume_kind = resume_continue;
  615.   lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;

  616.   lp->ptid = ptid;
  617.   lp->core = -1;

  618.   lp->next = lwp_list;
  619.   lwp_list = lp;

  620.   return lp;
  621. }

  622. /* Add the LWP specified by PID to the list.  Return a pointer to the
  623.    structure describing the new LWP.  The LWP should already be
  624.    stopped.  */

  625. static struct lwp_info *
  626. add_lwp (ptid_t ptid)
  627. {
  628.   struct lwp_info *lp;

  629.   lp = add_initial_lwp (ptid);

  630.   /* Let the arch specific bits know about this new thread.  Current
  631.      clients of this callback take the opportunity to install
  632.      watchpoints in the new thread.  We don't do this for the first
  633.      thread though.  See add_initial_lwp.  */
  634.   if (linux_nat_new_thread != NULL)
  635.     linux_nat_new_thread (lp);

  636.   return lp;
  637. }

  638. /* Remove the LWP specified by PID from the list.  */

  639. static void
  640. delete_lwp (ptid_t ptid)
  641. {
  642.   struct lwp_info *lp, *lpprev;

  643.   lpprev = NULL;

  644.   for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
  645.     if (ptid_equal (lp->ptid, ptid))
  646.       break;

  647.   if (!lp)
  648.     return;

  649.   if (lpprev)
  650.     lpprev->next = lp->next;
  651.   else
  652.     lwp_list = lp->next;

  653.   lwp_free (lp);
  654. }

  655. /* Return a pointer to the structure describing the LWP corresponding
  656.    to PID.  If no corresponding LWP could be found, return NULL.  */

  657. static struct lwp_info *
  658. find_lwp_pid (ptid_t ptid)
  659. {
  660.   struct lwp_info *lp;
  661.   int lwp;

  662.   if (ptid_lwp_p (ptid))
  663.     lwp = ptid_get_lwp (ptid);
  664.   else
  665.     lwp = ptid_get_pid (ptid);

  666.   for (lp = lwp_list; lp; lp = lp->next)
  667.     if (lwp == ptid_get_lwp (lp->ptid))
  668.       return lp;

  669.   return NULL;
  670. }

  671. /* Call CALLBACK with its second argument set to DATA for every LWP in
  672.    the list.  If CALLBACK returns 1 for a particular LWP, return a
  673.    pointer to the structure describing that LWP immediately.
  674.    Otherwise return NULL.  */

  675. struct lwp_info *
  676. iterate_over_lwps (ptid_t filter,
  677.                    int (*callback) (struct lwp_info *, void *),
  678.                    void *data)
  679. {
  680.   struct lwp_info *lp, *lpnext;

  681.   for (lp = lwp_list; lp; lp = lpnext)
  682.     {
  683.       lpnext = lp->next;

  684.       if (ptid_match (lp->ptid, filter))
  685.         {
  686.           if ((*callback) (lp, data))
  687.             return lp;
  688.         }
  689.     }

  690.   return NULL;
  691. }

  692. /* Update our internal state when changing from one checkpoint to
  693.    another indicated by NEW_PTID.  We can only switch single-threaded
  694.    applications, so we only create one new LWP, and the previous list
  695.    is discarded.  */

  696. void
  697. linux_nat_switch_fork (ptid_t new_ptid)
  698. {
  699.   struct lwp_info *lp;

  700.   purge_lwp_list (ptid_get_pid (inferior_ptid));

  701.   lp = add_lwp (new_ptid);
  702.   lp->stopped = 1;

  703.   /* This changes the thread's ptid while preserving the gdb thread
  704.      num.  Also changes the inferior pid, while preserving the
  705.      inferior num.  */
  706.   thread_change_ptid (inferior_ptid, new_ptid);

  707.   /* We've just told GDB core that the thread changed target id, but,
  708.      in fact, it really is a different thread, with different register
  709.      contents.  */
  710.   registers_changed ();
  711. }

  712. /* Handle the exit of a single thread LP.  */

  713. static void
  714. exit_lwp (struct lwp_info *lp)
  715. {
  716.   struct thread_info *th = find_thread_ptid (lp->ptid);

  717.   if (th)
  718.     {
  719.       if (print_thread_events)
  720.         printf_unfiltered (_("[%s exited]\n"), target_pid_to_str (lp->ptid));

  721.       delete_thread (lp->ptid);
  722.     }

  723.   delete_lwp (lp->ptid);
  724. }

  725. /* Wait for the LWP specified by LP, which we have just attached to.
  726.    Returns a wait status for that LWP, to cache.  */

  727. static int
  728. linux_nat_post_attach_wait (ptid_t ptid, int first, int *cloned,
  729.                             int *signalled)
  730. {
  731.   pid_t new_pid, pid = ptid_get_lwp (ptid);
  732.   int status;

  733.   if (linux_proc_pid_is_stopped (pid))
  734.     {
  735.       if (debug_linux_nat)
  736.         fprintf_unfiltered (gdb_stdlog,
  737.                             "LNPAW: Attaching to a stopped process\n");

  738.       /* The process is definitely stopped.  It is in a job control
  739.          stop, unless the kernel predates the TASK_STOPPED /
  740.          TASK_TRACED distinction, in which case it might be in a
  741.          ptrace stop.  Make sure it is in a ptrace stop; from there we
  742.          can kill it, signal it, et cetera.

  743.          First make sure there is a pending SIGSTOP.  Since we are
  744.          already attached, the process can not transition from stopped
  745.          to running without a PTRACE_CONT; so we know this signal will
  746.          go into the queue.  The SIGSTOP generated by PTRACE_ATTACH is
  747.          probably already in the queue (unless this kernel is old
  748.          enough to use TASK_STOPPED for ptrace stops); but since SIGSTOP
  749.          is not an RT signal, it can only be queued once.  */
  750.       kill_lwp (pid, SIGSTOP);

  751.       /* Finally, resume the stopped process.  This will deliver the SIGSTOP
  752.          (or a higher priority signal, just like normal PTRACE_ATTACH).  */
  753.       ptrace (PTRACE_CONT, pid, 0, 0);
  754.     }

  755.   /* Make sure the initial process is stopped.  The user-level threads
  756.      layer might want to poke around in the inferior, and that won't
  757.      work if things haven't stabilized yet.  */
  758.   new_pid = my_waitpid (pid, &status, 0);
  759.   if (new_pid == -1 && errno == ECHILD)
  760.     {
  761.       if (first)
  762.         warning (_("%s is a cloned process"), target_pid_to_str (ptid));

  763.       /* Try again with __WCLONE to check cloned processes.  */
  764.       new_pid = my_waitpid (pid, &status, __WCLONE);
  765.       *cloned = 1;
  766.     }

  767.   gdb_assert (pid == new_pid);

  768.   if (!WIFSTOPPED (status))
  769.     {
  770.       /* The pid we tried to attach has apparently just exited.  */
  771.       if (debug_linux_nat)
  772.         fprintf_unfiltered (gdb_stdlog, "LNPAW: Failed to stop %d: %s",
  773.                             pid, status_to_str (status));
  774.       return status;
  775.     }

  776.   if (WSTOPSIG (status) != SIGSTOP)
  777.     {
  778.       *signalled = 1;
  779.       if (debug_linux_nat)
  780.         fprintf_unfiltered (gdb_stdlog,
  781.                             "LNPAW: Received %s after attaching\n",
  782.                             status_to_str (status));
  783.     }

  784.   return status;
  785. }

  786. /* Attach to the LWP specified by PID.  Return 0 if successful, -1 if
  787.    the new LWP could not be attached, or 1 if we're already auto
  788.    attached to this thread, but haven't processed the
  789.    PTRACE_EVENT_CLONE event of its parent thread, so we just ignore
  790.    its existance, without considering it an error.  */

  791. int
  792. lin_lwp_attach_lwp (ptid_t ptid)
  793. {
  794.   struct lwp_info *lp;
  795.   int lwpid;

  796.   gdb_assert (ptid_lwp_p (ptid));

  797.   lp = find_lwp_pid (ptid);
  798.   lwpid = ptid_get_lwp (ptid);

  799.   /* We assume that we're already attached to any LWP that has an id
  800.      equal to the overall process id, and to any LWP that is already
  801.      in our list of LWPs.  If we're not seeing exit events from threads
  802.      and we've had PID wraparound since we last tried to stop all threads,
  803.      this assumption might be wrong; fortunately, this is very unlikely
  804.      to happen.  */
  805.   if (lwpid != ptid_get_pid (ptid) && lp == NULL)
  806.     {
  807.       int status, cloned = 0, signalled = 0;

  808.       if (ptrace (PTRACE_ATTACH, lwpid, 0, 0) < 0)
  809.         {
  810.           if (linux_supports_tracefork ())
  811.             {
  812.               /* If we haven't stopped all threads when we get here,
  813.                  we may have seen a thread listed in thread_db's list,
  814.                  but not processed the PTRACE_EVENT_CLONE yet.  If
  815.                  that's the case, ignore this new thread, and let
  816.                  normal event handling discover it later.  */
  817.               if (in_pid_list_p (stopped_pids, lwpid))
  818.                 {
  819.                   /* We've already seen this thread stop, but we
  820.                      haven't seen the PTRACE_EVENT_CLONE extended
  821.                      event yet.  */
  822.                   return 0;
  823.                 }
  824.               else
  825.                 {
  826.                   int new_pid;
  827.                   int status;

  828.                   /* See if we've got a stop for this new child
  829.                      pending.  If so, we're already attached.  */
  830.                   gdb_assert (lwpid > 0);
  831.                   new_pid = my_waitpid (lwpid, &status, WNOHANG);
  832.                   if (new_pid == -1 && errno == ECHILD)
  833.                     new_pid = my_waitpid (lwpid, &status, __WCLONE | WNOHANG);
  834.                   if (new_pid != -1)
  835.                     {
  836.                       if (WIFSTOPPED (status))
  837.                         add_to_pid_list (&stopped_pids, lwpid, status);
  838.                       return 1;
  839.                     }
  840.                 }
  841.             }

  842.           /* If we fail to attach to the thread, issue a warning,
  843.              but continue.  One way this can happen is if thread
  844.              creation is interrupted; as of Linux kernel 2.6.19, a
  845.              bug may place threads in the thread list and then fail
  846.              to create them.  */
  847.           warning (_("Can't attach %s: %s"), target_pid_to_str (ptid),
  848.                    safe_strerror (errno));
  849.           return -1;
  850.         }

  851.       if (debug_linux_nat)
  852.         fprintf_unfiltered (gdb_stdlog,
  853.                             "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
  854.                             target_pid_to_str (ptid));

  855.       status = linux_nat_post_attach_wait (ptid, 0, &cloned, &signalled);
  856.       if (!WIFSTOPPED (status))
  857.         return 1;

  858.       lp = add_lwp (ptid);
  859.       lp->stopped = 1;
  860.       lp->cloned = cloned;
  861.       lp->signalled = signalled;
  862.       if (WSTOPSIG (status) != SIGSTOP)
  863.         {
  864.           lp->resumed = 1;
  865.           lp->status = status;
  866.         }

  867.       target_post_attach (ptid_get_lwp (lp->ptid));

  868.       if (debug_linux_nat)
  869.         {
  870.           fprintf_unfiltered (gdb_stdlog,
  871.                               "LLAL: waitpid %s received %s\n",
  872.                               target_pid_to_str (ptid),
  873.                               status_to_str (status));
  874.         }
  875.     }
  876.   else
  877.     {
  878.       /* We assume that the LWP representing the original process is
  879.          already stopped.  Mark it as stopped in the data structure
  880.          that the GNU/linux ptrace layer uses to keep track of
  881.          threads.  Note that this won't have already been done since
  882.          the main thread will have, we assume, been stopped by an
  883.          attach from a different layer.  */
  884.       if (lp == NULL)
  885.         lp = add_lwp (ptid);
  886.       lp->stopped = 1;
  887.     }

  888.   lp->last_resume_kind = resume_stop;
  889.   return 0;
  890. }

  891. static void
  892. linux_nat_create_inferior (struct target_ops *ops,
  893.                            char *exec_file, char *allargs, char **env,
  894.                            int from_tty)
  895. {
  896. #ifdef HAVE_PERSONALITY
  897.   int personality_orig = 0, personality_set = 0;
  898. #endif /* HAVE_PERSONALITY */

  899.   /* The fork_child mechanism is synchronous and calls target_wait, so
  900.      we have to mask the async mode.  */

  901. #ifdef HAVE_PERSONALITY
  902.   if (disable_randomization)
  903.     {
  904.       errno = 0;
  905.       personality_orig = personality (0xffffffff);
  906.       if (errno == 0 && !(personality_orig & ADDR_NO_RANDOMIZE))
  907.         {
  908.           personality_set = 1;
  909.           personality (personality_orig | ADDR_NO_RANDOMIZE);
  910.         }
  911.       if (errno != 0 || (personality_set
  912.                          && !(personality (0xffffffff) & ADDR_NO_RANDOMIZE)))
  913.         warning (_("Error disabling address space randomization: %s"),
  914.                  safe_strerror (errno));
  915.     }
  916. #endif /* HAVE_PERSONALITY */

  917.   /* Make sure we report all signals during startup.  */
  918.   linux_nat_pass_signals (ops, 0, NULL);

  919.   linux_ops->to_create_inferior (ops, exec_file, allargs, env, from_tty);

  920. #ifdef HAVE_PERSONALITY
  921.   if (personality_set)
  922.     {
  923.       errno = 0;
  924.       personality (personality_orig);
  925.       if (errno != 0)
  926.         warning (_("Error restoring address space randomization: %s"),
  927.                  safe_strerror (errno));
  928.     }
  929. #endif /* HAVE_PERSONALITY */
  930. }

  931. /* Callback for linux_proc_attach_tgid_threads.  Attach to PTID if not
  932.    already attached.  Returns true if a new LWP is found, false
  933.    otherwise.  */

  934. static int
  935. attach_proc_task_lwp_callback (ptid_t ptid)
  936. {
  937.   struct lwp_info *lp;

  938.   /* Ignore LWPs we're already attached to.  */
  939.   lp = find_lwp_pid (ptid);
  940.   if (lp == NULL)
  941.     {
  942.       int lwpid = ptid_get_lwp (ptid);

  943.       if (ptrace (PTRACE_ATTACH, lwpid, 0, 0) < 0)
  944.         {
  945.           int err = errno;

  946.           /* Be quiet if we simply raced with the thread exiting.
  947.              EPERM is returned if the thread's task still exists, and
  948.              is marked as exited or zombie, as well as other
  949.              conditions, so in that case, confirm the status in
  950.              /proc/PID/status.  */
  951.           if (err == ESRCH
  952.               || (err == EPERM && linux_proc_pid_is_gone (lwpid)))
  953.             {
  954.               if (debug_linux_nat)
  955.                 {
  956.                   fprintf_unfiltered (gdb_stdlog,
  957.                                       "Cannot attach to lwp %d: "
  958.                                       "thread is gone (%d: %s)\n",
  959.                                       lwpid, err, safe_strerror (err));
  960.                 }
  961.             }
  962.           else
  963.             {
  964.               warning (_("Cannot attach to lwp %d: %s\n"),
  965.                        lwpid,
  966.                        linux_ptrace_attach_fail_reason_string (ptid,
  967.                                                                err));
  968.             }
  969.         }
  970.       else
  971.         {
  972.           if (debug_linux_nat)
  973.             fprintf_unfiltered (gdb_stdlog,
  974.                                 "PTRACE_ATTACH %s, 0, 0 (OK)\n",
  975.                                 target_pid_to_str (ptid));

  976.           lp = add_lwp (ptid);
  977.           lp->cloned = 1;

  978.           /* The next time we wait for this LWP we'll see a SIGSTOP as
  979.              PTRACE_ATTACH brings it to a halt.  */
  980.           lp->signalled = 1;

  981.           /* We need to wait for a stop before being able to make the
  982.              next ptrace call on this LWP.  */
  983.           lp->must_set_ptrace_flags = 1;
  984.         }

  985.       return 1;
  986.     }
  987.   return 0;
  988. }

  989. static void
  990. linux_nat_attach (struct target_ops *ops, const char *args, int from_tty)
  991. {
  992.   struct lwp_info *lp;
  993.   int status;
  994.   ptid_t ptid;
  995.   volatile struct gdb_exception ex;

  996.   /* Make sure we report all signals during attach.  */
  997.   linux_nat_pass_signals (ops, 0, NULL);

  998.   TRY_CATCH (ex, RETURN_MASK_ERROR)
  999.     {
  1000.       linux_ops->to_attach (ops, args, from_tty);
  1001.     }
  1002.   if (ex.reason < 0)
  1003.     {
  1004.       pid_t pid = parse_pid_to_attach (args);
  1005.       struct buffer buffer;
  1006.       char *message, *buffer_s;

  1007.       message = xstrdup (ex.message);
  1008.       make_cleanup (xfree, message);

  1009.       buffer_init (&buffer);
  1010.       linux_ptrace_attach_fail_reason (pid, &buffer);

  1011.       buffer_grow_str0 (&buffer, "");
  1012.       buffer_s = buffer_finish (&buffer);
  1013.       make_cleanup (xfree, buffer_s);

  1014.       if (*buffer_s != '\0')
  1015.         throw_error (ex.error, "warning: %s\n%s", buffer_s, message);
  1016.       else
  1017.         throw_error (ex.error, "%s", message);
  1018.     }

  1019.   /* The ptrace base target adds the main thread with (pid,0,0)
  1020.      format.  Decorate it with lwp info.  */
  1021.   ptid = ptid_build (ptid_get_pid (inferior_ptid),
  1022.                      ptid_get_pid (inferior_ptid),
  1023.                      0);
  1024.   thread_change_ptid (inferior_ptid, ptid);

  1025.   /* Add the initial process as the first LWP to the list.  */
  1026.   lp = add_initial_lwp (ptid);

  1027.   status = linux_nat_post_attach_wait (lp->ptid, 1, &lp->cloned,
  1028.                                        &lp->signalled);
  1029.   if (!WIFSTOPPED (status))
  1030.     {
  1031.       if (WIFEXITED (status))
  1032.         {
  1033.           int exit_code = WEXITSTATUS (status);

  1034.           target_terminal_ours ();
  1035.           target_mourn_inferior ();
  1036.           if (exit_code == 0)
  1037.             error (_("Unable to attach: program exited normally."));
  1038.           else
  1039.             error (_("Unable to attach: program exited with code %d."),
  1040.                    exit_code);
  1041.         }
  1042.       else if (WIFSIGNALED (status))
  1043.         {
  1044.           enum gdb_signal signo;

  1045.           target_terminal_ours ();
  1046.           target_mourn_inferior ();

  1047.           signo = gdb_signal_from_host (WTERMSIG (status));
  1048.           error (_("Unable to attach: program terminated with signal "
  1049.                    "%s, %s."),
  1050.                  gdb_signal_to_name (signo),
  1051.                  gdb_signal_to_string (signo));
  1052.         }

  1053.       internal_error (__FILE__, __LINE__,
  1054.                       _("unexpected status %d for PID %ld"),
  1055.                       status, (long) ptid_get_lwp (ptid));
  1056.     }

  1057.   lp->stopped = 1;

  1058.   /* Save the wait status to report later.  */
  1059.   lp->resumed = 1;
  1060.   if (debug_linux_nat)
  1061.     fprintf_unfiltered (gdb_stdlog,
  1062.                         "LNA: waitpid %ld, saving status %s\n",
  1063.                         (long) ptid_get_pid (lp->ptid), status_to_str (status));

  1064.   lp->status = status;

  1065.   /* We must attach to every LWP.  If /proc is mounted, use that to
  1066.      find them now.  The inferior may be using raw clone instead of
  1067.      using pthreads.  But even if it is using pthreads, thread_db
  1068.      walks structures in the inferior's address space to find the list
  1069.      of threads/LWPs, and those structures may well be corrupted.
  1070.      Note that once thread_db is loaded, we'll still use it to list
  1071.      threads and associate pthread info with each LWP.  */
  1072.   linux_proc_attach_tgid_threads (ptid_get_pid (lp->ptid),
  1073.                                   attach_proc_task_lwp_callback);

  1074.   if (target_can_async_p ())
  1075.     target_async (inferior_event_handler, 0);
  1076. }

  1077. /* Get pending status of LP.  */
  1078. static int
  1079. get_pending_status (struct lwp_info *lp, int *status)
  1080. {
  1081.   enum gdb_signal signo = GDB_SIGNAL_0;

  1082.   /* If we paused threads momentarily, we may have stored pending
  1083.      events in lp->status or lp->waitstatus (see stop_wait_callback),
  1084.      and GDB core hasn't seen any signal for those threads.
  1085.      Otherwise, the last signal reported to the core is found in the
  1086.      thread object's stop_signal.

  1087.      There's a corner case that isn't handled here at present.  Only
  1088.      if the thread stopped with a TARGET_WAITKIND_STOPPED does
  1089.      stop_signal make sense as a real signal to pass to the inferior.
  1090.      Some catchpoint related events, like
  1091.      TARGET_WAITKIND_(V)FORK|EXEC|SYSCALL, have their stop_signal set
  1092.      to GDB_SIGNAL_SIGTRAP when the catchpoint triggers.  But,
  1093.      those traps are debug API (ptrace in our case) related and
  1094.      induced; the inferior wouldn't see them if it wasn't being
  1095.      traced.  Hence, we should never pass them to the inferior, even
  1096.      when set to pass state.  Since this corner case isn't handled by
  1097.      infrun.c when proceeding with a signal, for consistency, neither
  1098.      do we handle it here (or elsewhere in the file we check for
  1099.      signal pass state).  Normally SIGTRAP isn't set to pass state, so
  1100.      this is really a corner case.  */

  1101.   if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
  1102.     signo = GDB_SIGNAL_0; /* a pending ptrace event, not a real signal.  */
  1103.   else if (lp->status)
  1104.     signo = gdb_signal_from_host (WSTOPSIG (lp->status));
  1105.   else if (non_stop && !is_executing (lp->ptid))
  1106.     {
  1107.       struct thread_info *tp = find_thread_ptid (lp->ptid);

  1108.       signo = tp->suspend.stop_signal;
  1109.     }
  1110.   else if (!non_stop)
  1111.     {
  1112.       struct target_waitstatus last;
  1113.       ptid_t last_ptid;

  1114.       get_last_target_status (&last_ptid, &last);

  1115.       if (ptid_get_lwp (lp->ptid) == ptid_get_lwp (last_ptid))
  1116.         {
  1117.           struct thread_info *tp = find_thread_ptid (lp->ptid);

  1118.           signo = tp->suspend.stop_signal;
  1119.         }
  1120.     }

  1121.   *status = 0;

  1122.   if (signo == GDB_SIGNAL_0)
  1123.     {
  1124.       if (debug_linux_nat)
  1125.         fprintf_unfiltered (gdb_stdlog,
  1126.                             "GPT: lwp %s has no pending signal\n",
  1127.                             target_pid_to_str (lp->ptid));
  1128.     }
  1129.   else if (!signal_pass_state (signo))
  1130.     {
  1131.       if (debug_linux_nat)
  1132.         fprintf_unfiltered (gdb_stdlog,
  1133.                             "GPT: lwp %s had signal %s, "
  1134.                             "but it is in no pass state\n",
  1135.                             target_pid_to_str (lp->ptid),
  1136.                             gdb_signal_to_string (signo));
  1137.     }
  1138.   else
  1139.     {
  1140.       *status = W_STOPCODE (gdb_signal_to_host (signo));

  1141.       if (debug_linux_nat)
  1142.         fprintf_unfiltered (gdb_stdlog,
  1143.                             "GPT: lwp %s has pending signal %s\n",
  1144.                             target_pid_to_str (lp->ptid),
  1145.                             gdb_signal_to_string (signo));
  1146.     }

  1147.   return 0;
  1148. }

  1149. static int
  1150. detach_callback (struct lwp_info *lp, void *data)
  1151. {
  1152.   gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));

  1153.   if (debug_linux_nat && lp->status)
  1154.     fprintf_unfiltered (gdb_stdlog, "DC:  Pending %s for %s on detach.\n",
  1155.                         strsignal (WSTOPSIG (lp->status)),
  1156.                         target_pid_to_str (lp->ptid));

  1157.   /* If there is a pending SIGSTOP, get rid of it.  */
  1158.   if (lp->signalled)
  1159.     {
  1160.       if (debug_linux_nat)
  1161.         fprintf_unfiltered (gdb_stdlog,
  1162.                             "DC: Sending SIGCONT to %s\n",
  1163.                             target_pid_to_str (lp->ptid));

  1164.       kill_lwp (ptid_get_lwp (lp->ptid), SIGCONT);
  1165.       lp->signalled = 0;
  1166.     }

  1167.   /* We don't actually detach from the LWP that has an id equal to the
  1168.      overall process id just yet.  */
  1169.   if (ptid_get_lwp (lp->ptid) != ptid_get_pid (lp->ptid))
  1170.     {
  1171.       int status = 0;

  1172.       /* Pass on any pending signal for this LWP.  */
  1173.       get_pending_status (lp, &status);

  1174.       if (linux_nat_prepare_to_resume != NULL)
  1175.         linux_nat_prepare_to_resume (lp);
  1176.       errno = 0;
  1177.       if (ptrace (PTRACE_DETACH, ptid_get_lwp (lp->ptid), 0,
  1178.                   WSTOPSIG (status)) < 0)
  1179.         error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
  1180.                safe_strerror (errno));

  1181.       if (debug_linux_nat)
  1182.         fprintf_unfiltered (gdb_stdlog,
  1183.                             "PTRACE_DETACH (%s, %s, 0) (OK)\n",
  1184.                             target_pid_to_str (lp->ptid),
  1185.                             strsignal (WSTOPSIG (status)));

  1186.       delete_lwp (lp->ptid);
  1187.     }

  1188.   return 0;
  1189. }

  1190. static void
  1191. linux_nat_detach (struct target_ops *ops, const char *args, int from_tty)
  1192. {
  1193.   int pid;
  1194.   int status;
  1195.   struct lwp_info *main_lwp;

  1196.   pid = ptid_get_pid (inferior_ptid);

  1197.   /* Don't unregister from the event loop, as there may be other
  1198.      inferiors running. */

  1199.   /* Stop all threads before detaching.  ptrace requires that the
  1200.      thread is stopped to sucessfully detach.  */
  1201.   iterate_over_lwps (pid_to_ptid (pid), stop_callback, NULL);
  1202.   /* ... and wait until all of them have reported back that
  1203.      they're no longer running.  */
  1204.   iterate_over_lwps (pid_to_ptid (pid), stop_wait_callback, NULL);

  1205.   iterate_over_lwps (pid_to_ptid (pid), detach_callback, NULL);

  1206.   /* Only the initial process should be left right now.  */
  1207.   gdb_assert (num_lwps (ptid_get_pid (inferior_ptid)) == 1);

  1208.   main_lwp = find_lwp_pid (pid_to_ptid (pid));

  1209.   /* Pass on any pending signal for the last LWP.  */
  1210.   if ((args == NULL || *args == '\0')
  1211.       && get_pending_status (main_lwp, &status) != -1
  1212.       && WIFSTOPPED (status))
  1213.     {
  1214.       char *tem;

  1215.       /* Put the signal number in ARGS so that inf_ptrace_detach will
  1216.          pass it along with PTRACE_DETACH.  */
  1217.       tem = alloca (8);
  1218.       xsnprintf (tem, 8, "%d", (int) WSTOPSIG (status));
  1219.       args = tem;
  1220.       if (debug_linux_nat)
  1221.         fprintf_unfiltered (gdb_stdlog,
  1222.                             "LND: Sending signal %s to %s\n",
  1223.                             args,
  1224.                             target_pid_to_str (main_lwp->ptid));
  1225.     }

  1226.   if (linux_nat_prepare_to_resume != NULL)
  1227.     linux_nat_prepare_to_resume (main_lwp);
  1228.   delete_lwp (main_lwp->ptid);

  1229.   if (forks_exist_p ())
  1230.     {
  1231.       /* Multi-fork case.  The current inferior_ptid is being detached
  1232.          from, but there are other viable forks to debug.  Detach from
  1233.          the current fork, and context-switch to the first
  1234.          available.  */
  1235.       linux_fork_detach (args, from_tty);
  1236.     }
  1237.   else
  1238.     linux_ops->to_detach (ops, args, from_tty);
  1239. }

  1240. /* Resume execution of the inferior process.  If STEP is nonzero,
  1241.    single-step it.  If SIGNAL is nonzero, give it that signal.  */

  1242. static void
  1243. linux_resume_one_lwp (struct lwp_info *lp, int step, enum gdb_signal signo)
  1244. {
  1245.   ptid_t ptid;

  1246.   lp->step = step;

  1247.   /* stop_pc doubles as the PC the LWP had when it was last resumed.
  1248.      We only presently need that if the LWP is stepped though (to
  1249.      handle the case of stepping a breakpoint instruction).  */
  1250.   if (step)
  1251.     {
  1252.       struct regcache *regcache = get_thread_regcache (lp->ptid);

  1253.       lp->stop_pc = regcache_read_pc (regcache);
  1254.     }
  1255.   else
  1256.     lp->stop_pc = 0;

  1257.   if (linux_nat_prepare_to_resume != NULL)
  1258.     linux_nat_prepare_to_resume (lp);
  1259.   /* Convert to something the lower layer understands.  */
  1260.   ptid = pid_to_ptid (ptid_get_lwp (lp->ptid));
  1261.   linux_ops->to_resume (linux_ops, ptid, step, signo);
  1262.   lp->stop_reason = LWP_STOPPED_BY_NO_REASON;
  1263.   lp->stopped = 0;
  1264.   registers_changed_ptid (lp->ptid);
  1265. }

  1266. /* Resume LP.  */

  1267. static void
  1268. resume_lwp (struct lwp_info *lp, int step, enum gdb_signal signo)
  1269. {
  1270.   if (lp->stopped)
  1271.     {
  1272.       struct inferior *inf = find_inferior_ptid (lp->ptid);

  1273.       if (inf->vfork_child != NULL)
  1274.         {
  1275.           if (debug_linux_nat)
  1276.             fprintf_unfiltered (gdb_stdlog,
  1277.                                 "RC: Not resuming %s (vfork parent)\n",
  1278.                                 target_pid_to_str (lp->ptid));
  1279.         }
  1280.       else if (!lwp_status_pending_p (lp))
  1281.         {
  1282.           if (debug_linux_nat)
  1283.             fprintf_unfiltered (gdb_stdlog,
  1284.                                 "RC: Resuming sibling %s, %s, %s\n",
  1285.                                 target_pid_to_str (lp->ptid),
  1286.                                 (signo != GDB_SIGNAL_0
  1287.                                  ? strsignal (gdb_signal_to_host (signo))
  1288.                                  : "0"),
  1289.                                 step ? "step" : "resume");

  1290.           linux_resume_one_lwp (lp, step, signo);
  1291.         }
  1292.       else
  1293.         {
  1294.           if (debug_linux_nat)
  1295.             fprintf_unfiltered (gdb_stdlog,
  1296.                                 "RC: Not resuming sibling %s (has pending)\n",
  1297.                                 target_pid_to_str (lp->ptid));
  1298.         }
  1299.     }
  1300.   else
  1301.     {
  1302.       if (debug_linux_nat)
  1303.         fprintf_unfiltered (gdb_stdlog,
  1304.                             "RC: Not resuming sibling %s (not stopped)\n",
  1305.                             target_pid_to_str (lp->ptid));
  1306.     }
  1307. }

  1308. /* Callback for iterate_over_lwps.  If LWP is EXCEPT, do nothing.
  1309.    Resume LWP with the last stop signal, if it is in pass state.  */

  1310. static int
  1311. linux_nat_resume_callback (struct lwp_info *lp, void *except)
  1312. {
  1313.   enum gdb_signal signo = GDB_SIGNAL_0;

  1314.   if (lp == except)
  1315.     return 0;

  1316.   if (lp->stopped)
  1317.     {
  1318.       struct thread_info *thread;

  1319.       thread = find_thread_ptid (lp->ptid);
  1320.       if (thread != NULL)
  1321.         {
  1322.           signo = thread->suspend.stop_signal;
  1323.           thread->suspend.stop_signal = GDB_SIGNAL_0;
  1324.         }
  1325.     }

  1326.   resume_lwp (lp, 0, signo);
  1327.   return 0;
  1328. }

  1329. static int
  1330. resume_clear_callback (struct lwp_info *lp, void *data)
  1331. {
  1332.   lp->resumed = 0;
  1333.   lp->last_resume_kind = resume_stop;
  1334.   return 0;
  1335. }

  1336. static int
  1337. resume_set_callback (struct lwp_info *lp, void *data)
  1338. {
  1339.   lp->resumed = 1;
  1340.   lp->last_resume_kind = resume_continue;
  1341.   return 0;
  1342. }

  1343. static void
  1344. linux_nat_resume (struct target_ops *ops,
  1345.                   ptid_t ptid, int step, enum gdb_signal signo)
  1346. {
  1347.   struct lwp_info *lp;
  1348.   int resume_many;

  1349.   if (debug_linux_nat)
  1350.     fprintf_unfiltered (gdb_stdlog,
  1351.                         "LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
  1352.                         step ? "step" : "resume",
  1353.                         target_pid_to_str (ptid),
  1354.                         (signo != GDB_SIGNAL_0
  1355.                          ? strsignal (gdb_signal_to_host (signo)) : "0"),
  1356.                         target_pid_to_str (inferior_ptid));

  1357.   /* A specific PTID means `step only this process id'.  */
  1358.   resume_many = (ptid_equal (minus_one_ptid, ptid)
  1359.                  || ptid_is_pid (ptid));

  1360.   /* Mark the lwps we're resuming as resumed.  */
  1361.   iterate_over_lwps (ptid, resume_set_callback, NULL);

  1362.   /* See if it's the current inferior that should be handled
  1363.      specially.  */
  1364.   if (resume_many)
  1365.     lp = find_lwp_pid (inferior_ptid);
  1366.   else
  1367.     lp = find_lwp_pid (ptid);
  1368.   gdb_assert (lp != NULL);

  1369.   /* Remember if we're stepping.  */
  1370.   lp->last_resume_kind = step ? resume_step : resume_continue;

  1371.   /* If we have a pending wait status for this thread, there is no
  1372.      point in resuming the process.  But first make sure that
  1373.      linux_nat_wait won't preemptively handle the event - we
  1374.      should never take this short-circuit if we are going to
  1375.      leave LP running, since we have skipped resuming all the
  1376.      other threads.  This bit of code needs to be synchronized
  1377.      with linux_nat_wait.  */

  1378.   if (lp->status && WIFSTOPPED (lp->status))
  1379.     {
  1380.       if (!lp->step
  1381.           && WSTOPSIG (lp->status)
  1382.           && sigismember (&pass_mask, WSTOPSIG (lp->status)))
  1383.         {
  1384.           if (debug_linux_nat)
  1385.             fprintf_unfiltered (gdb_stdlog,
  1386.                                 "LLR: Not short circuiting for ignored "
  1387.                                 "status 0x%x\n", lp->status);

  1388.           /* FIXME: What should we do if we are supposed to continue
  1389.              this thread with a signal?  */
  1390.           gdb_assert (signo == GDB_SIGNAL_0);
  1391.           signo = gdb_signal_from_host (WSTOPSIG (lp->status));
  1392.           lp->status = 0;
  1393.         }
  1394.     }

  1395.   if (lwp_status_pending_p (lp))
  1396.     {
  1397.       /* FIXME: What should we do if we are supposed to continue
  1398.          this thread with a signal?  */
  1399.       gdb_assert (signo == GDB_SIGNAL_0);

  1400.       if (debug_linux_nat)
  1401.         fprintf_unfiltered (gdb_stdlog,
  1402.                             "LLR: Short circuiting for status 0x%x\n",
  1403.                             lp->status);

  1404.       if (target_can_async_p ())
  1405.         {
  1406.           target_async (inferior_event_handler, 0);
  1407.           /* Tell the event loop we have something to process.  */
  1408.           async_file_mark ();
  1409.         }
  1410.       return;
  1411.     }

  1412.   if (resume_many)
  1413.     iterate_over_lwps (ptid, linux_nat_resume_callback, lp);

  1414.   linux_resume_one_lwp (lp, step, signo);

  1415.   if (debug_linux_nat)
  1416.     fprintf_unfiltered (gdb_stdlog,
  1417.                         "LLR: %s %s, %s (resume event thread)\n",
  1418.                         step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
  1419.                         target_pid_to_str (ptid),
  1420.                         (signo != GDB_SIGNAL_0
  1421.                          ? strsignal (gdb_signal_to_host (signo)) : "0"));

  1422.   if (target_can_async_p ())
  1423.     target_async (inferior_event_handler, 0);
  1424. }

  1425. /* Send a signal to an LWP.  */

  1426. static int
  1427. kill_lwp (int lwpid, int signo)
  1428. {
  1429.   /* Use tkill, if possible, in case we are using nptl threads.  If tkill
  1430.      fails, then we are not using nptl threads and we should be using kill.  */

  1431. #ifdef HAVE_TKILL_SYSCALL
  1432.   {
  1433.     static int tkill_failed;

  1434.     if (!tkill_failed)
  1435.       {
  1436.         int ret;

  1437.         errno = 0;
  1438.         ret = syscall (__NR_tkill, lwpid, signo);
  1439.         if (errno != ENOSYS)
  1440.           return ret;
  1441.         tkill_failed = 1;
  1442.       }
  1443.   }
  1444. #endif

  1445.   return kill (lwpid, signo);
  1446. }

  1447. /* Handle a GNU/Linux syscall trap wait response.  If we see a syscall
  1448.    event, check if the core is interested in it: if not, ignore the
  1449.    event, and keep waiting; otherwise, we need to toggle the LWP's
  1450.    syscall entry/exit status, since the ptrace event itself doesn't
  1451.    indicate it, and report the trap to higher layers.  */

  1452. static int
  1453. linux_handle_syscall_trap (struct lwp_info *lp, int stopping)
  1454. {
  1455.   struct target_waitstatus *ourstatus = &lp->waitstatus;
  1456.   struct gdbarch *gdbarch = target_thread_architecture (lp->ptid);
  1457.   int syscall_number = (int) gdbarch_get_syscall_number (gdbarch, lp->ptid);

  1458.   if (stopping)
  1459.     {
  1460.       /* If we're stopping threads, there's a SIGSTOP pending, which
  1461.          makes it so that the LWP reports an immediate syscall return,
  1462.          followed by the SIGSTOP.  Skip seeing that "return" using
  1463.          PTRACE_CONT directly, and let stop_wait_callback collect the
  1464.          SIGSTOP.  Later when the thread is resumed, a new syscall
  1465.          entry event.  If we didn't do this (and returned 0), we'd
  1466.          leave a syscall entry pending, and our caller, by using
  1467.          PTRACE_CONT to collect the SIGSTOP, skips the syscall return
  1468.          itself.  Later, when the user re-resumes this LWP, we'd see
  1469.          another syscall entry event and we'd mistake it for a return.

  1470.          If stop_wait_callback didn't force the SIGSTOP out of the LWP
  1471.          (leaving immediately with LWP->signalled set, without issuing
  1472.          a PTRACE_CONT), it would still be problematic to leave this
  1473.          syscall enter pending, as later when the thread is resumed,
  1474.          it would then see the same syscall exit mentioned above,
  1475.          followed by the delayed SIGSTOP, while the syscall didn't
  1476.          actually get to execute.  It seems it would be even more
  1477.          confusing to the user.  */

  1478.       if (debug_linux_nat)
  1479.         fprintf_unfiltered (gdb_stdlog,
  1480.                             "LHST: ignoring syscall %d "
  1481.                             "for LWP %ld (stopping threads), "
  1482.                             "resuming with PTRACE_CONT for SIGSTOP\n",
  1483.                             syscall_number,
  1484.                             ptid_get_lwp (lp->ptid));

  1485.       lp->syscall_state = TARGET_WAITKIND_IGNORE;
  1486.       ptrace (PTRACE_CONT, ptid_get_lwp (lp->ptid), 0, 0);
  1487.       lp->stopped = 0;
  1488.       return 1;
  1489.     }

  1490.   if (catch_syscall_enabled ())
  1491.     {
  1492.       /* Always update the entry/return state, even if this particular
  1493.          syscall isn't interesting to the core now.  In async mode,
  1494.          the user could install a new catchpoint for this syscall
  1495.          between syscall enter/return, and we'll need to know to
  1496.          report a syscall return if that happens.  */
  1497.       lp->syscall_state = (lp->syscall_state == TARGET_WAITKIND_SYSCALL_ENTRY
  1498.                            ? TARGET_WAITKIND_SYSCALL_RETURN
  1499.                            : TARGET_WAITKIND_SYSCALL_ENTRY);

  1500.       if (catching_syscall_number (syscall_number))
  1501.         {
  1502.           /* Alright, an event to report.  */
  1503.           ourstatus->kind = lp->syscall_state;
  1504.           ourstatus->value.syscall_number = syscall_number;

  1505.           if (debug_linux_nat)
  1506.             fprintf_unfiltered (gdb_stdlog,
  1507.                                 "LHST: stopping for %s of syscall %d"
  1508.                                 " for LWP %ld\n",
  1509.                                 lp->syscall_state
  1510.                                 == TARGET_WAITKIND_SYSCALL_ENTRY
  1511.                                 ? "entry" : "return",
  1512.                                 syscall_number,
  1513.                                 ptid_get_lwp (lp->ptid));
  1514.           return 0;
  1515.         }

  1516.       if (debug_linux_nat)
  1517.         fprintf_unfiltered (gdb_stdlog,
  1518.                             "LHST: ignoring %s of syscall %d "
  1519.                             "for LWP %ld\n",
  1520.                             lp->syscall_state == TARGET_WAITKIND_SYSCALL_ENTRY
  1521.                             ? "entry" : "return",
  1522.                             syscall_number,
  1523.                             ptid_get_lwp (lp->ptid));
  1524.     }
  1525.   else
  1526.     {
  1527.       /* If we had been syscall tracing, and hence used PT_SYSCALL
  1528.          before on this LWP, it could happen that the user removes all
  1529.          syscall catchpoints before we get to process this event.
  1530.          There are two noteworthy issues here:

  1531.          - When stopped at a syscall entry event, resuming with
  1532.            PT_STEP still resumes executing the syscall and reports a
  1533.            syscall return.

  1534.          - Only PT_SYSCALL catches syscall enters.  If we last
  1535.            single-stepped this thread, then this event can't be a
  1536.            syscall enter.  If we last single-stepped this thread, this
  1537.            has to be a syscall exit.

  1538.          The points above mean that the next resume, be it PT_STEP or
  1539.          PT_CONTINUE, can not trigger a syscall trace event.  */
  1540.       if (debug_linux_nat)
  1541.         fprintf_unfiltered (gdb_stdlog,
  1542.                             "LHST: caught syscall event "
  1543.                             "with no syscall catchpoints."
  1544.                             " %d for LWP %ld, ignoring\n",
  1545.                             syscall_number,
  1546.                             ptid_get_lwp (lp->ptid));
  1547.       lp->syscall_state = TARGET_WAITKIND_IGNORE;
  1548.     }

  1549.   /* The core isn't interested in this event.  For efficiency, avoid
  1550.      stopping all threads only to have the core resume them all again.
  1551.      Since we're not stopping threads, if we're still syscall tracing
  1552.      and not stepping, we can't use PTRACE_CONT here, as we'd miss any
  1553.      subsequent syscall.  Simply resume using the inf-ptrace layer,
  1554.      which knows when to use PT_SYSCALL or PT_CONTINUE.  */

  1555.   linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
  1556.   return 1;
  1557. }

  1558. /* Handle a GNU/Linux extended wait response.  If we see a clone
  1559.    event, we need to add the new LWP to our list (and not report the
  1560.    trap to higher layers).  This function returns non-zero if the
  1561.    event should be ignored and we should wait again.  If STOPPING is
  1562.    true, the new LWP remains stopped, otherwise it is continued.  */

  1563. static int
  1564. linux_handle_extended_wait (struct lwp_info *lp, int status,
  1565.                             int stopping)
  1566. {
  1567.   int pid = ptid_get_lwp (lp->ptid);
  1568.   struct target_waitstatus *ourstatus = &lp->waitstatus;
  1569.   int event = linux_ptrace_get_extended_event (status);

  1570.   if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
  1571.       || event == PTRACE_EVENT_CLONE)
  1572.     {
  1573.       unsigned long new_pid;
  1574.       int ret;

  1575.       ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);

  1576.       /* If we haven't already seen the new PID stop, wait for it now.  */
  1577.       if (! pull_pid_from_list (&stopped_pids, new_pid, &status))
  1578.         {
  1579.           /* The new child has a pending SIGSTOP.  We can't affect it until it
  1580.              hits the SIGSTOP, but we're already attached.  */
  1581.           ret = my_waitpid (new_pid, &status,
  1582.                             (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
  1583.           if (ret == -1)
  1584.             perror_with_name (_("waiting for new child"));
  1585.           else if (ret != new_pid)
  1586.             internal_error (__FILE__, __LINE__,
  1587.                             _("wait returned unexpected PID %d"), ret);
  1588.           else if (!WIFSTOPPED (status))
  1589.             internal_error (__FILE__, __LINE__,
  1590.                             _("wait returned unexpected status 0x%x"), status);
  1591.         }

  1592.       ourstatus->value.related_pid = ptid_build (new_pid, new_pid, 0);

  1593.       if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK)
  1594.         {
  1595.           /* The arch-specific native code may need to know about new
  1596.              forks even if those end up never mapped to an
  1597.              inferior.  */
  1598.           if (linux_nat_new_fork != NULL)
  1599.             linux_nat_new_fork (lp, new_pid);
  1600.         }

  1601.       if (event == PTRACE_EVENT_FORK
  1602.           && linux_fork_checkpointing_p (ptid_get_pid (lp->ptid)))
  1603.         {
  1604.           /* Handle checkpointing by linux-fork.c here as a special
  1605.              case.  We don't want the follow-fork-mode or 'catch fork'
  1606.              to interfere with this.  */

  1607.           /* This won't actually modify the breakpoint list, but will
  1608.              physically remove the breakpoints from the child.  */
  1609.           detach_breakpoints (ptid_build (new_pid, new_pid, 0));

  1610.           /* Retain child fork in ptrace (stopped) state.  */
  1611.           if (!find_fork_pid (new_pid))
  1612.             add_fork (new_pid);

  1613.           /* Report as spurious, so that infrun doesn't want to follow
  1614.              this fork.  We're actually doing an infcall in
  1615.              linux-fork.c.  */
  1616.           ourstatus->kind = TARGET_WAITKIND_SPURIOUS;

  1617.           /* Report the stop to the core.  */
  1618.           return 0;
  1619.         }

  1620.       if (event == PTRACE_EVENT_FORK)
  1621.         ourstatus->kind = TARGET_WAITKIND_FORKED;
  1622.       else if (event == PTRACE_EVENT_VFORK)
  1623.         ourstatus->kind = TARGET_WAITKIND_VFORKED;
  1624.       else
  1625.         {
  1626.           struct lwp_info *new_lp;

  1627.           ourstatus->kind = TARGET_WAITKIND_IGNORE;

  1628.           if (debug_linux_nat)
  1629.             fprintf_unfiltered (gdb_stdlog,
  1630.                                 "LHEW: Got clone event "
  1631.                                 "from LWP %d, new child is LWP %ld\n",
  1632.                                 pid, new_pid);

  1633.           new_lp = add_lwp (ptid_build (ptid_get_pid (lp->ptid), new_pid, 0));
  1634.           new_lp->cloned = 1;
  1635.           new_lp->stopped = 1;

  1636.           if (WSTOPSIG (status) != SIGSTOP)
  1637.             {
  1638.               /* This can happen if someone starts sending signals to
  1639.                  the new thread before it gets a chance to run, which
  1640.                  have a lower number than SIGSTOP (e.g. SIGUSR1).
  1641.                  This is an unlikely case, and harder to handle for
  1642.                  fork / vfork than for clone, so we do not try - but
  1643.                  we handle it for clone events here.  We'll send
  1644.                  the other signal on to the thread below.  */

  1645.               new_lp->signalled = 1;
  1646.             }
  1647.           else
  1648.             {
  1649.               struct thread_info *tp;

  1650.               /* When we stop for an event in some other thread, and
  1651.                  pull the thread list just as this thread has cloned,
  1652.                  we'll have seen the new thread in the thread_db list
  1653.                  before handling the CLONE event (glibc's
  1654.                  pthread_create adds the new thread to the thread list
  1655.                  before clone'ing, and has the kernel fill in the
  1656.                  thread's tid on the clone call with
  1657.                  CLONE_PARENT_SETTID).  If that happened, and the core
  1658.                  had requested the new thread to stop, we'll have
  1659.                  killed it with SIGSTOP.  But since SIGSTOP is not an
  1660.                  RT signal, it can only be queued once.  We need to be
  1661.                  careful to not resume the LWP if we wanted it to
  1662.                  stop.  In that case, we'll leave the SIGSTOP pending.
  1663.                  It will later be reported as GDB_SIGNAL_0.  */
  1664.               tp = find_thread_ptid (new_lp->ptid);
  1665.               if (tp != NULL && tp->stop_requested)
  1666.                 new_lp->last_resume_kind = resume_stop;
  1667.               else
  1668.                 status = 0;
  1669.             }

  1670.           if (non_stop)
  1671.             {
  1672.               /* Add the new thread to GDB's lists as soon as possible
  1673.                  so that:

  1674.                  1) the frontend doesn't have to wait for a stop to
  1675.                  display them, and,

  1676.                  2) we tag it with the correct running state.  */

  1677.               /* If the thread_db layer is active, let it know about
  1678.                  this new thread, and add it to GDB's list.  */
  1679.               if (!thread_db_attach_lwp (new_lp->ptid))
  1680.                 {
  1681.                   /* We're not using thread_db.  Add it to GDB's
  1682.                      list.  */
  1683.                   target_post_attach (ptid_get_lwp (new_lp->ptid));
  1684.                   add_thread (new_lp->ptid);
  1685.                 }

  1686.               if (!stopping)
  1687.                 {
  1688.                   set_running (new_lp->ptid, 1);
  1689.                   set_executing (new_lp->ptid, 1);
  1690.                   /* thread_db_attach_lwp -> lin_lwp_attach_lwp forced
  1691.                      resume_stop.  */
  1692.                   new_lp->last_resume_kind = resume_continue;
  1693.                 }
  1694.             }

  1695.           if (status != 0)
  1696.             {
  1697.               /* We created NEW_LP so it cannot yet contain STATUS.  */
  1698.               gdb_assert (new_lp->status == 0);

  1699.               /* Save the wait status to report later.  */
  1700.               if (debug_linux_nat)
  1701.                 fprintf_unfiltered (gdb_stdlog,
  1702.                                     "LHEW: waitpid of new LWP %ld, "
  1703.                                     "saving status %s\n",
  1704.                                     (long) ptid_get_lwp (new_lp->ptid),
  1705.                                     status_to_str (status));
  1706.               new_lp->status = status;
  1707.             }

  1708.           /* Note the need to use the low target ops to resume, to
  1709.              handle resuming with PT_SYSCALL if we have syscall
  1710.              catchpoints.  */
  1711.           if (!stopping)
  1712.             {
  1713.               new_lp->resumed = 1;

  1714.               if (status == 0)
  1715.                 {
  1716.                   gdb_assert (new_lp->last_resume_kind == resume_continue);
  1717.                   if (debug_linux_nat)
  1718.                     fprintf_unfiltered (gdb_stdlog,
  1719.                                         "LHEW: resuming new LWP %ld\n",
  1720.                                         ptid_get_lwp (new_lp->ptid));
  1721.                   linux_resume_one_lwp (new_lp, 0, GDB_SIGNAL_0);
  1722.                 }
  1723.             }

  1724.           if (debug_linux_nat)
  1725.             fprintf_unfiltered (gdb_stdlog,
  1726.                                 "LHEW: resuming parent LWP %d\n", pid);
  1727.           linux_resume_one_lwp (lp, 0, GDB_SIGNAL_0);
  1728.           return 1;
  1729.         }

  1730.       return 0;
  1731.     }

  1732.   if (event == PTRACE_EVENT_EXEC)
  1733.     {
  1734.       if (debug_linux_nat)
  1735.         fprintf_unfiltered (gdb_stdlog,
  1736.                             "LHEW: Got exec event from LWP %ld\n",
  1737.                             ptid_get_lwp (lp->ptid));

  1738.       ourstatus->kind = TARGET_WAITKIND_EXECD;
  1739.       ourstatus->value.execd_pathname
  1740.         = xstrdup (linux_child_pid_to_exec_file (NULL, pid));

  1741.       /* The thread that execed must have been resumed, but, when a
  1742.          thread execs, it changes its tid to the tgid, and the old
  1743.          tgid thread might have not been resumed.  */
  1744.       lp->resumed = 1;
  1745.       return 0;
  1746.     }

  1747.   if (event == PTRACE_EVENT_VFORK_DONE)
  1748.     {
  1749.       if (current_inferior ()->waiting_for_vfork_done)
  1750.         {
  1751.           if (debug_linux_nat)
  1752.             fprintf_unfiltered (gdb_stdlog,
  1753.                                 "LHEW: Got expected PTRACE_EVENT_"
  1754.                                 "VFORK_DONE from LWP %ld: stopping\n",
  1755.                                 ptid_get_lwp (lp->ptid));

  1756.           ourstatus->kind = TARGET_WAITKIND_VFORK_DONE;
  1757.           return 0;
  1758.         }

  1759.       if (debug_linux_nat)
  1760.         fprintf_unfiltered (gdb_stdlog,
  1761.                             "LHEW: Got PTRACE_EVENT_VFORK_DONE "
  1762.                             "from LWP %ld: resuming\n",
  1763.                             ptid_get_lwp (lp->ptid));
  1764.       ptrace (PTRACE_CONT, ptid_get_lwp (lp->ptid), 0, 0);
  1765.       return 1;
  1766.     }

  1767.   internal_error (__FILE__, __LINE__,
  1768.                   _("unknown ptrace event %d"), event);
  1769. }

  1770. /* Wait for LP to stop.  Returns the wait status, or 0 if the LWP has
  1771.    exited.  */

  1772. static int
  1773. wait_lwp (struct lwp_info *lp)
  1774. {
  1775.   pid_t pid;
  1776.   int status = 0;
  1777.   int thread_dead = 0;
  1778.   sigset_t prev_mask;

  1779.   gdb_assert (!lp->stopped);
  1780.   gdb_assert (lp->status == 0);

  1781.   /* Make sure SIGCHLD is blocked for sigsuspend avoiding a race below.  */
  1782.   block_child_signals (&prev_mask);

  1783.   for (;;)
  1784.     {
  1785.       /* If my_waitpid returns 0 it means the __WCLONE vs. non-__WCLONE kind
  1786.          was right and we should just call sigsuspend.  */

  1787.       pid = my_waitpid (ptid_get_lwp (lp->ptid), &status, WNOHANG);
  1788.       if (pid == -1 && errno == ECHILD)
  1789.         pid = my_waitpid (ptid_get_lwp (lp->ptid), &status, __WCLONE | WNOHANG);
  1790.       if (pid == -1 && errno == ECHILD)
  1791.         {
  1792.           /* The thread has previously exited.  We need to delete it
  1793.              now because, for some vendor 2.4 kernels with NPTL
  1794.              support backported, there won't be an exit event unless
  1795.              it is the main thread.  2.6 kernels will report an exit
  1796.              event for each thread that exits, as expected.  */
  1797.           thread_dead = 1;
  1798.           if (debug_linux_nat)
  1799.             fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
  1800.                                 target_pid_to_str (lp->ptid));
  1801.         }
  1802.       if (pid != 0)
  1803.         break;

  1804.       /* Bugs 10970, 12702.
  1805.          Thread group leader may have exited in which case we'll lock up in
  1806.          waitpid if there are other threads, even if they are all zombies too.
  1807.          Basically, we're not supposed to use waitpid this way.
  1808.          __WCLONE is not applicable for the leader so we can't use that.
  1809.          LINUX_NAT_THREAD_ALIVE cannot be used here as it requires a STOPPED
  1810.          process; it gets ESRCH both for the zombie and for running processes.

  1811.          As a workaround, check if we're waiting for the thread group leader and
  1812.          if it's a zombie, and avoid calling waitpid if it is.

  1813.          This is racy, what if the tgl becomes a zombie right after we check?
  1814.          Therefore always use WNOHANG with sigsuspend - it is equivalent to
  1815.          waiting waitpid but linux_proc_pid_is_zombie is safe this way.  */

  1816.       if (ptid_get_pid (lp->ptid) == ptid_get_lwp (lp->ptid)
  1817.           && linux_proc_pid_is_zombie (ptid_get_lwp (lp->ptid)))
  1818.         {
  1819.           thread_dead = 1;
  1820.           if (debug_linux_nat)
  1821.             fprintf_unfiltered (gdb_stdlog,
  1822.                                 "WL: Thread group leader %s vanished.\n",
  1823.                                 target_pid_to_str (lp->ptid));
  1824.           break;
  1825.         }

  1826.       /* Wait for next SIGCHLD and try again.  This may let SIGCHLD handlers
  1827.          get invoked despite our caller had them intentionally blocked by
  1828.          block_child_signals.  This is sensitive only to the loop of
  1829.          linux_nat_wait_1 and there if we get called my_waitpid gets called
  1830.          again before it gets to sigsuspend so we can safely let the handlers
  1831.          get executed here.  */

  1832.       if (debug_linux_nat)
  1833.         fprintf_unfiltered (gdb_stdlog, "WL: about to sigsuspend\n");
  1834.       sigsuspend (&suspend_mask);
  1835.     }

  1836.   restore_child_signals_mask (&prev_mask);

  1837.   if (!thread_dead)
  1838.     {
  1839.       gdb_assert (pid == ptid_get_lwp (lp->ptid));

  1840.       if (debug_linux_nat)
  1841.         {
  1842.           fprintf_unfiltered (gdb_stdlog,
  1843.                               "WL: waitpid %s received %s\n",
  1844.                               target_pid_to_str (lp->ptid),
  1845.                               status_to_str (status));
  1846.         }

  1847.       /* Check if the thread has exited.  */
  1848.       if (WIFEXITED (status) || WIFSIGNALED (status))
  1849.         {
  1850.           thread_dead = 1;
  1851.           if (debug_linux_nat)
  1852.             fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
  1853.                                 target_pid_to_str (lp->ptid));
  1854.         }
  1855.     }

  1856.   if (thread_dead)
  1857.     {
  1858.       exit_lwp (lp);
  1859.       return 0;
  1860.     }

  1861.   gdb_assert (WIFSTOPPED (status));
  1862.   lp->stopped = 1;

  1863.   if (lp->must_set_ptrace_flags)
  1864.     {
  1865.       struct inferior *inf = find_inferior_pid (ptid_get_pid (lp->ptid));

  1866.       linux_enable_event_reporting (ptid_get_lwp (lp->ptid), inf->attach_flag);
  1867.       lp->must_set_ptrace_flags = 0;
  1868.     }

  1869.   /* Handle GNU/Linux's syscall SIGTRAPs.  */
  1870.   if (WIFSTOPPED (status) && WSTOPSIG (status) == SYSCALL_SIGTRAP)
  1871.     {
  1872.       /* No longer need the sysgood bit.  The ptrace event ends up
  1873.          recorded in lp->waitstatus if we care for it.  We can carry
  1874.          on handling the event like a regular SIGTRAP from here
  1875.          on.  */
  1876.       status = W_STOPCODE (SIGTRAP);
  1877.       if (linux_handle_syscall_trap (lp, 1))
  1878.         return wait_lwp (lp);
  1879.     }

  1880.   /* Handle GNU/Linux's extended waitstatus for trace events.  */
  1881.   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP
  1882.       && linux_is_extended_waitstatus (status))
  1883.     {
  1884.       if (debug_linux_nat)
  1885.         fprintf_unfiltered (gdb_stdlog,
  1886.                             "WL: Handling extended status 0x%06x\n",
  1887.                             status);
  1888.       if (linux_handle_extended_wait (lp, status, 1))
  1889.         return wait_lwp (lp);
  1890.     }

  1891.   return status;
  1892. }

  1893. /* Send a SIGSTOP to LP.  */

  1894. static int
  1895. stop_callback (struct lwp_info *lp, void *data)
  1896. {
  1897.   if (!lp->stopped && !lp->signalled)
  1898.     {
  1899.       int ret;

  1900.       if (debug_linux_nat)
  1901.         {
  1902.           fprintf_unfiltered (gdb_stdlog,
  1903.                               "SC:  kill %s **<SIGSTOP>**\n",
  1904.                               target_pid_to_str (lp->ptid));
  1905.         }
  1906.       errno = 0;
  1907.       ret = kill_lwp (ptid_get_lwp (lp->ptid), SIGSTOP);
  1908.       if (debug_linux_nat)
  1909.         {
  1910.           fprintf_unfiltered (gdb_stdlog,
  1911.                               "SC:  lwp kill %d %s\n",
  1912.                               ret,
  1913.                               errno ? safe_strerror (errno) : "ERRNO-OK");
  1914.         }

  1915.       lp->signalled = 1;
  1916.       gdb_assert (lp->status == 0);
  1917.     }

  1918.   return 0;
  1919. }

  1920. /* Request a stop on LWP.  */

  1921. void
  1922. linux_stop_lwp (struct lwp_info *lwp)
  1923. {
  1924.   stop_callback (lwp, NULL);
  1925. }

  1926. /* Return non-zero if LWP PID has a pending SIGINT.  */

  1927. static int
  1928. linux_nat_has_pending_sigint (int pid)
  1929. {
  1930.   sigset_t pending, blocked, ignored;

  1931.   linux_proc_pending_signals (pid, &pending, &blocked, &ignored);

  1932.   if (sigismember (&pending, SIGINT)
  1933.       && !sigismember (&ignored, SIGINT))
  1934.     return 1;

  1935.   return 0;
  1936. }

  1937. /* Set a flag in LP indicating that we should ignore its next SIGINT.  */

  1938. static int
  1939. set_ignore_sigint (struct lwp_info *lp, void *data)
  1940. {
  1941.   /* If a thread has a pending SIGINT, consume it; otherwise, set a
  1942.      flag to consume the next one.  */
  1943.   if (lp->stopped && lp->status != 0 && WIFSTOPPED (lp->status)
  1944.       && WSTOPSIG (lp->status) == SIGINT)
  1945.     lp->status = 0;
  1946.   else
  1947.     lp->ignore_sigint = 1;

  1948.   return 0;
  1949. }

  1950. /* If LP does not have a SIGINT pending, then clear the ignore_sigint flag.
  1951.    This function is called after we know the LWP has stopped; if the LWP
  1952.    stopped before the expected SIGINT was delivered, then it will never have
  1953.    arrived.  Also, if the signal was delivered to a shared queue and consumed
  1954.    by a different thread, it will never be delivered to this LWP.  */

  1955. static void
  1956. maybe_clear_ignore_sigint (struct lwp_info *lp)
  1957. {
  1958.   if (!lp->ignore_sigint)
  1959.     return;

  1960.   if (!linux_nat_has_pending_sigint (ptid_get_lwp (lp->ptid)))
  1961.     {
  1962.       if (debug_linux_nat)
  1963.         fprintf_unfiltered (gdb_stdlog,
  1964.                             "MCIS: Clearing bogus flag for %s\n",
  1965.                             target_pid_to_str (lp->ptid));
  1966.       lp->ignore_sigint = 0;
  1967.     }
  1968. }

  1969. /* Fetch the possible triggered data watchpoint info and store it in
  1970.    LP.

  1971.    On some archs, like x86, that use debug registers to set
  1972.    watchpoints, it's possible that the way to know which watched
  1973.    address trapped, is to check the register that is used to select
  1974.    which address to watch.  Problem is, between setting the watchpoint
  1975.    and reading back which data address trapped, the user may change
  1976.    the set of watchpoints, and, as a consequence, GDB changes the
  1977.    debug registers in the inferior.  To avoid reading back a stale
  1978.    stopped-data-address when that happens, we cache in LP the fact
  1979.    that a watchpoint trapped, and the corresponding data address, as
  1980.    soon as we see LP stop with a SIGTRAP.  If GDB changes the debug
  1981.    registers meanwhile, we have the cached data we can rely on.  */

  1982. static int
  1983. check_stopped_by_watchpoint (struct lwp_info *lp)
  1984. {
  1985.   struct cleanup *old_chain;

  1986.   if (linux_ops->to_stopped_by_watchpoint == NULL)
  1987.     return 0;

  1988.   old_chain = save_inferior_ptid ();
  1989.   inferior_ptid = lp->ptid;

  1990.   if (linux_ops->to_stopped_by_watchpoint (linux_ops))
  1991.     {
  1992.       lp->stop_reason = LWP_STOPPED_BY_WATCHPOINT;

  1993.       if (linux_ops->to_stopped_data_address != NULL)
  1994.         lp->stopped_data_address_p =
  1995.           linux_ops->to_stopped_data_address (&current_target,
  1996.                                               &lp->stopped_data_address);
  1997.       else
  1998.         lp->stopped_data_address_p = 0;
  1999.     }

  2000.   do_cleanups (old_chain);

  2001.   return lp->stop_reason == LWP_STOPPED_BY_WATCHPOINT;
  2002. }

  2003. /* Called when the LWP stopped for a trap that could be explained by a
  2004.    watchpoint or a breakpoint.  */

  2005. static void
  2006. save_sigtrap (struct lwp_info *lp)
  2007. {
  2008.   gdb_assert (lp->stop_reason == LWP_STOPPED_BY_NO_REASON);
  2009.   gdb_assert (lp->status != 0);

  2010.   if (check_stopped_by_watchpoint (lp))
  2011.     return;

  2012.   if (linux_nat_status_is_event (lp->status))
  2013.     check_stopped_by_breakpoint (lp);
  2014. }

  2015. /* Returns true if the LWP had stopped for a watchpoint.  */

  2016. static int
  2017. linux_nat_stopped_by_watchpoint (struct target_ops *ops)
  2018. {
  2019.   struct lwp_info *lp = find_lwp_pid (inferior_ptid);

  2020.   gdb_assert (lp != NULL);

  2021.   return lp->stop_reason == LWP_STOPPED_BY_WATCHPOINT;
  2022. }

  2023. static int
  2024. linux_nat_stopped_data_address (struct target_ops *ops, CORE_ADDR *addr_p)
  2025. {
  2026.   struct lwp_info *lp = find_lwp_pid (inferior_ptid);

  2027.   gdb_assert (lp != NULL);

  2028.   *addr_p = lp->stopped_data_address;

  2029.   return lp->stopped_data_address_p;
  2030. }

  2031. /* Commonly any breakpoint / watchpoint generate only SIGTRAP.  */

  2032. static int
  2033. sigtrap_is_event (int status)
  2034. {
  2035.   return WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP;
  2036. }

  2037. /* Set alternative SIGTRAP-like events recognizer.  If
  2038.    breakpoint_inserted_here_p there then gdbarch_decr_pc_after_break will be
  2039.    applied.  */

  2040. void
  2041. linux_nat_set_status_is_event (struct target_ops *t,
  2042.                                int (*status_is_event) (int status))
  2043. {
  2044.   linux_nat_status_is_event = status_is_event;
  2045. }

  2046. /* Wait until LP is stopped.  */

  2047. static int
  2048. stop_wait_callback (struct lwp_info *lp, void *data)
  2049. {
  2050.   struct inferior *inf = find_inferior_ptid (lp->ptid);

  2051.   /* If this is a vfork parent, bail out, it is not going to report
  2052.      any SIGSTOP until the vfork is done with.  */
  2053.   if (inf->vfork_child != NULL)
  2054.     return 0;

  2055.   if (!lp->stopped)
  2056.     {
  2057.       int status;

  2058.       status = wait_lwp (lp);
  2059.       if (status == 0)
  2060.         return 0;

  2061.       if (lp->ignore_sigint && WIFSTOPPED (status)
  2062.           && WSTOPSIG (status) == SIGINT)
  2063.         {
  2064.           lp->ignore_sigint = 0;

  2065.           errno = 0;
  2066.           ptrace (PTRACE_CONT, ptid_get_lwp (lp->ptid), 0, 0);
  2067.           lp->stopped = 0;
  2068.           if (debug_linux_nat)
  2069.             fprintf_unfiltered (gdb_stdlog,
  2070.                                 "PTRACE_CONT %s, 0, 0 (%s) "
  2071.                                 "(discarding SIGINT)\n",
  2072.                                 target_pid_to_str (lp->ptid),
  2073.                                 errno ? safe_strerror (errno) : "OK");

  2074.           return stop_wait_callback (lp, NULL);
  2075.         }

  2076.       maybe_clear_ignore_sigint (lp);

  2077.       if (WSTOPSIG (status) != SIGSTOP)
  2078.         {
  2079.           /* The thread was stopped with a signal other than SIGSTOP.  */

  2080.           if (debug_linux_nat)
  2081.             fprintf_unfiltered (gdb_stdlog,
  2082.                                 "SWC: Pending event %s in %s\n",
  2083.                                 status_to_str ((int) status),
  2084.                                 target_pid_to_str (lp->ptid));

  2085.           /* Save the sigtrap event.  */
  2086.           lp->status = status;
  2087.           gdb_assert (lp->signalled);
  2088.           save_sigtrap (lp);
  2089.         }
  2090.       else
  2091.         {
  2092.           /* We caught the SIGSTOP that we intended to catch, so
  2093.              there's no SIGSTOP pending.  */

  2094.           if (debug_linux_nat)
  2095.             fprintf_unfiltered (gdb_stdlog,
  2096.                                 "SWC: Delayed SIGSTOP caught for %s.\n",
  2097.                                 target_pid_to_str (lp->ptid));

  2098.           /* Reset SIGNALLED only after the stop_wait_callback call
  2099.              above as it does gdb_assert on SIGNALLED.  */
  2100.           lp->signalled = 0;
  2101.         }
  2102.     }

  2103.   return 0;
  2104. }

  2105. /* Return non-zero if LP has a wait status pending.  Discard the
  2106.    pending event and resume the LWP if the event that originally
  2107.    caused the stop became uninteresting.  */

  2108. static int
  2109. status_callback (struct lwp_info *lp, void *data)
  2110. {
  2111.   /* Only report a pending wait status if we pretend that this has
  2112.      indeed been resumed.  */
  2113.   if (!lp->resumed)
  2114.     return 0;

  2115.   if (lp->stop_reason == LWP_STOPPED_BY_SW_BREAKPOINT
  2116.       || lp->stop_reason == LWP_STOPPED_BY_HW_BREAKPOINT)
  2117.     {
  2118.       struct regcache *regcache = get_thread_regcache (lp->ptid);
  2119.       struct gdbarch *gdbarch = get_regcache_arch (regcache);
  2120.       CORE_ADDR pc;
  2121.       int discard = 0;

  2122.       gdb_assert (lp->status != 0);

  2123.       pc = regcache_read_pc (regcache);

  2124.       if (pc != lp->stop_pc)
  2125.         {
  2126.           if (debug_linux_nat)
  2127.             fprintf_unfiltered (gdb_stdlog,
  2128.                                 "SC: PC of %s changed.  was=%s, now=%s\n",
  2129.                                 target_pid_to_str (lp->ptid),
  2130.                                 paddress (target_gdbarch (), lp->stop_pc),
  2131.                                 paddress (target_gdbarch (), pc));
  2132.           discard = 1;
  2133.         }
  2134.       else if (!breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
  2135.         {
  2136.           if (debug_linux_nat)
  2137.             fprintf_unfiltered (gdb_stdlog,
  2138.                                 "SC: previous breakpoint of %s, at %s gone\n",
  2139.                                 target_pid_to_str (lp->ptid),
  2140.                                 paddress (target_gdbarch (), lp->stop_pc));

  2141.           discard = 1;
  2142.         }

  2143.       if (discard)
  2144.         {
  2145.           if (debug_linux_nat)
  2146.             fprintf_unfiltered (gdb_stdlog,
  2147.                                 "SC: pending event of %s cancelled.\n",
  2148.                                 target_pid_to_str (lp->ptid));

  2149.           lp->status = 0;
  2150.           linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
  2151.           return 0;
  2152.         }
  2153.       return 1;
  2154.     }

  2155.   return lwp_status_pending_p (lp);
  2156. }

  2157. /* Return non-zero if LP isn't stopped.  */

  2158. static int
  2159. running_callback (struct lwp_info *lp, void *data)
  2160. {
  2161.   return (!lp->stopped
  2162.           || (lwp_status_pending_p (lp) && lp->resumed));
  2163. }

  2164. /* Count the LWP's that have had events.  */

  2165. static int
  2166. count_events_callback (struct lwp_info *lp, void *data)
  2167. {
  2168.   int *count = data;

  2169.   gdb_assert (count != NULL);

  2170.   /* Select only resumed LWPs that have an event pending.  */
  2171.   if (lp->resumed && lwp_status_pending_p (lp))
  2172.     (*count)++;

  2173.   return 0;
  2174. }

  2175. /* Select the LWP (if any) that is currently being single-stepped.  */

  2176. static int
  2177. select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
  2178. {
  2179.   if (lp->last_resume_kind == resume_step
  2180.       && lp->status != 0)
  2181.     return 1;
  2182.   else
  2183.     return 0;
  2184. }

  2185. /* Returns true if LP has a status pending.  */

  2186. static int
  2187. lwp_status_pending_p (struct lwp_info *lp)
  2188. {
  2189.   /* We check for lp->waitstatus in addition to lp->status, because we
  2190.      can have pending process exits recorded in lp->status and
  2191.      W_EXITCODE(0,0) happens to be 0.  */
  2192.   return lp->status != 0 || lp->waitstatus.kind != TARGET_WAITKIND_IGNORE;
  2193. }

  2194. /* Select the Nth LWP that has had a SIGTRAP event.  */

  2195. static int
  2196. select_event_lwp_callback (struct lwp_info *lp, void *data)
  2197. {
  2198.   int *selector = data;

  2199.   gdb_assert (selector != NULL);

  2200.   /* Select only resumed LWPs that have an event pending.  */
  2201.   if (lp->resumed && lwp_status_pending_p (lp))
  2202.     if ((*selector)-- == 0)
  2203.       return 1;

  2204.   return 0;
  2205. }

  2206. /* Called when the LWP got a signal/trap that could be explained by a
  2207.    software or hardware breakpoint.  */

  2208. static int
  2209. check_stopped_by_breakpoint (struct lwp_info *lp)
  2210. {
  2211.   /* Arrange for a breakpoint to be hit again later.  We don't keep
  2212.      the SIGTRAP status and don't forward the SIGTRAP signal to the
  2213.      LWP.  We will handle the current event, eventually we will resume
  2214.      this LWP, and this breakpoint will trap again.

  2215.      If we do not do this, then we run the risk that the user will
  2216.      delete or disable the breakpoint, but the LWP will have already
  2217.      tripped on it.  */

  2218.   struct regcache *regcache = get_thread_regcache (lp->ptid);
  2219.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  2220.   CORE_ADDR pc;
  2221.   CORE_ADDR sw_bp_pc;

  2222.   pc = regcache_read_pc (regcache);
  2223.   sw_bp_pc = pc - target_decr_pc_after_break (gdbarch);

  2224.   if ((!lp->step || lp->stop_pc == sw_bp_pc)
  2225.       && software_breakpoint_inserted_here_p (get_regcache_aspace (regcache),
  2226.                                               sw_bp_pc))
  2227.     {
  2228.       /* The LWP was either continued, or stepped a software
  2229.          breakpoint instruction.  */
  2230.       if (debug_linux_nat)
  2231.         fprintf_unfiltered (gdb_stdlog,
  2232.                             "CB: Push back software breakpoint for %s\n",
  2233.                             target_pid_to_str (lp->ptid));

  2234.       /* Back up the PC if necessary.  */
  2235.       if (pc != sw_bp_pc)
  2236.         regcache_write_pc (regcache, sw_bp_pc);

  2237.       lp->stop_pc = sw_bp_pc;
  2238.       lp->stop_reason = LWP_STOPPED_BY_SW_BREAKPOINT;
  2239.       return 1;
  2240.     }

  2241.   if (hardware_breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
  2242.     {
  2243.       if (debug_linux_nat)
  2244.         fprintf_unfiltered (gdb_stdlog,
  2245.                             "CB: Push back hardware breakpoint for %s\n",
  2246.                             target_pid_to_str (lp->ptid));

  2247.       lp->stop_pc = pc;
  2248.       lp->stop_reason = LWP_STOPPED_BY_HW_BREAKPOINT;
  2249.       return 1;
  2250.     }

  2251.   return 0;
  2252. }

  2253. /* Select one LWP out of those that have events pending.  */

  2254. static void
  2255. select_event_lwp (ptid_t filter, struct lwp_info **orig_lp, int *status)
  2256. {
  2257.   int num_events = 0;
  2258.   int random_selector;
  2259.   struct lwp_info *event_lp = NULL;

  2260.   /* Record the wait status for the original LWP.  */
  2261.   (*orig_lp)->status = *status;

  2262.   /* In all-stop, give preference to the LWP that is being
  2263.      single-stepped.  There will be at most one, and it will be the
  2264.      LWP that the core is most interested in.  If we didn't do this,
  2265.      then we'd have to handle pending step SIGTRAPs somehow in case
  2266.      the core later continues the previously-stepped thread, as
  2267.      otherwise we'd report the pending SIGTRAP then, and the core, not
  2268.      having stepped the thread, wouldn't understand what the trap was
  2269.      for, and therefore would report it to the user as a random
  2270.      signal.  */
  2271.   if (!non_stop)
  2272.     {
  2273.       event_lp = iterate_over_lwps (filter,
  2274.                                     select_singlestep_lwp_callback, NULL);
  2275.       if (event_lp != NULL)
  2276.         {
  2277.           if (debug_linux_nat)
  2278.             fprintf_unfiltered (gdb_stdlog,
  2279.                                 "SEL: Select single-step %s\n",
  2280.                                 target_pid_to_str (event_lp->ptid));
  2281.         }
  2282.     }

  2283.   if (event_lp == NULL)
  2284.     {
  2285.       /* Pick one at random, out of those which have had events.  */

  2286.       /* First see how many events we have.  */
  2287.       iterate_over_lwps (filter, count_events_callback, &num_events);

  2288.       /* Now randomly pick a LWP out of those that have had
  2289.          events.  */
  2290.       random_selector = (int)
  2291.         ((num_events * (double) rand ()) / (RAND_MAX + 1.0));

  2292.       if (debug_linux_nat && num_events > 1)
  2293.         fprintf_unfiltered (gdb_stdlog,
  2294.                             "SEL: Found %d events, selecting #%d\n",
  2295.                             num_events, random_selector);

  2296.       event_lp = iterate_over_lwps (filter,
  2297.                                     select_event_lwp_callback,
  2298.                                     &random_selector);
  2299.     }

  2300.   if (event_lp != NULL)
  2301.     {
  2302.       /* Switch the event LWP.  */
  2303.       *orig_lp = event_lp;
  2304.       *status = event_lp->status;
  2305.     }

  2306.   /* Flush the wait status for the event LWP.  */
  2307.   (*orig_lp)->status = 0;
  2308. }

  2309. /* Return non-zero if LP has been resumed.  */

  2310. static int
  2311. resumed_callback (struct lwp_info *lp, void *data)
  2312. {
  2313.   return lp->resumed;
  2314. }

  2315. /* Stop an active thread, verify it still exists, then resume it.  If
  2316.    the thread ends up with a pending status, then it is not resumed,
  2317.    and *DATA (really a pointer to int), is set.  */

  2318. static int
  2319. stop_and_resume_callback (struct lwp_info *lp, void *data)
  2320. {
  2321.   if (!lp->stopped)
  2322.     {
  2323.       ptid_t ptid = lp->ptid;

  2324.       stop_callback (lp, NULL);
  2325.       stop_wait_callback (lp, NULL);

  2326.       /* Resume if the lwp still exists, and the core wanted it
  2327.          running.  */
  2328.       lp = find_lwp_pid (ptid);
  2329.       if (lp != NULL)
  2330.         {
  2331.           if (lp->last_resume_kind == resume_stop
  2332.               && !lwp_status_pending_p (lp))
  2333.             {
  2334.               /* The core wanted the LWP to stop.  Even if it stopped
  2335.                  cleanly (with SIGSTOP), leave the event pending.  */
  2336.               if (debug_linux_nat)
  2337.                 fprintf_unfiltered (gdb_stdlog,
  2338.                                     "SARC: core wanted LWP %ld stopped "
  2339.                                     "(leaving SIGSTOP pending)\n",
  2340.                                     ptid_get_lwp (lp->ptid));
  2341.               lp->status = W_STOPCODE (SIGSTOP);
  2342.             }

  2343.           if (!lwp_status_pending_p (lp))
  2344.             {
  2345.               if (debug_linux_nat)
  2346.                 fprintf_unfiltered (gdb_stdlog,
  2347.                                     "SARC: re-resuming LWP %ld\n",
  2348.                                     ptid_get_lwp (lp->ptid));
  2349.               resume_lwp (lp, lp->step, GDB_SIGNAL_0);
  2350.             }
  2351.           else
  2352.             {
  2353.               if (debug_linux_nat)
  2354.                 fprintf_unfiltered (gdb_stdlog,
  2355.                                     "SARC: not re-resuming LWP %ld "
  2356.                                     "(has pending)\n",
  2357.                                     ptid_get_lwp (lp->ptid));
  2358.             }
  2359.         }
  2360.     }
  2361.   return 0;
  2362. }

  2363. /* Check if we should go on and pass this event to common code.
  2364.    Return the affected lwp if we are, or NULL otherwise.  */

  2365. static struct lwp_info *
  2366. linux_nat_filter_event (int lwpid, int status)
  2367. {
  2368.   struct lwp_info *lp;
  2369.   int event = linux_ptrace_get_extended_event (status);

  2370.   lp = find_lwp_pid (pid_to_ptid (lwpid));

  2371.   /* Check for stop events reported by a process we didn't already
  2372.      know about - anything not already in our LWP list.

  2373.      If we're expecting to receive stopped processes after
  2374.      fork, vfork, and clone events, then we'll just add the
  2375.      new one to our list and go back to waiting for the event
  2376.      to be reported - the stopped process might be returned
  2377.      from waitpid before or after the event is.

  2378.      But note the case of a non-leader thread exec'ing after the
  2379.      leader having exited, and gone from our lists.  The non-leader
  2380.      thread changes its tid to the tgid.  */

  2381.   if (WIFSTOPPED (status) && lp == NULL
  2382.       && (WSTOPSIG (status) == SIGTRAP && event == PTRACE_EVENT_EXEC))
  2383.     {
  2384.       /* A multi-thread exec after we had seen the leader exiting.  */
  2385.       if (debug_linux_nat)
  2386.         fprintf_unfiltered (gdb_stdlog,
  2387.                             "LLW: Re-adding thread group leader LWP %d.\n",
  2388.                             lwpid);

  2389.       lp = add_lwp (ptid_build (lwpid, lwpid, 0));
  2390.       lp->stopped = 1;
  2391.       lp->resumed = 1;
  2392.       add_thread (lp->ptid);
  2393.     }

  2394.   if (WIFSTOPPED (status) && !lp)
  2395.     {
  2396.       add_to_pid_list (&stopped_pids, lwpid, status);
  2397.       return NULL;
  2398.     }

  2399.   /* Make sure we don't report an event for the exit of an LWP not in
  2400.      our list, i.e. not part of the current process.  This can happen
  2401.      if we detach from a program we originally forked and then it
  2402.      exits.  */
  2403.   if (!WIFSTOPPED (status) && !lp)
  2404.     return NULL;

  2405.   /* This LWP is stopped now.  (And if dead, this prevents it from
  2406.      ever being continued.)  */
  2407.   lp->stopped = 1;

  2408.   if (WIFSTOPPED (status) && lp->must_set_ptrace_flags)
  2409.     {
  2410.       struct inferior *inf = find_inferior_pid (ptid_get_pid (lp->ptid));

  2411.       linux_enable_event_reporting (ptid_get_lwp (lp->ptid), inf->attach_flag);
  2412.       lp->must_set_ptrace_flags = 0;
  2413.     }

  2414.   /* Handle GNU/Linux's syscall SIGTRAPs.  */
  2415.   if (WIFSTOPPED (status) && WSTOPSIG (status) == SYSCALL_SIGTRAP)
  2416.     {
  2417.       /* No longer need the sysgood bit.  The ptrace event ends up
  2418.          recorded in lp->waitstatus if we care for it.  We can carry
  2419.          on handling the event like a regular SIGTRAP from here
  2420.          on.  */
  2421.       status = W_STOPCODE (SIGTRAP);
  2422.       if (linux_handle_syscall_trap (lp, 0))
  2423.         return NULL;
  2424.     }

  2425.   /* Handle GNU/Linux's extended waitstatus for trace events.  */
  2426.   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP
  2427.       && linux_is_extended_waitstatus (status))
  2428.     {
  2429.       if (debug_linux_nat)
  2430.         fprintf_unfiltered (gdb_stdlog,
  2431.                             "LLW: Handling extended status 0x%06x\n",
  2432.                             status);
  2433.       if (linux_handle_extended_wait (lp, status, 0))
  2434.         return NULL;
  2435.     }

  2436.   /* Check if the thread has exited.  */
  2437.   if (WIFEXITED (status) || WIFSIGNALED (status))
  2438.     {
  2439.       if (num_lwps (ptid_get_pid (lp->ptid)) > 1)
  2440.         {
  2441.           /* If this is the main thread, we must stop all threads and
  2442.              verify if they are still alive.  This is because in the
  2443.              nptl thread model on Linux 2.4, there is no signal issued
  2444.              for exiting LWPs other than the main thread.  We only get
  2445.              the main thread exit signal once all child threads have
  2446.              already exited.  If we stop all the threads and use the
  2447.              stop_wait_callback to check if they have exited we can
  2448.              determine whether this signal should be ignored or
  2449.              whether it means the end of the debugged application,
  2450.              regardless of which threading model is being used.  */
  2451.           if (ptid_get_pid (lp->ptid) == ptid_get_lwp (lp->ptid))
  2452.             {
  2453.               iterate_over_lwps (pid_to_ptid (ptid_get_pid (lp->ptid)),
  2454.                                  stop_and_resume_callback, NULL);
  2455.             }

  2456.           if (debug_linux_nat)
  2457.             fprintf_unfiltered (gdb_stdlog,
  2458.                                 "LLW: %s exited.\n",
  2459.                                 target_pid_to_str (lp->ptid));

  2460.           if (num_lwps (ptid_get_pid (lp->ptid)) > 1)
  2461.             {
  2462.               /* If there is at least one more LWP, then the exit signal
  2463.                  was not the end of the debugged application and should be
  2464.                  ignored.  */
  2465.               exit_lwp (lp);
  2466.               return NULL;
  2467.             }
  2468.         }

  2469.       gdb_assert (lp->resumed);

  2470.       if (debug_linux_nat)
  2471.         fprintf_unfiltered (gdb_stdlog,
  2472.                             "Process %ld exited\n",
  2473.                             ptid_get_lwp (lp->ptid));

  2474.       /* This was the last lwp in the process.  Since events are
  2475.          serialized to GDB core, we may not be able report this one
  2476.          right now, but GDB core and the other target layers will want
  2477.          to be notified about the exit code/signal, leave the status
  2478.          pending for the next time we're able to report it.  */

  2479.       /* Dead LWP's aren't expected to reported a pending sigstop.  */
  2480.       lp->signalled = 0;

  2481.       /* Store the pending event in the waitstatus, because
  2482.          W_EXITCODE(0,0) == 0.  */
  2483.       store_waitstatus (&lp->waitstatus, status);
  2484.       return lp;
  2485.     }

  2486.   /* Check if the current LWP has previously exited.  In the nptl
  2487.      thread model, LWPs other than the main thread do not issue
  2488.      signals when they exit so we must check whenever the thread has
  2489.      stopped.  A similar check is made in stop_wait_callback().  */
  2490.   if (num_lwps (ptid_get_pid (lp->ptid)) > 1 && !linux_thread_alive (lp->ptid))
  2491.     {
  2492.       ptid_t ptid = pid_to_ptid (ptid_get_pid (lp->ptid));

  2493.       if (debug_linux_nat)
  2494.         fprintf_unfiltered (gdb_stdlog,
  2495.                             "LLW: %s exited.\n",
  2496.                             target_pid_to_str (lp->ptid));

  2497.       exit_lwp (lp);

  2498.       /* Make sure there is at least one thread running.  */
  2499.       gdb_assert (iterate_over_lwps (ptid, running_callback, NULL));

  2500.       /* Discard the event.  */
  2501.       return NULL;
  2502.     }

  2503.   /* Make sure we don't report a SIGSTOP that we sent ourselves in
  2504.      an attempt to stop an LWP.  */
  2505.   if (lp->signalled
  2506.       && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
  2507.     {
  2508.       if (debug_linux_nat)
  2509.         fprintf_unfiltered (gdb_stdlog,
  2510.                             "LLW: Delayed SIGSTOP caught for %s.\n",
  2511.                             target_pid_to_str (lp->ptid));

  2512.       lp->signalled = 0;

  2513.       if (lp->last_resume_kind != resume_stop)
  2514.         {
  2515.           /* This is a delayed SIGSTOP.  */

  2516.           linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
  2517.           if (debug_linux_nat)
  2518.             fprintf_unfiltered (gdb_stdlog,
  2519.                                 "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
  2520.                                 lp->step ?
  2521.                                 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
  2522.                                 target_pid_to_str (lp->ptid));

  2523.           gdb_assert (lp->resumed);

  2524.           /* Discard the event.  */
  2525.           return NULL;
  2526.         }
  2527.     }

  2528.   /* Make sure we don't report a SIGINT that we have already displayed
  2529.      for another thread.  */
  2530.   if (lp->ignore_sigint
  2531.       && WIFSTOPPED (status) && WSTOPSIG (status) == SIGINT)
  2532.     {
  2533.       if (debug_linux_nat)
  2534.         fprintf_unfiltered (gdb_stdlog,
  2535.                             "LLW: Delayed SIGINT caught for %s.\n",
  2536.                             target_pid_to_str (lp->ptid));

  2537.       /* This is a delayed SIGINT.  */
  2538.       lp->ignore_sigint = 0;

  2539.       linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
  2540.       if (debug_linux_nat)
  2541.         fprintf_unfiltered (gdb_stdlog,
  2542.                             "LLW: %s %s, 0, 0 (discard SIGINT)\n",
  2543.                             lp->step ?
  2544.                             "PTRACE_SINGLESTEP" : "PTRACE_CONT",
  2545.                             target_pid_to_str (lp->ptid));
  2546.       gdb_assert (lp->resumed);

  2547.       /* Discard the event.  */
  2548.       return NULL;
  2549.     }

  2550.   /* Don't report signals that GDB isn't interested in, such as
  2551.      signals that are neither printed nor stopped upon.  Stopping all
  2552.      threads can be a bit time-consuming so if we want decent
  2553.      performance with heavily multi-threaded programs, especially when
  2554.      they're using a high frequency timer, we'd better avoid it if we
  2555.      can.  */
  2556.   if (WIFSTOPPED (status))
  2557.     {
  2558.       enum gdb_signal signo = gdb_signal_from_host (WSTOPSIG (status));

  2559.       if (!non_stop)
  2560.         {
  2561.           /* Only do the below in all-stop, as we currently use SIGSTOP
  2562.              to implement target_stop (see linux_nat_stop) in
  2563.              non-stop.  */
  2564.           if (signo == GDB_SIGNAL_INT && signal_pass_state (signo) == 0)
  2565.             {
  2566.               /* If ^C/BREAK is typed at the tty/console, SIGINT gets
  2567.                  forwarded to the entire process group, that is, all LWPs
  2568.                  will receive it - unless they're using CLONE_THREAD to
  2569.                  share signals.  Since we only want to report it once, we
  2570.                  mark it as ignored for all LWPs except this one.  */
  2571.               iterate_over_lwps (pid_to_ptid (ptid_get_pid (lp->ptid)),
  2572.                                               set_ignore_sigint, NULL);
  2573.               lp->ignore_sigint = 0;
  2574.             }
  2575.           else
  2576.             maybe_clear_ignore_sigint (lp);
  2577.         }

  2578.       /* When using hardware single-step, we need to report every signal.
  2579.          Otherwise, signals in pass_mask may be short-circuited.  */
  2580.       if (!lp->step
  2581.           && WSTOPSIG (status) && sigismember (&pass_mask, WSTOPSIG (status)))
  2582.         {
  2583.           linux_resume_one_lwp (lp, lp->step, signo);
  2584.           if (debug_linux_nat)
  2585.             fprintf_unfiltered (gdb_stdlog,
  2586.                                 "LLW: %s %s, %s (preempt 'handle')\n",
  2587.                                 lp->step ?
  2588.                                 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
  2589.                                 target_pid_to_str (lp->ptid),
  2590.                                 (signo != GDB_SIGNAL_0
  2591.                                  ? strsignal (gdb_signal_to_host (signo))
  2592.                                  : "0"));
  2593.           return NULL;
  2594.         }
  2595.     }

  2596.   /* An interesting event.  */
  2597.   gdb_assert (lp);
  2598.   lp->status = status;
  2599.   save_sigtrap (lp);
  2600.   return lp;
  2601. }

  2602. /* Detect zombie thread group leaders, and "exit" them.  We can't reap
  2603.    their exits until all other threads in the group have exited.  */

  2604. static void
  2605. check_zombie_leaders (void)
  2606. {
  2607.   struct inferior *inf;

  2608.   ALL_INFERIORS (inf)
  2609.     {
  2610.       struct lwp_info *leader_lp;

  2611.       if (inf->pid == 0)
  2612.         continue;

  2613.       leader_lp = find_lwp_pid (pid_to_ptid (inf->pid));
  2614.       if (leader_lp != NULL
  2615.           /* Check if there are other threads in the group, as we may
  2616.              have raced with the inferior simply exiting.  */
  2617.           && num_lwps (inf->pid) > 1
  2618.           && linux_proc_pid_is_zombie (inf->pid))
  2619.         {
  2620.           if (debug_linux_nat)
  2621.             fprintf_unfiltered (gdb_stdlog,
  2622.                                 "CZL: Thread group leader %d zombie "
  2623.                                 "(it exited, or another thread execd).\n",
  2624.                                 inf->pid);

  2625.           /* A leader zombie can mean one of two things:

  2626.              - It exited, and there's an exit status pending
  2627.              available, or only the leader exited (not the whole
  2628.              program).  In the latter case, we can't waitpid the
  2629.              leader's exit status until all other threads are gone.

  2630.              - There are 3 or more threads in the group, and a thread
  2631.              other than the leader exec'd.  On an exec, the Linux
  2632.              kernel destroys all other threads (except the execing
  2633.              one) in the thread group, and resets the execing thread's
  2634.              tid to the tgid.  No exit notification is sent for the
  2635.              execing thread -- from the ptracer's perspective, it
  2636.              appears as though the execing thread just vanishes.
  2637.              Until we reap all other threads except the leader and the
  2638.              execing thread, the leader will be zombie, and the
  2639.              execing thread will be in `D (disc sleep)'.  As soon as
  2640.              all other threads are reaped, the execing thread changes
  2641.              it's tid to the tgid, and the previous (zombie) leader
  2642.              vanishes, giving place to the "new" leader.  We could try
  2643.              distinguishing the exit and exec cases, by waiting once
  2644.              more, and seeing if something comes out, but it doesn't
  2645.              sound useful.  The previous leader _does_ go away, and
  2646.              we'll re-add the new one once we see the exec event
  2647.              (which is just the same as what would happen if the
  2648.              previous leader did exit voluntarily before some other
  2649.              thread execs).  */

  2650.           if (debug_linux_nat)
  2651.             fprintf_unfiltered (gdb_stdlog,
  2652.                                 "CZL: Thread group leader %d vanished.\n",
  2653.                                 inf->pid);
  2654.           exit_lwp (leader_lp);
  2655.         }
  2656.     }
  2657. }

  2658. static ptid_t
  2659. linux_nat_wait_1 (struct target_ops *ops,
  2660.                   ptid_t ptid, struct target_waitstatus *ourstatus,
  2661.                   int target_options)
  2662. {
  2663.   sigset_t prev_mask;
  2664.   enum resume_kind last_resume_kind;
  2665.   struct lwp_info *lp;
  2666.   int status;

  2667.   if (debug_linux_nat)
  2668.     fprintf_unfiltered (gdb_stdlog, "LLW: enter\n");

  2669.   /* The first time we get here after starting a new inferior, we may
  2670.      not have added it to the LWP list yet - this is the earliest
  2671.      moment at which we know its PID.  */
  2672.   if (ptid_is_pid (inferior_ptid))
  2673.     {
  2674.       /* Upgrade the main thread's ptid.  */
  2675.       thread_change_ptid (inferior_ptid,
  2676.                           ptid_build (ptid_get_pid (inferior_ptid),
  2677.                                       ptid_get_pid (inferior_ptid), 0));

  2678.       lp = add_initial_lwp (inferior_ptid);
  2679.       lp->resumed = 1;
  2680.     }

  2681.   /* Make sure SIGCHLD is blocked until the sigsuspend below.  */
  2682.   block_child_signals (&prev_mask);

  2683.   /* First check if there is a LWP with a wait status pending.  */
  2684.   lp = iterate_over_lwps (ptid, status_callback, NULL);
  2685.   if (lp != NULL)
  2686.     {
  2687.       if (debug_linux_nat)
  2688.         fprintf_unfiltered (gdb_stdlog,
  2689.                             "LLW: Using pending wait status %s for %s.\n",
  2690.                             status_to_str (lp->status),
  2691.                             target_pid_to_str (lp->ptid));
  2692.     }

  2693.   if (!target_can_async_p ())
  2694.     {
  2695.       /* Causes SIGINT to be passed on to the attached process.  */
  2696.       set_sigint_trap ();
  2697.     }

  2698.   /* But if we don't find a pending event, we'll have to wait.  Always
  2699.      pull all events out of the kernel.  We'll randomly select an
  2700.      event LWP out of all that have events, to prevent starvation.  */

  2701.   while (lp == NULL)
  2702.     {
  2703.       pid_t lwpid;

  2704.       /* Always use -1 and WNOHANG, due to couple of a kernel/ptrace
  2705.          quirks:

  2706.          - If the thread group leader exits while other threads in the
  2707.            thread group still exist, waitpid(TGID, ...) hangs.  That
  2708.            waitpid won't return an exit status until the other threads
  2709.            in the group are reapped.

  2710.          - When a non-leader thread execs, that thread just vanishes
  2711.            without reporting an exit (so we'd hang if we waited for it
  2712.            explicitly in that case).  The exec event is reported to
  2713.            the TGID pid.  */

  2714.       errno = 0;
  2715.       lwpid = my_waitpid (-1, &status,  __WCLONE | WNOHANG);
  2716.       if (lwpid == 0 || (lwpid == -1 && errno == ECHILD))
  2717.         lwpid = my_waitpid (-1, &status, WNOHANG);

  2718.       if (debug_linux_nat)
  2719.         fprintf_unfiltered (gdb_stdlog,
  2720.                             "LNW: waitpid(-1, ...) returned %d, %s\n",
  2721.                             lwpid, errno ? safe_strerror (errno) : "ERRNO-OK");

  2722.       if (lwpid > 0)
  2723.         {
  2724.           if (debug_linux_nat)
  2725.             {
  2726.               fprintf_unfiltered (gdb_stdlog,
  2727.                                   "LLW: waitpid %ld received %s\n",
  2728.                                   (long) lwpid, status_to_str (status));
  2729.             }

  2730.           linux_nat_filter_event (lwpid, status);
  2731.           /* Retry until nothing comes out of waitpid.  A single
  2732.              SIGCHLD can indicate more than one child stopped.  */
  2733.           continue;
  2734.         }

  2735.       /* Now that we've pulled all events out of the kernel, check if
  2736.          there's any LWP with a status to report to the core.  */
  2737.       lp = iterate_over_lwps (ptid, status_callback, NULL);
  2738.       if (lp != NULL)
  2739.         break;

  2740.       /* Check for zombie thread group leaders.  Those can't be reaped
  2741.          until all other threads in the thread group are.  */
  2742.       check_zombie_leaders ();

  2743.       /* If there are no resumed children left, bail.  We'd be stuck
  2744.          forever in the sigsuspend call below otherwise.  */
  2745.       if (iterate_over_lwps (ptid, resumed_callback, NULL) == NULL)
  2746.         {
  2747.           if (debug_linux_nat)
  2748.             fprintf_unfiltered (gdb_stdlog, "LLW: exit (no resumed LWP)\n");

  2749.           ourstatus->kind = TARGET_WAITKIND_NO_RESUMED;

  2750.           if (!target_can_async_p ())
  2751.             clear_sigint_trap ();

  2752.           restore_child_signals_mask (&prev_mask);
  2753.           return minus_one_ptid;
  2754.         }

  2755.       /* No interesting event to report to the core.  */

  2756.       if (target_options & TARGET_WNOHANG)
  2757.         {
  2758.           if (debug_linux_nat)
  2759.             fprintf_unfiltered (gdb_stdlog, "LLW: exit (ignore)\n");

  2760.           ourstatus->kind = TARGET_WAITKIND_IGNORE;
  2761.           restore_child_signals_mask (&prev_mask);
  2762.           return minus_one_ptid;
  2763.         }

  2764.       /* We shouldn't end up here unless we want to try again.  */
  2765.       gdb_assert (lp == NULL);

  2766.       /* Block until we get an event reported with SIGCHLD.  */
  2767.       if (debug_linux_nat)
  2768.         fprintf_unfiltered (gdb_stdlog, "LNW: about to sigsuspend\n");
  2769.       sigsuspend (&suspend_mask);
  2770.     }

  2771.   if (!target_can_async_p ())
  2772.     clear_sigint_trap ();

  2773.   gdb_assert (lp);

  2774.   status = lp->status;
  2775.   lp->status = 0;

  2776.   if (!non_stop)
  2777.     {
  2778.       /* Now stop all other LWP's ...  */
  2779.       iterate_over_lwps (minus_one_ptid, stop_callback, NULL);

  2780.       /* ... and wait until all of them have reported back that
  2781.          they're no longer running.  */
  2782.       iterate_over_lwps (minus_one_ptid, stop_wait_callback, NULL);
  2783.     }

  2784.   /* If we're not waiting for a specific LWP, choose an event LWP from
  2785.      among those that have had events.  Giving equal priority to all
  2786.      LWPs that have had events helps prevent starvation.  */
  2787.   if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
  2788.     select_event_lwp (ptid, &lp, &status);

  2789.   gdb_assert (lp != NULL);

  2790.   /* Now that we've selected our final event LWP, un-adjust its PC if
  2791.      it was a software breakpoint.  */
  2792.   if (lp->stop_reason == LWP_STOPPED_BY_SW_BREAKPOINT)
  2793.     {
  2794.       struct regcache *regcache = get_thread_regcache (lp->ptid);
  2795.       struct gdbarch *gdbarch = get_regcache_arch (regcache);
  2796.       int decr_pc = target_decr_pc_after_break (gdbarch);

  2797.       if (decr_pc != 0)
  2798.         {
  2799.           CORE_ADDR pc;

  2800.           pc = regcache_read_pc (regcache);
  2801.           regcache_write_pc (regcache, pc + decr_pc);
  2802.         }
  2803.     }

  2804.   /* We'll need this to determine whether to report a SIGSTOP as
  2805.      GDB_SIGNAL_0.  Need to take a copy because resume_clear_callback
  2806.      clears it.  */
  2807.   last_resume_kind = lp->last_resume_kind;

  2808.   if (!non_stop)
  2809.     {
  2810.       /* In all-stop, from the core's perspective, all LWPs are now
  2811.          stopped until a new resume action is sent over.  */
  2812.       iterate_over_lwps (minus_one_ptid, resume_clear_callback, NULL);
  2813.     }
  2814.   else
  2815.     {
  2816.       resume_clear_callback (lp, NULL);
  2817.     }

  2818.   if (linux_nat_status_is_event (status))
  2819.     {
  2820.       if (debug_linux_nat)
  2821.         fprintf_unfiltered (gdb_stdlog,
  2822.                             "LLW: trap ptid is %s.\n",
  2823.                             target_pid_to_str (lp->ptid));
  2824.     }

  2825.   if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
  2826.     {
  2827.       *ourstatus = lp->waitstatus;
  2828.       lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
  2829.     }
  2830.   else
  2831.     store_waitstatus (ourstatus, status);

  2832.   if (debug_linux_nat)
  2833.     fprintf_unfiltered (gdb_stdlog, "LLW: exit\n");

  2834.   restore_child_signals_mask (&prev_mask);

  2835.   if (last_resume_kind == resume_stop
  2836.       && ourstatus->kind == TARGET_WAITKIND_STOPPED
  2837.       && WSTOPSIG (status) == SIGSTOP)
  2838.     {
  2839.       /* A thread that has been requested to stop by GDB with
  2840.          target_stop, and it stopped cleanly, so report as SIG0.  The
  2841.          use of SIGSTOP is an implementation detail.  */
  2842.       ourstatus->value.sig = GDB_SIGNAL_0;
  2843.     }

  2844.   if (ourstatus->kind == TARGET_WAITKIND_EXITED
  2845.       || ourstatus->kind == TARGET_WAITKIND_SIGNALLED)
  2846.     lp->core = -1;
  2847.   else
  2848.     lp->core = linux_common_core_of_thread (lp->ptid);

  2849.   return lp->ptid;
  2850. }

  2851. /* Resume LWPs that are currently stopped without any pending status
  2852.    to report, but are resumed from the core's perspective.  */

  2853. static int
  2854. resume_stopped_resumed_lwps (struct lwp_info *lp, void *data)
  2855. {
  2856.   ptid_t *wait_ptid_p = data;

  2857.   if (lp->stopped
  2858.       && lp->resumed
  2859.       && !lwp_status_pending_p (lp))
  2860.     {
  2861.       struct regcache *regcache = get_thread_regcache (lp->ptid);
  2862.       struct gdbarch *gdbarch = get_regcache_arch (regcache);
  2863.       CORE_ADDR pc = regcache_read_pc (regcache);

  2864.       gdb_assert (is_executing (lp->ptid));

  2865.       /* Don't bother if there's a breakpoint at PC that we'd hit
  2866.          immediately, and we're not waiting for this LWP.  */
  2867.       if (!ptid_match (lp->ptid, *wait_ptid_p))
  2868.         {
  2869.           if (breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
  2870.             return 0;
  2871.         }

  2872.       if (debug_linux_nat)
  2873.         fprintf_unfiltered (gdb_stdlog,
  2874.                             "RSRL: resuming stopped-resumed LWP %s at %s: step=%d\n",
  2875.                             target_pid_to_str (lp->ptid),
  2876.                             paddress (gdbarch, pc),
  2877.                             lp->step);

  2878.       linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
  2879.     }

  2880.   return 0;
  2881. }

  2882. static ptid_t
  2883. linux_nat_wait (struct target_ops *ops,
  2884.                 ptid_t ptid, struct target_waitstatus *ourstatus,
  2885.                 int target_options)
  2886. {
  2887.   ptid_t event_ptid;

  2888.   if (debug_linux_nat)
  2889.     {
  2890.       char *options_string;

  2891.       options_string = target_options_to_string (target_options);
  2892.       fprintf_unfiltered (gdb_stdlog,
  2893.                           "linux_nat_wait: [%s], [%s]\n",
  2894.                           target_pid_to_str (ptid),
  2895.                           options_string);
  2896.       xfree (options_string);
  2897.     }

  2898.   /* Flush the async file first.  */
  2899.   if (target_can_async_p ())
  2900.     async_file_flush ();

  2901.   /* Resume LWPs that are currently stopped without any pending status
  2902.      to report, but are resumed from the core's perspective.  LWPs get
  2903.      in this state if we find them stopping at a time we're not
  2904.      interested in reporting the event (target_wait on a
  2905.      specific_process, for example, see linux_nat_wait_1), and
  2906.      meanwhile the event became uninteresting.  Don't bother resuming
  2907.      LWPs we're not going to wait for if they'd stop immediately.  */
  2908.   if (non_stop)
  2909.     iterate_over_lwps (minus_one_ptid, resume_stopped_resumed_lwps, &ptid);

  2910.   event_ptid = linux_nat_wait_1 (ops, ptid, ourstatus, target_options);

  2911.   /* If we requested any event, and something came out, assume there
  2912.      may be more.  If we requested a specific lwp or process, also
  2913.      assume there may be more.  */
  2914.   if (target_can_async_p ()
  2915.       && ((ourstatus->kind != TARGET_WAITKIND_IGNORE
  2916.            && ourstatus->kind != TARGET_WAITKIND_NO_RESUMED)
  2917.           || !ptid_equal (ptid, minus_one_ptid)))
  2918.     async_file_mark ();

  2919.   /* Get ready for the next event.  */
  2920.   if (target_can_async_p ())
  2921.     target_async (inferior_event_handler, 0);

  2922.   return event_ptid;
  2923. }

  2924. static int
  2925. kill_callback (struct lwp_info *lp, void *data)
  2926. {
  2927.   /* PTRACE_KILL may resume the inferior.  Send SIGKILL first.  */

  2928.   errno = 0;
  2929.   kill_lwp (ptid_get_lwp (lp->ptid), SIGKILL);
  2930.   if (debug_linux_nat)
  2931.     {
  2932.       int save_errno = errno;

  2933.       fprintf_unfiltered (gdb_stdlog,
  2934.                           "KC:  kill (SIGKILL) %s, 0, 0 (%s)\n",
  2935.                           target_pid_to_str (lp->ptid),
  2936.                           save_errno ? safe_strerror (save_errno) : "OK");
  2937.     }

  2938.   /* Some kernels ignore even SIGKILL for processes under ptrace.  */

  2939.   errno = 0;
  2940.   ptrace (PTRACE_KILL, ptid_get_lwp (lp->ptid), 0, 0);
  2941.   if (debug_linux_nat)
  2942.     {
  2943.       int save_errno = errno;

  2944.       fprintf_unfiltered (gdb_stdlog,
  2945.                           "KC:  PTRACE_KILL %s, 0, 0 (%s)\n",
  2946.                           target_pid_to_str (lp->ptid),
  2947.                           save_errno ? safe_strerror (save_errno) : "OK");
  2948.     }

  2949.   return 0;
  2950. }

  2951. static int
  2952. kill_wait_callback (struct lwp_info *lp, void *data)
  2953. {
  2954.   pid_t pid;

  2955.   /* We must make sure that there are no pending events (delayed
  2956.      SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
  2957.      program doesn't interfere with any following debugging session.  */

  2958.   /* For cloned processes we must check both with __WCLONE and
  2959.      without, since the exit status of a cloned process isn't reported
  2960.      with __WCLONE.  */
  2961.   if (lp->cloned)
  2962.     {
  2963.       do
  2964.         {
  2965.           pid = my_waitpid (ptid_get_lwp (lp->ptid), NULL, __WCLONE);
  2966.           if (pid != (pid_t) -1)
  2967.             {
  2968.               if (debug_linux_nat)
  2969.                 fprintf_unfiltered (gdb_stdlog,
  2970.                                     "KWC: wait %s received unknown.\n",
  2971.                                     target_pid_to_str (lp->ptid));
  2972.               /* The Linux kernel sometimes fails to kill a thread
  2973.                  completely after PTRACE_KILL; that goes from the stop
  2974.                  point in do_fork out to the one in
  2975.                  get_signal_to_deliever and waits again.  So kill it
  2976.                  again.  */
  2977.               kill_callback (lp, NULL);
  2978.             }
  2979.         }
  2980.       while (pid == ptid_get_lwp (lp->ptid));

  2981.       gdb_assert (pid == -1 && errno == ECHILD);
  2982.     }

  2983.   do
  2984.     {
  2985.       pid = my_waitpid (ptid_get_lwp (lp->ptid), NULL, 0);
  2986.       if (pid != (pid_t) -1)
  2987.         {
  2988.           if (debug_linux_nat)
  2989.             fprintf_unfiltered (gdb_stdlog,
  2990.                                 "KWC: wait %s received unk.\n",
  2991.                                 target_pid_to_str (lp->ptid));
  2992.           /* See the call to kill_callback above.  */
  2993.           kill_callback (lp, NULL);
  2994.         }
  2995.     }
  2996.   while (pid == ptid_get_lwp (lp->ptid));

  2997.   gdb_assert (pid == -1 && errno == ECHILD);
  2998.   return 0;
  2999. }

  3000. static void
  3001. linux_nat_kill (struct target_ops *ops)
  3002. {
  3003.   struct target_waitstatus last;
  3004.   ptid_t last_ptid;
  3005.   int status;

  3006.   /* If we're stopped while forking and we haven't followed yet,
  3007.      kill the other task.  We need to do this first because the
  3008.      parent will be sleeping if this is a vfork.  */

  3009.   get_last_target_status (&last_ptid, &last);

  3010.   if (last.kind == TARGET_WAITKIND_FORKED
  3011.       || last.kind == TARGET_WAITKIND_VFORKED)
  3012.     {
  3013.       ptrace (PT_KILL, ptid_get_pid (last.value.related_pid), 0, 0);
  3014.       wait (&status);

  3015.       /* Let the arch-specific native code know this process is
  3016.          gone.  */
  3017.       linux_nat_forget_process (ptid_get_pid (last.value.related_pid));
  3018.     }

  3019.   if (forks_exist_p ())
  3020.     linux_fork_killall ();
  3021.   else
  3022.     {
  3023.       ptid_t ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));

  3024.       /* Stop all threads before killing them, since ptrace requires
  3025.          that the thread is stopped to sucessfully PTRACE_KILL.  */
  3026.       iterate_over_lwps (ptid, stop_callback, NULL);
  3027.       /* ... and wait until all of them have reported back that
  3028.          they're no longer running.  */
  3029.       iterate_over_lwps (ptid, stop_wait_callback, NULL);

  3030.       /* Kill all LWP's ...  */
  3031.       iterate_over_lwps (ptid, kill_callback, NULL);

  3032.       /* ... and wait until we've flushed all events.  */
  3033.       iterate_over_lwps (ptid, kill_wait_callback, NULL);
  3034.     }

  3035.   target_mourn_inferior ();
  3036. }

  3037. static void
  3038. linux_nat_mourn_inferior (struct target_ops *ops)
  3039. {
  3040.   int pid = ptid_get_pid (inferior_ptid);

  3041.   purge_lwp_list (pid);

  3042.   if (! forks_exist_p ())
  3043.     /* Normal case, no other forks available.  */
  3044.     linux_ops->to_mourn_inferior (ops);
  3045.   else
  3046.     /* Multi-fork case.  The current inferior_ptid has exited, but
  3047.        there are other viable forks to debug.  Delete the exiting
  3048.        one and context-switch to the first available.  */
  3049.     linux_fork_mourn_inferior ();

  3050.   /* Let the arch-specific native code know this process is gone.  */
  3051.   linux_nat_forget_process (pid);
  3052. }

  3053. /* Convert a native/host siginfo object, into/from the siginfo in the
  3054.    layout of the inferiors' architecture.  */

  3055. static void
  3056. siginfo_fixup (siginfo_t *siginfo, gdb_byte *inf_siginfo, int direction)
  3057. {
  3058.   int done = 0;

  3059.   if (linux_nat_siginfo_fixup != NULL)
  3060.     done = linux_nat_siginfo_fixup (siginfo, inf_siginfo, direction);

  3061.   /* If there was no callback, or the callback didn't do anything,
  3062.      then just do a straight memcpy.  */
  3063.   if (!done)
  3064.     {
  3065.       if (direction == 1)
  3066.         memcpy (siginfo, inf_siginfo, sizeof (siginfo_t));
  3067.       else
  3068.         memcpy (inf_siginfo, siginfo, sizeof (siginfo_t));
  3069.     }
  3070. }

  3071. static enum target_xfer_status
  3072. linux_xfer_siginfo (struct target_ops *ops, enum target_object object,
  3073.                     const char *annex, gdb_byte *readbuf,
  3074.                     const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  3075.                     ULONGEST *xfered_len)
  3076. {
  3077.   int pid;
  3078.   siginfo_t siginfo;
  3079.   gdb_byte inf_siginfo[sizeof (siginfo_t)];

  3080.   gdb_assert (object == TARGET_OBJECT_SIGNAL_INFO);
  3081.   gdb_assert (readbuf || writebuf);

  3082.   pid = ptid_get_lwp (inferior_ptid);
  3083.   if (pid == 0)
  3084.     pid = ptid_get_pid (inferior_ptid);

  3085.   if (offset > sizeof (siginfo))
  3086.     return TARGET_XFER_E_IO;

  3087.   errno = 0;
  3088.   ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
  3089.   if (errno != 0)
  3090.     return TARGET_XFER_E_IO;

  3091.   /* When GDB is built as a 64-bit application, ptrace writes into
  3092.      SIGINFO an object with 64-bit layout.  Since debugging a 32-bit
  3093.      inferior with a 64-bit GDB should look the same as debugging it
  3094.      with a 32-bit GDB, we need to convert it.  GDB core always sees
  3095.      the converted layout, so any read/write will have to be done
  3096.      post-conversion.  */
  3097.   siginfo_fixup (&siginfo, inf_siginfo, 0);

  3098.   if (offset + len > sizeof (siginfo))
  3099.     len = sizeof (siginfo) - offset;

  3100.   if (readbuf != NULL)
  3101.     memcpy (readbuf, inf_siginfo + offset, len);
  3102.   else
  3103.     {
  3104.       memcpy (inf_siginfo + offset, writebuf, len);

  3105.       /* Convert back to ptrace layout before flushing it out.  */
  3106.       siginfo_fixup (&siginfo, inf_siginfo, 1);

  3107.       errno = 0;
  3108.       ptrace (PTRACE_SETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
  3109.       if (errno != 0)
  3110.         return TARGET_XFER_E_IO;
  3111.     }

  3112.   *xfered_len = len;
  3113.   return TARGET_XFER_OK;
  3114. }

  3115. static enum target_xfer_status
  3116. linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
  3117.                         const char *annex, gdb_byte *readbuf,
  3118.                         const gdb_byte *writebuf,
  3119.                         ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
  3120. {
  3121.   struct cleanup *old_chain;
  3122.   enum target_xfer_status xfer;

  3123.   if (object == TARGET_OBJECT_SIGNAL_INFO)
  3124.     return linux_xfer_siginfo (ops, object, annex, readbuf, writebuf,
  3125.                                offset, len, xfered_len);

  3126.   /* The target is connected but no live inferior is selected.  Pass
  3127.      this request down to a lower stratum (e.g., the executable
  3128.      file).  */
  3129.   if (object == TARGET_OBJECT_MEMORY && ptid_equal (inferior_ptid, null_ptid))
  3130.     return TARGET_XFER_EOF;

  3131.   old_chain = save_inferior_ptid ();

  3132.   if (ptid_lwp_p (inferior_ptid))
  3133.     inferior_ptid = pid_to_ptid (ptid_get_lwp (inferior_ptid));

  3134.   xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
  3135.                                      offset, len, xfered_len);

  3136.   do_cleanups (old_chain);
  3137.   return xfer;
  3138. }

  3139. static int
  3140. linux_thread_alive (ptid_t ptid)
  3141. {
  3142.   int err, tmp_errno;

  3143.   gdb_assert (ptid_lwp_p (ptid));

  3144.   /* Send signal 0 instead of anything ptrace, because ptracing a
  3145.      running thread errors out claiming that the thread doesn't
  3146.      exist.  */
  3147.   err = kill_lwp (ptid_get_lwp (ptid), 0);
  3148.   tmp_errno = errno;
  3149.   if (debug_linux_nat)
  3150.     fprintf_unfiltered (gdb_stdlog,
  3151.                         "LLTA: KILL(SIG0) %s (%s)\n",
  3152.                         target_pid_to_str (ptid),
  3153.                         err ? safe_strerror (tmp_errno) : "OK");

  3154.   if (err != 0)
  3155.     return 0;

  3156.   return 1;
  3157. }

  3158. static int
  3159. linux_nat_thread_alive (struct target_ops *ops, ptid_t ptid)
  3160. {
  3161.   return linux_thread_alive (ptid);
  3162. }

  3163. static char *
  3164. linux_nat_pid_to_str (struct target_ops *ops, ptid_t ptid)
  3165. {
  3166.   static char buf[64];

  3167.   if (ptid_lwp_p (ptid)
  3168.       && (ptid_get_pid (ptid) != ptid_get_lwp (ptid)
  3169.           || num_lwps (ptid_get_pid (ptid)) > 1))
  3170.     {
  3171.       snprintf (buf, sizeof (buf), "LWP %ld", ptid_get_lwp (ptid));
  3172.       return buf;
  3173.     }

  3174.   return normal_pid_to_str (ptid);
  3175. }

  3176. static char *
  3177. linux_nat_thread_name (struct target_ops *self, struct thread_info *thr)
  3178. {
  3179.   int pid = ptid_get_pid (thr->ptid);
  3180.   long lwp = ptid_get_lwp (thr->ptid);
  3181. #define FORMAT "/proc/%d/task/%ld/comm"
  3182.   char buf[sizeof (FORMAT) + 30];
  3183.   FILE *comm_file;
  3184.   char *result = NULL;

  3185.   snprintf (buf, sizeof (buf), FORMAT, pid, lwp);
  3186.   comm_file = gdb_fopen_cloexec (buf, "r");
  3187.   if (comm_file)
  3188.     {
  3189.       /* Not exported by the kernel, so we define it here.  */
  3190. #define COMM_LEN 16
  3191.       static char line[COMM_LEN + 1];

  3192.       if (fgets (line, sizeof (line), comm_file))
  3193.         {
  3194.           char *nl = strchr (line, '\n');

  3195.           if (nl)
  3196.             *nl = '\0';
  3197.           if (*line != '\0')
  3198.             result = line;
  3199.         }

  3200.       fclose (comm_file);
  3201.     }

  3202. #undef COMM_LEN
  3203. #undef FORMAT

  3204.   return result;
  3205. }

  3206. /* Accepts an integer PID; Returns a string representing a file that
  3207.    can be opened to get the symbols for the child process.  */

  3208. static char *
  3209. linux_child_pid_to_exec_file (struct target_ops *self, int pid)
  3210. {
  3211.   static char buf[PATH_MAX];
  3212.   char name[PATH_MAX];

  3213.   xsnprintf (name, PATH_MAX, "/proc/%d/exe", pid);
  3214.   memset (buf, 0, PATH_MAX);
  3215.   if (readlink (name, buf, PATH_MAX - 1) <= 0)
  3216.     strcpy (buf, name);

  3217.   return buf;
  3218. }

  3219. /* Implement the to_xfer_partial interface for memory reads using the /proc
  3220.    filesystem.  Because we can use a single read() call for /proc, this
  3221.    can be much more efficient than banging away at PTRACE_PEEKTEXT,
  3222.    but it doesn't support writes.  */

  3223. static enum target_xfer_status
  3224. linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
  3225.                          const char *annex, gdb_byte *readbuf,
  3226.                          const gdb_byte *writebuf,
  3227.                          ULONGEST offset, LONGEST len, ULONGEST *xfered_len)
  3228. {
  3229.   LONGEST ret;
  3230.   int fd;
  3231.   char filename[64];

  3232.   if (object != TARGET_OBJECT_MEMORY || !readbuf)
  3233.     return 0;

  3234.   /* Don't bother for one word.  */
  3235.   if (len < 3 * sizeof (long))
  3236.     return TARGET_XFER_EOF;

  3237.   /* We could keep this file open and cache it - possibly one per
  3238.      thread.  That requires some juggling, but is even faster.  */
  3239.   xsnprintf (filename, sizeof filename, "/proc/%d/mem",
  3240.              ptid_get_pid (inferior_ptid));
  3241.   fd = gdb_open_cloexec (filename, O_RDONLY | O_LARGEFILE, 0);
  3242.   if (fd == -1)
  3243.     return TARGET_XFER_EOF;

  3244.   /* If pread64 is available, use it.  It's faster if the kernel
  3245.      supports it (only one syscall), and it's 64-bit safe even on
  3246.      32-bit platforms (for instance, SPARC debugging a SPARC64
  3247.      application).  */
  3248. #ifdef HAVE_PREAD64
  3249.   if (pread64 (fd, readbuf, len, offset) != len)
  3250. #else
  3251.   if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
  3252. #endif
  3253.     ret = 0;
  3254.   else
  3255.     ret = len;

  3256.   close (fd);

  3257.   if (ret == 0)
  3258.     return TARGET_XFER_EOF;
  3259.   else
  3260.     {
  3261.       *xfered_len = ret;
  3262.       return TARGET_XFER_OK;
  3263.     }
  3264. }


  3265. /* Enumerate spufs IDs for process PID.  */
  3266. static LONGEST
  3267. spu_enumerate_spu_ids (int pid, gdb_byte *buf, ULONGEST offset, ULONGEST len)
  3268. {
  3269.   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
  3270.   LONGEST pos = 0;
  3271.   LONGEST written = 0;
  3272.   char path[128];
  3273.   DIR *dir;
  3274.   struct dirent *entry;

  3275.   xsnprintf (path, sizeof path, "/proc/%d/fd", pid);
  3276.   dir = opendir (path);
  3277.   if (!dir)
  3278.     return -1;

  3279.   rewinddir (dir);
  3280.   while ((entry = readdir (dir)) != NULL)
  3281.     {
  3282.       struct stat st;
  3283.       struct statfs stfs;
  3284.       int fd;

  3285.       fd = atoi (entry->d_name);
  3286.       if (!fd)
  3287.         continue;

  3288.       xsnprintf (path, sizeof path, "/proc/%d/fd/%d", pid, fd);
  3289.       if (stat (path, &st) != 0)
  3290.         continue;
  3291.       if (!S_ISDIR (st.st_mode))
  3292.         continue;

  3293.       if (statfs (path, &stfs) != 0)
  3294.         continue;
  3295.       if (stfs.f_type != SPUFS_MAGIC)
  3296.         continue;

  3297.       if (pos >= offset && pos + 4 <= offset + len)
  3298.         {
  3299.           store_unsigned_integer (buf + pos - offset, 4, byte_order, fd);
  3300.           written += 4;
  3301.         }
  3302.       pos += 4;
  3303.     }

  3304.   closedir (dir);
  3305.   return written;
  3306. }

  3307. /* Implement the to_xfer_partial interface for the TARGET_OBJECT_SPU
  3308.    object type, using the /proc file system.  */

  3309. static enum target_xfer_status
  3310. linux_proc_xfer_spu (struct target_ops *ops, enum target_object object,
  3311.                      const char *annex, gdb_byte *readbuf,
  3312.                      const gdb_byte *writebuf,
  3313.                      ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
  3314. {
  3315.   char buf[128];
  3316.   int fd = 0;
  3317.   int ret = -1;
  3318.   int pid = ptid_get_pid (inferior_ptid);

  3319.   if (!annex)
  3320.     {
  3321.       if (!readbuf)
  3322.         return TARGET_XFER_E_IO;
  3323.       else
  3324.         {
  3325.           LONGEST l = spu_enumerate_spu_ids (pid, readbuf, offset, len);

  3326.           if (l < 0)
  3327.             return TARGET_XFER_E_IO;
  3328.           else if (l == 0)
  3329.             return TARGET_XFER_EOF;
  3330.           else
  3331.             {
  3332.               *xfered_len = (ULONGEST) l;
  3333.               return TARGET_XFER_OK;
  3334.             }
  3335.         }
  3336.     }

  3337.   xsnprintf (buf, sizeof buf, "/proc/%d/fd/%s", pid, annex);
  3338.   fd = gdb_open_cloexec (buf, writebuf? O_WRONLY : O_RDONLY, 0);
  3339.   if (fd <= 0)
  3340.     return TARGET_XFER_E_IO;

  3341.   if (offset != 0
  3342.       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
  3343.     {
  3344.       close (fd);
  3345.       return TARGET_XFER_EOF;
  3346.     }

  3347.   if (writebuf)
  3348.     ret = write (fd, writebuf, (size_t) len);
  3349.   else if (readbuf)
  3350.     ret = read (fd, readbuf, (size_t) len);

  3351.   close (fd);

  3352.   if (ret < 0)
  3353.     return TARGET_XFER_E_IO;
  3354.   else if (ret == 0)
  3355.     return TARGET_XFER_EOF;
  3356.   else
  3357.     {
  3358.       *xfered_len = (ULONGEST) ret;
  3359.       return TARGET_XFER_OK;
  3360.     }
  3361. }


  3362. /* Parse LINE as a signal set and add its set bits to SIGS.  */

  3363. static void
  3364. add_line_to_sigset (const char *line, sigset_t *sigs)
  3365. {
  3366.   int len = strlen (line) - 1;
  3367.   const char *p;
  3368.   int signum;

  3369.   if (line[len] != '\n')
  3370.     error (_("Could not parse signal set: %s"), line);

  3371.   p = line;
  3372.   signum = len * 4;
  3373.   while (len-- > 0)
  3374.     {
  3375.       int digit;

  3376.       if (*p >= '0' && *p <= '9')
  3377.         digit = *p - '0';
  3378.       else if (*p >= 'a' && *p <= 'f')
  3379.         digit = *p - 'a' + 10;
  3380.       else
  3381.         error (_("Could not parse signal set: %s"), line);

  3382.       signum -= 4;

  3383.       if (digit & 1)
  3384.         sigaddset (sigs, signum + 1);
  3385.       if (digit & 2)
  3386.         sigaddset (sigs, signum + 2);
  3387.       if (digit & 4)
  3388.         sigaddset (sigs, signum + 3);
  3389.       if (digit & 8)
  3390.         sigaddset (sigs, signum + 4);

  3391.       p++;
  3392.     }
  3393. }

  3394. /* Find process PID's pending signals from /proc/pid/status and set
  3395.    SIGS to match.  */

  3396. void
  3397. linux_proc_pending_signals (int pid, sigset_t *pending,
  3398.                             sigset_t *blocked, sigset_t *ignored)
  3399. {
  3400.   FILE *procfile;
  3401.   char buffer[PATH_MAX], fname[PATH_MAX];
  3402.   struct cleanup *cleanup;

  3403.   sigemptyset (pending);
  3404.   sigemptyset (blocked);
  3405.   sigemptyset (ignored);
  3406.   xsnprintf (fname, sizeof fname, "/proc/%d/status", pid);
  3407.   procfile = gdb_fopen_cloexec (fname, "r");
  3408.   if (procfile == NULL)
  3409.     error (_("Could not open %s"), fname);
  3410.   cleanup = make_cleanup_fclose (procfile);

  3411.   while (fgets (buffer, PATH_MAX, procfile) != NULL)
  3412.     {
  3413.       /* Normal queued signals are on the SigPnd line in the status
  3414.          file.  However, 2.6 kernels also have a "shared" pending
  3415.          queue for delivering signals to a thread group, so check for
  3416.          a ShdPnd line also.

  3417.          Unfortunately some Red Hat kernels include the shared pending
  3418.          queue but not the ShdPnd status field.  */

  3419.       if (strncmp (buffer, "SigPnd:\t", 8) == 0)
  3420.         add_line_to_sigset (buffer + 8, pending);
  3421.       else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
  3422.         add_line_to_sigset (buffer + 8, pending);
  3423.       else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
  3424.         add_line_to_sigset (buffer + 8, blocked);
  3425.       else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
  3426.         add_line_to_sigset (buffer + 8, ignored);
  3427.     }

  3428.   do_cleanups (cleanup);
  3429. }

  3430. static enum target_xfer_status
  3431. linux_nat_xfer_osdata (struct target_ops *ops, enum target_object object,
  3432.                        const char *annex, gdb_byte *readbuf,
  3433.                        const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  3434.                        ULONGEST *xfered_len)
  3435. {
  3436.   gdb_assert (object == TARGET_OBJECT_OSDATA);

  3437.   *xfered_len = linux_common_xfer_osdata (annex, readbuf, offset, len);
  3438.   if (*xfered_len == 0)
  3439.     return TARGET_XFER_EOF;
  3440.   else
  3441.     return TARGET_XFER_OK;
  3442. }

  3443. static enum target_xfer_status
  3444. linux_xfer_partial (struct target_ops *ops, enum target_object object,
  3445.                     const char *annex, gdb_byte *readbuf,
  3446.                     const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  3447.                     ULONGEST *xfered_len)
  3448. {
  3449.   enum target_xfer_status xfer;

  3450.   if (object == TARGET_OBJECT_AUXV)
  3451.     return memory_xfer_auxv (ops, object, annex, readbuf, writebuf,
  3452.                              offset, len, xfered_len);

  3453.   if (object == TARGET_OBJECT_OSDATA)
  3454.     return linux_nat_xfer_osdata (ops, object, annex, readbuf, writebuf,
  3455.                                   offset, len, xfered_len);

  3456.   if (object == TARGET_OBJECT_SPU)
  3457.     return linux_proc_xfer_spu (ops, object, annex, readbuf, writebuf,
  3458.                                 offset, len, xfered_len);

  3459.   /* GDB calculates all the addresses in possibly larget width of the address.
  3460.      Address width needs to be masked before its final use - either by
  3461.      linux_proc_xfer_partial or inf_ptrace_xfer_partial.

  3462.      Compare ADDR_BIT first to avoid a compiler warning on shift overflow.  */

  3463.   if (object == TARGET_OBJECT_MEMORY)
  3464.     {
  3465.       int addr_bit = gdbarch_addr_bit (target_gdbarch ());

  3466.       if (addr_bit < (sizeof (ULONGEST) * HOST_CHAR_BIT))
  3467.         offset &= ((ULONGEST) 1 << addr_bit) - 1;
  3468.     }

  3469.   xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
  3470.                                   offset, len, xfered_len);
  3471.   if (xfer != TARGET_XFER_EOF)
  3472.     return xfer;

  3473.   return super_xfer_partial (ops, object, annex, readbuf, writebuf,
  3474.                              offset, len, xfered_len);
  3475. }

  3476. static void
  3477. cleanup_target_stop (void *arg)
  3478. {
  3479.   ptid_t *ptid = (ptid_t *) arg;

  3480.   gdb_assert (arg != NULL);

  3481.   /* Unpause all */
  3482.   target_resume (*ptid, 0, GDB_SIGNAL_0);
  3483. }

  3484. static VEC(static_tracepoint_marker_p) *
  3485. linux_child_static_tracepoint_markers_by_strid (struct target_ops *self,
  3486.                                                 const char *strid)
  3487. {
  3488.   char s[IPA_CMD_BUF_SIZE];
  3489.   struct cleanup *old_chain;
  3490.   int pid = ptid_get_pid (inferior_ptid);
  3491.   VEC(static_tracepoint_marker_p) *markers = NULL;
  3492.   struct static_tracepoint_marker *marker = NULL;
  3493.   char *p = s;
  3494.   ptid_t ptid = ptid_build (pid, 0, 0);

  3495.   /* Pause all */
  3496.   target_stop (ptid);

  3497.   memcpy (s, "qTfSTM", sizeof ("qTfSTM"));
  3498.   s[sizeof ("qTfSTM")] = 0;

  3499.   agent_run_command (pid, s, strlen (s) + 1);

  3500.   old_chain = make_cleanup (free_current_marker, &marker);
  3501.   make_cleanup (cleanup_target_stop, &ptid);

  3502.   while (*p++ == 'm')
  3503.     {
  3504.       if (marker == NULL)
  3505.         marker = XCNEW (struct static_tracepoint_marker);

  3506.       do
  3507.         {
  3508.           parse_static_tracepoint_marker_definition (p, &p, marker);

  3509.           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
  3510.             {
  3511.               VEC_safe_push (static_tracepoint_marker_p,
  3512.                              markers, marker);
  3513.               marker = NULL;
  3514.             }
  3515.           else
  3516.             {
  3517.               release_static_tracepoint_marker (marker);
  3518.               memset (marker, 0, sizeof (*marker));
  3519.             }
  3520.         }
  3521.       while (*p++ == ',');        /* comma-separated list */

  3522.       memcpy (s, "qTsSTM", sizeof ("qTsSTM"));
  3523.       s[sizeof ("qTsSTM")] = 0;
  3524.       agent_run_command (pid, s, strlen (s) + 1);
  3525.       p = s;
  3526.     }

  3527.   do_cleanups (old_chain);

  3528.   return markers;
  3529. }

  3530. /* Create a prototype generic GNU/Linux target.  The client can override
  3531.    it with local methods.  */

  3532. static void
  3533. linux_target_install_ops (struct target_ops *t)
  3534. {
  3535.   t->to_insert_fork_catchpoint = linux_child_insert_fork_catchpoint;
  3536.   t->to_remove_fork_catchpoint = linux_child_remove_fork_catchpoint;
  3537.   t->to_insert_vfork_catchpoint = linux_child_insert_vfork_catchpoint;
  3538.   t->to_remove_vfork_catchpoint = linux_child_remove_vfork_catchpoint;
  3539.   t->to_insert_exec_catchpoint = linux_child_insert_exec_catchpoint;
  3540.   t->to_remove_exec_catchpoint = linux_child_remove_exec_catchpoint;
  3541.   t->to_set_syscall_catchpoint = linux_child_set_syscall_catchpoint;
  3542.   t->to_pid_to_exec_file = linux_child_pid_to_exec_file;
  3543.   t->to_post_startup_inferior = linux_child_post_startup_inferior;
  3544.   t->to_post_attach = linux_child_post_attach;
  3545.   t->to_follow_fork = linux_child_follow_fork;

  3546.   super_xfer_partial = t->to_xfer_partial;
  3547.   t->to_xfer_partial = linux_xfer_partial;

  3548.   t->to_static_tracepoint_markers_by_strid
  3549.     = linux_child_static_tracepoint_markers_by_strid;
  3550. }

  3551. struct target_ops *
  3552. linux_target (void)
  3553. {
  3554.   struct target_ops *t;

  3555.   t = inf_ptrace_target ();
  3556.   linux_target_install_ops (t);

  3557.   return t;
  3558. }

  3559. struct target_ops *
  3560. linux_trad_target (CORE_ADDR (*register_u_offset)(struct gdbarch *, int, int))
  3561. {
  3562.   struct target_ops *t;

  3563.   t = inf_ptrace_trad_target (register_u_offset);
  3564.   linux_target_install_ops (t);

  3565.   return t;
  3566. }

  3567. /* target_is_async_p implementation.  */

  3568. static int
  3569. linux_nat_is_async_p (struct target_ops *ops)
  3570. {
  3571.   /* NOTE: palves 2008-03-21: We're only async when the user requests
  3572.      it explicitly with the "set target-async" command.
  3573.      Someday, linux will always be async.  */
  3574.   return target_async_permitted;
  3575. }

  3576. /* target_can_async_p implementation.  */

  3577. static int
  3578. linux_nat_can_async_p (struct target_ops *ops)
  3579. {
  3580.   /* NOTE: palves 2008-03-21: We're only async when the user requests
  3581.      it explicitly with the "set target-async" command.
  3582.      Someday, linux will always be async.  */
  3583.   return target_async_permitted;
  3584. }

  3585. static int
  3586. linux_nat_supports_non_stop (struct target_ops *self)
  3587. {
  3588.   return 1;
  3589. }

  3590. /* True if we want to support multi-process.  To be removed when GDB
  3591.    supports multi-exec.  */

  3592. int linux_multi_process = 1;

  3593. static int
  3594. linux_nat_supports_multi_process (struct target_ops *self)
  3595. {
  3596.   return linux_multi_process;
  3597. }

  3598. static int
  3599. linux_nat_supports_disable_randomization (struct target_ops *self)
  3600. {
  3601. #ifdef HAVE_PERSONALITY
  3602.   return 1;
  3603. #else
  3604.   return 0;
  3605. #endif
  3606. }

  3607. static int async_terminal_is_ours = 1;

  3608. /* target_terminal_inferior implementation.

  3609.    This is a wrapper around child_terminal_inferior to add async support.  */

  3610. static void
  3611. linux_nat_terminal_inferior (struct target_ops *self)
  3612. {
  3613.   if (!target_is_async_p ())
  3614.     {
  3615.       /* Async mode is disabled.  */
  3616.       child_terminal_inferior (self);
  3617.       return;
  3618.     }

  3619.   child_terminal_inferior (self);

  3620.   /* Calls to target_terminal_*() are meant to be idempotent.  */
  3621.   if (!async_terminal_is_ours)
  3622.     return;

  3623.   delete_file_handler (input_fd);
  3624.   async_terminal_is_ours = 0;
  3625.   set_sigint_trap ();
  3626. }

  3627. /* target_terminal_ours implementation.

  3628.    This is a wrapper around child_terminal_ours to add async support (and
  3629.    implement the target_terminal_ours vs target_terminal_ours_for_output
  3630.    distinction).  child_terminal_ours is currently no different than
  3631.    child_terminal_ours_for_output.
  3632.    We leave target_terminal_ours_for_output alone, leaving it to
  3633.    child_terminal_ours_for_output.  */

  3634. static void
  3635. linux_nat_terminal_ours (struct target_ops *self)
  3636. {
  3637.   if (!target_is_async_p ())
  3638.     {
  3639.       /* Async mode is disabled.  */
  3640.       child_terminal_ours (self);
  3641.       return;
  3642.     }

  3643.   /* GDB should never give the terminal to the inferior if the
  3644.      inferior is running in the background (run&, continue&, etc.),
  3645.      but claiming it sure should.  */
  3646.   child_terminal_ours (self);

  3647.   if (async_terminal_is_ours)
  3648.     return;

  3649.   clear_sigint_trap ();
  3650.   add_file_handler (input_fd, stdin_event_handler, 0);
  3651.   async_terminal_is_ours = 1;
  3652. }

  3653. static void (*async_client_callback) (enum inferior_event_type event_type,
  3654.                                       void *context);
  3655. static void *async_client_context;

  3656. /* SIGCHLD handler that serves two purposes: In non-stop/async mode,
  3657.    so we notice when any child changes state, and notify the
  3658.    event-loop; it allows us to use sigsuspend in linux_nat_wait_1
  3659.    above to wait for the arrival of a SIGCHLD.  */

  3660. static void
  3661. sigchld_handler (int signo)
  3662. {
  3663.   int old_errno = errno;

  3664.   if (debug_linux_nat)
  3665.     ui_file_write_async_safe (gdb_stdlog,
  3666.                               "sigchld\n", sizeof ("sigchld\n") - 1);

  3667.   if (signo == SIGCHLD
  3668.       && linux_nat_event_pipe[0] != -1)
  3669.     async_file_mark (); /* Let the event loop know that there are
  3670.                            events to handle.  */

  3671.   errno = old_errno;
  3672. }

  3673. /* Callback registered with the target events file descriptor.  */

  3674. static void
  3675. handle_target_event (int error, gdb_client_data client_data)
  3676. {
  3677.   (*async_client_callback) (INF_REG_EVENT, async_client_context);
  3678. }

  3679. /* Create/destroy the target events pipe.  Returns previous state.  */

  3680. static int
  3681. linux_async_pipe (int enable)
  3682. {
  3683.   int previous = (linux_nat_event_pipe[0] != -1);

  3684.   if (previous != enable)
  3685.     {
  3686.       sigset_t prev_mask;

  3687.       /* Block child signals while we create/destroy the pipe, as
  3688.          their handler writes to it.  */
  3689.       block_child_signals (&prev_mask);

  3690.       if (enable)
  3691.         {
  3692.           if (gdb_pipe_cloexec (linux_nat_event_pipe) == -1)
  3693.             internal_error (__FILE__, __LINE__,
  3694.                             "creating event pipe failed.");

  3695.           fcntl (linux_nat_event_pipe[0], F_SETFL, O_NONBLOCK);
  3696.           fcntl (linux_nat_event_pipe[1], F_SETFL, O_NONBLOCK);
  3697.         }
  3698.       else
  3699.         {
  3700.           close (linux_nat_event_pipe[0]);
  3701.           close (linux_nat_event_pipe[1]);
  3702.           linux_nat_event_pipe[0] = -1;
  3703.           linux_nat_event_pipe[1] = -1;
  3704.         }

  3705.       restore_child_signals_mask (&prev_mask);
  3706.     }

  3707.   return previous;
  3708. }

  3709. /* target_async implementation.  */

  3710. static void
  3711. linux_nat_async (struct target_ops *ops,
  3712.                  void (*callback) (enum inferior_event_type event_type,
  3713.                                    void *context),
  3714.                  void *context)
  3715. {
  3716.   if (callback != NULL)
  3717.     {
  3718.       async_client_callback = callback;
  3719.       async_client_context = context;
  3720.       if (!linux_async_pipe (1))
  3721.         {
  3722.           add_file_handler (linux_nat_event_pipe[0],
  3723.                             handle_target_event, NULL);
  3724.           /* There may be pending events to handle.  Tell the event loop
  3725.              to poll them.  */
  3726.           async_file_mark ();
  3727.         }
  3728.     }
  3729.   else
  3730.     {
  3731.       async_client_callback = callback;
  3732.       async_client_context = context;
  3733.       delete_file_handler (linux_nat_event_pipe[0]);
  3734.       linux_async_pipe (0);
  3735.     }
  3736.   return;
  3737. }

  3738. /* Stop an LWP, and push a GDB_SIGNAL_0 stop status if no other
  3739.    event came out.  */

  3740. static int
  3741. linux_nat_stop_lwp (struct lwp_info *lwp, void *data)
  3742. {
  3743.   if (!lwp->stopped)
  3744.     {
  3745.       if (debug_linux_nat)
  3746.         fprintf_unfiltered (gdb_stdlog,
  3747.                             "LNSL: running -> suspending %s\n",
  3748.                             target_pid_to_str (lwp->ptid));


  3749.       if (lwp->last_resume_kind == resume_stop)
  3750.         {
  3751.           if (debug_linux_nat)
  3752.             fprintf_unfiltered (gdb_stdlog,
  3753.                                 "linux-nat: already stopping LWP %ld at "
  3754.                                 "GDB's request\n",
  3755.                                 ptid_get_lwp (lwp->ptid));
  3756.           return 0;
  3757.         }

  3758.       stop_callback (lwp, NULL);
  3759.       lwp->last_resume_kind = resume_stop;
  3760.     }
  3761.   else
  3762.     {
  3763.       /* Already known to be stopped; do nothing.  */

  3764.       if (debug_linux_nat)
  3765.         {
  3766.           if (find_thread_ptid (lwp->ptid)->stop_requested)
  3767.             fprintf_unfiltered (gdb_stdlog,
  3768.                                 "LNSL: already stopped/stop_requested %s\n",
  3769.                                 target_pid_to_str (lwp->ptid));
  3770.           else
  3771.             fprintf_unfiltered (gdb_stdlog,
  3772.                                 "LNSL: already stopped/no "
  3773.                                 "stop_requested yet %s\n",
  3774.                                 target_pid_to_str (lwp->ptid));
  3775.         }
  3776.     }
  3777.   return 0;
  3778. }

  3779. static void
  3780. linux_nat_stop (struct target_ops *self, ptid_t ptid)
  3781. {
  3782.   if (non_stop)
  3783.     iterate_over_lwps (ptid, linux_nat_stop_lwp, NULL);
  3784.   else
  3785.     linux_ops->to_stop (linux_ops, ptid);
  3786. }

  3787. static void
  3788. linux_nat_close (struct target_ops *self)
  3789. {
  3790.   /* Unregister from the event loop.  */
  3791.   if (linux_nat_is_async_p (self))
  3792.     linux_nat_async (self, NULL, NULL);

  3793.   if (linux_ops->to_close)
  3794.     linux_ops->to_close (linux_ops);

  3795.   super_close (self);
  3796. }

  3797. /* When requests are passed down from the linux-nat layer to the
  3798.    single threaded inf-ptrace layer, ptids of (lwpid,0,0) form are
  3799.    used.  The address space pointer is stored in the inferior object,
  3800.    but the common code that is passed such ptid can't tell whether
  3801.    lwpid is a "main" process id or not (it assumes so).  We reverse
  3802.    look up the "main" process id from the lwp here.  */

  3803. static struct address_space *
  3804. linux_nat_thread_address_space (struct target_ops *t, ptid_t ptid)
  3805. {
  3806.   struct lwp_info *lwp;
  3807.   struct inferior *inf;
  3808.   int pid;

  3809.   if (ptid_get_lwp (ptid) == 0)
  3810.     {
  3811.       /* An (lwpid,0,0) ptid.  Look up the lwp object to get at the
  3812.          tgid.  */
  3813.       lwp = find_lwp_pid (ptid);
  3814.       pid = ptid_get_pid (lwp->ptid);
  3815.     }
  3816.   else
  3817.     {
  3818.       /* A (pid,lwpid,0) ptid.  */
  3819.       pid = ptid_get_pid (ptid);
  3820.     }

  3821.   inf = find_inferior_pid (pid);
  3822.   gdb_assert (inf != NULL);
  3823.   return inf->aspace;
  3824. }

  3825. /* Return the cached value of the processor core for thread PTID.  */

  3826. static int
  3827. linux_nat_core_of_thread (struct target_ops *ops, ptid_t ptid)
  3828. {
  3829.   struct lwp_info *info = find_lwp_pid (ptid);

  3830.   if (info)
  3831.     return info->core;
  3832.   return -1;
  3833. }

  3834. void
  3835. linux_nat_add_target (struct target_ops *t)
  3836. {
  3837.   /* Save the provided single-threaded target.  We save this in a separate
  3838.      variable because another target we've inherited from (e.g. inf-ptrace)
  3839.      may have saved a pointer to T; we want to use it for the final
  3840.      process stratum target.  */
  3841.   linux_ops_saved = *t;
  3842.   linux_ops = &linux_ops_saved;

  3843.   /* Override some methods for multithreading.  */
  3844.   t->to_create_inferior = linux_nat_create_inferior;
  3845.   t->to_attach = linux_nat_attach;
  3846.   t->to_detach = linux_nat_detach;
  3847.   t->to_resume = linux_nat_resume;
  3848.   t->to_wait = linux_nat_wait;
  3849.   t->to_pass_signals = linux_nat_pass_signals;
  3850.   t->to_xfer_partial = linux_nat_xfer_partial;
  3851.   t->to_kill = linux_nat_kill;
  3852.   t->to_mourn_inferior = linux_nat_mourn_inferior;
  3853.   t->to_thread_alive = linux_nat_thread_alive;
  3854.   t->to_pid_to_str = linux_nat_pid_to_str;
  3855.   t->to_thread_name = linux_nat_thread_name;
  3856.   t->to_has_thread_control = tc_schedlock;
  3857.   t->to_thread_address_space = linux_nat_thread_address_space;
  3858.   t->to_stopped_by_watchpoint = linux_nat_stopped_by_watchpoint;
  3859.   t->to_stopped_data_address = linux_nat_stopped_data_address;

  3860.   t->to_can_async_p = linux_nat_can_async_p;
  3861.   t->to_is_async_p = linux_nat_is_async_p;
  3862.   t->to_supports_non_stop = linux_nat_supports_non_stop;
  3863.   t->to_async = linux_nat_async;
  3864.   t->to_terminal_inferior = linux_nat_terminal_inferior;
  3865.   t->to_terminal_ours = linux_nat_terminal_ours;

  3866.   super_close = t->to_close;
  3867.   t->to_close = linux_nat_close;

  3868.   /* Methods for non-stop support.  */
  3869.   t->to_stop = linux_nat_stop;

  3870.   t->to_supports_multi_process = linux_nat_supports_multi_process;

  3871.   t->to_supports_disable_randomization
  3872.     = linux_nat_supports_disable_randomization;

  3873.   t->to_core_of_thread = linux_nat_core_of_thread;

  3874.   /* We don't change the stratum; this target will sit at
  3875.      process_stratum and thread_db will set at thread_stratum.  This
  3876.      is a little strange, since this is a multi-threaded-capable
  3877.      target, but we want to be on the stack below thread_db, and we
  3878.      also want to be used for single-threaded processes.  */

  3879.   add_target (t);
  3880. }

  3881. /* Register a method to call whenever a new thread is attached.  */
  3882. void
  3883. linux_nat_set_new_thread (struct target_ops *t,
  3884.                           void (*new_thread) (struct lwp_info *))
  3885. {
  3886.   /* Save the pointer.  We only support a single registered instance
  3887.      of the GNU/Linux native target, so we do not need to map this to
  3888.      T.  */
  3889.   linux_nat_new_thread = new_thread;
  3890. }

  3891. /* See declaration in linux-nat.h.  */

  3892. void
  3893. linux_nat_set_new_fork (struct target_ops *t,
  3894.                         linux_nat_new_fork_ftype *new_fork)
  3895. {
  3896.   /* Save the pointer.  */
  3897.   linux_nat_new_fork = new_fork;
  3898. }

  3899. /* See declaration in linux-nat.h.  */

  3900. void
  3901. linux_nat_set_forget_process (struct target_ops *t,
  3902.                               linux_nat_forget_process_ftype *fn)
  3903. {
  3904.   /* Save the pointer.  */
  3905.   linux_nat_forget_process_hook = fn;
  3906. }

  3907. /* See declaration in linux-nat.h.  */

  3908. void
  3909. linux_nat_forget_process (pid_t pid)
  3910. {
  3911.   if (linux_nat_forget_process_hook != NULL)
  3912.     linux_nat_forget_process_hook (pid);
  3913. }

  3914. /* Register a method that converts a siginfo object between the layout
  3915.    that ptrace returns, and the layout in the architecture of the
  3916.    inferior.  */
  3917. void
  3918. linux_nat_set_siginfo_fixup (struct target_ops *t,
  3919.                              int (*siginfo_fixup) (siginfo_t *,
  3920.                                                    gdb_byte *,
  3921.                                                    int))
  3922. {
  3923.   /* Save the pointer.  */
  3924.   linux_nat_siginfo_fixup = siginfo_fixup;
  3925. }

  3926. /* Register a method to call prior to resuming a thread.  */

  3927. void
  3928. linux_nat_set_prepare_to_resume (struct target_ops *t,
  3929.                                  void (*prepare_to_resume) (struct lwp_info *))
  3930. {
  3931.   /* Save the pointer.  */
  3932.   linux_nat_prepare_to_resume = prepare_to_resume;
  3933. }

  3934. /* See linux-nat.h.  */

  3935. int
  3936. linux_nat_get_siginfo (ptid_t ptid, siginfo_t *siginfo)
  3937. {
  3938.   int pid;

  3939.   pid = ptid_get_lwp (ptid);
  3940.   if (pid == 0)
  3941.     pid = ptid_get_pid (ptid);

  3942.   errno = 0;
  3943.   ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, siginfo);
  3944.   if (errno != 0)
  3945.     {
  3946.       memset (siginfo, 0, sizeof (*siginfo));
  3947.       return 0;
  3948.     }
  3949.   return 1;
  3950. }

  3951. /* Provide a prototype to silence -Wmissing-prototypes.  */
  3952. extern initialize_file_ftype _initialize_linux_nat;

  3953. void
  3954. _initialize_linux_nat (void)
  3955. {
  3956.   add_setshow_zuinteger_cmd ("lin-lwp", class_maintenance,
  3957.                              &debug_linux_nat, _("\
  3958. Set debugging of GNU/Linux lwp module."), _("\
  3959. Show debugging of GNU/Linux lwp module."), _("\
  3960. Enables printf debugging output."),
  3961.                              NULL,
  3962.                              show_debug_linux_nat,
  3963.                              &setdebuglist, &showdebuglist);

  3964.   /* Save this mask as the default.  */
  3965.   sigprocmask (SIG_SETMASK, NULL, &normal_mask);

  3966.   /* Install a SIGCHLD handler.  */
  3967.   sigchld_action.sa_handler = sigchld_handler;
  3968.   sigemptyset (&sigchld_action.sa_mask);
  3969.   sigchld_action.sa_flags = SA_RESTART;

  3970.   /* Make it the default.  */
  3971.   sigaction (SIGCHLD, &sigchld_action, NULL);

  3972.   /* Make sure we don't block SIGCHLD during a sigsuspend.  */
  3973.   sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
  3974.   sigdelset (&suspend_mask, SIGCHLD);

  3975.   sigemptyset (&blocked_mask);

  3976.   /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to
  3977.      support read-only process state.  */
  3978.   linux_ptrace_set_additional_flags (PTRACE_O_TRACESYSGOOD
  3979.                                      | PTRACE_O_TRACEVFORKDONE
  3980.                                      | PTRACE_O_TRACEVFORK
  3981.                                      | PTRACE_O_TRACEFORK
  3982.                                      | PTRACE_O_TRACEEXEC);
  3983. }


  3984. /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
  3985.    the GNU/Linux Threads library and therefore doesn't really belong
  3986.    here.  */

  3987. /* Read variable NAME in the target and return its value if found.
  3988.    Otherwise return zero.  It is assumed that the type of the variable
  3989.    is `int'.  */

  3990. static int
  3991. get_signo (const char *name)
  3992. {
  3993.   struct bound_minimal_symbol ms;
  3994.   int signo;

  3995.   ms = lookup_minimal_symbol (name, NULL, NULL);
  3996.   if (ms.minsym == NULL)
  3997.     return 0;

  3998.   if (target_read_memory (BMSYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
  3999.                           sizeof (signo)) != 0)
  4000.     return 0;

  4001.   return signo;
  4002. }

  4003. /* Return the set of signals used by the threads library in *SET.  */

  4004. void
  4005. lin_thread_get_thread_signals (sigset_t *set)
  4006. {
  4007.   struct sigaction action;
  4008.   int restart, cancel;

  4009.   sigemptyset (&blocked_mask);
  4010.   sigemptyset (set);

  4011.   restart = get_signo ("__pthread_sig_restart");
  4012.   cancel = get_signo ("__pthread_sig_cancel");

  4013.   /* LinuxThreads normally uses the first two RT signals, but in some legacy
  4014.      cases may use SIGUSR1/SIGUSR2.  NPTL always uses RT signals, but does
  4015.      not provide any way for the debugger to query the signal numbers -
  4016.      fortunately they don't change!  */

  4017.   if (restart == 0)
  4018.     restart = __SIGRTMIN;

  4019.   if (cancel == 0)
  4020.     cancel = __SIGRTMIN + 1;

  4021.   sigaddset (set, restart);
  4022.   sigaddset (set, cancel);

  4023.   /* The GNU/Linux Threads library makes terminating threads send a
  4024.      special "cancel" signal instead of SIGCHLD.  Make sure we catch
  4025.      those (to prevent them from terminating GDB itself, which is
  4026.      likely to be their default action) and treat them the same way as
  4027.      SIGCHLD.  */

  4028.   action.sa_handler = sigchld_handler;
  4029.   sigemptyset (&action.sa_mask);
  4030.   action.sa_flags = SA_RESTART;
  4031.   sigaction (cancel, &action, NULL);

  4032.   /* We block the "cancel" signal throughout this code ...  */
  4033.   sigaddset (&blocked_mask, cancel);
  4034.   sigprocmask (SIG_BLOCK, &blocked_mask, NULL);

  4035.   /* ... except during a sigsuspend.  */
  4036.   sigdelset (&suspend_mask, cancel);
  4037. }