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