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