Home | History | Annotate | Line # | Download | only in gdb
linux-nat.c revision 1.8
      1 /* GNU/Linux native-dependent code common to multiple platforms.
      2 
      3    Copyright (C) 2001-2019 Free Software Foundation, Inc.
      4 
      5    This file is part of GDB.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     19 
     20 #include "defs.h"
     21 #include "inferior.h"
     22 #include "infrun.h"
     23 #include "target.h"
     24 #include "nat/linux-nat.h"
     25 #include "nat/linux-waitpid.h"
     26 #include "common/gdb_wait.h"
     27 #include <unistd.h>
     28 #include <sys/syscall.h>
     29 #include "nat/gdb_ptrace.h"
     30 #include "linux-nat.h"
     31 #include "nat/linux-ptrace.h"
     32 #include "nat/linux-procfs.h"
     33 #include "nat/linux-personality.h"
     34 #include "linux-fork.h"
     35 #include "gdbthread.h"
     36 #include "gdbcmd.h"
     37 #include "regcache.h"
     38 #include "regset.h"
     39 #include "inf-child.h"
     40 #include "inf-ptrace.h"
     41 #include "auxv.h"
     42 #include <sys/procfs.h>		/* for elf_gregset etc.  */
     43 #include "elf-bfd.h"		/* for elfcore_write_* */
     44 #include "gregset.h"		/* for gregset */
     45 #include "gdbcore.h"		/* for get_exec_file */
     46 #include <ctype.h>		/* for isdigit */
     47 #include <sys/stat.h>		/* for struct stat */
     48 #include <fcntl.h>		/* for O_RDONLY */
     49 #include "inf-loop.h"
     50 #include "event-loop.h"
     51 #include "event-top.h"
     52 #include <pwd.h>
     53 #include <sys/types.h>
     54 #include <dirent.h>
     55 #include "xml-support.h"
     56 #include <sys/vfs.h>
     57 #include "solib.h"
     58 #include "nat/linux-osdata.h"
     59 #include "linux-tdep.h"
     60 #include "symfile.h"
     61 #include "common/agent.h"
     62 #include "tracepoint.h"
     63 #include "common/buffer.h"
     64 #include "target-descriptions.h"
     65 #include "common/filestuff.h"
     66 #include "objfiles.h"
     67 #include "nat/linux-namespaces.h"
     68 #include "common/fileio.h"
     69 #include "common/scope-exit.h"
     70 
     71 #ifndef SPUFS_MAGIC
     72 #define SPUFS_MAGIC 0x23c9b64e
     73 #endif
     74 
     75 /* This comment documents high-level logic of this file.
     76 
     77 Waiting for events in sync mode
     78 ===============================
     79 
     80 When waiting for an event in a specific thread, we just use waitpid,
     81 passing the specific pid, and not passing WNOHANG.
     82 
     83 When waiting for an event in all threads, waitpid is not quite good:
     84 
     85 - If the thread group leader exits while other threads in the thread
     86   group still exist, waitpid(TGID, ...) hangs.  That waitpid won't
     87   return an exit status until the other threads in the group are
     88   reaped.
     89 
     90 - When a non-leader thread execs, that thread just vanishes without
     91   reporting an exit (so we'd hang if we waited for it explicitly in
     92   that case).  The exec event is instead reported to the TGID pid.
     93 
     94 The solution is to always use -1 and WNOHANG, together with
     95 sigsuspend.
     96 
     97 First, we use non-blocking waitpid to check for events.  If nothing is
     98 found, we use sigsuspend to wait for SIGCHLD.  When SIGCHLD arrives,
     99 it means something happened to a child process.  As soon as we know
    100 there's an event, we get back to calling nonblocking waitpid.
    101 
    102 Note that SIGCHLD should be blocked between waitpid and sigsuspend
    103 calls, so that we don't miss a signal.  If SIGCHLD arrives in between,
    104 when it's blocked, the signal becomes pending and sigsuspend
    105 immediately notices it and returns.
    106 
    107 Waiting for events in async mode (TARGET_WNOHANG)
    108 =================================================
    109 
    110 In async mode, GDB should always be ready to handle both user input
    111 and target events, so neither blocking waitpid nor sigsuspend are
    112 viable options.  Instead, we should asynchronously notify the GDB main
    113 event loop whenever there's an unprocessed event from the target.  We
    114 detect asynchronous target events by handling SIGCHLD signals.  To
    115 notify the event loop about target events, the self-pipe trick is used
    116 --- a pipe is registered as waitable event source in the event loop,
    117 the event loop select/poll's on the read end of this pipe (as well on
    118 other event sources, e.g., stdin), and the SIGCHLD handler writes a
    119 byte to this pipe.  This is more portable than relying on
    120 pselect/ppoll, since on kernels that lack those syscalls, libc
    121 emulates them with select/poll+sigprocmask, and that is racy
    122 (a.k.a. plain broken).
    123 
    124 Obviously, if we fail to notify the event loop if there's a target
    125 event, it's bad.  OTOH, if we notify the event loop when there's no
    126 event from the target, linux_nat_wait will detect that there's no real
    127 event to report, and return event of type TARGET_WAITKIND_IGNORE.
    128 This is mostly harmless, but it will waste time and is better avoided.
    129 
    130 The main design point is that every time GDB is outside linux-nat.c,
    131 we have a SIGCHLD handler installed that is called when something
    132 happens to the target and notifies the GDB event loop.  Whenever GDB
    133 core decides to handle the event, and calls into linux-nat.c, we
    134 process things as in sync mode, except that the we never block in
    135 sigsuspend.
    136 
    137 While processing an event, we may end up momentarily blocked in
    138 waitpid calls.  Those waitpid calls, while blocking, are guarantied to
    139 return quickly.  E.g., in all-stop mode, before reporting to the core
    140 that an LWP hit a breakpoint, all LWPs are stopped by sending them
    141 SIGSTOP, and synchronously waiting for the SIGSTOP to be reported.
    142 Note that this is different from blocking indefinitely waiting for the
    143 next event --- here, we're already handling an event.
    144 
    145 Use of signals
    146 ==============
    147 
    148 We stop threads by sending a SIGSTOP.  The use of SIGSTOP instead of another
    149 signal is not entirely significant; we just need for a signal to be delivered,
    150 so that we can intercept it.  SIGSTOP's advantage is that it can not be
    151 blocked.  A disadvantage is that it is not a real-time signal, so it can only
    152 be queued once; we do not keep track of other sources of SIGSTOP.
    153 
    154 Two other signals that can't be blocked are SIGCONT and SIGKILL.  But we can't
    155 use them, because they have special behavior when the signal is generated -
    156 not when it is delivered.  SIGCONT resumes the entire thread group and SIGKILL
    157 kills the entire thread group.
    158 
    159 A delivered SIGSTOP would stop the entire thread group, not just the thread we
    160 tkill'd.  But we never let the SIGSTOP be delivered; we always intercept and
    161 cancel it (by PTRACE_CONT without passing SIGSTOP).
    162 
    163 We could use a real-time signal instead.  This would solve those problems; we
    164 could use PTRACE_GETSIGINFO to locate the specific stop signals sent by GDB.
    165 But we would still have to have some support for SIGSTOP, since PTRACE_ATTACH
    166 generates it, and there are races with trying to find a signal that is not
    167 blocked.
    168 
    169 Exec events
    170 ===========
    171 
    172 The case of a thread group (process) with 3 or more threads, and a
    173 thread other than the leader execs is worth detailing:
    174 
    175 On an exec, the Linux kernel destroys all threads except the execing
    176 one in the thread group, and resets the execing thread's tid to the
    177 tgid.  No exit notification is sent for the execing thread -- from the
    178 ptracer's perspective, it appears as though the execing thread just
    179 vanishes.  Until we reap all other threads except the leader and the
    180 execing thread, the leader will be zombie, and the execing thread will
    181 be in `D (disc sleep)' state.  As soon as all other threads are
    182 reaped, the execing thread changes its tid to the tgid, and the
    183 previous (zombie) leader vanishes, giving place to the "new"
    184 leader.  */
    185 
    186 #ifndef O_LARGEFILE
    187 #define O_LARGEFILE 0
    188 #endif
    189 
    190 struct linux_nat_target *linux_target;
    191 
    192 /* Does the current host support PTRACE_GETREGSET?  */
    193 enum tribool have_ptrace_getregset = TRIBOOL_UNKNOWN;
    194 
    195 static unsigned int debug_linux_nat;
    196 static void
    197 show_debug_linux_nat (struct ui_file *file, int from_tty,
    198 		      struct cmd_list_element *c, const char *value)
    199 {
    200   fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
    201 		    value);
    202 }
    203 
    204 struct simple_pid_list
    205 {
    206   int pid;
    207   int status;
    208   struct simple_pid_list *next;
    209 };
    210 struct simple_pid_list *stopped_pids;
    211 
    212 /* Whether target_thread_events is in effect.  */
    213 static int report_thread_events;
    214 
    215 /* Async mode support.  */
    216 
    217 /* The read/write ends of the pipe registered as waitable file in the
    218    event loop.  */
    219 static int linux_nat_event_pipe[2] = { -1, -1 };
    220 
    221 /* True if we're currently in async mode.  */
    222 #define linux_is_async_p() (linux_nat_event_pipe[0] != -1)
    223 
    224 /* Flush the event pipe.  */
    225 
    226 static void
    227 async_file_flush (void)
    228 {
    229   int ret;
    230   char buf;
    231 
    232   do
    233     {
    234       ret = read (linux_nat_event_pipe[0], &buf, 1);
    235     }
    236   while (ret >= 0 || (ret == -1 && errno == EINTR));
    237 }
    238 
    239 /* Put something (anything, doesn't matter what, or how much) in event
    240    pipe, so that the select/poll in the event-loop realizes we have
    241    something to process.  */
    242 
    243 static void
    244 async_file_mark (void)
    245 {
    246   int ret;
    247 
    248   /* It doesn't really matter what the pipe contains, as long we end
    249      up with something in it.  Might as well flush the previous
    250      left-overs.  */
    251   async_file_flush ();
    252 
    253   do
    254     {
    255       ret = write (linux_nat_event_pipe[1], "+", 1);
    256     }
    257   while (ret == -1 && errno == EINTR);
    258 
    259   /* Ignore EAGAIN.  If the pipe is full, the event loop will already
    260      be awakened anyway.  */
    261 }
    262 
    263 static int kill_lwp (int lwpid, int signo);
    264 
    265 static int stop_callback (struct lwp_info *lp, void *data);
    266 static int resume_stopped_resumed_lwps (struct lwp_info *lp, void *data);
    267 
    268 static void block_child_signals (sigset_t *prev_mask);
    269 static void restore_child_signals_mask (sigset_t *prev_mask);
    270 
    271 struct lwp_info;
    272 static struct lwp_info *add_lwp (ptid_t ptid);
    273 static void purge_lwp_list (int pid);
    274 static void delete_lwp (ptid_t ptid);
    275 static struct lwp_info *find_lwp_pid (ptid_t ptid);
    276 
    277 static int lwp_status_pending_p (struct lwp_info *lp);
    278 
    279 static void save_stop_reason (struct lwp_info *lp);
    280 
    281 
    282 /* LWP accessors.  */
    284 
    285 /* See nat/linux-nat.h.  */
    286 
    287 ptid_t
    288 ptid_of_lwp (struct lwp_info *lwp)
    289 {
    290   return lwp->ptid;
    291 }
    292 
    293 /* See nat/linux-nat.h.  */
    294 
    295 void
    296 lwp_set_arch_private_info (struct lwp_info *lwp,
    297 			   struct arch_lwp_info *info)
    298 {
    299   lwp->arch_private = info;
    300 }
    301 
    302 /* See nat/linux-nat.h.  */
    303 
    304 struct arch_lwp_info *
    305 lwp_arch_private_info (struct lwp_info *lwp)
    306 {
    307   return lwp->arch_private;
    308 }
    309 
    310 /* See nat/linux-nat.h.  */
    311 
    312 int
    313 lwp_is_stopped (struct lwp_info *lwp)
    314 {
    315   return lwp->stopped;
    316 }
    317 
    318 /* See nat/linux-nat.h.  */
    319 
    320 enum target_stop_reason
    321 lwp_stop_reason (struct lwp_info *lwp)
    322 {
    323   return lwp->stop_reason;
    324 }
    325 
    326 /* See nat/linux-nat.h.  */
    327 
    328 int
    329 lwp_is_stepping (struct lwp_info *lwp)
    330 {
    331   return lwp->step;
    332 }
    333 
    334 
    335 /* Trivial list manipulation functions to keep track of a list of
    337    new stopped processes.  */
    338 static void
    339 add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
    340 {
    341   struct simple_pid_list *new_pid = XNEW (struct simple_pid_list);
    342 
    343   new_pid->pid = pid;
    344   new_pid->status = status;
    345   new_pid->next = *listp;
    346   *listp = new_pid;
    347 }
    348 
    349 static int
    350 pull_pid_from_list (struct simple_pid_list **listp, int pid, int *statusp)
    351 {
    352   struct simple_pid_list **p;
    353 
    354   for (p = listp; *p != NULL; p = &(*p)->next)
    355     if ((*p)->pid == pid)
    356       {
    357 	struct simple_pid_list *next = (*p)->next;
    358 
    359 	*statusp = (*p)->status;
    360 	xfree (*p);
    361 	*p = next;
    362 	return 1;
    363       }
    364   return 0;
    365 }
    366 
    367 /* Return the ptrace options that we want to try to enable.  */
    368 
    369 static int
    370 linux_nat_ptrace_options (int attached)
    371 {
    372   int options = 0;
    373 
    374   if (!attached)
    375     options |= PTRACE_O_EXITKILL;
    376 
    377   options |= (PTRACE_O_TRACESYSGOOD
    378 	      | PTRACE_O_TRACEVFORKDONE
    379 	      | PTRACE_O_TRACEVFORK
    380 	      | PTRACE_O_TRACEFORK
    381 	      | PTRACE_O_TRACEEXEC);
    382 
    383   return options;
    384 }
    385 
    386 /* Initialize ptrace and procfs warnings and check for supported
    387    ptrace features given PID.
    388 
    389    ATTACHED should be nonzero iff we attached to the inferior.  */
    390 
    391 static void
    392 linux_init_ptrace_procfs (pid_t pid, int attached)
    393 {
    394   int options = linux_nat_ptrace_options (attached);
    395 
    396   linux_enable_event_reporting (pid, options);
    397   linux_ptrace_init_warnings ();
    398   linux_proc_init_warnings ();
    399 }
    400 
    401 linux_nat_target::~linux_nat_target ()
    402 {}
    403 
    404 void
    405 linux_nat_target::post_attach (int pid)
    406 {
    407   linux_init_ptrace_procfs (pid, 1);
    408 }
    409 
    410 void
    411 linux_nat_target::post_startup_inferior (ptid_t ptid)
    412 {
    413   linux_init_ptrace_procfs (ptid.pid (), 0);
    414 }
    415 
    416 /* Return the number of known LWPs in the tgid given by PID.  */
    417 
    418 static int
    419 num_lwps (int pid)
    420 {
    421   int count = 0;
    422   struct lwp_info *lp;
    423 
    424   for (lp = lwp_list; lp; lp = lp->next)
    425     if (lp->ptid.pid () == pid)
    426       count++;
    427 
    428   return count;
    429 }
    430 
    431 /* Deleter for lwp_info unique_ptr specialisation.  */
    432 
    433 struct lwp_deleter
    434 {
    435   void operator() (struct lwp_info *lwp) const
    436   {
    437     delete_lwp (lwp->ptid);
    438   }
    439 };
    440 
    441 /* A unique_ptr specialisation for lwp_info.  */
    442 
    443 typedef std::unique_ptr<struct lwp_info, lwp_deleter> lwp_info_up;
    444 
    445 /* Target hook for follow_fork.  On entry inferior_ptid must be the
    446    ptid of the followed inferior.  At return, inferior_ptid will be
    447    unchanged.  */
    448 
    449 int
    450 linux_nat_target::follow_fork (int follow_child, int detach_fork)
    451 {
    452   if (!follow_child)
    453     {
    454       struct lwp_info *child_lp = NULL;
    455       int has_vforked;
    456       ptid_t parent_ptid, child_ptid;
    457       int parent_pid, child_pid;
    458 
    459       has_vforked = (inferior_thread ()->pending_follow.kind
    460 		     == TARGET_WAITKIND_VFORKED);
    461       parent_ptid = inferior_ptid;
    462       child_ptid = inferior_thread ()->pending_follow.value.related_pid;
    463       parent_pid = parent_ptid.lwp ();
    464       child_pid = child_ptid.lwp ();
    465 
    466       /* We're already attached to the parent, by default.  */
    467       child_lp = add_lwp (child_ptid);
    468       child_lp->stopped = 1;
    469       child_lp->last_resume_kind = resume_stop;
    470 
    471       /* Detach new forked process?  */
    472       if (detach_fork)
    473 	{
    474 	  int child_stop_signal = 0;
    475 	  bool detach_child = true;
    476 
    477 	  /* Move CHILD_LP into a unique_ptr and clear the source pointer
    478 	     to prevent us doing anything stupid with it.  */
    479 	  lwp_info_up child_lp_ptr (child_lp);
    480 	  child_lp = nullptr;
    481 
    482 	  linux_target->low_prepare_to_resume (child_lp_ptr.get ());
    483 
    484 	  /* When debugging an inferior in an architecture that supports
    485 	     hardware single stepping on a kernel without commit
    486 	     6580807da14c423f0d0a708108e6df6ebc8bc83d, the vfork child
    487 	     process starts with the TIF_SINGLESTEP/X86_EFLAGS_TF bits
    488 	     set if the parent process had them set.
    489 	     To work around this, single step the child process
    490 	     once before detaching to clear the flags.  */
    491 
    492 	  /* Note that we consult the parent's architecture instead of
    493 	     the child's because there's no inferior for the child at
    494 	     this point.  */
    495 	  if (!gdbarch_software_single_step_p (target_thread_architecture
    496 					       (parent_ptid)))
    497 	    {
    498 	      int status;
    499 
    500 	      linux_disable_event_reporting (child_pid);
    501 	      if (ptrace (PTRACE_SINGLESTEP, child_pid, 0, 0) < 0)
    502 		perror_with_name (_("Couldn't do single step"));
    503 	      if (my_waitpid (child_pid, &status, 0) < 0)
    504 		perror_with_name (_("Couldn't wait vfork process"));
    505 	      else
    506 		{
    507 		  detach_child = WIFSTOPPED (status);
    508 		  child_stop_signal = WSTOPSIG (status);
    509 		}
    510 	    }
    511 
    512 	  if (detach_child)
    513 	    {
    514 	      int signo = child_stop_signal;
    515 
    516 	      if (signo != 0
    517 		  && !signal_pass_state (gdb_signal_from_host (signo)))
    518 		signo = 0;
    519 	      ptrace (PTRACE_DETACH, child_pid, 0, signo);
    520 	    }
    521 	}
    522       else
    523 	{
    524 	  scoped_restore save_inferior_ptid
    525 	    = make_scoped_restore (&inferior_ptid);
    526 	  inferior_ptid = child_ptid;
    527 
    528 	  /* Let the thread_db layer learn about this new process.  */
    529 	  check_for_thread_db ();
    530 	}
    531 
    532       if (has_vforked)
    533 	{
    534 	  struct lwp_info *parent_lp;
    535 
    536 	  parent_lp = find_lwp_pid (parent_ptid);
    537 	  gdb_assert (linux_supports_tracefork () >= 0);
    538 
    539 	  if (linux_supports_tracevforkdone ())
    540 	    {
    541   	      if (debug_linux_nat)
    542   		fprintf_unfiltered (gdb_stdlog,
    543   				    "LCFF: waiting for VFORK_DONE on %d\n",
    544   				    parent_pid);
    545 	      parent_lp->stopped = 1;
    546 
    547 	      /* We'll handle the VFORK_DONE event like any other
    548 		 event, in target_wait.  */
    549 	    }
    550 	  else
    551 	    {
    552 	      /* We can't insert breakpoints until the child has
    553 		 finished with the shared memory region.  We need to
    554 		 wait until that happens.  Ideal would be to just
    555 		 call:
    556 		 - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
    557 		 - waitpid (parent_pid, &status, __WALL);
    558 		 However, most architectures can't handle a syscall
    559 		 being traced on the way out if it wasn't traced on
    560 		 the way in.
    561 
    562 		 We might also think to loop, continuing the child
    563 		 until it exits or gets a SIGTRAP.  One problem is
    564 		 that the child might call ptrace with PTRACE_TRACEME.
    565 
    566 		 There's no simple and reliable way to figure out when
    567 		 the vforked child will be done with its copy of the
    568 		 shared memory.  We could step it out of the syscall,
    569 		 two instructions, let it go, and then single-step the
    570 		 parent once.  When we have hardware single-step, this
    571 		 would work; with software single-step it could still
    572 		 be made to work but we'd have to be able to insert
    573 		 single-step breakpoints in the child, and we'd have
    574 		 to insert -just- the single-step breakpoint in the
    575 		 parent.  Very awkward.
    576 
    577 		 In the end, the best we can do is to make sure it
    578 		 runs for a little while.  Hopefully it will be out of
    579 		 range of any breakpoints we reinsert.  Usually this
    580 		 is only the single-step breakpoint at vfork's return
    581 		 point.  */
    582 
    583   	      if (debug_linux_nat)
    584   		fprintf_unfiltered (gdb_stdlog,
    585 				    "LCFF: no VFORK_DONE "
    586 				    "support, sleeping a bit\n");
    587 
    588 	      usleep (10000);
    589 
    590 	      /* Pretend we've seen a PTRACE_EVENT_VFORK_DONE event,
    591 		 and leave it pending.  The next linux_nat_resume call
    592 		 will notice a pending event, and bypasses actually
    593 		 resuming the inferior.  */
    594 	      parent_lp->status = 0;
    595 	      parent_lp->waitstatus.kind = TARGET_WAITKIND_VFORK_DONE;
    596 	      parent_lp->stopped = 1;
    597 
    598 	      /* If we're in async mode, need to tell the event loop
    599 		 there's something here to process.  */
    600 	      if (target_is_async_p ())
    601 		async_file_mark ();
    602 	    }
    603 	}
    604     }
    605   else
    606     {
    607       struct lwp_info *child_lp;
    608 
    609       child_lp = add_lwp (inferior_ptid);
    610       child_lp->stopped = 1;
    611       child_lp->last_resume_kind = resume_stop;
    612 
    613       /* Let the thread_db layer learn about this new process.  */
    614       check_for_thread_db ();
    615     }
    616 
    617   return 0;
    618 }
    619 
    620 
    621 int
    623 linux_nat_target::insert_fork_catchpoint (int pid)
    624 {
    625   return !linux_supports_tracefork ();
    626 }
    627 
    628 int
    629 linux_nat_target::remove_fork_catchpoint (int pid)
    630 {
    631   return 0;
    632 }
    633 
    634 int
    635 linux_nat_target::insert_vfork_catchpoint (int pid)
    636 {
    637   return !linux_supports_tracefork ();
    638 }
    639 
    640 int
    641 linux_nat_target::remove_vfork_catchpoint (int pid)
    642 {
    643   return 0;
    644 }
    645 
    646 int
    647 linux_nat_target::insert_exec_catchpoint (int pid)
    648 {
    649   return !linux_supports_tracefork ();
    650 }
    651 
    652 int
    653 linux_nat_target::remove_exec_catchpoint (int pid)
    654 {
    655   return 0;
    656 }
    657 
    658 int
    659 linux_nat_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
    660 					  gdb::array_view<const int> syscall_counts)
    661 {
    662   if (!linux_supports_tracesysgood ())
    663     return 1;
    664 
    665   /* On GNU/Linux, we ignore the arguments.  It means that we only
    666      enable the syscall catchpoints, but do not disable them.
    667 
    668      Also, we do not use the `syscall_counts' information because we do not
    669      filter system calls here.  We let GDB do the logic for us.  */
    670   return 0;
    671 }
    672 
    673 /* List of known LWPs, keyed by LWP PID.  This speeds up the common
    674    case of mapping a PID returned from the kernel to our corresponding
    675    lwp_info data structure.  */
    676 static htab_t lwp_lwpid_htab;
    677 
    678 /* Calculate a hash from a lwp_info's LWP PID.  */
    679 
    680 static hashval_t
    681 lwp_info_hash (const void *ap)
    682 {
    683   const struct lwp_info *lp = (struct lwp_info *) ap;
    684   pid_t pid = lp->ptid.lwp ();
    685 
    686   return iterative_hash_object (pid, 0);
    687 }
    688 
    689 /* Equality function for the lwp_info hash table.  Compares the LWP's
    690    PID.  */
    691 
    692 static int
    693 lwp_lwpid_htab_eq (const void *a, const void *b)
    694 {
    695   const struct lwp_info *entry = (const struct lwp_info *) a;
    696   const struct lwp_info *element = (const struct lwp_info *) b;
    697 
    698   return entry->ptid.lwp () == element->ptid.lwp ();
    699 }
    700 
    701 /* Create the lwp_lwpid_htab hash table.  */
    702 
    703 static void
    704 lwp_lwpid_htab_create (void)
    705 {
    706   lwp_lwpid_htab = htab_create (100, lwp_info_hash, lwp_lwpid_htab_eq, NULL);
    707 }
    708 
    709 /* Add LP to the hash table.  */
    710 
    711 static void
    712 lwp_lwpid_htab_add_lwp (struct lwp_info *lp)
    713 {
    714   void **slot;
    715 
    716   slot = htab_find_slot (lwp_lwpid_htab, lp, INSERT);
    717   gdb_assert (slot != NULL && *slot == NULL);
    718   *slot = lp;
    719 }
    720 
    721 /* Head of doubly-linked list of known LWPs.  Sorted by reverse
    722    creation order.  This order is assumed in some cases.  E.g.,
    723    reaping status after killing alls lwps of a process: the leader LWP
    724    must be reaped last.  */
    725 struct lwp_info *lwp_list;
    726 
    727 /* Add LP to sorted-by-reverse-creation-order doubly-linked list.  */
    728 
    729 static void
    730 lwp_list_add (struct lwp_info *lp)
    731 {
    732   lp->next = lwp_list;
    733   if (lwp_list != NULL)
    734     lwp_list->prev = lp;
    735   lwp_list = lp;
    736 }
    737 
    738 /* Remove LP from sorted-by-reverse-creation-order doubly-linked
    739    list.  */
    740 
    741 static void
    742 lwp_list_remove (struct lwp_info *lp)
    743 {
    744   /* Remove from sorted-by-creation-order list.  */
    745   if (lp->next != NULL)
    746     lp->next->prev = lp->prev;
    747   if (lp->prev != NULL)
    748     lp->prev->next = lp->next;
    749   if (lp == lwp_list)
    750     lwp_list = lp->next;
    751 }
    752 
    753 
    754 
    756 /* Original signal mask.  */
    757 static sigset_t normal_mask;
    758 
    759 /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
    760    _initialize_linux_nat.  */
    761 static sigset_t suspend_mask;
    762 
    763 /* Signals to block to make that sigsuspend work.  */
    764 static sigset_t blocked_mask;
    765 
    766 /* SIGCHLD action.  */
    767 struct sigaction sigchld_action;
    768 
    769 /* Block child signals (SIGCHLD and linux threads signals), and store
    770    the previous mask in PREV_MASK.  */
    771 
    772 static void
    773 block_child_signals (sigset_t *prev_mask)
    774 {
    775   /* Make sure SIGCHLD is blocked.  */
    776   if (!sigismember (&blocked_mask, SIGCHLD))
    777     sigaddset (&blocked_mask, SIGCHLD);
    778 
    779   sigprocmask (SIG_BLOCK, &blocked_mask, prev_mask);
    780 }
    781 
    782 /* Restore child signals mask, previously returned by
    783    block_child_signals.  */
    784 
    785 static void
    786 restore_child_signals_mask (sigset_t *prev_mask)
    787 {
    788   sigprocmask (SIG_SETMASK, prev_mask, NULL);
    789 }
    790 
    791 /* Mask of signals to pass directly to the inferior.  */
    792 static sigset_t pass_mask;
    793 
    794 /* Update signals to pass to the inferior.  */
    795 void
    796 linux_nat_target::pass_signals
    797   (gdb::array_view<const unsigned char> pass_signals)
    798 {
    799   int signo;
    800 
    801   sigemptyset (&pass_mask);
    802 
    803   for (signo = 1; signo < NSIG; signo++)
    804     {
    805       int target_signo = gdb_signal_from_host (signo);
    806       if (target_signo < pass_signals.size () && pass_signals[target_signo])
    807         sigaddset (&pass_mask, signo);
    808     }
    809 }
    810 
    811 
    812 
    814 /* Prototypes for local functions.  */
    815 static int stop_wait_callback (struct lwp_info *lp, void *data);
    816 static int resume_stopped_resumed_lwps (struct lwp_info *lp, void *data);
    817 static int check_ptrace_stopped_lwp_gone (struct lwp_info *lp);
    818 
    819 
    820 
    822 /* Destroy and free LP.  */
    823 
    824 static void
    825 lwp_free (struct lwp_info *lp)
    826 {
    827   /* Let the arch specific bits release arch_lwp_info.  */
    828   linux_target->low_delete_thread (lp->arch_private);
    829 
    830   xfree (lp);
    831 }
    832 
    833 /* Traversal function for purge_lwp_list.  */
    834 
    835 static int
    836 lwp_lwpid_htab_remove_pid (void **slot, void *info)
    837 {
    838   struct lwp_info *lp = (struct lwp_info *) *slot;
    839   int pid = *(int *) info;
    840 
    841   if (lp->ptid.pid () == pid)
    842     {
    843       htab_clear_slot (lwp_lwpid_htab, slot);
    844       lwp_list_remove (lp);
    845       lwp_free (lp);
    846     }
    847 
    848   return 1;
    849 }
    850 
    851 /* Remove all LWPs belong to PID from the lwp list.  */
    852 
    853 static void
    854 purge_lwp_list (int pid)
    855 {
    856   htab_traverse_noresize (lwp_lwpid_htab, lwp_lwpid_htab_remove_pid, &pid);
    857 }
    858 
    859 /* Add the LWP specified by PTID to the list.  PTID is the first LWP
    860    in the process.  Return a pointer to the structure describing the
    861    new LWP.
    862 
    863    This differs from add_lwp in that we don't let the arch specific
    864    bits know about this new thread.  Current clients of this callback
    865    take the opportunity to install watchpoints in the new thread, and
    866    we shouldn't do that for the first thread.  If we're spawning a
    867    child ("run"), the thread executes the shell wrapper first, and we
    868    shouldn't touch it until it execs the program we want to debug.
    869    For "attach", it'd be okay to call the callback, but it's not
    870    necessary, because watchpoints can't yet have been inserted into
    871    the inferior.  */
    872 
    873 static struct lwp_info *
    874 add_initial_lwp (ptid_t ptid)
    875 {
    876   struct lwp_info *lp;
    877 
    878   gdb_assert (ptid.lwp_p ());
    879 
    880   lp = XNEW (struct lwp_info);
    881 
    882   memset (lp, 0, sizeof (struct lwp_info));
    883 
    884   lp->last_resume_kind = resume_continue;
    885   lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
    886 
    887   lp->ptid = ptid;
    888   lp->core = -1;
    889 
    890   /* Add to sorted-by-reverse-creation-order list.  */
    891   lwp_list_add (lp);
    892 
    893   /* Add to keyed-by-pid htab.  */
    894   lwp_lwpid_htab_add_lwp (lp);
    895 
    896   return lp;
    897 }
    898 
    899 /* Add the LWP specified by PID to the list.  Return a pointer to the
    900    structure describing the new LWP.  The LWP should already be
    901    stopped.  */
    902 
    903 static struct lwp_info *
    904 add_lwp (ptid_t ptid)
    905 {
    906   struct lwp_info *lp;
    907 
    908   lp = add_initial_lwp (ptid);
    909 
    910   /* Let the arch specific bits know about this new thread.  Current
    911      clients of this callback take the opportunity to install
    912      watchpoints in the new thread.  We don't do this for the first
    913      thread though.  See add_initial_lwp.  */
    914   linux_target->low_new_thread (lp);
    915 
    916   return lp;
    917 }
    918 
    919 /* Remove the LWP specified by PID from the list.  */
    920 
    921 static void
    922 delete_lwp (ptid_t ptid)
    923 {
    924   struct lwp_info *lp;
    925   void **slot;
    926   struct lwp_info dummy;
    927 
    928   dummy.ptid = ptid;
    929   slot = htab_find_slot (lwp_lwpid_htab, &dummy, NO_INSERT);
    930   if (slot == NULL)
    931     return;
    932 
    933   lp = *(struct lwp_info **) slot;
    934   gdb_assert (lp != NULL);
    935 
    936   htab_clear_slot (lwp_lwpid_htab, slot);
    937 
    938   /* Remove from sorted-by-creation-order list.  */
    939   lwp_list_remove (lp);
    940 
    941   /* Release.  */
    942   lwp_free (lp);
    943 }
    944 
    945 /* Return a pointer to the structure describing the LWP corresponding
    946    to PID.  If no corresponding LWP could be found, return NULL.  */
    947 
    948 static struct lwp_info *
    949 find_lwp_pid (ptid_t ptid)
    950 {
    951   struct lwp_info *lp;
    952   int lwp;
    953   struct lwp_info dummy;
    954 
    955   if (ptid.lwp_p ())
    956     lwp = ptid.lwp ();
    957   else
    958     lwp = ptid.pid ();
    959 
    960   dummy.ptid = ptid_t (0, lwp, 0);
    961   lp = (struct lwp_info *) htab_find (lwp_lwpid_htab, &dummy);
    962   return lp;
    963 }
    964 
    965 /* See nat/linux-nat.h.  */
    966 
    967 struct lwp_info *
    968 iterate_over_lwps (ptid_t filter,
    969 		   iterate_over_lwps_ftype callback,
    970 		   void *data)
    971 {
    972   struct lwp_info *lp, *lpnext;
    973 
    974   for (lp = lwp_list; lp; lp = lpnext)
    975     {
    976       lpnext = lp->next;
    977 
    978       if (lp->ptid.matches (filter))
    979 	{
    980 	  if ((*callback) (lp, data) != 0)
    981 	    return lp;
    982 	}
    983     }
    984 
    985   return NULL;
    986 }
    987 
    988 /* Update our internal state when changing from one checkpoint to
    989    another indicated by NEW_PTID.  We can only switch single-threaded
    990    applications, so we only create one new LWP, and the previous list
    991    is discarded.  */
    992 
    993 void
    994 linux_nat_switch_fork (ptid_t new_ptid)
    995 {
    996   struct lwp_info *lp;
    997 
    998   purge_lwp_list (inferior_ptid.pid ());
    999 
   1000   lp = add_lwp (new_ptid);
   1001   lp->stopped = 1;
   1002 
   1003   /* This changes the thread's ptid while preserving the gdb thread
   1004      num.  Also changes the inferior pid, while preserving the
   1005      inferior num.  */
   1006   thread_change_ptid (inferior_ptid, new_ptid);
   1007 
   1008   /* We've just told GDB core that the thread changed target id, but,
   1009      in fact, it really is a different thread, with different register
   1010      contents.  */
   1011   registers_changed ();
   1012 }
   1013 
   1014 /* Handle the exit of a single thread LP.  */
   1015 
   1016 static void
   1017 exit_lwp (struct lwp_info *lp)
   1018 {
   1019   struct thread_info *th = find_thread_ptid (lp->ptid);
   1020 
   1021   if (th)
   1022     {
   1023       if (print_thread_events)
   1024 	printf_unfiltered (_("[%s exited]\n"), target_pid_to_str (lp->ptid));
   1025 
   1026       delete_thread (th);
   1027     }
   1028 
   1029   delete_lwp (lp->ptid);
   1030 }
   1031 
   1032 /* Wait for the LWP specified by LP, which we have just attached to.
   1033    Returns a wait status for that LWP, to cache.  */
   1034 
   1035 static int
   1036 linux_nat_post_attach_wait (ptid_t ptid, int *signalled)
   1037 {
   1038   pid_t new_pid, pid = ptid.lwp ();
   1039   int status;
   1040 
   1041   if (linux_proc_pid_is_stopped (pid))
   1042     {
   1043       if (debug_linux_nat)
   1044 	fprintf_unfiltered (gdb_stdlog,
   1045 			    "LNPAW: Attaching to a stopped process\n");
   1046 
   1047       /* The process is definitely stopped.  It is in a job control
   1048 	 stop, unless the kernel predates the TASK_STOPPED /
   1049 	 TASK_TRACED distinction, in which case it might be in a
   1050 	 ptrace stop.  Make sure it is in a ptrace stop; from there we
   1051 	 can kill it, signal it, et cetera.
   1052 
   1053          First make sure there is a pending SIGSTOP.  Since we are
   1054 	 already attached, the process can not transition from stopped
   1055 	 to running without a PTRACE_CONT; so we know this signal will
   1056 	 go into the queue.  The SIGSTOP generated by PTRACE_ATTACH is
   1057 	 probably already in the queue (unless this kernel is old
   1058 	 enough to use TASK_STOPPED for ptrace stops); but since SIGSTOP
   1059 	 is not an RT signal, it can only be queued once.  */
   1060       kill_lwp (pid, SIGSTOP);
   1061 
   1062       /* Finally, resume the stopped process.  This will deliver the SIGSTOP
   1063 	 (or a higher priority signal, just like normal PTRACE_ATTACH).  */
   1064       ptrace (PTRACE_CONT, pid, 0, 0);
   1065     }
   1066 
   1067   /* Make sure the initial process is stopped.  The user-level threads
   1068      layer might want to poke around in the inferior, and that won't
   1069      work if things haven't stabilized yet.  */
   1070   new_pid = my_waitpid (pid, &status, __WALL);
   1071   gdb_assert (pid == new_pid);
   1072 
   1073   if (!WIFSTOPPED (status))
   1074     {
   1075       /* The pid we tried to attach has apparently just exited.  */
   1076       if (debug_linux_nat)
   1077 	fprintf_unfiltered (gdb_stdlog, "LNPAW: Failed to stop %d: %s",
   1078 			    pid, status_to_str (status));
   1079       return status;
   1080     }
   1081 
   1082   if (WSTOPSIG (status) != SIGSTOP)
   1083     {
   1084       *signalled = 1;
   1085       if (debug_linux_nat)
   1086 	fprintf_unfiltered (gdb_stdlog,
   1087 			    "LNPAW: Received %s after attaching\n",
   1088 			    status_to_str (status));
   1089     }
   1090 
   1091   return status;
   1092 }
   1093 
   1094 void
   1095 linux_nat_target::create_inferior (const char *exec_file,
   1096 				   const std::string &allargs,
   1097 				   char **env, int from_tty)
   1098 {
   1099   maybe_disable_address_space_randomization restore_personality
   1100     (disable_randomization);
   1101 
   1102   /* The fork_child mechanism is synchronous and calls target_wait, so
   1103      we have to mask the async mode.  */
   1104 
   1105   /* Make sure we report all signals during startup.  */
   1106   pass_signals ({});
   1107 
   1108   inf_ptrace_target::create_inferior (exec_file, allargs, env, from_tty);
   1109 }
   1110 
   1111 /* Callback for linux_proc_attach_tgid_threads.  Attach to PTID if not
   1112    already attached.  Returns true if a new LWP is found, false
   1113    otherwise.  */
   1114 
   1115 static int
   1116 attach_proc_task_lwp_callback (ptid_t ptid)
   1117 {
   1118   struct lwp_info *lp;
   1119 
   1120   /* Ignore LWPs we're already attached to.  */
   1121   lp = find_lwp_pid (ptid);
   1122   if (lp == NULL)
   1123     {
   1124       int lwpid = ptid.lwp ();
   1125 
   1126       if (ptrace (PTRACE_ATTACH, lwpid, 0, 0) < 0)
   1127 	{
   1128 	  int err = errno;
   1129 
   1130 	  /* Be quiet if we simply raced with the thread exiting.
   1131 	     EPERM is returned if the thread's task still exists, and
   1132 	     is marked as exited or zombie, as well as other
   1133 	     conditions, so in that case, confirm the status in
   1134 	     /proc/PID/status.  */
   1135 	  if (err == ESRCH
   1136 	      || (err == EPERM && linux_proc_pid_is_gone (lwpid)))
   1137 	    {
   1138 	      if (debug_linux_nat)
   1139 		{
   1140 		  fprintf_unfiltered (gdb_stdlog,
   1141 				      "Cannot attach to lwp %d: "
   1142 				      "thread is gone (%d: %s)\n",
   1143 				      lwpid, err, safe_strerror (err));
   1144 		}
   1145 	    }
   1146 	  else
   1147 	    {
   1148 	      std::string reason
   1149 		= linux_ptrace_attach_fail_reason_string (ptid, err);
   1150 
   1151 	      warning (_("Cannot attach to lwp %d: %s"),
   1152 		       lwpid, reason.c_str ());
   1153 	    }
   1154 	}
   1155       else
   1156 	{
   1157 	  if (debug_linux_nat)
   1158 	    fprintf_unfiltered (gdb_stdlog,
   1159 				"PTRACE_ATTACH %s, 0, 0 (OK)\n",
   1160 				target_pid_to_str (ptid));
   1161 
   1162 	  lp = add_lwp (ptid);
   1163 
   1164 	  /* The next time we wait for this LWP we'll see a SIGSTOP as
   1165 	     PTRACE_ATTACH brings it to a halt.  */
   1166 	  lp->signalled = 1;
   1167 
   1168 	  /* We need to wait for a stop before being able to make the
   1169 	     next ptrace call on this LWP.  */
   1170 	  lp->must_set_ptrace_flags = 1;
   1171 
   1172 	  /* So that wait collects the SIGSTOP.  */
   1173 	  lp->resumed = 1;
   1174 
   1175 	  /* Also add the LWP to gdb's thread list, in case a
   1176 	     matching libthread_db is not found (or the process uses
   1177 	     raw clone).  */
   1178 	  add_thread (lp->ptid);
   1179 	  set_running (lp->ptid, 1);
   1180 	  set_executing (lp->ptid, 1);
   1181 	}
   1182 
   1183       return 1;
   1184     }
   1185   return 0;
   1186 }
   1187 
   1188 void
   1189 linux_nat_target::attach (const char *args, int from_tty)
   1190 {
   1191   struct lwp_info *lp;
   1192   int status;
   1193   ptid_t ptid;
   1194 
   1195   /* Make sure we report all signals during attach.  */
   1196   pass_signals ({});
   1197 
   1198   TRY
   1199     {
   1200       inf_ptrace_target::attach (args, from_tty);
   1201     }
   1202   CATCH (ex, RETURN_MASK_ERROR)
   1203     {
   1204       pid_t pid = parse_pid_to_attach (args);
   1205       std::string reason = linux_ptrace_attach_fail_reason (pid);
   1206 
   1207       if (!reason.empty ())
   1208 	throw_error (ex.error, "warning: %s\n%s", reason.c_str (), ex.message);
   1209       else
   1210 	throw_error (ex.error, "%s", ex.message);
   1211     }
   1212   END_CATCH
   1213 
   1214   /* The ptrace base target adds the main thread with (pid,0,0)
   1215      format.  Decorate it with lwp info.  */
   1216   ptid = ptid_t (inferior_ptid.pid (),
   1217 		 inferior_ptid.pid (),
   1218 		 0);
   1219   thread_change_ptid (inferior_ptid, ptid);
   1220 
   1221   /* Add the initial process as the first LWP to the list.  */
   1222   lp = add_initial_lwp (ptid);
   1223 
   1224   status = linux_nat_post_attach_wait (lp->ptid, &lp->signalled);
   1225   if (!WIFSTOPPED (status))
   1226     {
   1227       if (WIFEXITED (status))
   1228 	{
   1229 	  int exit_code = WEXITSTATUS (status);
   1230 
   1231 	  target_terminal::ours ();
   1232 	  target_mourn_inferior (inferior_ptid);
   1233 	  if (exit_code == 0)
   1234 	    error (_("Unable to attach: program exited normally."));
   1235 	  else
   1236 	    error (_("Unable to attach: program exited with code %d."),
   1237 		   exit_code);
   1238 	}
   1239       else if (WIFSIGNALED (status))
   1240 	{
   1241 	  enum gdb_signal signo;
   1242 
   1243 	  target_terminal::ours ();
   1244 	  target_mourn_inferior (inferior_ptid);
   1245 
   1246 	  signo = gdb_signal_from_host (WTERMSIG (status));
   1247 	  error (_("Unable to attach: program terminated with signal "
   1248 		   "%s, %s."),
   1249 		 gdb_signal_to_name (signo),
   1250 		 gdb_signal_to_string (signo));
   1251 	}
   1252 
   1253       internal_error (__FILE__, __LINE__,
   1254 		      _("unexpected status %d for PID %ld"),
   1255 		      status, (long) ptid.lwp ());
   1256     }
   1257 
   1258   lp->stopped = 1;
   1259 
   1260   /* Save the wait status to report later.  */
   1261   lp->resumed = 1;
   1262   if (debug_linux_nat)
   1263     fprintf_unfiltered (gdb_stdlog,
   1264 			"LNA: waitpid %ld, saving status %s\n",
   1265 			(long) lp->ptid.pid (), status_to_str (status));
   1266 
   1267   lp->status = status;
   1268 
   1269   /* We must attach to every LWP.  If /proc is mounted, use that to
   1270      find them now.  The inferior may be using raw clone instead of
   1271      using pthreads.  But even if it is using pthreads, thread_db
   1272      walks structures in the inferior's address space to find the list
   1273      of threads/LWPs, and those structures may well be corrupted.
   1274      Note that once thread_db is loaded, we'll still use it to list
   1275      threads and associate pthread info with each LWP.  */
   1276   linux_proc_attach_tgid_threads (lp->ptid.pid (),
   1277 				  attach_proc_task_lwp_callback);
   1278 
   1279   if (target_can_async_p ())
   1280     target_async (1);
   1281 }
   1282 
   1283 /* Get pending signal of THREAD as a host signal number, for detaching
   1284    purposes.  This is the signal the thread last stopped for, which we
   1285    need to deliver to the thread when detaching, otherwise, it'd be
   1286    suppressed/lost.  */
   1287 
   1288 static int
   1289 get_detach_signal (struct lwp_info *lp)
   1290 {
   1291   enum gdb_signal signo = GDB_SIGNAL_0;
   1292 
   1293   /* If we paused threads momentarily, we may have stored pending
   1294      events in lp->status or lp->waitstatus (see stop_wait_callback),
   1295      and GDB core hasn't seen any signal for those threads.
   1296      Otherwise, the last signal reported to the core is found in the
   1297      thread object's stop_signal.
   1298 
   1299      There's a corner case that isn't handled here at present.  Only
   1300      if the thread stopped with a TARGET_WAITKIND_STOPPED does
   1301      stop_signal make sense as a real signal to pass to the inferior.
   1302      Some catchpoint related events, like
   1303      TARGET_WAITKIND_(V)FORK|EXEC|SYSCALL, have their stop_signal set
   1304      to GDB_SIGNAL_SIGTRAP when the catchpoint triggers.  But,
   1305      those traps are debug API (ptrace in our case) related and
   1306      induced; the inferior wouldn't see them if it wasn't being
   1307      traced.  Hence, we should never pass them to the inferior, even
   1308      when set to pass state.  Since this corner case isn't handled by
   1309      infrun.c when proceeding with a signal, for consistency, neither
   1310      do we handle it here (or elsewhere in the file we check for
   1311      signal pass state).  Normally SIGTRAP isn't set to pass state, so
   1312      this is really a corner case.  */
   1313 
   1314   if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
   1315     signo = GDB_SIGNAL_0; /* a pending ptrace event, not a real signal.  */
   1316   else if (lp->status)
   1317     signo = gdb_signal_from_host (WSTOPSIG (lp->status));
   1318   else
   1319     {
   1320       struct thread_info *tp = find_thread_ptid (lp->ptid);
   1321 
   1322       if (target_is_non_stop_p () && !tp->executing)
   1323 	{
   1324 	  if (tp->suspend.waitstatus_pending_p)
   1325 	    signo = tp->suspend.waitstatus.value.sig;
   1326 	  else
   1327 	    signo = tp->suspend.stop_signal;
   1328 	}
   1329       else if (!target_is_non_stop_p ())
   1330 	{
   1331 	  struct target_waitstatus last;
   1332 	  ptid_t last_ptid;
   1333 
   1334 	  get_last_target_status (&last_ptid, &last);
   1335 
   1336 	  if (lp->ptid.lwp () == last_ptid.lwp ())
   1337 	    signo = tp->suspend.stop_signal;
   1338 	}
   1339     }
   1340 
   1341   if (signo == GDB_SIGNAL_0)
   1342     {
   1343       if (debug_linux_nat)
   1344 	fprintf_unfiltered (gdb_stdlog,
   1345 			    "GPT: lwp %s has no pending signal\n",
   1346 			    target_pid_to_str (lp->ptid));
   1347     }
   1348   else if (!signal_pass_state (signo))
   1349     {
   1350       if (debug_linux_nat)
   1351 	fprintf_unfiltered (gdb_stdlog,
   1352 			    "GPT: lwp %s had signal %s, "
   1353 			    "but it is in no pass state\n",
   1354 			    target_pid_to_str (lp->ptid),
   1355 			    gdb_signal_to_string (signo));
   1356     }
   1357   else
   1358     {
   1359       if (debug_linux_nat)
   1360 	fprintf_unfiltered (gdb_stdlog,
   1361 			    "GPT: lwp %s has pending signal %s\n",
   1362 			    target_pid_to_str (lp->ptid),
   1363 			    gdb_signal_to_string (signo));
   1364 
   1365       return gdb_signal_to_host (signo);
   1366     }
   1367 
   1368   return 0;
   1369 }
   1370 
   1371 /* Detach from LP.  If SIGNO_P is non-NULL, then it points to the
   1372    signal number that should be passed to the LWP when detaching.
   1373    Otherwise pass any pending signal the LWP may have, if any.  */
   1374 
   1375 static void
   1376 detach_one_lwp (struct lwp_info *lp, int *signo_p)
   1377 {
   1378   int lwpid = lp->ptid.lwp ();
   1379   int signo;
   1380 
   1381   gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
   1382 
   1383   if (debug_linux_nat && lp->status)
   1384     fprintf_unfiltered (gdb_stdlog, "DC:  Pending %s for %s on detach.\n",
   1385 			strsignal (WSTOPSIG (lp->status)),
   1386 			target_pid_to_str (lp->ptid));
   1387 
   1388   /* If there is a pending SIGSTOP, get rid of it.  */
   1389   if (lp->signalled)
   1390     {
   1391       if (debug_linux_nat)
   1392 	fprintf_unfiltered (gdb_stdlog,
   1393 			    "DC: Sending SIGCONT to %s\n",
   1394 			    target_pid_to_str (lp->ptid));
   1395 
   1396       kill_lwp (lwpid, SIGCONT);
   1397       lp->signalled = 0;
   1398     }
   1399 
   1400   if (signo_p == NULL)
   1401     {
   1402       /* Pass on any pending signal for this LWP.  */
   1403       signo = get_detach_signal (lp);
   1404     }
   1405   else
   1406     signo = *signo_p;
   1407 
   1408   /* Preparing to resume may try to write registers, and fail if the
   1409      lwp is zombie.  If that happens, ignore the error.  We'll handle
   1410      it below, when detach fails with ESRCH.  */
   1411   TRY
   1412     {
   1413       linux_target->low_prepare_to_resume (lp);
   1414     }
   1415   CATCH (ex, RETURN_MASK_ERROR)
   1416     {
   1417       if (!check_ptrace_stopped_lwp_gone (lp))
   1418 	throw_exception (ex);
   1419     }
   1420   END_CATCH
   1421 
   1422   if (ptrace (PTRACE_DETACH, lwpid, 0, signo) < 0)
   1423     {
   1424       int save_errno = errno;
   1425 
   1426       /* We know the thread exists, so ESRCH must mean the lwp is
   1427 	 zombie.  This can happen if one of the already-detached
   1428 	 threads exits the whole thread group.  In that case we're
   1429 	 still attached, and must reap the lwp.  */
   1430       if (save_errno == ESRCH)
   1431 	{
   1432 	  int ret, status;
   1433 
   1434 	  ret = my_waitpid (lwpid, &status, __WALL);
   1435 	  if (ret == -1)
   1436 	    {
   1437 	      warning (_("Couldn't reap LWP %d while detaching: %s"),
   1438 		       lwpid, strerror (errno));
   1439 	    }
   1440 	  else if (!WIFEXITED (status) && !WIFSIGNALED (status))
   1441 	    {
   1442 	      warning (_("Reaping LWP %d while detaching "
   1443 			 "returned unexpected status 0x%x"),
   1444 		       lwpid, status);
   1445 	    }
   1446 	}
   1447       else
   1448 	{
   1449 	  error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
   1450 		 safe_strerror (save_errno));
   1451 	}
   1452     }
   1453   else if (debug_linux_nat)
   1454     {
   1455       fprintf_unfiltered (gdb_stdlog,
   1456 			  "PTRACE_DETACH (%s, %s, 0) (OK)\n",
   1457 			  target_pid_to_str (lp->ptid),
   1458 			  strsignal (signo));
   1459     }
   1460 
   1461   delete_lwp (lp->ptid);
   1462 }
   1463 
   1464 static int
   1465 detach_callback (struct lwp_info *lp, void *data)
   1466 {
   1467   /* We don't actually detach from the thread group leader just yet.
   1468      If the thread group exits, we must reap the zombie clone lwps
   1469      before we're able to reap the leader.  */
   1470   if (lp->ptid.lwp () != lp->ptid.pid ())
   1471     detach_one_lwp (lp, NULL);
   1472   return 0;
   1473 }
   1474 
   1475 void
   1476 linux_nat_target::detach (inferior *inf, int from_tty)
   1477 {
   1478   struct lwp_info *main_lwp;
   1479   int pid = inf->pid;
   1480 
   1481   /* Don't unregister from the event loop, as there may be other
   1482      inferiors running. */
   1483 
   1484   /* Stop all threads before detaching.  ptrace requires that the
   1485      thread is stopped to sucessfully detach.  */
   1486   iterate_over_lwps (ptid_t (pid), stop_callback, NULL);
   1487   /* ... and wait until all of them have reported back that
   1488      they're no longer running.  */
   1489   iterate_over_lwps (ptid_t (pid), stop_wait_callback, NULL);
   1490 
   1491   iterate_over_lwps (ptid_t (pid), detach_callback, NULL);
   1492 
   1493   /* Only the initial process should be left right now.  */
   1494   gdb_assert (num_lwps (pid) == 1);
   1495 
   1496   main_lwp = find_lwp_pid (ptid_t (pid));
   1497 
   1498   if (forks_exist_p ())
   1499     {
   1500       /* Multi-fork case.  The current inferior_ptid is being detached
   1501 	 from, but there are other viable forks to debug.  Detach from
   1502 	 the current fork, and context-switch to the first
   1503 	 available.  */
   1504       linux_fork_detach (from_tty);
   1505     }
   1506   else
   1507     {
   1508       target_announce_detach (from_tty);
   1509 
   1510       /* Pass on any pending signal for the last LWP.  */
   1511       int signo = get_detach_signal (main_lwp);
   1512 
   1513       detach_one_lwp (main_lwp, &signo);
   1514 
   1515       detach_success (inf);
   1516     }
   1517 }
   1518 
   1519 /* Resume execution of the inferior process.  If STEP is nonzero,
   1520    single-step it.  If SIGNAL is nonzero, give it that signal.  */
   1521 
   1522 static void
   1523 linux_resume_one_lwp_throw (struct lwp_info *lp, int step,
   1524 			    enum gdb_signal signo)
   1525 {
   1526   lp->step = step;
   1527 
   1528   /* stop_pc doubles as the PC the LWP had when it was last resumed.
   1529      We only presently need that if the LWP is stepped though (to
   1530      handle the case of stepping a breakpoint instruction).  */
   1531   if (step)
   1532     {
   1533       struct regcache *regcache = get_thread_regcache (lp->ptid);
   1534 
   1535       lp->stop_pc = regcache_read_pc (regcache);
   1536     }
   1537   else
   1538     lp->stop_pc = 0;
   1539 
   1540   linux_target->low_prepare_to_resume (lp);
   1541   linux_target->low_resume (lp->ptid, step, signo);
   1542 
   1543   /* Successfully resumed.  Clear state that no longer makes sense,
   1544      and mark the LWP as running.  Must not do this before resuming
   1545      otherwise if that fails other code will be confused.  E.g., we'd
   1546      later try to stop the LWP and hang forever waiting for a stop
   1547      status.  Note that we must not throw after this is cleared,
   1548      otherwise handle_zombie_lwp_error would get confused.  */
   1549   lp->stopped = 0;
   1550   lp->core = -1;
   1551   lp->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   1552   registers_changed_ptid (lp->ptid);
   1553 }
   1554 
   1555 /* Called when we try to resume a stopped LWP and that errors out.  If
   1556    the LWP is no longer in ptrace-stopped state (meaning it's zombie,
   1557    or about to become), discard the error, clear any pending status
   1558    the LWP may have, and return true (we'll collect the exit status
   1559    soon enough).  Otherwise, return false.  */
   1560 
   1561 static int
   1562 check_ptrace_stopped_lwp_gone (struct lwp_info *lp)
   1563 {
   1564   /* If we get an error after resuming the LWP successfully, we'd
   1565      confuse !T state for the LWP being gone.  */
   1566   gdb_assert (lp->stopped);
   1567 
   1568   /* We can't just check whether the LWP is in 'Z (Zombie)' state,
   1569      because even if ptrace failed with ESRCH, the tracee may be "not
   1570      yet fully dead", but already refusing ptrace requests.  In that
   1571      case the tracee has 'R (Running)' state for a little bit
   1572      (observed in Linux 3.18).  See also the note on ESRCH in the
   1573      ptrace(2) man page.  Instead, check whether the LWP has any state
   1574      other than ptrace-stopped.  */
   1575 
   1576   /* Don't assume anything if /proc/PID/status can't be read.  */
   1577   if (linux_proc_pid_is_trace_stopped_nowarn (lp->ptid.lwp ()) == 0)
   1578     {
   1579       lp->stop_reason = TARGET_STOPPED_BY_NO_REASON;
   1580       lp->status = 0;
   1581       lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
   1582       return 1;
   1583     }
   1584   return 0;
   1585 }
   1586 
   1587 /* Like linux_resume_one_lwp_throw, but no error is thrown if the LWP
   1588    disappears while we try to resume it.  */
   1589 
   1590 static void
   1591 linux_resume_one_lwp (struct lwp_info *lp, int step, enum gdb_signal signo)
   1592 {
   1593   TRY
   1594     {
   1595       linux_resume_one_lwp_throw (lp, step, signo);
   1596     }
   1597   CATCH (ex, RETURN_MASK_ERROR)
   1598     {
   1599       if (!check_ptrace_stopped_lwp_gone (lp))
   1600 	throw_exception (ex);
   1601     }
   1602   END_CATCH
   1603 }
   1604 
   1605 /* Resume LP.  */
   1606 
   1607 static void
   1608 resume_lwp (struct lwp_info *lp, int step, enum gdb_signal signo)
   1609 {
   1610   if (lp->stopped)
   1611     {
   1612       struct inferior *inf = find_inferior_ptid (lp->ptid);
   1613 
   1614       if (inf->vfork_child != NULL)
   1615 	{
   1616 	  if (debug_linux_nat)
   1617 	    fprintf_unfiltered (gdb_stdlog,
   1618 				"RC: Not resuming %s (vfork parent)\n",
   1619 				target_pid_to_str (lp->ptid));
   1620 	}
   1621       else if (!lwp_status_pending_p (lp))
   1622 	{
   1623 	  if (debug_linux_nat)
   1624 	    fprintf_unfiltered (gdb_stdlog,
   1625 				"RC: Resuming sibling %s, %s, %s\n",
   1626 				target_pid_to_str (lp->ptid),
   1627 				(signo != GDB_SIGNAL_0
   1628 				 ? strsignal (gdb_signal_to_host (signo))
   1629 				 : "0"),
   1630 				step ? "step" : "resume");
   1631 
   1632 	  linux_resume_one_lwp (lp, step, signo);
   1633 	}
   1634       else
   1635 	{
   1636 	  if (debug_linux_nat)
   1637 	    fprintf_unfiltered (gdb_stdlog,
   1638 				"RC: Not resuming sibling %s (has pending)\n",
   1639 				target_pid_to_str (lp->ptid));
   1640 	}
   1641     }
   1642   else
   1643     {
   1644       if (debug_linux_nat)
   1645 	fprintf_unfiltered (gdb_stdlog,
   1646 			    "RC: Not resuming sibling %s (not stopped)\n",
   1647 			    target_pid_to_str (lp->ptid));
   1648     }
   1649 }
   1650 
   1651 /* Callback for iterate_over_lwps.  If LWP is EXCEPT, do nothing.
   1652    Resume LWP with the last stop signal, if it is in pass state.  */
   1653 
   1654 static int
   1655 linux_nat_resume_callback (struct lwp_info *lp, void *except)
   1656 {
   1657   enum gdb_signal signo = GDB_SIGNAL_0;
   1658 
   1659   if (lp == except)
   1660     return 0;
   1661 
   1662   if (lp->stopped)
   1663     {
   1664       struct thread_info *thread;
   1665 
   1666       thread = find_thread_ptid (lp->ptid);
   1667       if (thread != NULL)
   1668 	{
   1669 	  signo = thread->suspend.stop_signal;
   1670 	  thread->suspend.stop_signal = GDB_SIGNAL_0;
   1671 	}
   1672     }
   1673 
   1674   resume_lwp (lp, 0, signo);
   1675   return 0;
   1676 }
   1677 
   1678 static int
   1679 resume_clear_callback (struct lwp_info *lp, void *data)
   1680 {
   1681   lp->resumed = 0;
   1682   lp->last_resume_kind = resume_stop;
   1683   return 0;
   1684 }
   1685 
   1686 static int
   1687 resume_set_callback (struct lwp_info *lp, void *data)
   1688 {
   1689   lp->resumed = 1;
   1690   lp->last_resume_kind = resume_continue;
   1691   return 0;
   1692 }
   1693 
   1694 void
   1695 linux_nat_target::resume (ptid_t ptid, int step, enum gdb_signal signo)
   1696 {
   1697   struct lwp_info *lp;
   1698   int resume_many;
   1699 
   1700   if (debug_linux_nat)
   1701     fprintf_unfiltered (gdb_stdlog,
   1702 			"LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
   1703 			step ? "step" : "resume",
   1704 			target_pid_to_str (ptid),
   1705 			(signo != GDB_SIGNAL_0
   1706 			 ? strsignal (gdb_signal_to_host (signo)) : "0"),
   1707 			target_pid_to_str (inferior_ptid));
   1708 
   1709   /* A specific PTID means `step only this process id'.  */
   1710   resume_many = (minus_one_ptid == ptid
   1711 		 || ptid.is_pid ());
   1712 
   1713   /* Mark the lwps we're resuming as resumed.  */
   1714   iterate_over_lwps (ptid, resume_set_callback, NULL);
   1715 
   1716   /* See if it's the current inferior that should be handled
   1717      specially.  */
   1718   if (resume_many)
   1719     lp = find_lwp_pid (inferior_ptid);
   1720   else
   1721     lp = find_lwp_pid (ptid);
   1722   gdb_assert (lp != NULL);
   1723 
   1724   /* Remember if we're stepping.  */
   1725   lp->last_resume_kind = step ? resume_step : resume_continue;
   1726 
   1727   /* If we have a pending wait status for this thread, there is no
   1728      point in resuming the process.  But first make sure that
   1729      linux_nat_wait won't preemptively handle the event - we
   1730      should never take this short-circuit if we are going to
   1731      leave LP running, since we have skipped resuming all the
   1732      other threads.  This bit of code needs to be synchronized
   1733      with linux_nat_wait.  */
   1734 
   1735   if (lp->status && WIFSTOPPED (lp->status))
   1736     {
   1737       if (!lp->step
   1738 	  && WSTOPSIG (lp->status)
   1739 	  && sigismember (&pass_mask, WSTOPSIG (lp->status)))
   1740 	{
   1741 	  if (debug_linux_nat)
   1742 	    fprintf_unfiltered (gdb_stdlog,
   1743 				"LLR: Not short circuiting for ignored "
   1744 				"status 0x%x\n", lp->status);
   1745 
   1746 	  /* FIXME: What should we do if we are supposed to continue
   1747 	     this thread with a signal?  */
   1748 	  gdb_assert (signo == GDB_SIGNAL_0);
   1749 	  signo = gdb_signal_from_host (WSTOPSIG (lp->status));
   1750 	  lp->status = 0;
   1751 	}
   1752     }
   1753 
   1754   if (lwp_status_pending_p (lp))
   1755     {
   1756       /* FIXME: What should we do if we are supposed to continue
   1757 	 this thread with a signal?  */
   1758       gdb_assert (signo == GDB_SIGNAL_0);
   1759 
   1760       if (debug_linux_nat)
   1761 	fprintf_unfiltered (gdb_stdlog,
   1762 			    "LLR: Short circuiting for status 0x%x\n",
   1763 			    lp->status);
   1764 
   1765       if (target_can_async_p ())
   1766 	{
   1767 	  target_async (1);
   1768 	  /* Tell the event loop we have something to process.  */
   1769 	  async_file_mark ();
   1770 	}
   1771       return;
   1772     }
   1773 
   1774   if (resume_many)
   1775     iterate_over_lwps (ptid, linux_nat_resume_callback, lp);
   1776 
   1777   if (debug_linux_nat)
   1778     fprintf_unfiltered (gdb_stdlog,
   1779 			"LLR: %s %s, %s (resume event thread)\n",
   1780 			step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
   1781 			target_pid_to_str (lp->ptid),
   1782 			(signo != GDB_SIGNAL_0
   1783 			 ? strsignal (gdb_signal_to_host (signo)) : "0"));
   1784 
   1785   linux_resume_one_lwp (lp, step, signo);
   1786 
   1787   if (target_can_async_p ())
   1788     target_async (1);
   1789 }
   1790 
   1791 /* Send a signal to an LWP.  */
   1792 
   1793 static int
   1794 kill_lwp (int lwpid, int signo)
   1795 {
   1796   int ret;
   1797 
   1798   errno = 0;
   1799   ret = syscall (__NR_tkill, lwpid, signo);
   1800   if (errno == ENOSYS)
   1801     {
   1802       /* If tkill fails, then we are not using nptl threads, a
   1803 	 configuration we no longer support.  */
   1804       perror_with_name (("tkill"));
   1805     }
   1806   return ret;
   1807 }
   1808 
   1809 /* Handle a GNU/Linux syscall trap wait response.  If we see a syscall
   1810    event, check if the core is interested in it: if not, ignore the
   1811    event, and keep waiting; otherwise, we need to toggle the LWP's
   1812    syscall entry/exit status, since the ptrace event itself doesn't
   1813    indicate it, and report the trap to higher layers.  */
   1814 
   1815 static int
   1816 linux_handle_syscall_trap (struct lwp_info *lp, int stopping)
   1817 {
   1818   struct target_waitstatus *ourstatus = &lp->waitstatus;
   1819   struct gdbarch *gdbarch = target_thread_architecture (lp->ptid);
   1820   thread_info *thread = find_thread_ptid (lp->ptid);
   1821   int syscall_number = (int) gdbarch_get_syscall_number (gdbarch, thread);
   1822 
   1823   if (stopping)
   1824     {
   1825       /* If we're stopping threads, there's a SIGSTOP pending, which
   1826 	 makes it so that the LWP reports an immediate syscall return,
   1827 	 followed by the SIGSTOP.  Skip seeing that "return" using
   1828 	 PTRACE_CONT directly, and let stop_wait_callback collect the
   1829 	 SIGSTOP.  Later when the thread is resumed, a new syscall
   1830 	 entry event.  If we didn't do this (and returned 0), we'd
   1831 	 leave a syscall entry pending, and our caller, by using
   1832 	 PTRACE_CONT to collect the SIGSTOP, skips the syscall return
   1833 	 itself.  Later, when the user re-resumes this LWP, we'd see
   1834 	 another syscall entry event and we'd mistake it for a return.
   1835 
   1836 	 If stop_wait_callback didn't force the SIGSTOP out of the LWP
   1837 	 (leaving immediately with LWP->signalled set, without issuing
   1838 	 a PTRACE_CONT), it would still be problematic to leave this
   1839 	 syscall enter pending, as later when the thread is resumed,
   1840 	 it would then see the same syscall exit mentioned above,
   1841 	 followed by the delayed SIGSTOP, while the syscall didn't
   1842 	 actually get to execute.  It seems it would be even more
   1843 	 confusing to the user.  */
   1844 
   1845       if (debug_linux_nat)
   1846 	fprintf_unfiltered (gdb_stdlog,
   1847 			    "LHST: ignoring syscall %d "
   1848 			    "for LWP %ld (stopping threads), "
   1849 			    "resuming with PTRACE_CONT for SIGSTOP\n",
   1850 			    syscall_number,
   1851 			    lp->ptid.lwp ());
   1852 
   1853       lp->syscall_state = TARGET_WAITKIND_IGNORE;
   1854       ptrace (PTRACE_CONT, lp->ptid.lwp (), 0, 0);
   1855       lp->stopped = 0;
   1856       return 1;
   1857     }
   1858 
   1859   /* Always update the entry/return state, even if this particular
   1860      syscall isn't interesting to the core now.  In async mode,
   1861      the user could install a new catchpoint for this syscall
   1862      between syscall enter/return, and we'll need to know to
   1863      report a syscall return if that happens.  */
   1864   lp->syscall_state = (lp->syscall_state == TARGET_WAITKIND_SYSCALL_ENTRY
   1865 		       ? TARGET_WAITKIND_SYSCALL_RETURN
   1866 		       : TARGET_WAITKIND_SYSCALL_ENTRY);
   1867 
   1868   if (catch_syscall_enabled ())
   1869     {
   1870       if (catching_syscall_number (syscall_number))
   1871 	{
   1872 	  /* Alright, an event to report.  */
   1873 	  ourstatus->kind = lp->syscall_state;
   1874 	  ourstatus->value.syscall_number = syscall_number;
   1875 
   1876 	  if (debug_linux_nat)
   1877 	    fprintf_unfiltered (gdb_stdlog,
   1878 				"LHST: stopping for %s of syscall %d"
   1879 				" for LWP %ld\n",
   1880 				lp->syscall_state
   1881 				== TARGET_WAITKIND_SYSCALL_ENTRY
   1882 				? "entry" : "return",
   1883 				syscall_number,
   1884 				lp->ptid.lwp ());
   1885 	  return 0;
   1886 	}
   1887 
   1888       if (debug_linux_nat)
   1889 	fprintf_unfiltered (gdb_stdlog,
   1890 			    "LHST: ignoring %s of syscall %d "
   1891 			    "for LWP %ld\n",
   1892 			    lp->syscall_state == TARGET_WAITKIND_SYSCALL_ENTRY
   1893 			    ? "entry" : "return",
   1894 			    syscall_number,
   1895 			    lp->ptid.lwp ());
   1896     }
   1897   else
   1898     {
   1899       /* If we had been syscall tracing, and hence used PT_SYSCALL
   1900 	 before on this LWP, it could happen that the user removes all
   1901 	 syscall catchpoints before we get to process this event.
   1902 	 There are two noteworthy issues here:
   1903 
   1904 	 - When stopped at a syscall entry event, resuming with
   1905 	   PT_STEP still resumes executing the syscall and reports a
   1906 	   syscall return.
   1907 
   1908 	 - Only PT_SYSCALL catches syscall enters.  If we last
   1909 	   single-stepped this thread, then this event can't be a
   1910 	   syscall enter.  If we last single-stepped this thread, this
   1911 	   has to be a syscall exit.
   1912 
   1913 	 The points above mean that the next resume, be it PT_STEP or
   1914 	 PT_CONTINUE, can not trigger a syscall trace event.  */
   1915       if (debug_linux_nat)
   1916 	fprintf_unfiltered (gdb_stdlog,
   1917 			    "LHST: caught syscall event "
   1918 			    "with no syscall catchpoints."
   1919 			    " %d for LWP %ld, ignoring\n",
   1920 			    syscall_number,
   1921 			    lp->ptid.lwp ());
   1922       lp->syscall_state = TARGET_WAITKIND_IGNORE;
   1923     }
   1924 
   1925   /* The core isn't interested in this event.  For efficiency, avoid
   1926      stopping all threads only to have the core resume them all again.
   1927      Since we're not stopping threads, if we're still syscall tracing
   1928      and not stepping, we can't use PTRACE_CONT here, as we'd miss any
   1929      subsequent syscall.  Simply resume using the inf-ptrace layer,
   1930      which knows when to use PT_SYSCALL or PT_CONTINUE.  */
   1931 
   1932   linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
   1933   return 1;
   1934 }
   1935 
   1936 /* Handle a GNU/Linux extended wait response.  If we see a clone
   1937    event, we need to add the new LWP to our list (and not report the
   1938    trap to higher layers).  This function returns non-zero if the
   1939    event should be ignored and we should wait again.  If STOPPING is
   1940    true, the new LWP remains stopped, otherwise it is continued.  */
   1941 
   1942 static int
   1943 linux_handle_extended_wait (struct lwp_info *lp, int status)
   1944 {
   1945   int pid = lp->ptid.lwp ();
   1946   struct target_waitstatus *ourstatus = &lp->waitstatus;
   1947   int event = linux_ptrace_get_extended_event (status);
   1948 
   1949   /* All extended events we currently use are mid-syscall.  Only
   1950      PTRACE_EVENT_STOP is delivered more like a signal-stop, but
   1951      you have to be using PTRACE_SEIZE to get that.  */
   1952   lp->syscall_state = TARGET_WAITKIND_SYSCALL_ENTRY;
   1953 
   1954   if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
   1955       || event == PTRACE_EVENT_CLONE)
   1956     {
   1957       unsigned long new_pid;
   1958       int ret;
   1959 
   1960       ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
   1961 
   1962       /* If we haven't already seen the new PID stop, wait for it now.  */
   1963       if (! pull_pid_from_list (&stopped_pids, new_pid, &status))
   1964 	{
   1965 	  /* The new child has a pending SIGSTOP.  We can't affect it until it
   1966 	     hits the SIGSTOP, but we're already attached.  */
   1967 	  ret = my_waitpid (new_pid, &status, __WALL);
   1968 	  if (ret == -1)
   1969 	    perror_with_name (_("waiting for new child"));
   1970 	  else if (ret != new_pid)
   1971 	    internal_error (__FILE__, __LINE__,
   1972 			    _("wait returned unexpected PID %d"), ret);
   1973 	  else if (!WIFSTOPPED (status))
   1974 	    internal_error (__FILE__, __LINE__,
   1975 			    _("wait returned unexpected status 0x%x"), status);
   1976 	}
   1977 
   1978       ourstatus->value.related_pid = ptid_t (new_pid, new_pid, 0);
   1979 
   1980       if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK)
   1981 	{
   1982 	  /* The arch-specific native code may need to know about new
   1983 	     forks even if those end up never mapped to an
   1984 	     inferior.  */
   1985 	  linux_target->low_new_fork (lp, new_pid);
   1986 	}
   1987 
   1988       if (event == PTRACE_EVENT_FORK
   1989 	  && linux_fork_checkpointing_p (lp->ptid.pid ()))
   1990 	{
   1991 	  /* Handle checkpointing by linux-fork.c here as a special
   1992 	     case.  We don't want the follow-fork-mode or 'catch fork'
   1993 	     to interfere with this.  */
   1994 
   1995 	  /* This won't actually modify the breakpoint list, but will
   1996 	     physically remove the breakpoints from the child.  */
   1997 	  detach_breakpoints (ptid_t (new_pid, new_pid, 0));
   1998 
   1999 	  /* Retain child fork in ptrace (stopped) state.  */
   2000 	  if (!find_fork_pid (new_pid))
   2001 	    add_fork (new_pid);
   2002 
   2003 	  /* Report as spurious, so that infrun doesn't want to follow
   2004 	     this fork.  We're actually doing an infcall in
   2005 	     linux-fork.c.  */
   2006 	  ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
   2007 
   2008 	  /* Report the stop to the core.  */
   2009 	  return 0;
   2010 	}
   2011 
   2012       if (event == PTRACE_EVENT_FORK)
   2013 	ourstatus->kind = TARGET_WAITKIND_FORKED;
   2014       else if (event == PTRACE_EVENT_VFORK)
   2015 	ourstatus->kind = TARGET_WAITKIND_VFORKED;
   2016       else if (event == PTRACE_EVENT_CLONE)
   2017 	{
   2018 	  struct lwp_info *new_lp;
   2019 
   2020 	  ourstatus->kind = TARGET_WAITKIND_IGNORE;
   2021 
   2022 	  if (debug_linux_nat)
   2023 	    fprintf_unfiltered (gdb_stdlog,
   2024 				"LHEW: Got clone event "
   2025 				"from LWP %d, new child is LWP %ld\n",
   2026 				pid, new_pid);
   2027 
   2028 	  new_lp = add_lwp (ptid_t (lp->ptid.pid (), new_pid, 0));
   2029 	  new_lp->stopped = 1;
   2030 	  new_lp->resumed = 1;
   2031 
   2032 	  /* If the thread_db layer is active, let it record the user
   2033 	     level thread id and status, and add the thread to GDB's
   2034 	     list.  */
   2035 	  if (!thread_db_notice_clone (lp->ptid, new_lp->ptid))
   2036 	    {
   2037 	      /* The process is not using thread_db.  Add the LWP to
   2038 		 GDB's list.  */
   2039 	      target_post_attach (new_lp->ptid.lwp ());
   2040 	      add_thread (new_lp->ptid);
   2041 	    }
   2042 
   2043 	  /* Even if we're stopping the thread for some reason
   2044 	     internal to this module, from the perspective of infrun
   2045 	     and the user/frontend, this new thread is running until
   2046 	     it next reports a stop.  */
   2047 	  set_running (new_lp->ptid, 1);
   2048 	  set_executing (new_lp->ptid, 1);
   2049 
   2050 	  if (WSTOPSIG (status) != SIGSTOP)
   2051 	    {
   2052 	      /* This can happen if someone starts sending signals to
   2053 		 the new thread before it gets a chance to run, which
   2054 		 have a lower number than SIGSTOP (e.g. SIGUSR1).
   2055 		 This is an unlikely case, and harder to handle for
   2056 		 fork / vfork than for clone, so we do not try - but
   2057 		 we handle it for clone events here.  */
   2058 
   2059 	      new_lp->signalled = 1;
   2060 
   2061 	      /* We created NEW_LP so it cannot yet contain STATUS.  */
   2062 	      gdb_assert (new_lp->status == 0);
   2063 
   2064 	      /* Save the wait status to report later.  */
   2065 	      if (debug_linux_nat)
   2066 		fprintf_unfiltered (gdb_stdlog,
   2067 				    "LHEW: waitpid of new LWP %ld, "
   2068 				    "saving status %s\n",
   2069 				    (long) new_lp->ptid.lwp (),
   2070 				    status_to_str (status));
   2071 	      new_lp->status = status;
   2072 	    }
   2073 	  else if (report_thread_events)
   2074 	    {
   2075 	      new_lp->waitstatus.kind = TARGET_WAITKIND_THREAD_CREATED;
   2076 	      new_lp->status = status;
   2077 	    }
   2078 
   2079 	  return 1;
   2080 	}
   2081 
   2082       return 0;
   2083     }
   2084 
   2085   if (event == PTRACE_EVENT_EXEC)
   2086     {
   2087       if (debug_linux_nat)
   2088 	fprintf_unfiltered (gdb_stdlog,
   2089 			    "LHEW: Got exec event from LWP %ld\n",
   2090 			    lp->ptid.lwp ());
   2091 
   2092       ourstatus->kind = TARGET_WAITKIND_EXECD;
   2093       ourstatus->value.execd_pathname
   2094 	= xstrdup (linux_proc_pid_to_exec_file (pid));
   2095 
   2096       /* The thread that execed must have been resumed, but, when a
   2097 	 thread execs, it changes its tid to the tgid, and the old
   2098 	 tgid thread might have not been resumed.  */
   2099       lp->resumed = 1;
   2100       return 0;
   2101     }
   2102 
   2103   if (event == PTRACE_EVENT_VFORK_DONE)
   2104     {
   2105       if (current_inferior ()->waiting_for_vfork_done)
   2106 	{
   2107 	  if (debug_linux_nat)
   2108 	    fprintf_unfiltered (gdb_stdlog,
   2109 				"LHEW: Got expected PTRACE_EVENT_"
   2110 				"VFORK_DONE from LWP %ld: stopping\n",
   2111 				lp->ptid.lwp ());
   2112 
   2113 	  ourstatus->kind = TARGET_WAITKIND_VFORK_DONE;
   2114 	  return 0;
   2115 	}
   2116 
   2117       if (debug_linux_nat)
   2118 	fprintf_unfiltered (gdb_stdlog,
   2119 			    "LHEW: Got PTRACE_EVENT_VFORK_DONE "
   2120 			    "from LWP %ld: ignoring\n",
   2121 			    lp->ptid.lwp ());
   2122       return 1;
   2123     }
   2124 
   2125   internal_error (__FILE__, __LINE__,
   2126 		  _("unknown ptrace event %d"), event);
   2127 }
   2128 
   2129 /* Suspend waiting for a signal.  We're mostly interested in
   2130    SIGCHLD/SIGINT.  */
   2131 
   2132 static void
   2133 wait_for_signal ()
   2134 {
   2135   if (debug_linux_nat)
   2136     fprintf_unfiltered (gdb_stdlog, "linux-nat: about to sigsuspend\n");
   2137   sigsuspend (&suspend_mask);
   2138 
   2139   /* If the quit flag is set, it means that the user pressed Ctrl-C
   2140      and we're debugging a process that is running on a separate
   2141      terminal, so we must forward the Ctrl-C to the inferior.  (If the
   2142      inferior is sharing GDB's terminal, then the Ctrl-C reaches the
   2143      inferior directly.)  We must do this here because functions that
   2144      need to block waiting for a signal loop forever until there's an
   2145      event to report before returning back to the event loop.  */
   2146   if (!target_terminal::is_ours ())
   2147     {
   2148       if (check_quit_flag ())
   2149 	target_pass_ctrlc ();
   2150     }
   2151 }
   2152 
   2153 /* Wait for LP to stop.  Returns the wait status, or 0 if the LWP has
   2154    exited.  */
   2155 
   2156 static int
   2157 wait_lwp (struct lwp_info *lp)
   2158 {
   2159   pid_t pid;
   2160   int status = 0;
   2161   int thread_dead = 0;
   2162   sigset_t prev_mask;
   2163 
   2164   gdb_assert (!lp->stopped);
   2165   gdb_assert (lp->status == 0);
   2166 
   2167   /* Make sure SIGCHLD is blocked for sigsuspend avoiding a race below.  */
   2168   block_child_signals (&prev_mask);
   2169 
   2170   for (;;)
   2171     {
   2172       pid = my_waitpid (lp->ptid.lwp (), &status, __WALL | WNOHANG);
   2173       if (pid == -1 && errno == ECHILD)
   2174 	{
   2175 	  /* The thread has previously exited.  We need to delete it
   2176 	     now because if this was a non-leader thread execing, we
   2177 	     won't get an exit event.  See comments on exec events at
   2178 	     the top of the file.  */
   2179 	  thread_dead = 1;
   2180 	  if (debug_linux_nat)
   2181 	    fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
   2182 				target_pid_to_str (lp->ptid));
   2183 	}
   2184       if (pid != 0)
   2185 	break;
   2186 
   2187       /* Bugs 10970, 12702.
   2188 	 Thread group leader may have exited in which case we'll lock up in
   2189 	 waitpid if there are other threads, even if they are all zombies too.
   2190 	 Basically, we're not supposed to use waitpid this way.
   2191 	  tkill(pid,0) cannot be used here as it gets ESRCH for both
   2192 	 for zombie and running processes.
   2193 
   2194 	 As a workaround, check if we're waiting for the thread group leader and
   2195 	 if it's a zombie, and avoid calling waitpid if it is.
   2196 
   2197 	 This is racy, what if the tgl becomes a zombie right after we check?
   2198 	 Therefore always use WNOHANG with sigsuspend - it is equivalent to
   2199 	 waiting waitpid but linux_proc_pid_is_zombie is safe this way.  */
   2200 
   2201       if (lp->ptid.pid () == lp->ptid.lwp ()
   2202 	  && linux_proc_pid_is_zombie (lp->ptid.lwp ()))
   2203 	{
   2204 	  thread_dead = 1;
   2205 	  if (debug_linux_nat)
   2206 	    fprintf_unfiltered (gdb_stdlog,
   2207 				"WL: Thread group leader %s vanished.\n",
   2208 				target_pid_to_str (lp->ptid));
   2209 	  break;
   2210 	}
   2211 
   2212       /* Wait for next SIGCHLD and try again.  This may let SIGCHLD handlers
   2213 	 get invoked despite our caller had them intentionally blocked by
   2214 	 block_child_signals.  This is sensitive only to the loop of
   2215 	 linux_nat_wait_1 and there if we get called my_waitpid gets called
   2216 	 again before it gets to sigsuspend so we can safely let the handlers
   2217 	 get executed here.  */
   2218       wait_for_signal ();
   2219     }
   2220 
   2221   restore_child_signals_mask (&prev_mask);
   2222 
   2223   if (!thread_dead)
   2224     {
   2225       gdb_assert (pid == lp->ptid.lwp ());
   2226 
   2227       if (debug_linux_nat)
   2228 	{
   2229 	  fprintf_unfiltered (gdb_stdlog,
   2230 			      "WL: waitpid %s received %s\n",
   2231 			      target_pid_to_str (lp->ptid),
   2232 			      status_to_str (status));
   2233 	}
   2234 
   2235       /* Check if the thread has exited.  */
   2236       if (WIFEXITED (status) || WIFSIGNALED (status))
   2237 	{
   2238 	  if (report_thread_events
   2239 	      || lp->ptid.pid () == lp->ptid.lwp ())
   2240 	    {
   2241 	      if (debug_linux_nat)
   2242 		fprintf_unfiltered (gdb_stdlog, "WL: LWP %d exited.\n",
   2243 				    lp->ptid.pid ());
   2244 
   2245 	      /* If this is the leader exiting, it means the whole
   2246 		 process is gone.  Store the status to report to the
   2247 		 core.  Store it in lp->waitstatus, because lp->status
   2248 		 would be ambiguous (W_EXITCODE(0,0) == 0).  */
   2249 	      store_waitstatus (&lp->waitstatus, status);
   2250 	      return 0;
   2251 	    }
   2252 
   2253 	  thread_dead = 1;
   2254 	  if (debug_linux_nat)
   2255 	    fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
   2256 				target_pid_to_str (lp->ptid));
   2257 	}
   2258     }
   2259 
   2260   if (thread_dead)
   2261     {
   2262       exit_lwp (lp);
   2263       return 0;
   2264     }
   2265 
   2266   gdb_assert (WIFSTOPPED (status));
   2267   lp->stopped = 1;
   2268 
   2269   if (lp->must_set_ptrace_flags)
   2270     {
   2271       struct inferior *inf = find_inferior_pid (lp->ptid.pid ());
   2272       int options = linux_nat_ptrace_options (inf->attach_flag);
   2273 
   2274       linux_enable_event_reporting (lp->ptid.lwp (), options);
   2275       lp->must_set_ptrace_flags = 0;
   2276     }
   2277 
   2278   /* Handle GNU/Linux's syscall SIGTRAPs.  */
   2279   if (WIFSTOPPED (status) && WSTOPSIG (status) == SYSCALL_SIGTRAP)
   2280     {
   2281       /* No longer need the sysgood bit.  The ptrace event ends up
   2282 	 recorded in lp->waitstatus if we care for it.  We can carry
   2283 	 on handling the event like a regular SIGTRAP from here
   2284 	 on.  */
   2285       status = W_STOPCODE (SIGTRAP);
   2286       if (linux_handle_syscall_trap (lp, 1))
   2287 	return wait_lwp (lp);
   2288     }
   2289   else
   2290     {
   2291       /* Almost all other ptrace-stops are known to be outside of system
   2292 	 calls, with further exceptions in linux_handle_extended_wait.  */
   2293       lp->syscall_state = TARGET_WAITKIND_IGNORE;
   2294     }
   2295 
   2296   /* Handle GNU/Linux's extended waitstatus for trace events.  */
   2297   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP
   2298       && linux_is_extended_waitstatus (status))
   2299     {
   2300       if (debug_linux_nat)
   2301 	fprintf_unfiltered (gdb_stdlog,
   2302 			    "WL: Handling extended status 0x%06x\n",
   2303 			    status);
   2304       linux_handle_extended_wait (lp, status);
   2305       return 0;
   2306     }
   2307 
   2308   return status;
   2309 }
   2310 
   2311 /* Send a SIGSTOP to LP.  */
   2312 
   2313 static int
   2314 stop_callback (struct lwp_info *lp, void *data)
   2315 {
   2316   if (!lp->stopped && !lp->signalled)
   2317     {
   2318       int ret;
   2319 
   2320       if (debug_linux_nat)
   2321 	{
   2322 	  fprintf_unfiltered (gdb_stdlog,
   2323 			      "SC:  kill %s **<SIGSTOP>**\n",
   2324 			      target_pid_to_str (lp->ptid));
   2325 	}
   2326       errno = 0;
   2327       ret = kill_lwp (lp->ptid.lwp (), SIGSTOP);
   2328       if (debug_linux_nat)
   2329 	{
   2330 	  fprintf_unfiltered (gdb_stdlog,
   2331 			      "SC:  lwp kill %d %s\n",
   2332 			      ret,
   2333 			      errno ? safe_strerror (errno) : "ERRNO-OK");
   2334 	}
   2335 
   2336       lp->signalled = 1;
   2337       gdb_assert (lp->status == 0);
   2338     }
   2339 
   2340   return 0;
   2341 }
   2342 
   2343 /* Request a stop on LWP.  */
   2344 
   2345 void
   2346 linux_stop_lwp (struct lwp_info *lwp)
   2347 {
   2348   stop_callback (lwp, NULL);
   2349 }
   2350 
   2351 /* See linux-nat.h  */
   2352 
   2353 void
   2354 linux_stop_and_wait_all_lwps (void)
   2355 {
   2356   /* Stop all LWP's ...  */
   2357   iterate_over_lwps (minus_one_ptid, stop_callback, NULL);
   2358 
   2359   /* ... and wait until all of them have reported back that
   2360      they're no longer running.  */
   2361   iterate_over_lwps (minus_one_ptid, stop_wait_callback, NULL);
   2362 }
   2363 
   2364 /* See linux-nat.h  */
   2365 
   2366 void
   2367 linux_unstop_all_lwps (void)
   2368 {
   2369   iterate_over_lwps (minus_one_ptid,
   2370 		     resume_stopped_resumed_lwps, &minus_one_ptid);
   2371 }
   2372 
   2373 /* Return non-zero if LWP PID has a pending SIGINT.  */
   2374 
   2375 static int
   2376 linux_nat_has_pending_sigint (int pid)
   2377 {
   2378   sigset_t pending, blocked, ignored;
   2379 
   2380   linux_proc_pending_signals (pid, &pending, &blocked, &ignored);
   2381 
   2382   if (sigismember (&pending, SIGINT)
   2383       && !sigismember (&ignored, SIGINT))
   2384     return 1;
   2385 
   2386   return 0;
   2387 }
   2388 
   2389 /* Set a flag in LP indicating that we should ignore its next SIGINT.  */
   2390 
   2391 static int
   2392 set_ignore_sigint (struct lwp_info *lp, void *data)
   2393 {
   2394   /* If a thread has a pending SIGINT, consume it; otherwise, set a
   2395      flag to consume the next one.  */
   2396   if (lp->stopped && lp->status != 0 && WIFSTOPPED (lp->status)
   2397       && WSTOPSIG (lp->status) == SIGINT)
   2398     lp->status = 0;
   2399   else
   2400     lp->ignore_sigint = 1;
   2401 
   2402   return 0;
   2403 }
   2404 
   2405 /* If LP does not have a SIGINT pending, then clear the ignore_sigint flag.
   2406    This function is called after we know the LWP has stopped; if the LWP
   2407    stopped before the expected SIGINT was delivered, then it will never have
   2408    arrived.  Also, if the signal was delivered to a shared queue and consumed
   2409    by a different thread, it will never be delivered to this LWP.  */
   2410 
   2411 static void
   2412 maybe_clear_ignore_sigint (struct lwp_info *lp)
   2413 {
   2414   if (!lp->ignore_sigint)
   2415     return;
   2416 
   2417   if (!linux_nat_has_pending_sigint (lp->ptid.lwp ()))
   2418     {
   2419       if (debug_linux_nat)
   2420 	fprintf_unfiltered (gdb_stdlog,
   2421 			    "MCIS: Clearing bogus flag for %s\n",
   2422 			    target_pid_to_str (lp->ptid));
   2423       lp->ignore_sigint = 0;
   2424     }
   2425 }
   2426 
   2427 /* Fetch the possible triggered data watchpoint info and store it in
   2428    LP.
   2429 
   2430    On some archs, like x86, that use debug registers to set
   2431    watchpoints, it's possible that the way to know which watched
   2432    address trapped, is to check the register that is used to select
   2433    which address to watch.  Problem is, between setting the watchpoint
   2434    and reading back which data address trapped, the user may change
   2435    the set of watchpoints, and, as a consequence, GDB changes the
   2436    debug registers in the inferior.  To avoid reading back a stale
   2437    stopped-data-address when that happens, we cache in LP the fact
   2438    that a watchpoint trapped, and the corresponding data address, as
   2439    soon as we see LP stop with a SIGTRAP.  If GDB changes the debug
   2440    registers meanwhile, we have the cached data we can rely on.  */
   2441 
   2442 static int
   2443 check_stopped_by_watchpoint (struct lwp_info *lp)
   2444 {
   2445   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
   2446   inferior_ptid = lp->ptid;
   2447 
   2448   if (linux_target->low_stopped_by_watchpoint ())
   2449     {
   2450       lp->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
   2451       lp->stopped_data_address_p
   2452 	= linux_target->low_stopped_data_address (&lp->stopped_data_address);
   2453     }
   2454 
   2455   return lp->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
   2456 }
   2457 
   2458 /* Returns true if the LWP had stopped for a watchpoint.  */
   2459 
   2460 bool
   2461 linux_nat_target::stopped_by_watchpoint ()
   2462 {
   2463   struct lwp_info *lp = find_lwp_pid (inferior_ptid);
   2464 
   2465   gdb_assert (lp != NULL);
   2466 
   2467   return lp->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
   2468 }
   2469 
   2470 bool
   2471 linux_nat_target::stopped_data_address (CORE_ADDR *addr_p)
   2472 {
   2473   struct lwp_info *lp = find_lwp_pid (inferior_ptid);
   2474 
   2475   gdb_assert (lp != NULL);
   2476 
   2477   *addr_p = lp->stopped_data_address;
   2478 
   2479   return lp->stopped_data_address_p;
   2480 }
   2481 
   2482 /* Commonly any breakpoint / watchpoint generate only SIGTRAP.  */
   2483 
   2484 bool
   2485 linux_nat_target::low_status_is_event (int status)
   2486 {
   2487   return WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP;
   2488 }
   2489 
   2490 /* Wait until LP is stopped.  */
   2491 
   2492 static int
   2493 stop_wait_callback (struct lwp_info *lp, void *data)
   2494 {
   2495   struct inferior *inf = find_inferior_ptid (lp->ptid);
   2496 
   2497   /* If this is a vfork parent, bail out, it is not going to report
   2498      any SIGSTOP until the vfork is done with.  */
   2499   if (inf->vfork_child != NULL)
   2500     return 0;
   2501 
   2502   if (!lp->stopped)
   2503     {
   2504       int status;
   2505 
   2506       status = wait_lwp (lp);
   2507       if (status == 0)
   2508 	return 0;
   2509 
   2510       if (lp->ignore_sigint && WIFSTOPPED (status)
   2511 	  && WSTOPSIG (status) == SIGINT)
   2512 	{
   2513 	  lp->ignore_sigint = 0;
   2514 
   2515 	  errno = 0;
   2516 	  ptrace (PTRACE_CONT, lp->ptid.lwp (), 0, 0);
   2517 	  lp->stopped = 0;
   2518 	  if (debug_linux_nat)
   2519 	    fprintf_unfiltered (gdb_stdlog,
   2520 				"PTRACE_CONT %s, 0, 0 (%s) "
   2521 				"(discarding SIGINT)\n",
   2522 				target_pid_to_str (lp->ptid),
   2523 				errno ? safe_strerror (errno) : "OK");
   2524 
   2525 	  return stop_wait_callback (lp, NULL);
   2526 	}
   2527 
   2528       maybe_clear_ignore_sigint (lp);
   2529 
   2530       if (WSTOPSIG (status) != SIGSTOP)
   2531 	{
   2532 	  /* The thread was stopped with a signal other than SIGSTOP.  */
   2533 
   2534 	  if (debug_linux_nat)
   2535 	    fprintf_unfiltered (gdb_stdlog,
   2536 				"SWC: Pending event %s in %s\n",
   2537 				status_to_str ((int) status),
   2538 				target_pid_to_str (lp->ptid));
   2539 
   2540 	  /* Save the sigtrap event.  */
   2541 	  lp->status = status;
   2542 	  gdb_assert (lp->signalled);
   2543 	  save_stop_reason (lp);
   2544 	}
   2545       else
   2546 	{
   2547 	  /* We caught the SIGSTOP that we intended to catch.  */
   2548 
   2549 	  if (debug_linux_nat)
   2550 	    fprintf_unfiltered (gdb_stdlog,
   2551 				"SWC: Expected SIGSTOP caught for %s.\n",
   2552 				target_pid_to_str (lp->ptid));
   2553 
   2554 	  lp->signalled = 0;
   2555 
   2556 	  /* If we are waiting for this stop so we can report the thread
   2557 	     stopped then we need to record this status.  Otherwise, we can
   2558 	     now discard this stop event.  */
   2559 	  if (lp->last_resume_kind == resume_stop)
   2560 	    {
   2561 	      lp->status = status;
   2562 	      save_stop_reason (lp);
   2563 	    }
   2564 	}
   2565     }
   2566 
   2567   return 0;
   2568 }
   2569 
   2570 /* Return non-zero if LP has a wait status pending.  Discard the
   2571    pending event and resume the LWP if the event that originally
   2572    caused the stop became uninteresting.  */
   2573 
   2574 static int
   2575 status_callback (struct lwp_info *lp, void *data)
   2576 {
   2577   /* Only report a pending wait status if we pretend that this has
   2578      indeed been resumed.  */
   2579   if (!lp->resumed)
   2580     return 0;
   2581 
   2582   if (!lwp_status_pending_p (lp))
   2583     return 0;
   2584 
   2585   if (lp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
   2586       || lp->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT)
   2587     {
   2588       struct regcache *regcache = get_thread_regcache (lp->ptid);
   2589       CORE_ADDR pc;
   2590       int discard = 0;
   2591 
   2592       pc = regcache_read_pc (regcache);
   2593 
   2594       if (pc != lp->stop_pc)
   2595 	{
   2596 	  if (debug_linux_nat)
   2597 	    fprintf_unfiltered (gdb_stdlog,
   2598 				"SC: PC of %s changed.  was=%s, now=%s\n",
   2599 				target_pid_to_str (lp->ptid),
   2600 				paddress (target_gdbarch (), lp->stop_pc),
   2601 				paddress (target_gdbarch (), pc));
   2602 	  discard = 1;
   2603 	}
   2604 
   2605 #if !USE_SIGTRAP_SIGINFO
   2606       else if (!breakpoint_inserted_here_p (regcache->aspace (), pc))
   2607 	{
   2608 	  if (debug_linux_nat)
   2609 	    fprintf_unfiltered (gdb_stdlog,
   2610 				"SC: previous breakpoint of %s, at %s gone\n",
   2611 				target_pid_to_str (lp->ptid),
   2612 				paddress (target_gdbarch (), lp->stop_pc));
   2613 
   2614 	  discard = 1;
   2615 	}
   2616 #endif
   2617 
   2618       if (discard)
   2619 	{
   2620 	  if (debug_linux_nat)
   2621 	    fprintf_unfiltered (gdb_stdlog,
   2622 				"SC: pending event of %s cancelled.\n",
   2623 				target_pid_to_str (lp->ptid));
   2624 
   2625 	  lp->status = 0;
   2626 	  linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
   2627 	  return 0;
   2628 	}
   2629     }
   2630 
   2631   return 1;
   2632 }
   2633 
   2634 /* Count the LWP's that have had events.  */
   2635 
   2636 static int
   2637 count_events_callback (struct lwp_info *lp, void *data)
   2638 {
   2639   int *count = (int *) data;
   2640 
   2641   gdb_assert (count != NULL);
   2642 
   2643   /* Select only resumed LWPs that have an event pending.  */
   2644   if (lp->resumed && lwp_status_pending_p (lp))
   2645     (*count)++;
   2646 
   2647   return 0;
   2648 }
   2649 
   2650 /* Select the LWP (if any) that is currently being single-stepped.  */
   2651 
   2652 static int
   2653 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
   2654 {
   2655   if (lp->last_resume_kind == resume_step
   2656       && lp->status != 0)
   2657     return 1;
   2658   else
   2659     return 0;
   2660 }
   2661 
   2662 /* Returns true if LP has a status pending.  */
   2663 
   2664 static int
   2665 lwp_status_pending_p (struct lwp_info *lp)
   2666 {
   2667   /* We check for lp->waitstatus in addition to lp->status, because we
   2668      can have pending process exits recorded in lp->status and
   2669      W_EXITCODE(0,0) happens to be 0.  */
   2670   return lp->status != 0 || lp->waitstatus.kind != TARGET_WAITKIND_IGNORE;
   2671 }
   2672 
   2673 /* Select the Nth LWP that has had an event.  */
   2674 
   2675 static int
   2676 select_event_lwp_callback (struct lwp_info *lp, void *data)
   2677 {
   2678   int *selector = (int *) data;
   2679 
   2680   gdb_assert (selector != NULL);
   2681 
   2682   /* Select only resumed LWPs that have an event pending.  */
   2683   if (lp->resumed && lwp_status_pending_p (lp))
   2684     if ((*selector)-- == 0)
   2685       return 1;
   2686 
   2687   return 0;
   2688 }
   2689 
   2690 /* Called when the LWP stopped for a signal/trap.  If it stopped for a
   2691    trap check what caused it (breakpoint, watchpoint, trace, etc.),
   2692    and save the result in the LWP's stop_reason field.  If it stopped
   2693    for a breakpoint, decrement the PC if necessary on the lwp's
   2694    architecture.  */
   2695 
   2696 static void
   2697 save_stop_reason (struct lwp_info *lp)
   2698 {
   2699   struct regcache *regcache;
   2700   struct gdbarch *gdbarch;
   2701   CORE_ADDR pc;
   2702   CORE_ADDR sw_bp_pc;
   2703 #if USE_SIGTRAP_SIGINFO
   2704   siginfo_t siginfo;
   2705 #endif
   2706 
   2707   gdb_assert (lp->stop_reason == TARGET_STOPPED_BY_NO_REASON);
   2708   gdb_assert (lp->status != 0);
   2709 
   2710   if (!linux_target->low_status_is_event (lp->status))
   2711     return;
   2712 
   2713   regcache = get_thread_regcache (lp->ptid);
   2714   gdbarch = regcache->arch ();
   2715 
   2716   pc = regcache_read_pc (regcache);
   2717   sw_bp_pc = pc - gdbarch_decr_pc_after_break (gdbarch);
   2718 
   2719 #if USE_SIGTRAP_SIGINFO
   2720   if (linux_nat_get_siginfo (lp->ptid, &siginfo))
   2721     {
   2722       if (siginfo.si_signo == SIGTRAP)
   2723 	{
   2724 	  if (GDB_ARCH_IS_TRAP_BRKPT (siginfo.si_code)
   2725 	      && GDB_ARCH_IS_TRAP_HWBKPT (siginfo.si_code))
   2726 	    {
   2727 	      /* The si_code is ambiguous on this arch -- check debug
   2728 		 registers.  */
   2729 	      if (!check_stopped_by_watchpoint (lp))
   2730 		lp->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
   2731 	    }
   2732 	  else if (GDB_ARCH_IS_TRAP_BRKPT (siginfo.si_code))
   2733 	    {
   2734 	      /* If we determine the LWP stopped for a SW breakpoint,
   2735 		 trust it.  Particularly don't check watchpoint
   2736 		 registers, because at least on s390, we'd find
   2737 		 stopped-by-watchpoint as long as there's a watchpoint
   2738 		 set.  */
   2739 	      lp->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
   2740 	    }
   2741 	  else if (GDB_ARCH_IS_TRAP_HWBKPT (siginfo.si_code))
   2742 	    {
   2743 	      /* This can indicate either a hardware breakpoint or
   2744 		 hardware watchpoint.  Check debug registers.  */
   2745 	      if (!check_stopped_by_watchpoint (lp))
   2746 		lp->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
   2747 	    }
   2748 	  else if (siginfo.si_code == TRAP_TRACE)
   2749 	    {
   2750 	      if (debug_linux_nat)
   2751 		fprintf_unfiltered (gdb_stdlog,
   2752 				    "CSBB: %s stopped by trace\n",
   2753 				    target_pid_to_str (lp->ptid));
   2754 
   2755 	      /* We may have single stepped an instruction that
   2756 		 triggered a watchpoint.  In that case, on some
   2757 		 architectures (such as x86), instead of TRAP_HWBKPT,
   2758 		 si_code indicates TRAP_TRACE, and we need to check
   2759 		 the debug registers separately.  */
   2760 	      check_stopped_by_watchpoint (lp);
   2761 	    }
   2762 	}
   2763     }
   2764 #else
   2765   if ((!lp->step || lp->stop_pc == sw_bp_pc)
   2766       && software_breakpoint_inserted_here_p (regcache->aspace (),
   2767 					      sw_bp_pc))
   2768     {
   2769       /* The LWP was either continued, or stepped a software
   2770 	 breakpoint instruction.  */
   2771       lp->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
   2772     }
   2773 
   2774   if (hardware_breakpoint_inserted_here_p (regcache->aspace (), pc))
   2775     lp->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
   2776 
   2777   if (lp->stop_reason == TARGET_STOPPED_BY_NO_REASON)
   2778     check_stopped_by_watchpoint (lp);
   2779 #endif
   2780 
   2781   if (lp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT)
   2782     {
   2783       if (debug_linux_nat)
   2784 	fprintf_unfiltered (gdb_stdlog,
   2785 			    "CSBB: %s stopped by software breakpoint\n",
   2786 			    target_pid_to_str (lp->ptid));
   2787 
   2788       /* Back up the PC if necessary.  */
   2789       if (pc != sw_bp_pc)
   2790 	regcache_write_pc (regcache, sw_bp_pc);
   2791 
   2792       /* Update this so we record the correct stop PC below.  */
   2793       pc = sw_bp_pc;
   2794     }
   2795   else if (lp->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT)
   2796     {
   2797       if (debug_linux_nat)
   2798 	fprintf_unfiltered (gdb_stdlog,
   2799 			    "CSBB: %s stopped by hardware breakpoint\n",
   2800 			    target_pid_to_str (lp->ptid));
   2801     }
   2802   else if (lp->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
   2803     {
   2804       if (debug_linux_nat)
   2805 	fprintf_unfiltered (gdb_stdlog,
   2806 			    "CSBB: %s stopped by hardware watchpoint\n",
   2807 			    target_pid_to_str (lp->ptid));
   2808     }
   2809 
   2810   lp->stop_pc = pc;
   2811 }
   2812 
   2813 
   2814 /* Returns true if the LWP had stopped for a software breakpoint.  */
   2815 
   2816 bool
   2817 linux_nat_target::stopped_by_sw_breakpoint ()
   2818 {
   2819   struct lwp_info *lp = find_lwp_pid (inferior_ptid);
   2820 
   2821   gdb_assert (lp != NULL);
   2822 
   2823   return lp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
   2824 }
   2825 
   2826 /* Implement the supports_stopped_by_sw_breakpoint method.  */
   2827 
   2828 bool
   2829 linux_nat_target::supports_stopped_by_sw_breakpoint ()
   2830 {
   2831   return USE_SIGTRAP_SIGINFO;
   2832 }
   2833 
   2834 /* Returns true if the LWP had stopped for a hardware
   2835    breakpoint/watchpoint.  */
   2836 
   2837 bool
   2838 linux_nat_target::stopped_by_hw_breakpoint ()
   2839 {
   2840   struct lwp_info *lp = find_lwp_pid (inferior_ptid);
   2841 
   2842   gdb_assert (lp != NULL);
   2843 
   2844   return lp->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
   2845 }
   2846 
   2847 /* Implement the supports_stopped_by_hw_breakpoint method.  */
   2848 
   2849 bool
   2850 linux_nat_target::supports_stopped_by_hw_breakpoint ()
   2851 {
   2852   return USE_SIGTRAP_SIGINFO;
   2853 }
   2854 
   2855 /* Select one LWP out of those that have events pending.  */
   2856 
   2857 static void
   2858 select_event_lwp (ptid_t filter, struct lwp_info **orig_lp, int *status)
   2859 {
   2860   int num_events = 0;
   2861   int random_selector;
   2862   struct lwp_info *event_lp = NULL;
   2863 
   2864   /* Record the wait status for the original LWP.  */
   2865   (*orig_lp)->status = *status;
   2866 
   2867   /* In all-stop, give preference to the LWP that is being
   2868      single-stepped.  There will be at most one, and it will be the
   2869      LWP that the core is most interested in.  If we didn't do this,
   2870      then we'd have to handle pending step SIGTRAPs somehow in case
   2871      the core later continues the previously-stepped thread, as
   2872      otherwise we'd report the pending SIGTRAP then, and the core, not
   2873      having stepped the thread, wouldn't understand what the trap was
   2874      for, and therefore would report it to the user as a random
   2875      signal.  */
   2876   if (!target_is_non_stop_p ())
   2877     {
   2878       event_lp = iterate_over_lwps (filter,
   2879 				    select_singlestep_lwp_callback, NULL);
   2880       if (event_lp != NULL)
   2881 	{
   2882 	  if (debug_linux_nat)
   2883 	    fprintf_unfiltered (gdb_stdlog,
   2884 				"SEL: Select single-step %s\n",
   2885 				target_pid_to_str (event_lp->ptid));
   2886 	}
   2887     }
   2888 
   2889   if (event_lp == NULL)
   2890     {
   2891       /* Pick one at random, out of those which have had events.  */
   2892 
   2893       /* First see how many events we have.  */
   2894       iterate_over_lwps (filter, count_events_callback, &num_events);
   2895       gdb_assert (num_events > 0);
   2896 
   2897       /* Now randomly pick a LWP out of those that have had
   2898 	 events.  */
   2899       random_selector = (int)
   2900 	((num_events * (double) rand ()) / (RAND_MAX + 1.0));
   2901 
   2902       if (debug_linux_nat && num_events > 1)
   2903 	fprintf_unfiltered (gdb_stdlog,
   2904 			    "SEL: Found %d events, selecting #%d\n",
   2905 			    num_events, random_selector);
   2906 
   2907       event_lp = iterate_over_lwps (filter,
   2908 				    select_event_lwp_callback,
   2909 				    &random_selector);
   2910     }
   2911 
   2912   if (event_lp != NULL)
   2913     {
   2914       /* Switch the event LWP.  */
   2915       *orig_lp = event_lp;
   2916       *status = event_lp->status;
   2917     }
   2918 
   2919   /* Flush the wait status for the event LWP.  */
   2920   (*orig_lp)->status = 0;
   2921 }
   2922 
   2923 /* Return non-zero if LP has been resumed.  */
   2924 
   2925 static int
   2926 resumed_callback (struct lwp_info *lp, void *data)
   2927 {
   2928   return lp->resumed;
   2929 }
   2930 
   2931 /* Check if we should go on and pass this event to common code.
   2932    Return the affected lwp if we are, or NULL otherwise.  */
   2933 
   2934 static struct lwp_info *
   2935 linux_nat_filter_event (int lwpid, int status)
   2936 {
   2937   struct lwp_info *lp;
   2938   int event = linux_ptrace_get_extended_event (status);
   2939 
   2940   lp = find_lwp_pid (ptid_t (lwpid));
   2941 
   2942   /* Check for stop events reported by a process we didn't already
   2943      know about - anything not already in our LWP list.
   2944 
   2945      If we're expecting to receive stopped processes after
   2946      fork, vfork, and clone events, then we'll just add the
   2947      new one to our list and go back to waiting for the event
   2948      to be reported - the stopped process might be returned
   2949      from waitpid before or after the event is.
   2950 
   2951      But note the case of a non-leader thread exec'ing after the
   2952      leader having exited, and gone from our lists.  The non-leader
   2953      thread changes its tid to the tgid.  */
   2954 
   2955   if (WIFSTOPPED (status) && lp == NULL
   2956       && (WSTOPSIG (status) == SIGTRAP && event == PTRACE_EVENT_EXEC))
   2957     {
   2958       /* A multi-thread exec after we had seen the leader exiting.  */
   2959       if (debug_linux_nat)
   2960 	fprintf_unfiltered (gdb_stdlog,
   2961 			    "LLW: Re-adding thread group leader LWP %d.\n",
   2962 			    lwpid);
   2963 
   2964       lp = add_lwp (ptid_t (lwpid, lwpid, 0));
   2965       lp->stopped = 1;
   2966       lp->resumed = 1;
   2967       add_thread (lp->ptid);
   2968     }
   2969 
   2970   if (WIFSTOPPED (status) && !lp)
   2971     {
   2972       if (debug_linux_nat)
   2973 	fprintf_unfiltered (gdb_stdlog,
   2974 			    "LHEW: saving LWP %ld status %s in stopped_pids list\n",
   2975 			    (long) lwpid, status_to_str (status));
   2976       add_to_pid_list (&stopped_pids, lwpid, status);
   2977       return NULL;
   2978     }
   2979 
   2980   /* Make sure we don't report an event for the exit of an LWP not in
   2981      our list, i.e. not part of the current process.  This can happen
   2982      if we detach from a program we originally forked and then it
   2983      exits.  */
   2984   if (!WIFSTOPPED (status) && !lp)
   2985     return NULL;
   2986 
   2987   /* This LWP is stopped now.  (And if dead, this prevents it from
   2988      ever being continued.)  */
   2989   lp->stopped = 1;
   2990 
   2991   if (WIFSTOPPED (status) && lp->must_set_ptrace_flags)
   2992     {
   2993       struct inferior *inf = find_inferior_pid (lp->ptid.pid ());
   2994       int options = linux_nat_ptrace_options (inf->attach_flag);
   2995 
   2996       linux_enable_event_reporting (lp->ptid.lwp (), options);
   2997       lp->must_set_ptrace_flags = 0;
   2998     }
   2999 
   3000   /* Handle GNU/Linux's syscall SIGTRAPs.  */
   3001   if (WIFSTOPPED (status) && WSTOPSIG (status) == SYSCALL_SIGTRAP)
   3002     {
   3003       /* No longer need the sysgood bit.  The ptrace event ends up
   3004 	 recorded in lp->waitstatus if we care for it.  We can carry
   3005 	 on handling the event like a regular SIGTRAP from here
   3006 	 on.  */
   3007       status = W_STOPCODE (SIGTRAP);
   3008       if (linux_handle_syscall_trap (lp, 0))
   3009 	return NULL;
   3010     }
   3011   else
   3012     {
   3013       /* Almost all other ptrace-stops are known to be outside of system
   3014 	 calls, with further exceptions in linux_handle_extended_wait.  */
   3015       lp->syscall_state = TARGET_WAITKIND_IGNORE;
   3016     }
   3017 
   3018   /* Handle GNU/Linux's extended waitstatus for trace events.  */
   3019   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP
   3020       && linux_is_extended_waitstatus (status))
   3021     {
   3022       if (debug_linux_nat)
   3023 	fprintf_unfiltered (gdb_stdlog,
   3024 			    "LLW: Handling extended status 0x%06x\n",
   3025 			    status);
   3026       if (linux_handle_extended_wait (lp, status))
   3027 	return NULL;
   3028     }
   3029 
   3030   /* Check if the thread has exited.  */
   3031   if (WIFEXITED (status) || WIFSIGNALED (status))
   3032     {
   3033       if (!report_thread_events
   3034 	  && num_lwps (lp->ptid.pid ()) > 1)
   3035 	{
   3036 	  if (debug_linux_nat)
   3037 	    fprintf_unfiltered (gdb_stdlog,
   3038 				"LLW: %s exited.\n",
   3039 				target_pid_to_str (lp->ptid));
   3040 
   3041 	  /* If there is at least one more LWP, then the exit signal
   3042 	     was not the end of the debugged application and should be
   3043 	     ignored.  */
   3044 	  exit_lwp (lp);
   3045 	  return NULL;
   3046 	}
   3047 
   3048       /* Note that even if the leader was ptrace-stopped, it can still
   3049 	 exit, if e.g., some other thread brings down the whole
   3050 	 process (calls `exit').  So don't assert that the lwp is
   3051 	 resumed.  */
   3052       if (debug_linux_nat)
   3053 	fprintf_unfiltered (gdb_stdlog,
   3054 			    "LWP %ld exited (resumed=%d)\n",
   3055 			    lp->ptid.lwp (), lp->resumed);
   3056 
   3057       /* Dead LWP's aren't expected to reported a pending sigstop.  */
   3058       lp->signalled = 0;
   3059 
   3060       /* Store the pending event in the waitstatus, because
   3061 	 W_EXITCODE(0,0) == 0.  */
   3062       store_waitstatus (&lp->waitstatus, status);
   3063       return lp;
   3064     }
   3065 
   3066   /* Make sure we don't report a SIGSTOP that we sent ourselves in
   3067      an attempt to stop an LWP.  */
   3068   if (lp->signalled
   3069       && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
   3070     {
   3071       lp->signalled = 0;
   3072 
   3073       if (lp->last_resume_kind == resume_stop)
   3074 	{
   3075 	  if (debug_linux_nat)
   3076 	    fprintf_unfiltered (gdb_stdlog,
   3077 				"LLW: resume_stop SIGSTOP caught for %s.\n",
   3078 				target_pid_to_str (lp->ptid));
   3079 	}
   3080       else
   3081 	{
   3082 	  /* This is a delayed SIGSTOP.  Filter out the event.  */
   3083 
   3084 	  if (debug_linux_nat)
   3085 	    fprintf_unfiltered (gdb_stdlog,
   3086 				"LLW: %s %s, 0, 0 (discard delayed SIGSTOP)\n",
   3087 				lp->step ?
   3088 				"PTRACE_SINGLESTEP" : "PTRACE_CONT",
   3089 				target_pid_to_str (lp->ptid));
   3090 
   3091 	  linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
   3092 	  gdb_assert (lp->resumed);
   3093 	  return NULL;
   3094 	}
   3095     }
   3096 
   3097   /* Make sure we don't report a SIGINT that we have already displayed
   3098      for another thread.  */
   3099   if (lp->ignore_sigint
   3100       && WIFSTOPPED (status) && WSTOPSIG (status) == SIGINT)
   3101     {
   3102       if (debug_linux_nat)
   3103 	fprintf_unfiltered (gdb_stdlog,
   3104 			    "LLW: Delayed SIGINT caught for %s.\n",
   3105 			    target_pid_to_str (lp->ptid));
   3106 
   3107       /* This is a delayed SIGINT.  */
   3108       lp->ignore_sigint = 0;
   3109 
   3110       linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
   3111       if (debug_linux_nat)
   3112 	fprintf_unfiltered (gdb_stdlog,
   3113 			    "LLW: %s %s, 0, 0 (discard SIGINT)\n",
   3114 			    lp->step ?
   3115 			    "PTRACE_SINGLESTEP" : "PTRACE_CONT",
   3116 			    target_pid_to_str (lp->ptid));
   3117       gdb_assert (lp->resumed);
   3118 
   3119       /* Discard the event.  */
   3120       return NULL;
   3121     }
   3122 
   3123   /* Don't report signals that GDB isn't interested in, such as
   3124      signals that are neither printed nor stopped upon.  Stopping all
   3125      threads can be a bit time-consuming so if we want decent
   3126      performance with heavily multi-threaded programs, especially when
   3127      they're using a high frequency timer, we'd better avoid it if we
   3128      can.  */
   3129   if (WIFSTOPPED (status))
   3130     {
   3131       enum gdb_signal signo = gdb_signal_from_host (WSTOPSIG (status));
   3132 
   3133       if (!target_is_non_stop_p ())
   3134 	{
   3135 	  /* Only do the below in all-stop, as we currently use SIGSTOP
   3136 	     to implement target_stop (see linux_nat_stop) in
   3137 	     non-stop.  */
   3138 	  if (signo == GDB_SIGNAL_INT && signal_pass_state (signo) == 0)
   3139 	    {
   3140 	      /* If ^C/BREAK is typed at the tty/console, SIGINT gets
   3141 		 forwarded to the entire process group, that is, all LWPs
   3142 		 will receive it - unless they're using CLONE_THREAD to
   3143 		 share signals.  Since we only want to report it once, we
   3144 		 mark it as ignored for all LWPs except this one.  */
   3145 	      iterate_over_lwps (ptid_t (lp->ptid.pid ()),
   3146 					      set_ignore_sigint, NULL);
   3147 	      lp->ignore_sigint = 0;
   3148 	    }
   3149 	  else
   3150 	    maybe_clear_ignore_sigint (lp);
   3151 	}
   3152 
   3153       /* When using hardware single-step, we need to report every signal.
   3154 	 Otherwise, signals in pass_mask may be short-circuited
   3155 	 except signals that might be caused by a breakpoint.  */
   3156       if (!lp->step
   3157 	  && WSTOPSIG (status) && sigismember (&pass_mask, WSTOPSIG (status))
   3158 	  && !linux_wstatus_maybe_breakpoint (status))
   3159 	{
   3160 	  linux_resume_one_lwp (lp, lp->step, signo);
   3161 	  if (debug_linux_nat)
   3162 	    fprintf_unfiltered (gdb_stdlog,
   3163 				"LLW: %s %s, %s (preempt 'handle')\n",
   3164 				lp->step ?
   3165 				"PTRACE_SINGLESTEP" : "PTRACE_CONT",
   3166 				target_pid_to_str (lp->ptid),
   3167 				(signo != GDB_SIGNAL_0
   3168 				 ? strsignal (gdb_signal_to_host (signo))
   3169 				 : "0"));
   3170 	  return NULL;
   3171 	}
   3172     }
   3173 
   3174   /* An interesting event.  */
   3175   gdb_assert (lp);
   3176   lp->status = status;
   3177   save_stop_reason (lp);
   3178   return lp;
   3179 }
   3180 
   3181 /* Detect zombie thread group leaders, and "exit" them.  We can't reap
   3182    their exits until all other threads in the group have exited.  */
   3183 
   3184 static void
   3185 check_zombie_leaders (void)
   3186 {
   3187   for (inferior *inf : all_inferiors ())
   3188     {
   3189       struct lwp_info *leader_lp;
   3190 
   3191       if (inf->pid == 0)
   3192 	continue;
   3193 
   3194       leader_lp = find_lwp_pid (ptid_t (inf->pid));
   3195       if (leader_lp != NULL
   3196 	  /* Check if there are other threads in the group, as we may
   3197 	     have raced with the inferior simply exiting.  */
   3198 	  && num_lwps (inf->pid) > 1
   3199 	  && linux_proc_pid_is_zombie (inf->pid))
   3200 	{
   3201 	  if (debug_linux_nat)
   3202 	    fprintf_unfiltered (gdb_stdlog,
   3203 				"CZL: Thread group leader %d zombie "
   3204 				"(it exited, or another thread execd).\n",
   3205 				inf->pid);
   3206 
   3207 	  /* A leader zombie can mean one of two things:
   3208 
   3209 	     - It exited, and there's an exit status pending
   3210 	     available, or only the leader exited (not the whole
   3211 	     program).  In the latter case, we can't waitpid the
   3212 	     leader's exit status until all other threads are gone.
   3213 
   3214 	     - There are 3 or more threads in the group, and a thread
   3215 	     other than the leader exec'd.  See comments on exec
   3216 	     events at the top of the file.  We could try
   3217 	     distinguishing the exit and exec cases, by waiting once
   3218 	     more, and seeing if something comes out, but it doesn't
   3219 	     sound useful.  The previous leader _does_ go away, and
   3220 	     we'll re-add the new one once we see the exec event
   3221 	     (which is just the same as what would happen if the
   3222 	     previous leader did exit voluntarily before some other
   3223 	     thread execs).  */
   3224 
   3225 	  if (debug_linux_nat)
   3226 	    fprintf_unfiltered (gdb_stdlog,
   3227 				"CZL: Thread group leader %d vanished.\n",
   3228 				inf->pid);
   3229 	  exit_lwp (leader_lp);
   3230 	}
   3231     }
   3232 }
   3233 
   3234 /* Convenience function that is called when the kernel reports an exit
   3235    event.  This decides whether to report the event to GDB as a
   3236    process exit event, a thread exit event, or to suppress the
   3237    event.  */
   3238 
   3239 static ptid_t
   3240 filter_exit_event (struct lwp_info *event_child,
   3241 		   struct target_waitstatus *ourstatus)
   3242 {
   3243   ptid_t ptid = event_child->ptid;
   3244 
   3245   if (num_lwps (ptid.pid ()) > 1)
   3246     {
   3247       if (report_thread_events)
   3248 	ourstatus->kind = TARGET_WAITKIND_THREAD_EXITED;
   3249       else
   3250 	ourstatus->kind = TARGET_WAITKIND_IGNORE;
   3251 
   3252       exit_lwp (event_child);
   3253     }
   3254 
   3255   return ptid;
   3256 }
   3257 
   3258 static ptid_t
   3259 linux_nat_wait_1 (ptid_t ptid, struct target_waitstatus *ourstatus,
   3260 		  int target_options)
   3261 {
   3262   sigset_t prev_mask;
   3263   enum resume_kind last_resume_kind;
   3264   struct lwp_info *lp;
   3265   int status;
   3266 
   3267   if (debug_linux_nat)
   3268     fprintf_unfiltered (gdb_stdlog, "LLW: enter\n");
   3269 
   3270   /* The first time we get here after starting a new inferior, we may
   3271      not have added it to the LWP list yet - this is the earliest
   3272      moment at which we know its PID.  */
   3273   if (inferior_ptid.is_pid ())
   3274     {
   3275       /* Upgrade the main thread's ptid.  */
   3276       thread_change_ptid (inferior_ptid,
   3277 			  ptid_t (inferior_ptid.pid (),
   3278 				  inferior_ptid.pid (), 0));
   3279 
   3280       lp = add_initial_lwp (inferior_ptid);
   3281       lp->resumed = 1;
   3282     }
   3283 
   3284   /* Make sure SIGCHLD is blocked until the sigsuspend below.  */
   3285   block_child_signals (&prev_mask);
   3286 
   3287   /* First check if there is a LWP with a wait status pending.  */
   3288   lp = iterate_over_lwps (ptid, status_callback, NULL);
   3289   if (lp != NULL)
   3290     {
   3291       if (debug_linux_nat)
   3292 	fprintf_unfiltered (gdb_stdlog,
   3293 			    "LLW: Using pending wait status %s for %s.\n",
   3294 			    status_to_str (lp->status),
   3295 			    target_pid_to_str (lp->ptid));
   3296     }
   3297 
   3298   /* But if we don't find a pending event, we'll have to wait.  Always
   3299      pull all events out of the kernel.  We'll randomly select an
   3300      event LWP out of all that have events, to prevent starvation.  */
   3301 
   3302   while (lp == NULL)
   3303     {
   3304       pid_t lwpid;
   3305 
   3306       /* Always use -1 and WNOHANG, due to couple of a kernel/ptrace
   3307 	 quirks:
   3308 
   3309 	 - If the thread group leader exits while other threads in the
   3310 	   thread group still exist, waitpid(TGID, ...) hangs.  That
   3311 	   waitpid won't return an exit status until the other threads
   3312 	   in the group are reapped.
   3313 
   3314 	 - When a non-leader thread execs, that thread just vanishes
   3315 	   without reporting an exit (so we'd hang if we waited for it
   3316 	   explicitly in that case).  The exec event is reported to
   3317 	   the TGID pid.  */
   3318 
   3319       errno = 0;
   3320       lwpid = my_waitpid (-1, &status,  __WALL | WNOHANG);
   3321 
   3322       if (debug_linux_nat)
   3323 	fprintf_unfiltered (gdb_stdlog,
   3324 			    "LNW: waitpid(-1, ...) returned %d, %s\n",
   3325 			    lwpid, errno ? safe_strerror (errno) : "ERRNO-OK");
   3326 
   3327       if (lwpid > 0)
   3328 	{
   3329 	  if (debug_linux_nat)
   3330 	    {
   3331 	      fprintf_unfiltered (gdb_stdlog,
   3332 				  "LLW: waitpid %ld received %s\n",
   3333 				  (long) lwpid, status_to_str (status));
   3334 	    }
   3335 
   3336 	  linux_nat_filter_event (lwpid, status);
   3337 	  /* Retry until nothing comes out of waitpid.  A single
   3338 	     SIGCHLD can indicate more than one child stopped.  */
   3339 	  continue;
   3340 	}
   3341 
   3342       /* Now that we've pulled all events out of the kernel, resume
   3343 	 LWPs that don't have an interesting event to report.  */
   3344       iterate_over_lwps (minus_one_ptid,
   3345 			 resume_stopped_resumed_lwps, &minus_one_ptid);
   3346 
   3347       /* ... and find an LWP with a status to report to the core, if
   3348 	 any.  */
   3349       lp = iterate_over_lwps (ptid, status_callback, NULL);
   3350       if (lp != NULL)
   3351 	break;
   3352 
   3353       /* Check for zombie thread group leaders.  Those can't be reaped
   3354 	 until all other threads in the thread group are.  */
   3355       check_zombie_leaders ();
   3356 
   3357       /* If there are no resumed children left, bail.  We'd be stuck
   3358 	 forever in the sigsuspend call below otherwise.  */
   3359       if (iterate_over_lwps (ptid, resumed_callback, NULL) == NULL)
   3360 	{
   3361 	  if (debug_linux_nat)
   3362 	    fprintf_unfiltered (gdb_stdlog, "LLW: exit (no resumed LWP)\n");
   3363 
   3364 	  ourstatus->kind = TARGET_WAITKIND_NO_RESUMED;
   3365 
   3366 	  restore_child_signals_mask (&prev_mask);
   3367 	  return minus_one_ptid;
   3368 	}
   3369 
   3370       /* No interesting event to report to the core.  */
   3371 
   3372       if (target_options & TARGET_WNOHANG)
   3373 	{
   3374 	  if (debug_linux_nat)
   3375 	    fprintf_unfiltered (gdb_stdlog, "LLW: exit (ignore)\n");
   3376 
   3377 	  ourstatus->kind = TARGET_WAITKIND_IGNORE;
   3378 	  restore_child_signals_mask (&prev_mask);
   3379 	  return minus_one_ptid;
   3380 	}
   3381 
   3382       /* We shouldn't end up here unless we want to try again.  */
   3383       gdb_assert (lp == NULL);
   3384 
   3385       /* Block until we get an event reported with SIGCHLD.  */
   3386       wait_for_signal ();
   3387     }
   3388 
   3389   gdb_assert (lp);
   3390 
   3391   status = lp->status;
   3392   lp->status = 0;
   3393 
   3394   if (!target_is_non_stop_p ())
   3395     {
   3396       /* Now stop all other LWP's ...  */
   3397       iterate_over_lwps (minus_one_ptid, stop_callback, NULL);
   3398 
   3399       /* ... and wait until all of them have reported back that
   3400 	 they're no longer running.  */
   3401       iterate_over_lwps (minus_one_ptid, stop_wait_callback, NULL);
   3402     }
   3403 
   3404   /* If we're not waiting for a specific LWP, choose an event LWP from
   3405      among those that have had events.  Giving equal priority to all
   3406      LWPs that have had events helps prevent starvation.  */
   3407   if (ptid == minus_one_ptid || ptid.is_pid ())
   3408     select_event_lwp (ptid, &lp, &status);
   3409 
   3410   gdb_assert (lp != NULL);
   3411 
   3412   /* Now that we've selected our final event LWP, un-adjust its PC if
   3413      it was a software breakpoint, and we can't reliably support the
   3414      "stopped by software breakpoint" stop reason.  */
   3415   if (lp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
   3416       && !USE_SIGTRAP_SIGINFO)
   3417     {
   3418       struct regcache *regcache = get_thread_regcache (lp->ptid);
   3419       struct gdbarch *gdbarch = regcache->arch ();
   3420       int decr_pc = gdbarch_decr_pc_after_break (gdbarch);
   3421 
   3422       if (decr_pc != 0)
   3423 	{
   3424 	  CORE_ADDR pc;
   3425 
   3426 	  pc = regcache_read_pc (regcache);
   3427 	  regcache_write_pc (regcache, pc + decr_pc);
   3428 	}
   3429     }
   3430 
   3431   /* We'll need this to determine whether to report a SIGSTOP as
   3432      GDB_SIGNAL_0.  Need to take a copy because resume_clear_callback
   3433      clears it.  */
   3434   last_resume_kind = lp->last_resume_kind;
   3435 
   3436   if (!target_is_non_stop_p ())
   3437     {
   3438       /* In all-stop, from the core's perspective, all LWPs are now
   3439 	 stopped until a new resume action is sent over.  */
   3440       iterate_over_lwps (minus_one_ptid, resume_clear_callback, NULL);
   3441     }
   3442   else
   3443     {
   3444       resume_clear_callback (lp, NULL);
   3445     }
   3446 
   3447   if (linux_target->low_status_is_event (status))
   3448     {
   3449       if (debug_linux_nat)
   3450 	fprintf_unfiltered (gdb_stdlog,
   3451 			    "LLW: trap ptid is %s.\n",
   3452 			    target_pid_to_str (lp->ptid));
   3453     }
   3454 
   3455   if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
   3456     {
   3457       *ourstatus = lp->waitstatus;
   3458       lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
   3459     }
   3460   else
   3461     store_waitstatus (ourstatus, status);
   3462 
   3463   if (debug_linux_nat)
   3464     fprintf_unfiltered (gdb_stdlog, "LLW: exit\n");
   3465 
   3466   restore_child_signals_mask (&prev_mask);
   3467 
   3468   if (last_resume_kind == resume_stop
   3469       && ourstatus->kind == TARGET_WAITKIND_STOPPED
   3470       && WSTOPSIG (status) == SIGSTOP)
   3471     {
   3472       /* A thread that has been requested to stop by GDB with
   3473 	 target_stop, and it stopped cleanly, so report as SIG0.  The
   3474 	 use of SIGSTOP is an implementation detail.  */
   3475       ourstatus->value.sig = GDB_SIGNAL_0;
   3476     }
   3477 
   3478   if (ourstatus->kind == TARGET_WAITKIND_EXITED
   3479       || ourstatus->kind == TARGET_WAITKIND_SIGNALLED)
   3480     lp->core = -1;
   3481   else
   3482     lp->core = linux_common_core_of_thread (lp->ptid);
   3483 
   3484   if (ourstatus->kind == TARGET_WAITKIND_EXITED)
   3485     return filter_exit_event (lp, ourstatus);
   3486 
   3487   return lp->ptid;
   3488 }
   3489 
   3490 /* Resume LWPs that are currently stopped without any pending status
   3491    to report, but are resumed from the core's perspective.  */
   3492 
   3493 static int
   3494 resume_stopped_resumed_lwps (struct lwp_info *lp, void *data)
   3495 {
   3496   ptid_t *wait_ptid_p = (ptid_t *) data;
   3497 
   3498   if (!lp->stopped)
   3499     {
   3500       if (debug_linux_nat)
   3501 	fprintf_unfiltered (gdb_stdlog,
   3502 			    "RSRL: NOT resuming LWP %s, not stopped\n",
   3503 			    target_pid_to_str (lp->ptid));
   3504     }
   3505   else if (!lp->resumed)
   3506     {
   3507       if (debug_linux_nat)
   3508 	fprintf_unfiltered (gdb_stdlog,
   3509 			    "RSRL: NOT resuming LWP %s, not resumed\n",
   3510 			    target_pid_to_str (lp->ptid));
   3511     }
   3512   else if (lwp_status_pending_p (lp))
   3513     {
   3514       if (debug_linux_nat)
   3515 	fprintf_unfiltered (gdb_stdlog,
   3516 			    "RSRL: NOT resuming LWP %s, has pending status\n",
   3517 			    target_pid_to_str (lp->ptid));
   3518     }
   3519   else
   3520     {
   3521       struct regcache *regcache = get_thread_regcache (lp->ptid);
   3522       struct gdbarch *gdbarch = regcache->arch ();
   3523 
   3524       TRY
   3525 	{
   3526 	  CORE_ADDR pc = regcache_read_pc (regcache);
   3527 	  int leave_stopped = 0;
   3528 
   3529 	  /* Don't bother if there's a breakpoint at PC that we'd hit
   3530 	     immediately, and we're not waiting for this LWP.  */
   3531 	  if (!lp->ptid.matches (*wait_ptid_p))
   3532 	    {
   3533 	      if (breakpoint_inserted_here_p (regcache->aspace (), pc))
   3534 		leave_stopped = 1;
   3535 	    }
   3536 
   3537 	  if (!leave_stopped)
   3538 	    {
   3539 	      if (debug_linux_nat)
   3540 		fprintf_unfiltered (gdb_stdlog,
   3541 				    "RSRL: resuming stopped-resumed LWP %s at "
   3542 				    "%s: step=%d\n",
   3543 				    target_pid_to_str (lp->ptid),
   3544 				    paddress (gdbarch, pc),
   3545 				    lp->step);
   3546 
   3547 	      linux_resume_one_lwp_throw (lp, lp->step, GDB_SIGNAL_0);
   3548 	    }
   3549 	}
   3550       CATCH (ex, RETURN_MASK_ERROR)
   3551 	{
   3552 	  if (!check_ptrace_stopped_lwp_gone (lp))
   3553 	    throw_exception (ex);
   3554 	}
   3555       END_CATCH
   3556     }
   3557 
   3558   return 0;
   3559 }
   3560 
   3561 ptid_t
   3562 linux_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
   3563 			int target_options)
   3564 {
   3565   ptid_t event_ptid;
   3566 
   3567   if (debug_linux_nat)
   3568     {
   3569       std::string options_string = target_options_to_string (target_options);
   3570       fprintf_unfiltered (gdb_stdlog,
   3571 			  "linux_nat_wait: [%s], [%s]\n",
   3572 			  target_pid_to_str (ptid),
   3573 			  options_string.c_str ());
   3574     }
   3575 
   3576   /* Flush the async file first.  */
   3577   if (target_is_async_p ())
   3578     async_file_flush ();
   3579 
   3580   /* Resume LWPs that are currently stopped without any pending status
   3581      to report, but are resumed from the core's perspective.  LWPs get
   3582      in this state if we find them stopping at a time we're not
   3583      interested in reporting the event (target_wait on a
   3584      specific_process, for example, see linux_nat_wait_1), and
   3585      meanwhile the event became uninteresting.  Don't bother resuming
   3586      LWPs we're not going to wait for if they'd stop immediately.  */
   3587   if (target_is_non_stop_p ())
   3588     iterate_over_lwps (minus_one_ptid, resume_stopped_resumed_lwps, &ptid);
   3589 
   3590   event_ptid = linux_nat_wait_1 (ptid, ourstatus, target_options);
   3591 
   3592   /* If we requested any event, and something came out, assume there
   3593      may be more.  If we requested a specific lwp or process, also
   3594      assume there may be more.  */
   3595   if (target_is_async_p ()
   3596       && ((ourstatus->kind != TARGET_WAITKIND_IGNORE
   3597 	   && ourstatus->kind != TARGET_WAITKIND_NO_RESUMED)
   3598 	  || ptid != minus_one_ptid))
   3599     async_file_mark ();
   3600 
   3601   return event_ptid;
   3602 }
   3603 
   3604 /* Kill one LWP.  */
   3605 
   3606 static void
   3607 kill_one_lwp (pid_t pid)
   3608 {
   3609   /* PTRACE_KILL may resume the inferior.  Send SIGKILL first.  */
   3610 
   3611   errno = 0;
   3612   kill_lwp (pid, SIGKILL);
   3613   if (debug_linux_nat)
   3614     {
   3615       int save_errno = errno;
   3616 
   3617       fprintf_unfiltered (gdb_stdlog,
   3618 			  "KC:  kill (SIGKILL) %ld, 0, 0 (%s)\n", (long) pid,
   3619 			  save_errno ? safe_strerror (save_errno) : "OK");
   3620     }
   3621 
   3622   /* Some kernels ignore even SIGKILL for processes under ptrace.  */
   3623 
   3624   errno = 0;
   3625   ptrace (PTRACE_KILL, pid, 0, 0);
   3626   if (debug_linux_nat)
   3627     {
   3628       int save_errno = errno;
   3629 
   3630       fprintf_unfiltered (gdb_stdlog,
   3631 			  "KC:  PTRACE_KILL %ld, 0, 0 (%s)\n", (long) pid,
   3632 			  save_errno ? safe_strerror (save_errno) : "OK");
   3633     }
   3634 }
   3635 
   3636 /* Wait for an LWP to die.  */
   3637 
   3638 static void
   3639 kill_wait_one_lwp (pid_t pid)
   3640 {
   3641   pid_t res;
   3642 
   3643   /* We must make sure that there are no pending events (delayed
   3644      SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
   3645      program doesn't interfere with any following debugging session.  */
   3646 
   3647   do
   3648     {
   3649       res = my_waitpid (pid, NULL, __WALL);
   3650       if (res != (pid_t) -1)
   3651 	{
   3652 	  if (debug_linux_nat)
   3653 	    fprintf_unfiltered (gdb_stdlog,
   3654 				"KWC: wait %ld received unknown.\n",
   3655 				(long) pid);
   3656 	  /* The Linux kernel sometimes fails to kill a thread
   3657 	     completely after PTRACE_KILL; that goes from the stop
   3658 	     point in do_fork out to the one in get_signal_to_deliver
   3659 	     and waits again.  So kill it again.  */
   3660 	  kill_one_lwp (pid);
   3661 	}
   3662     }
   3663   while (res == pid);
   3664 
   3665   gdb_assert (res == -1 && errno == ECHILD);
   3666 }
   3667 
   3668 /* Callback for iterate_over_lwps.  */
   3669 
   3670 static int
   3671 kill_callback (struct lwp_info *lp, void *data)
   3672 {
   3673   kill_one_lwp (lp->ptid.lwp ());
   3674   return 0;
   3675 }
   3676 
   3677 /* Callback for iterate_over_lwps.  */
   3678 
   3679 static int
   3680 kill_wait_callback (struct lwp_info *lp, void *data)
   3681 {
   3682   kill_wait_one_lwp (lp->ptid.lwp ());
   3683   return 0;
   3684 }
   3685 
   3686 /* Kill the fork children of any threads of inferior INF that are
   3687    stopped at a fork event.  */
   3688 
   3689 static void
   3690 kill_unfollowed_fork_children (struct inferior *inf)
   3691 {
   3692   for (thread_info *thread : inf->non_exited_threads ())
   3693     {
   3694       struct target_waitstatus *ws = &thread->pending_follow;
   3695 
   3696       if (ws->kind == TARGET_WAITKIND_FORKED
   3697 	  || ws->kind == TARGET_WAITKIND_VFORKED)
   3698 	{
   3699 	  ptid_t child_ptid = ws->value.related_pid;
   3700 	  int child_pid = child_ptid.pid ();
   3701 	  int child_lwp = child_ptid.lwp ();
   3702 
   3703 	  kill_one_lwp (child_lwp);
   3704 	  kill_wait_one_lwp (child_lwp);
   3705 
   3706 	  /* Let the arch-specific native code know this process is
   3707 	     gone.  */
   3708 	  linux_target->low_forget_process (child_pid);
   3709 	}
   3710     }
   3711 }
   3712 
   3713 void
   3714 linux_nat_target::kill ()
   3715 {
   3716   /* If we're stopped while forking and we haven't followed yet,
   3717      kill the other task.  We need to do this first because the
   3718      parent will be sleeping if this is a vfork.  */
   3719   kill_unfollowed_fork_children (current_inferior ());
   3720 
   3721   if (forks_exist_p ())
   3722     linux_fork_killall ();
   3723   else
   3724     {
   3725       ptid_t ptid = ptid_t (inferior_ptid.pid ());
   3726 
   3727       /* Stop all threads before killing them, since ptrace requires
   3728 	 that the thread is stopped to sucessfully PTRACE_KILL.  */
   3729       iterate_over_lwps (ptid, stop_callback, NULL);
   3730       /* ... and wait until all of them have reported back that
   3731 	 they're no longer running.  */
   3732       iterate_over_lwps (ptid, stop_wait_callback, NULL);
   3733 
   3734       /* Kill all LWP's ...  */
   3735       iterate_over_lwps (ptid, kill_callback, NULL);
   3736 
   3737       /* ... and wait until we've flushed all events.  */
   3738       iterate_over_lwps (ptid, kill_wait_callback, NULL);
   3739     }
   3740 
   3741   target_mourn_inferior (inferior_ptid);
   3742 }
   3743 
   3744 void
   3745 linux_nat_target::mourn_inferior ()
   3746 {
   3747   int pid = inferior_ptid.pid ();
   3748 
   3749   purge_lwp_list (pid);
   3750 
   3751   if (! forks_exist_p ())
   3752     /* Normal case, no other forks available.  */
   3753     inf_ptrace_target::mourn_inferior ();
   3754   else
   3755     /* Multi-fork case.  The current inferior_ptid has exited, but
   3756        there are other viable forks to debug.  Delete the exiting
   3757        one and context-switch to the first available.  */
   3758     linux_fork_mourn_inferior ();
   3759 
   3760   /* Let the arch-specific native code know this process is gone.  */
   3761   linux_target->low_forget_process (pid);
   3762 }
   3763 
   3764 /* Convert a native/host siginfo object, into/from the siginfo in the
   3765    layout of the inferiors' architecture.  */
   3766 
   3767 static void
   3768 siginfo_fixup (siginfo_t *siginfo, gdb_byte *inf_siginfo, int direction)
   3769 {
   3770   /* If the low target didn't do anything, then just do a straight
   3771      memcpy.  */
   3772   if (!linux_target->low_siginfo_fixup (siginfo, inf_siginfo, direction))
   3773     {
   3774       if (direction == 1)
   3775 	memcpy (siginfo, inf_siginfo, sizeof (siginfo_t));
   3776       else
   3777 	memcpy (inf_siginfo, siginfo, sizeof (siginfo_t));
   3778     }
   3779 }
   3780 
   3781 static enum target_xfer_status
   3782 linux_xfer_siginfo (enum target_object object,
   3783                     const char *annex, gdb_byte *readbuf,
   3784 		    const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
   3785 		    ULONGEST *xfered_len)
   3786 {
   3787   int pid;
   3788   siginfo_t siginfo;
   3789   gdb_byte inf_siginfo[sizeof (siginfo_t)];
   3790 
   3791   gdb_assert (object == TARGET_OBJECT_SIGNAL_INFO);
   3792   gdb_assert (readbuf || writebuf);
   3793 
   3794   pid = inferior_ptid.lwp ();
   3795   if (pid == 0)
   3796     pid = inferior_ptid.pid ();
   3797 
   3798   if (offset > sizeof (siginfo))
   3799     return TARGET_XFER_E_IO;
   3800 
   3801   errno = 0;
   3802   ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
   3803   if (errno != 0)
   3804     return TARGET_XFER_E_IO;
   3805 
   3806   /* When GDB is built as a 64-bit application, ptrace writes into
   3807      SIGINFO an object with 64-bit layout.  Since debugging a 32-bit
   3808      inferior with a 64-bit GDB should look the same as debugging it
   3809      with a 32-bit GDB, we need to convert it.  GDB core always sees
   3810      the converted layout, so any read/write will have to be done
   3811      post-conversion.  */
   3812   siginfo_fixup (&siginfo, inf_siginfo, 0);
   3813 
   3814   if (offset + len > sizeof (siginfo))
   3815     len = sizeof (siginfo) - offset;
   3816 
   3817   if (readbuf != NULL)
   3818     memcpy (readbuf, inf_siginfo + offset, len);
   3819   else
   3820     {
   3821       memcpy (inf_siginfo + offset, writebuf, len);
   3822 
   3823       /* Convert back to ptrace layout before flushing it out.  */
   3824       siginfo_fixup (&siginfo, inf_siginfo, 1);
   3825 
   3826       errno = 0;
   3827       ptrace (PTRACE_SETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
   3828       if (errno != 0)
   3829 	return TARGET_XFER_E_IO;
   3830     }
   3831 
   3832   *xfered_len = len;
   3833   return TARGET_XFER_OK;
   3834 }
   3835 
   3836 static enum target_xfer_status
   3837 linux_nat_xfer_osdata (enum target_object object,
   3838 		       const char *annex, gdb_byte *readbuf,
   3839 		       const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
   3840 		       ULONGEST *xfered_len);
   3841 
   3842 static enum target_xfer_status
   3843 linux_proc_xfer_spu (enum target_object object,
   3844 		     const char *annex, gdb_byte *readbuf,
   3845 		     const gdb_byte *writebuf,
   3846 		     ULONGEST offset, ULONGEST len, ULONGEST *xfered_len);
   3847 
   3848 static enum target_xfer_status
   3849 linux_proc_xfer_partial (enum target_object object,
   3850 			 const char *annex, gdb_byte *readbuf,
   3851 			 const gdb_byte *writebuf,
   3852 			 ULONGEST offset, LONGEST len, ULONGEST *xfered_len);
   3853 
   3854 enum target_xfer_status
   3855 linux_nat_target::xfer_partial (enum target_object object,
   3856 				const char *annex, gdb_byte *readbuf,
   3857 				const gdb_byte *writebuf,
   3858 				ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
   3859 {
   3860   enum target_xfer_status xfer;
   3861 
   3862   if (object == TARGET_OBJECT_SIGNAL_INFO)
   3863     return linux_xfer_siginfo (object, annex, readbuf, writebuf,
   3864 			       offset, len, xfered_len);
   3865 
   3866   /* The target is connected but no live inferior is selected.  Pass
   3867      this request down to a lower stratum (e.g., the executable
   3868      file).  */
   3869   if (object == TARGET_OBJECT_MEMORY && inferior_ptid == null_ptid)
   3870     return TARGET_XFER_EOF;
   3871 
   3872   if (object == TARGET_OBJECT_AUXV)
   3873     return memory_xfer_auxv (this, object, annex, readbuf, writebuf,
   3874 			     offset, len, xfered_len);
   3875 
   3876   if (object == TARGET_OBJECT_OSDATA)
   3877     return linux_nat_xfer_osdata (object, annex, readbuf, writebuf,
   3878 				  offset, len, xfered_len);
   3879 
   3880   if (object == TARGET_OBJECT_SPU)
   3881     return linux_proc_xfer_spu (object, annex, readbuf, writebuf,
   3882 				offset, len, xfered_len);
   3883 
   3884   /* GDB calculates all addresses in the largest possible address
   3885      width.
   3886      The address width must be masked before its final use - either by
   3887      linux_proc_xfer_partial or inf_ptrace_target::xfer_partial.
   3888 
   3889      Compare ADDR_BIT first to avoid a compiler warning on shift overflow.  */
   3890 
   3891   if (object == TARGET_OBJECT_MEMORY)
   3892     {
   3893       int addr_bit = gdbarch_addr_bit (target_gdbarch ());
   3894 
   3895       if (addr_bit < (sizeof (ULONGEST) * HOST_CHAR_BIT))
   3896 	offset &= ((ULONGEST) 1 << addr_bit) - 1;
   3897     }
   3898 
   3899   xfer = linux_proc_xfer_partial (object, annex, readbuf, writebuf,
   3900 				  offset, len, xfered_len);
   3901   if (xfer != TARGET_XFER_EOF)
   3902     return xfer;
   3903 
   3904   return inf_ptrace_target::xfer_partial (object, annex, readbuf, writebuf,
   3905 					  offset, len, xfered_len);
   3906 }
   3907 
   3908 bool
   3909 linux_nat_target::thread_alive (ptid_t ptid)
   3910 {
   3911   /* As long as a PTID is in lwp list, consider it alive.  */
   3912   return find_lwp_pid (ptid) != NULL;
   3913 }
   3914 
   3915 /* Implement the to_update_thread_list target method for this
   3916    target.  */
   3917 
   3918 void
   3919 linux_nat_target::update_thread_list ()
   3920 {
   3921   struct lwp_info *lwp;
   3922 
   3923   /* We add/delete threads from the list as clone/exit events are
   3924      processed, so just try deleting exited threads still in the
   3925      thread list.  */
   3926   delete_exited_threads ();
   3927 
   3928   /* Update the processor core that each lwp/thread was last seen
   3929      running on.  */
   3930   ALL_LWPS (lwp)
   3931     {
   3932       /* Avoid accessing /proc if the thread hasn't run since we last
   3933 	 time we fetched the thread's core.  Accessing /proc becomes
   3934 	 noticeably expensive when we have thousands of LWPs.  */
   3935       if (lwp->core == -1)
   3936 	lwp->core = linux_common_core_of_thread (lwp->ptid);
   3937     }
   3938 }
   3939 
   3940 const char *
   3941 linux_nat_target::pid_to_str (ptid_t ptid)
   3942 {
   3943   static char buf[64];
   3944 
   3945   if (ptid.lwp_p ()
   3946       && (ptid.pid () != ptid.lwp ()
   3947 	  || num_lwps (ptid.pid ()) > 1))
   3948     {
   3949       snprintf (buf, sizeof (buf), "LWP %ld", ptid.lwp ());
   3950       return buf;
   3951     }
   3952 
   3953   return normal_pid_to_str (ptid);
   3954 }
   3955 
   3956 const char *
   3957 linux_nat_target::thread_name (struct thread_info *thr)
   3958 {
   3959   return linux_proc_tid_get_name (thr->ptid);
   3960 }
   3961 
   3962 /* Accepts an integer PID; Returns a string representing a file that
   3963    can be opened to get the symbols for the child process.  */
   3964 
   3965 char *
   3966 linux_nat_target::pid_to_exec_file (int pid)
   3967 {
   3968   return linux_proc_pid_to_exec_file (pid);
   3969 }
   3970 
   3971 /* Implement the to_xfer_partial target method using /proc/<pid>/mem.
   3972    Because we can use a single read/write call, this can be much more
   3973    efficient than banging away at PTRACE_PEEKTEXT.  */
   3974 
   3975 static enum target_xfer_status
   3976 linux_proc_xfer_partial (enum target_object object,
   3977 			 const char *annex, gdb_byte *readbuf,
   3978 			 const gdb_byte *writebuf,
   3979 			 ULONGEST offset, LONGEST len, ULONGEST *xfered_len)
   3980 {
   3981   LONGEST ret;
   3982   int fd;
   3983   char filename[64];
   3984 
   3985   if (object != TARGET_OBJECT_MEMORY)
   3986     return TARGET_XFER_EOF;
   3987 
   3988   /* Don't bother for one word.  */
   3989   if (len < 3 * sizeof (long))
   3990     return TARGET_XFER_EOF;
   3991 
   3992   /* We could keep this file open and cache it - possibly one per
   3993      thread.  That requires some juggling, but is even faster.  */
   3994   xsnprintf (filename, sizeof filename, "/proc/%ld/mem",
   3995 	     inferior_ptid.lwp ());
   3996   fd = gdb_open_cloexec (filename, ((readbuf ? O_RDONLY : O_WRONLY)
   3997 				    | O_LARGEFILE), 0);
   3998   if (fd == -1)
   3999     return TARGET_XFER_EOF;
   4000 
   4001   /* Use pread64/pwrite64 if available, since they save a syscall and can
   4002      handle 64-bit offsets even on 32-bit platforms (for instance, SPARC
   4003      debugging a SPARC64 application).  */
   4004 #ifdef HAVE_PREAD64
   4005   ret = (readbuf ? pread64 (fd, readbuf, len, offset)
   4006 	 : pwrite64 (fd, writebuf, len, offset));
   4007 #else
   4008   ret = lseek (fd, offset, SEEK_SET);
   4009   if (ret != -1)
   4010     ret = (readbuf ? read (fd, readbuf, len)
   4011 	   : write (fd, writebuf, len));
   4012 #endif
   4013 
   4014   close (fd);
   4015 
   4016   if (ret == -1 || ret == 0)
   4017     return TARGET_XFER_EOF;
   4018   else
   4019     {
   4020       *xfered_len = ret;
   4021       return TARGET_XFER_OK;
   4022     }
   4023 }
   4024 
   4025 
   4026 /* Enumerate spufs IDs for process PID.  */
   4027 static LONGEST
   4028 spu_enumerate_spu_ids (int pid, gdb_byte *buf, ULONGEST offset, ULONGEST len)
   4029 {
   4030   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
   4031   LONGEST pos = 0;
   4032   LONGEST written = 0;
   4033   char path[128];
   4034   DIR *dir;
   4035   struct dirent *entry;
   4036 
   4037   xsnprintf (path, sizeof path, "/proc/%d/fd", pid);
   4038   dir = opendir (path);
   4039   if (!dir)
   4040     return -1;
   4041 
   4042   rewinddir (dir);
   4043   while ((entry = readdir (dir)) != NULL)
   4044     {
   4045       struct stat st;
   4046       struct statfs stfs;
   4047       int fd;
   4048 
   4049       fd = atoi (entry->d_name);
   4050       if (!fd)
   4051 	continue;
   4052 
   4053       xsnprintf (path, sizeof path, "/proc/%d/fd/%d", pid, fd);
   4054       if (stat (path, &st) != 0)
   4055 	continue;
   4056       if (!S_ISDIR (st.st_mode))
   4057 	continue;
   4058 
   4059       if (statfs (path, &stfs) != 0)
   4060 	continue;
   4061       if (stfs.f_type != SPUFS_MAGIC)
   4062 	continue;
   4063 
   4064       if (pos >= offset && pos + 4 <= offset + len)
   4065 	{
   4066 	  store_unsigned_integer (buf + pos - offset, 4, byte_order, fd);
   4067 	  written += 4;
   4068 	}
   4069       pos += 4;
   4070     }
   4071 
   4072   closedir (dir);
   4073   return written;
   4074 }
   4075 
   4076 /* Implement the to_xfer_partial interface for the TARGET_OBJECT_SPU
   4077    object type, using the /proc file system.  */
   4078 
   4079 static enum target_xfer_status
   4080 linux_proc_xfer_spu (enum target_object object,
   4081 		     const char *annex, gdb_byte *readbuf,
   4082 		     const gdb_byte *writebuf,
   4083 		     ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
   4084 {
   4085   char buf[128];
   4086   int fd = 0;
   4087   int ret = -1;
   4088   int pid = inferior_ptid.lwp ();
   4089 
   4090   if (!annex)
   4091     {
   4092       if (!readbuf)
   4093 	return TARGET_XFER_E_IO;
   4094       else
   4095 	{
   4096 	  LONGEST l = spu_enumerate_spu_ids (pid, readbuf, offset, len);
   4097 
   4098 	  if (l < 0)
   4099 	    return TARGET_XFER_E_IO;
   4100 	  else if (l == 0)
   4101 	    return TARGET_XFER_EOF;
   4102 	  else
   4103 	    {
   4104 	      *xfered_len = (ULONGEST) l;
   4105 	      return TARGET_XFER_OK;
   4106 	    }
   4107 	}
   4108     }
   4109 
   4110   xsnprintf (buf, sizeof buf, "/proc/%d/fd/%s", pid, annex);
   4111   fd = gdb_open_cloexec (buf, writebuf? O_WRONLY : O_RDONLY, 0);
   4112   if (fd <= 0)
   4113     return TARGET_XFER_E_IO;
   4114 
   4115   if (offset != 0
   4116       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
   4117     {
   4118       close (fd);
   4119       return TARGET_XFER_EOF;
   4120     }
   4121 
   4122   if (writebuf)
   4123     ret = write (fd, writebuf, (size_t) len);
   4124   else if (readbuf)
   4125     ret = read (fd, readbuf, (size_t) len);
   4126 
   4127   close (fd);
   4128 
   4129   if (ret < 0)
   4130     return TARGET_XFER_E_IO;
   4131   else if (ret == 0)
   4132     return TARGET_XFER_EOF;
   4133   else
   4134     {
   4135       *xfered_len = (ULONGEST) ret;
   4136       return TARGET_XFER_OK;
   4137     }
   4138 }
   4139 
   4140 
   4141 /* Parse LINE as a signal set and add its set bits to SIGS.  */
   4142 
   4143 static void
   4144 add_line_to_sigset (const char *line, sigset_t *sigs)
   4145 {
   4146   int len = strlen (line) - 1;
   4147   const char *p;
   4148   int signum;
   4149 
   4150   if (line[len] != '\n')
   4151     error (_("Could not parse signal set: %s"), line);
   4152 
   4153   p = line;
   4154   signum = len * 4;
   4155   while (len-- > 0)
   4156     {
   4157       int digit;
   4158 
   4159       if (*p >= '0' && *p <= '9')
   4160 	digit = *p - '0';
   4161       else if (*p >= 'a' && *p <= 'f')
   4162 	digit = *p - 'a' + 10;
   4163       else
   4164 	error (_("Could not parse signal set: %s"), line);
   4165 
   4166       signum -= 4;
   4167 
   4168       if (digit & 1)
   4169 	sigaddset (sigs, signum + 1);
   4170       if (digit & 2)
   4171 	sigaddset (sigs, signum + 2);
   4172       if (digit & 4)
   4173 	sigaddset (sigs, signum + 3);
   4174       if (digit & 8)
   4175 	sigaddset (sigs, signum + 4);
   4176 
   4177       p++;
   4178     }
   4179 }
   4180 
   4181 /* Find process PID's pending signals from /proc/pid/status and set
   4182    SIGS to match.  */
   4183 
   4184 void
   4185 linux_proc_pending_signals (int pid, sigset_t *pending,
   4186 			    sigset_t *blocked, sigset_t *ignored)
   4187 {
   4188   char buffer[PATH_MAX], fname[PATH_MAX];
   4189 
   4190   sigemptyset (pending);
   4191   sigemptyset (blocked);
   4192   sigemptyset (ignored);
   4193   xsnprintf (fname, sizeof fname, "/proc/%d/status", pid);
   4194   gdb_file_up procfile = gdb_fopen_cloexec (fname, "r");
   4195   if (procfile == NULL)
   4196     error (_("Could not open %s"), fname);
   4197 
   4198   while (fgets (buffer, PATH_MAX, procfile.get ()) != NULL)
   4199     {
   4200       /* Normal queued signals are on the SigPnd line in the status
   4201 	 file.  However, 2.6 kernels also have a "shared" pending
   4202 	 queue for delivering signals to a thread group, so check for
   4203 	 a ShdPnd line also.
   4204 
   4205 	 Unfortunately some Red Hat kernels include the shared pending
   4206 	 queue but not the ShdPnd status field.  */
   4207 
   4208       if (startswith (buffer, "SigPnd:\t"))
   4209 	add_line_to_sigset (buffer + 8, pending);
   4210       else if (startswith (buffer, "ShdPnd:\t"))
   4211 	add_line_to_sigset (buffer + 8, pending);
   4212       else if (startswith (buffer, "SigBlk:\t"))
   4213 	add_line_to_sigset (buffer + 8, blocked);
   4214       else if (startswith (buffer, "SigIgn:\t"))
   4215 	add_line_to_sigset (buffer + 8, ignored);
   4216     }
   4217 }
   4218 
   4219 static enum target_xfer_status
   4220 linux_nat_xfer_osdata (enum target_object object,
   4221 		       const char *annex, gdb_byte *readbuf,
   4222 		       const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
   4223 		       ULONGEST *xfered_len)
   4224 {
   4225   gdb_assert (object == TARGET_OBJECT_OSDATA);
   4226 
   4227   *xfered_len = linux_common_xfer_osdata (annex, readbuf, offset, len);
   4228   if (*xfered_len == 0)
   4229     return TARGET_XFER_EOF;
   4230   else
   4231     return TARGET_XFER_OK;
   4232 }
   4233 
   4234 std::vector<static_tracepoint_marker>
   4235 linux_nat_target::static_tracepoint_markers_by_strid (const char *strid)
   4236 {
   4237   char s[IPA_CMD_BUF_SIZE];
   4238   int pid = inferior_ptid.pid ();
   4239   std::vector<static_tracepoint_marker> markers;
   4240   const char *p = s;
   4241   ptid_t ptid = ptid_t (pid, 0, 0);
   4242   static_tracepoint_marker marker;
   4243 
   4244   /* Pause all */
   4245   target_stop (ptid);
   4246 
   4247   memcpy (s, "qTfSTM", sizeof ("qTfSTM"));
   4248   s[sizeof ("qTfSTM")] = 0;
   4249 
   4250   agent_run_command (pid, s, strlen (s) + 1);
   4251 
   4252   /* Unpause all.  */
   4253   SCOPE_EXIT { target_continue_no_signal (ptid); };
   4254 
   4255   while (*p++ == 'm')
   4256     {
   4257       do
   4258 	{
   4259 	  parse_static_tracepoint_marker_definition (p, &p, &marker);
   4260 
   4261 	  if (strid == NULL || marker.str_id == strid)
   4262 	    markers.push_back (std::move (marker));
   4263 	}
   4264       while (*p++ == ',');	/* comma-separated list */
   4265 
   4266       memcpy (s, "qTsSTM", sizeof ("qTsSTM"));
   4267       s[sizeof ("qTsSTM")] = 0;
   4268       agent_run_command (pid, s, strlen (s) + 1);
   4269       p = s;
   4270     }
   4271 
   4272   return markers;
   4273 }
   4274 
   4275 /* target_is_async_p implementation.  */
   4276 
   4277 bool
   4278 linux_nat_target::is_async_p ()
   4279 {
   4280   return linux_is_async_p ();
   4281 }
   4282 
   4283 /* target_can_async_p implementation.  */
   4284 
   4285 bool
   4286 linux_nat_target::can_async_p ()
   4287 {
   4288   /* We're always async, unless the user explicitly prevented it with the
   4289      "maint set target-async" command.  */
   4290   return target_async_permitted;
   4291 }
   4292 
   4293 bool
   4294 linux_nat_target::supports_non_stop ()
   4295 {
   4296   return 1;
   4297 }
   4298 
   4299 /* to_always_non_stop_p implementation.  */
   4300 
   4301 bool
   4302 linux_nat_target::always_non_stop_p ()
   4303 {
   4304   return 1;
   4305 }
   4306 
   4307 /* True if we want to support multi-process.  To be removed when GDB
   4308    supports multi-exec.  */
   4309 
   4310 int linux_multi_process = 1;
   4311 
   4312 bool
   4313 linux_nat_target::supports_multi_process ()
   4314 {
   4315   return linux_multi_process;
   4316 }
   4317 
   4318 bool
   4319 linux_nat_target::supports_disable_randomization ()
   4320 {
   4321 #ifdef HAVE_PERSONALITY
   4322   return 1;
   4323 #else
   4324   return 0;
   4325 #endif
   4326 }
   4327 
   4328 /* SIGCHLD handler that serves two purposes: In non-stop/async mode,
   4329    so we notice when any child changes state, and notify the
   4330    event-loop; it allows us to use sigsuspend in linux_nat_wait_1
   4331    above to wait for the arrival of a SIGCHLD.  */
   4332 
   4333 static void
   4334 sigchld_handler (int signo)
   4335 {
   4336   int old_errno = errno;
   4337 
   4338   if (debug_linux_nat)
   4339     ui_file_write_async_safe (gdb_stdlog,
   4340 			      "sigchld\n", sizeof ("sigchld\n") - 1);
   4341 
   4342   if (signo == SIGCHLD
   4343       && linux_nat_event_pipe[0] != -1)
   4344     async_file_mark (); /* Let the event loop know that there are
   4345 			   events to handle.  */
   4346 
   4347   errno = old_errno;
   4348 }
   4349 
   4350 /* Callback registered with the target events file descriptor.  */
   4351 
   4352 static void
   4353 handle_target_event (int error, gdb_client_data client_data)
   4354 {
   4355   inferior_event_handler (INF_REG_EVENT, NULL);
   4356 }
   4357 
   4358 /* Create/destroy the target events pipe.  Returns previous state.  */
   4359 
   4360 static int
   4361 linux_async_pipe (int enable)
   4362 {
   4363   int previous = linux_is_async_p ();
   4364 
   4365   if (previous != enable)
   4366     {
   4367       sigset_t prev_mask;
   4368 
   4369       /* Block child signals while we create/destroy the pipe, as
   4370 	 their handler writes to it.  */
   4371       block_child_signals (&prev_mask);
   4372 
   4373       if (enable)
   4374 	{
   4375 	  if (gdb_pipe_cloexec (linux_nat_event_pipe) == -1)
   4376 	    internal_error (__FILE__, __LINE__,
   4377 			    "creating event pipe failed.");
   4378 
   4379 	  fcntl (linux_nat_event_pipe[0], F_SETFL, O_NONBLOCK);
   4380 	  fcntl (linux_nat_event_pipe[1], F_SETFL, O_NONBLOCK);
   4381 	}
   4382       else
   4383 	{
   4384 	  close (linux_nat_event_pipe[0]);
   4385 	  close (linux_nat_event_pipe[1]);
   4386 	  linux_nat_event_pipe[0] = -1;
   4387 	  linux_nat_event_pipe[1] = -1;
   4388 	}
   4389 
   4390       restore_child_signals_mask (&prev_mask);
   4391     }
   4392 
   4393   return previous;
   4394 }
   4395 
   4396 /* target_async implementation.  */
   4397 
   4398 void
   4399 linux_nat_target::async (int enable)
   4400 {
   4401   if (enable)
   4402     {
   4403       if (!linux_async_pipe (1))
   4404 	{
   4405 	  add_file_handler (linux_nat_event_pipe[0],
   4406 			    handle_target_event, NULL);
   4407 	  /* There may be pending events to handle.  Tell the event loop
   4408 	     to poll them.  */
   4409 	  async_file_mark ();
   4410 	}
   4411     }
   4412   else
   4413     {
   4414       delete_file_handler (linux_nat_event_pipe[0]);
   4415       linux_async_pipe (0);
   4416     }
   4417   return;
   4418 }
   4419 
   4420 /* Stop an LWP, and push a GDB_SIGNAL_0 stop status if no other
   4421    event came out.  */
   4422 
   4423 static int
   4424 linux_nat_stop_lwp (struct lwp_info *lwp, void *data)
   4425 {
   4426   if (!lwp->stopped)
   4427     {
   4428       if (debug_linux_nat)
   4429 	fprintf_unfiltered (gdb_stdlog,
   4430 			    "LNSL: running -> suspending %s\n",
   4431 			    target_pid_to_str (lwp->ptid));
   4432 
   4433 
   4434       if (lwp->last_resume_kind == resume_stop)
   4435 	{
   4436 	  if (debug_linux_nat)
   4437 	    fprintf_unfiltered (gdb_stdlog,
   4438 				"linux-nat: already stopping LWP %ld at "
   4439 				"GDB's request\n",
   4440 				lwp->ptid.lwp ());
   4441 	  return 0;
   4442 	}
   4443 
   4444       stop_callback (lwp, NULL);
   4445       lwp->last_resume_kind = resume_stop;
   4446     }
   4447   else
   4448     {
   4449       /* Already known to be stopped; do nothing.  */
   4450 
   4451       if (debug_linux_nat)
   4452 	{
   4453 	  if (find_thread_ptid (lwp->ptid)->stop_requested)
   4454 	    fprintf_unfiltered (gdb_stdlog,
   4455 				"LNSL: already stopped/stop_requested %s\n",
   4456 				target_pid_to_str (lwp->ptid));
   4457 	  else
   4458 	    fprintf_unfiltered (gdb_stdlog,
   4459 				"LNSL: already stopped/no "
   4460 				"stop_requested yet %s\n",
   4461 				target_pid_to_str (lwp->ptid));
   4462 	}
   4463     }
   4464   return 0;
   4465 }
   4466 
   4467 void
   4468 linux_nat_target::stop (ptid_t ptid)
   4469 {
   4470   iterate_over_lwps (ptid, linux_nat_stop_lwp, NULL);
   4471 }
   4472 
   4473 void
   4474 linux_nat_target::close ()
   4475 {
   4476   /* Unregister from the event loop.  */
   4477   if (is_async_p ())
   4478     async (0);
   4479 
   4480   inf_ptrace_target::close ();
   4481 }
   4482 
   4483 /* When requests are passed down from the linux-nat layer to the
   4484    single threaded inf-ptrace layer, ptids of (lwpid,0,0) form are
   4485    used.  The address space pointer is stored in the inferior object,
   4486    but the common code that is passed such ptid can't tell whether
   4487    lwpid is a "main" process id or not (it assumes so).  We reverse
   4488    look up the "main" process id from the lwp here.  */
   4489 
   4490 struct address_space *
   4491 linux_nat_target::thread_address_space (ptid_t ptid)
   4492 {
   4493   struct lwp_info *lwp;
   4494   struct inferior *inf;
   4495   int pid;
   4496 
   4497   if (ptid.lwp () == 0)
   4498     {
   4499       /* An (lwpid,0,0) ptid.  Look up the lwp object to get at the
   4500 	 tgid.  */
   4501       lwp = find_lwp_pid (ptid);
   4502       pid = lwp->ptid.pid ();
   4503     }
   4504   else
   4505     {
   4506       /* A (pid,lwpid,0) ptid.  */
   4507       pid = ptid.pid ();
   4508     }
   4509 
   4510   inf = find_inferior_pid (pid);
   4511   gdb_assert (inf != NULL);
   4512   return inf->aspace;
   4513 }
   4514 
   4515 /* Return the cached value of the processor core for thread PTID.  */
   4516 
   4517 int
   4518 linux_nat_target::core_of_thread (ptid_t ptid)
   4519 {
   4520   struct lwp_info *info = find_lwp_pid (ptid);
   4521 
   4522   if (info)
   4523     return info->core;
   4524   return -1;
   4525 }
   4526 
   4527 /* Implementation of to_filesystem_is_local.  */
   4528 
   4529 bool
   4530 linux_nat_target::filesystem_is_local ()
   4531 {
   4532   struct inferior *inf = current_inferior ();
   4533 
   4534   if (inf->fake_pid_p || inf->pid == 0)
   4535     return true;
   4536 
   4537   return linux_ns_same (inf->pid, LINUX_NS_MNT);
   4538 }
   4539 
   4540 /* Convert the INF argument passed to a to_fileio_* method
   4541    to a process ID suitable for passing to its corresponding
   4542    linux_mntns_* function.  If INF is non-NULL then the
   4543    caller is requesting the filesystem seen by INF.  If INF
   4544    is NULL then the caller is requesting the filesystem seen
   4545    by the GDB.  We fall back to GDB's filesystem in the case
   4546    that INF is non-NULL but its PID is unknown.  */
   4547 
   4548 static pid_t
   4549 linux_nat_fileio_pid_of (struct inferior *inf)
   4550 {
   4551   if (inf == NULL || inf->fake_pid_p || inf->pid == 0)
   4552     return getpid ();
   4553   else
   4554     return inf->pid;
   4555 }
   4556 
   4557 /* Implementation of to_fileio_open.  */
   4558 
   4559 int
   4560 linux_nat_target::fileio_open (struct inferior *inf, const char *filename,
   4561 			       int flags, int mode, int warn_if_slow,
   4562 			       int *target_errno)
   4563 {
   4564   int nat_flags;
   4565   mode_t nat_mode;
   4566   int fd;
   4567 
   4568   if (fileio_to_host_openflags (flags, &nat_flags) == -1
   4569       || fileio_to_host_mode (mode, &nat_mode) == -1)
   4570     {
   4571       *target_errno = FILEIO_EINVAL;
   4572       return -1;
   4573     }
   4574 
   4575   fd = linux_mntns_open_cloexec (linux_nat_fileio_pid_of (inf),
   4576 				 filename, nat_flags, nat_mode);
   4577   if (fd == -1)
   4578     *target_errno = host_to_fileio_error (errno);
   4579 
   4580   return fd;
   4581 }
   4582 
   4583 /* Implementation of to_fileio_readlink.  */
   4584 
   4585 gdb::optional<std::string>
   4586 linux_nat_target::fileio_readlink (struct inferior *inf, const char *filename,
   4587 				   int *target_errno)
   4588 {
   4589   char buf[PATH_MAX];
   4590   int len;
   4591 
   4592   len = linux_mntns_readlink (linux_nat_fileio_pid_of (inf),
   4593 			      filename, buf, sizeof (buf));
   4594   if (len < 0)
   4595     {
   4596       *target_errno = host_to_fileio_error (errno);
   4597       return {};
   4598     }
   4599 
   4600   return std::string (buf, len);
   4601 }
   4602 
   4603 /* Implementation of to_fileio_unlink.  */
   4604 
   4605 int
   4606 linux_nat_target::fileio_unlink (struct inferior *inf, const char *filename,
   4607 				 int *target_errno)
   4608 {
   4609   int ret;
   4610 
   4611   ret = linux_mntns_unlink (linux_nat_fileio_pid_of (inf),
   4612 			    filename);
   4613   if (ret == -1)
   4614     *target_errno = host_to_fileio_error (errno);
   4615 
   4616   return ret;
   4617 }
   4618 
   4619 /* Implementation of the to_thread_events method.  */
   4620 
   4621 void
   4622 linux_nat_target::thread_events (int enable)
   4623 {
   4624   report_thread_events = enable;
   4625 }
   4626 
   4627 linux_nat_target::linux_nat_target ()
   4628 {
   4629   /* We don't change the stratum; this target will sit at
   4630      process_stratum and thread_db will set at thread_stratum.  This
   4631      is a little strange, since this is a multi-threaded-capable
   4632      target, but we want to be on the stack below thread_db, and we
   4633      also want to be used for single-threaded processes.  */
   4634 }
   4635 
   4636 /* See linux-nat.h.  */
   4637 
   4638 int
   4639 linux_nat_get_siginfo (ptid_t ptid, siginfo_t *siginfo)
   4640 {
   4641   int pid;
   4642 
   4643   pid = ptid.lwp ();
   4644   if (pid == 0)
   4645     pid = ptid.pid ();
   4646 
   4647   errno = 0;
   4648   ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, siginfo);
   4649   if (errno != 0)
   4650     {
   4651       memset (siginfo, 0, sizeof (*siginfo));
   4652       return 0;
   4653     }
   4654   return 1;
   4655 }
   4656 
   4657 /* See nat/linux-nat.h.  */
   4658 
   4659 ptid_t
   4660 current_lwp_ptid (void)
   4661 {
   4662   gdb_assert (inferior_ptid.lwp_p ());
   4663   return inferior_ptid;
   4664 }
   4665 
   4666 void
   4667 _initialize_linux_nat (void)
   4668 {
   4669   add_setshow_zuinteger_cmd ("lin-lwp", class_maintenance,
   4670 			     &debug_linux_nat, _("\
   4671 Set debugging of GNU/Linux lwp module."), _("\
   4672 Show debugging of GNU/Linux lwp module."), _("\
   4673 Enables printf debugging output."),
   4674 			     NULL,
   4675 			     show_debug_linux_nat,
   4676 			     &setdebuglist, &showdebuglist);
   4677 
   4678   add_setshow_boolean_cmd ("linux-namespaces", class_maintenance,
   4679 			   &debug_linux_namespaces, _("\
   4680 Set debugging of GNU/Linux namespaces module."), _("\
   4681 Show debugging of GNU/Linux namespaces module."), _("\
   4682 Enables printf debugging output."),
   4683 			   NULL,
   4684 			   NULL,
   4685 			   &setdebuglist, &showdebuglist);
   4686 
   4687   /* Save this mask as the default.  */
   4688   sigprocmask (SIG_SETMASK, NULL, &normal_mask);
   4689 
   4690   /* Install a SIGCHLD handler.  */
   4691   sigchld_action.sa_handler = sigchld_handler;
   4692   sigemptyset (&sigchld_action.sa_mask);
   4693   sigchld_action.sa_flags = SA_RESTART;
   4694 
   4695   /* Make it the default.  */
   4696   sigaction (SIGCHLD, &sigchld_action, NULL);
   4697 
   4698   /* Make sure we don't block SIGCHLD during a sigsuspend.  */
   4699   sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
   4700   sigdelset (&suspend_mask, SIGCHLD);
   4701 
   4702   sigemptyset (&blocked_mask);
   4703 
   4704   lwp_lwpid_htab_create ();
   4705 }
   4706 
   4707 
   4709 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
   4710    the GNU/Linux Threads library and therefore doesn't really belong
   4711    here.  */
   4712 
   4713 /* Return the set of signals used by the threads library in *SET.  */
   4714 
   4715 void
   4716 lin_thread_get_thread_signals (sigset_t *set)
   4717 {
   4718   sigemptyset (set);
   4719 
   4720   /* NPTL reserves the first two RT signals, but does not provide any
   4721      way for the debugger to query the signal numbers - fortunately
   4722      they don't change.  */
   4723   sigaddset (set, __SIGRTMIN);
   4724   sigaddset (set, __SIGRTMIN + 1);
   4725 }
   4726