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