Debian Codegraph @

gdbserver/linux-low.cc

raw
1 /* Low level interface to ptrace, for the remote server for GDB.
2 Copyright (C) 1995-2025 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 #include "linux-low.h"
20 #include "nat/linux-osdata.h"
21 #include "gdbsupport/agent.h"
22 #include "tdesc.h"
23 #include "gdbsupport/event-loop.h"
24 #include "gdbsupport/event-pipe.h"
25 #include "gdbsupport/rsp-low.h"
26 #include "gdbsupport/signals-state-save-restore.h"
27 #include "nat/linux-nat.h"
28 #include "nat/linux-waitpid.h"
29 #include "gdbsupport/gdb_wait.h"
30 #include "nat/gdb_ptrace.h"
31 #include "nat/linux-ptrace.h"
32 #include "nat/linux-procfs.h"
33 #include "nat/linux-personality.h"
34 #include <signal.h>
35 #include <sys/ioctl.h>
36 #include <fcntl.h>
37 #include <unistd.h>
38 #include <sys/syscall.h>
39 #include <sched.h>
40 #include <pwd.h>
41 #include <sys/types.h>
42 #include <dirent.h>
43 #include <sys/stat.h>
44 #include <sys/vfs.h>
45 #include <sys/uio.h>
46 #include <langinfo.h>
47 #include <iconv.h>
48 #include "gdbsupport/filestuff.h"
49 #include "gdbsupport/gdb-safe-ctype.h"
50 #include "tracepoint.h"
51 #include <inttypes.h>
52 #include "gdbsupport/common-inferior.h"
53 #include "nat/fork-inferior.h"
54 #include "gdbsupport/environ.h"
55 #include "gdbsupport/gdb-sigmask.h"
56 #include "gdbsupport/scoped_restore.h"
57 #ifndef ELFMAG0
58 /* Don't include <linux/elf.h> here. If it got included by gdb_proc_service.h
59 then ELFMAG0 will have been defined. If it didn't get included by
60 gdb_proc_service.h then including it will likely introduce a duplicate
61 definition of elf_fpregset_t. */
62 #include <elf.h>
63 #endif
64 #include "nat/linux-namespaces.h"
65
66 #ifndef O_LARGEFILE
67 #define O_LARGEFILE 0
68 #endif
69
70 #ifndef AT_HWCAP2
71 #define AT_HWCAP2 26
72 #endif
73
74 /* Some targets did not define these ptrace constants from the start,
75 so gdbserver defines them locally here. In the future, these may
76 be removed after they are added to asm/ptrace.h. */
77 #if !(defined(PT_TEXT_ADDR) \
78 || defined(PT_DATA_ADDR) \
79 || defined(PT_TEXT_END_ADDR))
80 #if defined(__mcoldfire__)
81 /* These are still undefined in 3.10 kernels. */
82 #define PT_TEXT_ADDR 49*4
83 #define PT_DATA_ADDR 50*4
84 #define PT_TEXT_END_ADDR 51*4
85 /* These are still undefined in 3.10 kernels. */
86 #elif defined(__TMS320C6X__)
87 #define PT_TEXT_ADDR (0x10000*4)
88 #define PT_DATA_ADDR (0x10004*4)
89 #define PT_TEXT_END_ADDR (0x10008*4)
90 #endif
91 #endif
92
93 #if (defined(__UCLIBC__) \
94 && defined(HAS_NOMMU) \
95 && defined(PT_TEXT_ADDR) \
96 && defined(PT_DATA_ADDR) \
97 && defined(PT_TEXT_END_ADDR))
98 #define SUPPORTS_READ_OFFSETS
99 #endif
100
101 #ifdef HAVE_LINUX_BTRACE
102 # include "nat/linux-btrace.h"
103 # include "gdbsupport/btrace-common.h"
104 #endif
105
106 #ifndef HAVE_ELF32_AUXV_T
107 /* Copied from glibc's elf.h. */
108 typedef struct
109 {
110 uint32_t a_type; /* Entry type */
111 union
112 {
113 uint32_t a_val; /* Integer value */
114 /* We use to have pointer elements added here. We cannot do that,
115 though, since it does not work when using 32-bit definitions
116 on 64-bit platforms and vice versa. */
117 } a_un;
118 } Elf32_auxv_t;
119 #endif
120
121 #ifndef HAVE_ELF64_AUXV_T
122 /* Copied from glibc's elf.h. */
123 typedef struct
124 {
125 uint64_t a_type; /* Entry type */
126 union
127 {
128 uint64_t a_val; /* Integer value */
129 /* We use to have pointer elements added here. We cannot do that,
130 though, since it does not work when using 32-bit definitions
131 on 64-bit platforms and vice versa. */
132 } a_un;
133 } Elf64_auxv_t;
134 #endif
135
136 /* See nat/linux-nat.h. */
137 enum tribool have_ptrace_getregset = TRIBOOL_UNKNOWN;
138
139 /* Return TRUE if THREAD is the leader thread of the process. */
140
141 static bool
142 is_leader (thread_info *thread)
143 {
144 return thread->id.pid () == thread->id.lwp ();
145 }
146
147 /* Return true if we should report thread exit events to GDB, for
148 THR. */
149
150 static bool
151 report_exit_events_for (thread_info *thr)
152 {
153 client_state &cs = get_client_state ();
154
155 return (cs.report_thread_events
156 || (thr->thread_options & GDB_THREAD_OPTION_EXIT) != 0);
157 }
158
159 /* LWP accessors. */
160
161 /* See nat/linux-nat.h. */
162
163 ptid_t
164 ptid_of_lwp (struct lwp_info *lwp)
165 {
166 return lwp->thread->id;
167 }
168
169 /* See nat/linux-nat.h. */
170
171 void
172 lwp_set_arch_private_info (struct lwp_info *lwp,
173 struct arch_lwp_info *info)
174 {
175 lwp->arch_private = info;
176 }
177
178 /* See nat/linux-nat.h. */
179
180 struct arch_lwp_info *
181 lwp_arch_private_info (struct lwp_info *lwp)
182 {
183 return lwp->arch_private;
184 }
185
186 /* See nat/linux-nat.h. */
187
188 int
189 lwp_is_stopped (struct lwp_info *lwp)
190 {
191 return lwp->stopped;
192 }
193
194 /* See nat/linux-nat.h. */
195
196 enum target_stop_reason
197 lwp_stop_reason (struct lwp_info *lwp)
198 {
199 return lwp->stop_reason;
200 }
201
202 /* See nat/linux-nat.h. */
203
204 int
205 lwp_is_stepping (struct lwp_info *lwp)
206 {
207 return lwp->stepping;
208 }
209
210 /* A list of all unknown processes which receive stop signals. Some
211 other process will presumably claim each of these as forked
212 children momentarily. */
213
214 struct simple_pid_list
215 {
216 /* The process ID. */
217 int pid;
218
219 /* The status as reported by waitpid. */
220 int status;
221
222 /* Next in chain. */
223 struct simple_pid_list *next;
224 };
225 static struct simple_pid_list *stopped_pids;
226
227 /* Trivial list manipulation functions to keep track of a list of new
228 stopped processes. */
229
230 static void
231 add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
232 {
233 struct simple_pid_list *new_pid = XNEW (struct simple_pid_list);
234
235 new_pid->pid = pid;
236 new_pid->status = status;
237 new_pid->next = *listp;
238 *listp = new_pid;
239 }
240
241 static int
242 pull_pid_from_list (struct simple_pid_list **listp, int pid, int *statusp)
243 {
244 struct simple_pid_list **p;
245
246 for (p = listp; *p != NULL; p = &(*p)->next)
247 if ((*p)->pid == pid)
248 {
249 struct simple_pid_list *next = (*p)->next;
250
251 *statusp = (*p)->status;
252 xfree (*p);
253 *p = next;
254 return 1;
255 }
256 return 0;
257 }
258
259 enum stopping_threads_kind
260 {
261 /* Not stopping threads presently. */
262 NOT_STOPPING_THREADS,
263
264 /* Stopping threads. */
265 STOPPING_THREADS,
266
267 /* Stopping and suspending threads. */
268 STOPPING_AND_SUSPENDING_THREADS
269 };
270
271 /* This is set while stop_all_lwps is in effect. */
272 static stopping_threads_kind stopping_threads = NOT_STOPPING_THREADS;
273
274 /* FIXME make into a target method? */
275 int using_threads = 1;
276
277 /* True if we're presently stabilizing threads (moving them out of
278 jump pads). */
279 static int stabilizing_threads;
280
281 static void unsuspend_all_lwps (struct lwp_info *except);
282 static void mark_lwp_dead (struct lwp_info *lwp, int wstat,
283 bool thread_event);
284 static int lwp_is_marked_dead (struct lwp_info *lwp);
285 static int kill_lwp (unsigned long lwpid, int signo);
286 static void enqueue_pending_signal (struct lwp_info *lwp, int signal, siginfo_t *info);
287 static int linux_low_ptrace_options (int attached);
288 static int check_ptrace_stopped_lwp_gone (struct lwp_info *lp);
289
290 /* When the event-loop is doing a step-over, this points at the thread
291 being stepped. */
292 static ptid_t step_over_bkpt;
293
294 bool
295 linux_process_target::low_supports_breakpoints ()
296 {
297 return false;
298 }
299
300 CORE_ADDR
301 linux_process_target::low_get_pc (regcache *regcache)
302 {
303 return 0;
304 }
305
306 void
307 linux_process_target::low_set_pc (regcache *regcache, CORE_ADDR newpc)
308 {
309 gdb_assert_not_reached ("linux target op low_set_pc is not implemented");
310 }
311
312 std::vector<CORE_ADDR>
313 linux_process_target::low_get_next_pcs (regcache *regcache)
314 {
315 gdb_assert_not_reached ("linux target op low_get_next_pcs is not "
316 "implemented");
317 }
318
319 int
320 linux_process_target::low_decr_pc_after_break ()
321 {
322 return 0;
323 }
324
325 /* True if LWP is stopped in its stepping range. */
326
327 static int
328 lwp_in_step_range (struct lwp_info *lwp)
329 {
330 CORE_ADDR pc = lwp->stop_pc;
331
332 return (pc >= lwp->step_range_start && pc < lwp->step_range_end);
333 }
334
335 /* The event pipe registered as a waitable file in the event loop. */
336 static event_pipe linux_event_pipe;
337
338 /* True if we're currently in async mode. */
339 #define target_is_async_p() (linux_event_pipe.is_open ())
340
341 static void send_sigstop (struct lwp_info *lwp);
342
343 /* Return non-zero if HEADER is a 64-bit ELF file. */
344
345 static int
346 elf_64_header_p (const Elf64_Ehdr *header, unsigned int *machine)
347 {
348 if (header->e_ident[EI_MAG0] == ELFMAG0
349 && header->e_ident[EI_MAG1] == ELFMAG1
350 && header->e_ident[EI_MAG2] == ELFMAG2
351 && header->e_ident[EI_MAG3] == ELFMAG3)
352 {
353 *machine = header->e_machine;
354 return header->e_ident[EI_CLASS] == ELFCLASS64;
355
356 }
357 *machine = EM_NONE;
358 return -1;
359 }
360
361 /* Return non-zero if FILE is a 64-bit ELF file,
362 zero if the file is not a 64-bit ELF file,
363 and -1 if the file is not accessible or doesn't exist. */
364
365 static int
366 elf_64_file_p (const char *file, unsigned int *machine)
367 {
368 Elf64_Ehdr header;
369 int fd;
370
371 fd = open (file, O_RDONLY);
372 if (fd < 0)
373 return -1;
374
375 if (read (fd, &header, sizeof (header)) != sizeof (header))
376 {
377 close (fd);
378 return 0;
379 }
380 close (fd);
381
382 return elf_64_header_p (&header, machine);
383 }
384
385 /* Accepts an integer PID; Returns true if the executable PID is
386 running is a 64-bit ELF file.. */
387
388 int
389 linux_pid_exe_is_elf_64_file (int pid, unsigned int *machine)
390 {
391 char file[PATH_MAX];
392
393 sprintf (file, "/proc/%d/exe", pid);
394 return elf_64_file_p (file, machine);
395 }
396
397 void
398 linux_process_target::delete_lwp (lwp_info *lwp)
399 {
400 thread_info *thr = lwp->thread;
401
402 threads_debug_printf ("deleting %ld", thr->id.lwp ());
403
404 thr->process ()->remove_thread (thr);
405
406 low_delete_thread (lwp->arch_private);
407
408 delete lwp;
409 }
410
411 void
412 linux_process_target::low_delete_thread (arch_lwp_info *info)
413 {
414 /* Default implementation should be overridden if architecture-specific
415 info is being used. */
416 gdb_assert (info == nullptr);
417 }
418
419 /* Open the /proc/PID/mem file for PROC. */
420
421 static void
422 open_proc_mem_file (process_info *proc)
423 {
424 gdb_assert (proc->priv->mem_fd == -1);
425
426 char filename[64];
427 xsnprintf (filename, sizeof filename, "/proc/%d/mem", proc->pid);
428
429 proc->priv->mem_fd
430 = gdb_open_cloexec (filename, O_RDWR | O_LARGEFILE, 0).release ();
431 }
432
433 process_info *
434 linux_process_target::add_linux_process_no_mem_file (int pid, int attached)
435 {
436 struct process_info *proc;
437
438 proc = add_process (pid, attached);
439 proc->priv = XCNEW (struct process_info_private);
440
441 proc->priv->arch_private = low_new_process ();
442 proc->priv->mem_fd = -1;
443
444 return proc;
445 }
446
447
448 process_info *
449 linux_process_target::add_linux_process (int pid, int attached)
450 {
451 process_info *proc = add_linux_process_no_mem_file (pid, attached);
452 open_proc_mem_file (proc);
453 return proc;
454 }
455
456 void
457 linux_process_target::remove_linux_process (process_info *proc)
458 {
459 if (proc->priv->mem_fd >= 0)
460 close (proc->priv->mem_fd);
461
462 this->low_delete_process (proc->priv->arch_private);
463
464 xfree (proc->priv);
465 proc->priv = nullptr;
466
467 remove_process (proc);
468 }
469
470 arch_process_info *
471 linux_process_target::low_new_process ()
472 {
473 return nullptr;
474 }
475
476 void
477 linux_process_target::low_delete_process (arch_process_info *info)
478 {
479 /* Default implementation must be overridden if architecture-specific
480 info exists. */
481 gdb_assert (info == nullptr);
482 }
483
484 void
485 linux_process_target::low_new_fork (process_info *parent, process_info *child)
486 {
487 /* Nop. */
488 }
489
490 void
491 linux_process_target::arch_setup_thread (thread_info *thread)
492 {
493 scoped_restore_current_thread restore_thread;
494 switch_to_thread (thread);
495
496 low_arch_setup ();
497 }
498
499 int
500 linux_process_target::handle_extended_wait (lwp_info **orig_event_lwp,
501 int wstat)
502 {
503 client_state &cs = get_client_state ();
504 struct lwp_info *event_lwp = *orig_event_lwp;
505 int event = linux_ptrace_get_extended_event (wstat);
506 thread_info *event_thr = event_lwp->thread;
507
508 gdb_assert (event_lwp->waitstatus.kind () == TARGET_WAITKIND_IGNORE);
509
510 /* All extended events we currently use are mid-syscall. Only
511 PTRACE_EVENT_STOP is delivered more like a signal-stop, but
512 you have to be using PTRACE_SEIZE to get that. */
513 event_lwp->syscall_state = TARGET_WAITKIND_SYSCALL_ENTRY;
514
515 if ((event == PTRACE_EVENT_FORK) || (event == PTRACE_EVENT_VFORK)
516 || (event == PTRACE_EVENT_CLONE))
517 {
518 unsigned long new_pid;
519 int ret, status;
520
521 /* Get the pid of the new lwp. */
522 ptrace (PTRACE_GETEVENTMSG, event_thr->id.lwp (), (PTRACE_TYPE_ARG3) 0,
523 &new_pid);
524
525 /* If we haven't already seen the new PID stop, wait for it now. */
526 if (!pull_pid_from_list (&stopped_pids, new_pid, &status))
527 {
528 /* The new child has a pending SIGSTOP. We can't affect it until it
529 hits the SIGSTOP, but we're already attached. */
530
531 ret = my_waitpid (new_pid, &status, __WALL);
532
533 if (ret == -1)
534 perror_with_name ("waiting for new child");
535 else if (ret != new_pid)
536 warning ("wait returned unexpected PID %d", ret);
537 else if (!WIFSTOPPED (status))
538 warning ("wait returned unexpected status 0x%x", status);
539 }
540
541 if (debug_threads)
542 {
543 debug_printf ("HEW: Got %s event from LWP %ld, new child is %ld\n",
544 (event == PTRACE_EVENT_FORK ? "fork"
545 : event == PTRACE_EVENT_VFORK ? "vfork"
546 : event == PTRACE_EVENT_CLONE ? "clone"
547 : "???"),
548 event_thr->id.lwp (),
549 new_pid);
550 }
551
552 ptid_t child_ptid = (event != PTRACE_EVENT_CLONE
553 ? ptid_t (new_pid, new_pid)
554 : ptid_t (event_thr->id.pid (), new_pid));
555
556 process_info *child_proc = nullptr;
557
558 if (event != PTRACE_EVENT_CLONE)
559 {
560 /* Add the new process to the tables before we add the LWP.
561 We need to do this even if the new process will be
562 detached. See breakpoint cloning code further below. */
563 child_proc = add_linux_process (new_pid, 0);
564 }
565
566 lwp_info *child_lwp = add_lwp (child_ptid);
567 gdb_assert (child_lwp != NULL);
568 child_lwp->stopped = 1;
569 if (event != PTRACE_EVENT_CLONE)
570 child_lwp->must_set_ptrace_flags = 1;
571 child_lwp->status_pending_p = 0;
572
573 thread_info *child_thr = child_lwp->thread;
574
575 /* If we're suspending all threads, leave this one suspended
576 too. If the fork/clone parent is stepping over a breakpoint,
577 all other threads have been suspended already. Leave the
578 child suspended too. */
579 if (stopping_threads == STOPPING_AND_SUSPENDING_THREADS
580 || event_lwp->bp_reinsert != 0)
581 {
582 threads_debug_printf ("leaving child suspended");
583 child_lwp->suspended = 1;
584 }
585
586 if (event_lwp->bp_reinsert != 0
587 && supports_software_single_step ()
588 && event == PTRACE_EVENT_VFORK)
589 {
590 /* If we leave single-step breakpoints there, child will
591 hit it, so uninsert single-step breakpoints from parent
592 (and child). Once vfork child is done, reinsert
593 them back to parent. */
594 uninsert_single_step_breakpoints (event_thr);
595 }
596
597 if (event != PTRACE_EVENT_CLONE)
598 {
599 /* Clone the breakpoint lists of the parent. We need to do
600 this even if the new process will be detached, since we
601 will need the process object and the breakpoints to
602 remove any breakpoints from memory when we detach, and
603 the client side will access registers. */
604 gdb_assert (child_proc != NULL);
605
606 process_info *parent_proc = event_thr->process ();
607 child_proc->attached = parent_proc->attached;
608
609 clone_all_breakpoints (child_thr, event_thr);
610
611 target_desc_up tdesc = allocate_target_description ();
612 copy_target_description (tdesc.get (), parent_proc->tdesc);
613 child_proc->tdesc = tdesc.release ();
614
615 /* Clone arch-specific process data. */
616 low_new_fork (parent_proc, child_proc);
617 }
618
619 /* Save fork/clone info in the parent thread. */
620 if (event == PTRACE_EVENT_FORK)
621 event_lwp->waitstatus.set_forked (child_ptid);
622 else if (event == PTRACE_EVENT_VFORK)
623 event_lwp->waitstatus.set_vforked (child_ptid);
624 else if (event == PTRACE_EVENT_CLONE
625 && (event_thr->thread_options & GDB_THREAD_OPTION_CLONE) != 0)
626 event_lwp->waitstatus.set_thread_cloned (child_ptid);
627
628 if (event != PTRACE_EVENT_CLONE
629 || (event_thr->thread_options & GDB_THREAD_OPTION_CLONE) != 0)
630 {
631 /* The status_pending field contains bits denoting the
632 extended event, so when the pending event is handled, the
633 handler will look at lwp->waitstatus. */
634 event_lwp->status_pending_p = 1;
635 event_lwp->status_pending = wstat;
636
637 /* Link the threads until the parent's event is passed on to
638 GDB. */
639 event_lwp->relative = child_lwp;
640 child_lwp->relative = event_lwp;
641 }
642
643 /* If the parent thread is doing step-over with single-step
644 breakpoints, the list of single-step breakpoints are cloned
645 from the parent's. Remove them from the child process.
646 In case of vfork, we'll reinsert them back once vforked
647 child is done. */
648 if (event_lwp->bp_reinsert != 0
649 && supports_software_single_step ())
650 {
651 /* The child process is forked and stopped, so it is safe
652 to access its memory without stopping all other threads
653 from other processes. */
654 delete_single_step_breakpoints (child_thr);
655
656 gdb_assert (has_single_step_breakpoints (event_thr));
657 gdb_assert (!has_single_step_breakpoints (child_thr));
658 }
659
660 /* Normally we will get the pending SIGSTOP. But in some cases
661 we might get another signal delivered to the group first.
662 If we do get another signal, be sure not to lose it. */
663 if (WSTOPSIG (status) != SIGSTOP)
664 {
665 child_lwp->stop_expected = 1;
666 child_lwp->status_pending_p = 1;
667 child_lwp->status_pending = status;
668 }
669 else if (event == PTRACE_EVENT_CLONE && cs.report_thread_events)
670 {
671 child_lwp->waitstatus.set_thread_created ();
672 child_lwp->status_pending_p = 1;
673 child_lwp->status_pending = status;
674 }
675
676 if (event == PTRACE_EVENT_CLONE)
677 {
678 #ifdef USE_THREAD_DB
679 thread_db_notice_clone (event_thr, child_ptid);
680 #endif
681 }
682
683 if (event == PTRACE_EVENT_CLONE
684 && (event_thr->thread_options & GDB_THREAD_OPTION_CLONE) == 0)
685 {
686 threads_debug_printf
687 ("not reporting clone event from LWP %ld, new child is %ld\n",
688 event_thr->id.lwp (),
689 new_pid);
690 return 1;
691 }
692
693 /* Leave the child stopped until GDB processes the parent
694 event. */
695 child_thr->last_resume_kind = resume_stop;
696 child_thr->last_status.set_stopped (GDB_SIGNAL_0);
697
698 /* Report the event. */
699 threads_debug_printf
700 ("reporting %s event from LWP %ld, new child is %ld\n",
701 (event == PTRACE_EVENT_FORK ? "fork"
702 : event == PTRACE_EVENT_VFORK ? "vfork"
703 : event == PTRACE_EVENT_CLONE ? "clone"
704 : "???"),
705 event_thr->id.lwp (),
706 new_pid);
707 return 0;
708 }
709 else if (event == PTRACE_EVENT_VFORK_DONE)
710 {
711 event_lwp->waitstatus.set_vfork_done ();
712
713 if (event_lwp->bp_reinsert != 0 && supports_software_single_step ())
714 {
715 reinsert_single_step_breakpoints (event_thr);
716
717 gdb_assert (has_single_step_breakpoints (event_thr));
718 }
719
720 /* Report the event. */
721 return 0;
722 }
723 else if (event == PTRACE_EVENT_EXEC && cs.report_exec_events)
724 {
725 std::vector<int> syscalls_to_catch;
726 ptid_t event_ptid;
727 pid_t event_pid;
728
729 threads_debug_printf ("Got exec event from LWP %ld",
730 event_thr->id.lwp ());
731
732 /* Get the event ptid. */
733 event_ptid = event_thr->id;
734 event_pid = event_ptid.pid ();
735
736 /* Save the syscall list from the execing process. */
737 process_info *proc = event_thr->process ();
738 syscalls_to_catch = std::move (proc->syscalls_to_catch);
739
740 /* Delete the execing process and all its threads. */
741 mourn (proc);
742 switch_to_thread (nullptr);
743
744 /* Create a new process/lwp/thread. */
745 proc = add_linux_process (event_pid, 0);
746 event_lwp = add_lwp (event_ptid);
747 event_thr = event_lwp->thread;
748 gdb_assert (current_thread == event_thr);
749 arch_setup_thread (event_thr);
750
751 /* Set the event status. */
752 event_lwp->waitstatus.set_execd
753 (make_unique_xstrdup
754 (pid_to_exec_file (event_thr->id.lwp ())));
755
756 /* Mark the exec status as pending. */
757 event_lwp->stopped = 1;
758 event_lwp->status_pending_p = 1;
759 event_lwp->status_pending = wstat;
760 event_thr->last_resume_kind = resume_continue;
761 event_thr->last_status.set_ignore ();
762
763 /* Update syscall state in the new lwp, effectively mid-syscall too. */
764 event_lwp->syscall_state = TARGET_WAITKIND_SYSCALL_ENTRY;
765
766 /* Restore the list to catch. Don't rely on the client, which is free
767 to avoid sending a new list when the architecture doesn't change.
768 Also, for ANY_SYSCALL, the architecture doesn't really matter. */
769 proc->syscalls_to_catch = std::move (syscalls_to_catch);
770
771 /* Report the event. */
772 *orig_event_lwp = event_lwp;
773 return 0;
774 }
775
776 internal_error (_("unknown ptrace event %d"), event);
777 }
778
779 CORE_ADDR
780 linux_process_target::get_pc (lwp_info *lwp)
781 {
782 process_info *proc = lwp->thread->process ();
783 gdb_assert (!proc->starting_up);
784
785 if (!low_supports_breakpoints ())
786 return 0;
787
788 scoped_restore_current_thread restore_thread;
789 switch_to_thread (lwp->thread);
790
791 regcache *regcache = get_thread_regcache (current_thread);
792 CORE_ADDR pc = low_get_pc (regcache);
793
794 threads_debug_printf ("pc is 0x%lx", (long) pc);
795
796 return pc;
797 }
798
799 void
800 linux_process_target::get_syscall_trapinfo (lwp_info *lwp, int *sysno)
801 {
802 struct regcache *regcache;
803
804 scoped_restore_current_thread restore_thread;
805 switch_to_thread (lwp->thread);
806
807 regcache = get_thread_regcache (current_thread);
808 low_get_syscall_trapinfo (regcache, sysno);
809
810 threads_debug_printf ("get_syscall_trapinfo sysno %d", *sysno);
811 }
812
813 void
814 linux_process_target::low_get_syscall_trapinfo (regcache *regcache, int *sysno)
815 {
816 /* By default, report an unknown system call number. */
817 *sysno = UNKNOWN_SYSCALL;
818 }
819
820 bool
821 linux_process_target::save_stop_reason (lwp_info *lwp)
822 {
823 CORE_ADDR pc;
824 CORE_ADDR sw_breakpoint_pc;
825 siginfo_t siginfo;
826
827 if (!low_supports_breakpoints ())
828 return false;
829
830 process_info *proc = lwp->thread->process ();
831 if (proc->starting_up)
832 {
833 /* Claim we have the stop PC so that the caller doesn't try to
834 fetch it itself. */
835 return true;
836 }
837
838 pc = get_pc (lwp);
839 sw_breakpoint_pc = pc - low_decr_pc_after_break ();
840
841 /* breakpoint_at reads from the current thread. */
842 scoped_restore_current_thread restore_thread;
843 switch_to_thread (lwp->thread);
844
845 if (ptrace (PTRACE_GETSIGINFO, current_thread->id.lwp (),
846 (PTRACE_TYPE_ARG3) 0, &siginfo) == 0)
847 {
848 if (siginfo.si_signo == SIGTRAP)
849 {
850 if (GDB_ARCH_IS_TRAP_BRKPT (siginfo.si_code)
851 && GDB_ARCH_IS_TRAP_HWBKPT (siginfo.si_code))
852 {
853 /* The si_code is ambiguous on this arch -- check debug
854 registers. */
855 if (!check_stopped_by_watchpoint (lwp))
856 lwp->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
857 }
858 else if (GDB_ARCH_IS_TRAP_BRKPT (siginfo.si_code))
859 {
860 /* If we determine the LWP stopped for a SW breakpoint,
861 trust it. Particularly don't check watchpoint
862 registers, because at least on s390, we'd find
863 stopped-by-watchpoint as long as there's a watchpoint
864 set. */
865 lwp->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
866 }
867 else if (GDB_ARCH_IS_TRAP_HWBKPT (siginfo.si_code))
868 {
869 /* This can indicate either a hardware breakpoint or
870 hardware watchpoint. Check debug registers. */
871 if (!check_stopped_by_watchpoint (lwp))
872 lwp->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
873 }
874 else if (siginfo.si_code == TRAP_TRACE)
875 {
876 /* We may have single stepped an instruction that
877 triggered a watchpoint. In that case, on some
878 architectures (such as x86), instead of TRAP_HWBKPT,
879 si_code indicates TRAP_TRACE, and we need to check
880 the debug registers separately. */
881 if (!check_stopped_by_watchpoint (lwp))
882 lwp->stop_reason = TARGET_STOPPED_BY_SINGLE_STEP;
883 }
884 }
885 }
886
887 if (lwp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT)
888 {
889 threads_debug_printf
890 ("%s stopped by software breakpoint",
891 target_pid_to_str (lwp->thread->id).c_str ());
892
893 /* Back up the PC if necessary. */
894 if (pc != sw_breakpoint_pc)
895 {
896 struct regcache *regcache
897 = get_thread_regcache (current_thread);
898 low_set_pc (regcache, sw_breakpoint_pc);
899 }
900
901 /* Update this so we record the correct stop PC below. */
902 pc = sw_breakpoint_pc;
903 }
904 else if (lwp->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT)
905 threads_debug_printf
906 ("%s stopped by hardware breakpoint",
907 target_pid_to_str (lwp->thread->id).c_str ());
908 else if (lwp->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
909 threads_debug_printf
910 ("%s stopped by hardware watchpoint",
911 target_pid_to_str (lwp->thread->id).c_str ());
912 else if (lwp->stop_reason == TARGET_STOPPED_BY_SINGLE_STEP)
913 threads_debug_printf
914 ("%s stopped by trace",
915 target_pid_to_str (lwp->thread->id).c_str ());
916
917 lwp->stop_pc = pc;
918 return true;
919 }
920
921 lwp_info *
922 linux_process_target::add_lwp (ptid_t ptid)
923 {
924 lwp_info *lwp = new lwp_info;
925
926 lwp->thread = find_process_pid (ptid.pid ())->add_thread (ptid, lwp);
927
928 low_new_thread (lwp);
929
930 return lwp;
931 }
932
933 void
934 linux_process_target::low_new_thread (lwp_info *info)
935 {
936 /* Nop. */
937 }
938
939 /* Callback to be used when calling fork_inferior, responsible for
940 actually initiating the tracing of the inferior. */
941
942 static void
943 linux_ptrace_fun ()
944 {
945 if (ptrace (PTRACE_TRACEME, 0, (PTRACE_TYPE_ARG3) 0,
946 (PTRACE_TYPE_ARG4) 0) < 0)
947 trace_start_error_with_name ("ptrace");
948
949 if (setpgid (0, 0) < 0)
950 trace_start_error_with_name ("setpgid");
951
952 /* If GDBserver is connected to gdb via stdio, redirect the inferior's
953 stdout to stderr so that inferior i/o doesn't corrupt the connection.
954 Also, redirect stdin to /dev/null. */
955 if (remote_connection_is_stdio ())
956 {
957 if (close (0) < 0)
958 trace_start_error_with_name ("close");
959 if (open ("/dev/null", O_RDONLY) < 0)
960 trace_start_error_with_name ("open");
961 if (dup2 (2, 1) < 0)
962 trace_start_error_with_name ("dup2");
963 if (write (2, "stdin/stdout redirected\n",
964 sizeof ("stdin/stdout redirected\n") - 1) < 0)
965 {
966 /* Errors ignored. */;
967 }
968 }
969 }
970
971 /* Start an inferior process and returns its pid.
972 PROGRAM is the name of the program to be started, and PROGRAM_ARGS
973 are its arguments. */
974
975 int
976 linux_process_target::create_inferior (const char *program,
977 const std::string &program_args)
978 {
979 client_state &cs = get_client_state ();
980 struct lwp_info *new_lwp;
981 int pid;
982 ptid_t ptid;
983
984 {
985 maybe_disable_address_space_randomization restore_personality
986 (cs.disable_randomization);
987
988 pid = fork_inferior (program,
989 program_args.c_str (),
990 get_environ ()->envp (), linux_ptrace_fun,
991 NULL, NULL, NULL, NULL);
992 }
993
994 /* When spawning a new process, we can't open the mem file yet. We
995 still have to nurse the process through the shell, and that execs
996 a couple times. The address space a /proc/PID/mem file is
997 accessing is destroyed on exec. */
998 process_info *proc = add_linux_process_no_mem_file (pid, 0);
999
1000 ptid = ptid_t (pid, pid);
1001 new_lwp = add_lwp (ptid);
1002 new_lwp->must_set_ptrace_flags = 1;
1003
1004 post_fork_inferior (pid, program);
1005
1006 /* PROC is now past the shell running the program we want, so we can
1007 open the /proc/PID/mem file. */
1008 open_proc_mem_file (proc);
1009
1010 return pid;
1011 }
1012
1013 /* Implement the post_create_inferior target_ops method. */
1014
1015 void
1016 linux_process_target::post_create_inferior ()
1017 {
1018 struct lwp_info *lwp = get_thread_lwp (current_thread);
1019
1020 low_arch_setup ();
1021
1022 if (lwp->must_set_ptrace_flags)
1023 {
1024 struct process_info *proc = current_process ();
1025 int options = linux_low_ptrace_options (proc->attached);
1026
1027 linux_enable_event_reporting (current_thread->id.lwp (), options);
1028 lwp->must_set_ptrace_flags = 0;
1029 }
1030 }
1031
1032 int
1033 linux_process_target::attach_lwp (ptid_t ptid)
1034 {
1035 struct lwp_info *new_lwp;
1036 int lwpid = ptid.lwp ();
1037
1038 if (ptrace (PTRACE_ATTACH, lwpid, (PTRACE_TYPE_ARG3) 0, (PTRACE_TYPE_ARG4) 0)
1039 != 0)
1040 return errno;
1041
1042 new_lwp = add_lwp (ptid);
1043
1044 /* We need to wait for SIGSTOP before being able to make the next
1045 ptrace call on this LWP. */
1046 new_lwp->must_set_ptrace_flags = 1;
1047
1048 if (linux_proc_pid_is_stopped (lwpid))
1049 {
1050 threads_debug_printf ("Attached to a stopped process");
1051
1052 /* The process is definitely stopped. It is in a job control
1053 stop, unless the kernel predates the TASK_STOPPED /
1054 TASK_TRACED distinction, in which case it might be in a
1055 ptrace stop. Make sure it is in a ptrace stop; from there we
1056 can kill it, signal it, et cetera.
1057
1058 First make sure there is a pending SIGSTOP. Since we are
1059 already attached, the process can not transition from stopped
1060 to running without a PTRACE_CONT; so we know this signal will
1061 go into the queue. The SIGSTOP generated by PTRACE_ATTACH is
1062 probably already in the queue (unless this kernel is old
1063 enough to use TASK_STOPPED for ptrace stops); but since
1064 SIGSTOP is not an RT signal, it can only be queued once. */
1065 kill_lwp (lwpid, SIGSTOP);
1066
1067 /* Finally, resume the stopped process. This will deliver the
1068 SIGSTOP (or a higher priority signal, just like normal
1069 PTRACE_ATTACH), which we'll catch later on. */
1070 ptrace (PTRACE_CONT, lwpid, (PTRACE_TYPE_ARG3) 0, (PTRACE_TYPE_ARG4) 0);
1071 }
1072
1073 /* The next time we wait for this LWP we'll see a SIGSTOP as PTRACE_ATTACH
1074 brings it to a halt.
1075
1076 There are several cases to consider here:
1077
1078 1) gdbserver has already attached to the process and is being notified
1079 of a new thread that is being created.
1080 In this case we should ignore that SIGSTOP and resume the
1081 process. This is handled below by setting stop_expected = 1,
1082 and the fact that add_thread sets last_resume_kind ==
1083 resume_continue.
1084
1085 2) This is the first thread (the process thread), and we're attaching
1086 to it via attach_inferior.
1087 In this case we want the process thread to stop.
1088 This is handled by having linux_attach set last_resume_kind ==
1089 resume_stop after we return.
1090
1091 If the pid we are attaching to is also the tgid, we attach to and
1092 stop all the existing threads. Otherwise, we attach to pid and
1093 ignore any other threads in the same group as this pid.
1094
1095 3) GDB is connecting to gdbserver and is requesting an enumeration of all
1096 existing threads.
1097 In this case we want the thread to stop.
1098 FIXME: This case is currently not properly handled.
1099 We should wait for the SIGSTOP but don't. Things work apparently
1100 because enough time passes between when we ptrace (ATTACH) and when
1101 gdb makes the next ptrace call on the thread.
1102
1103 On the other hand, if we are currently trying to stop all threads, we
1104 should treat the new thread as if we had sent it a SIGSTOP. This works
1105 because we are guaranteed that the add_lwp call above added us to the
1106 end of the list, and so the new thread has not yet reached
1107 wait_for_sigstop (but will). */
1108 new_lwp->stop_expected = 1;
1109
1110 return 0;
1111 }
1112
1113 /* Callback for linux_proc_attach_tgid_threads. Attach to PTID if not
1114 already attached. Returns true if a new LWP is found, false
1115 otherwise. */
1116
1117 static int
1118 attach_proc_task_lwp_callback (ptid_t ptid)
1119 {
1120 /* Is this a new thread? */
1121 if (find_thread_ptid (ptid) == NULL)
1122 {
1123 int lwpid = ptid.lwp ();
1124 int err;
1125
1126 threads_debug_printf ("Found new lwp %d", lwpid);
1127
1128 err = the_linux_target->attach_lwp (ptid);
1129
1130 /* Be quiet if we simply raced with the thread exiting. EPERM
1131 is returned if the thread's task still exists, and is marked
1132 as exited or zombie, as well as other conditions, so in that
1133 case, confirm the status in /proc/PID/status. */
1134 if (err == ESRCH
1135 || (err == EPERM && linux_proc_pid_is_gone (lwpid)))
1136 threads_debug_printf
1137 ("Cannot attach to lwp %d: thread is gone (%d: %s)",
1138 lwpid, err, safe_strerror (err));
1139 else if (err != 0)
1140 {
1141 std::string reason
1142 = linux_ptrace_attach_fail_reason_string (ptid, err);
1143
1144 error (_("Cannot attach to lwp %d: %s"), lwpid, reason.c_str ());
1145 }
1146
1147 return 1;
1148 }
1149 return 0;
1150 }
1151
1152 static void async_file_mark (void);
1153
1154 /* Attach to PID. If PID is the tgid, attach to it and all
1155 of its threads. */
1156
1157 int
1158 linux_process_target::attach (unsigned long pid)
1159 {
1160 struct process_info *proc;
1161 thread_info *initial_thread;
1162 ptid_t ptid = ptid_t (pid, pid);
1163 int err;
1164
1165 /* Delay opening the /proc/PID/mem file until we've successfully
1166 attached. */
1167 proc = add_linux_process_no_mem_file (pid, 1);
1168
1169 /* Attach to PID. We will check for other threads
1170 soon. */
1171 err = attach_lwp (ptid);
1172 if (err != 0)
1173 {
1174 this->remove_linux_process (proc);
1175
1176 std::string reason = linux_ptrace_attach_fail_reason_string (ptid, err);
1177 error ("Cannot attach to process %ld: %s", pid, reason.c_str ());
1178 }
1179
1180 open_proc_mem_file (proc);
1181
1182 /* Don't ignore the initial SIGSTOP if we just attached to this
1183 process. It will be collected by wait shortly. */
1184 initial_thread = find_thread_ptid (ptid_t (pid, pid));
1185 gdb_assert (initial_thread != nullptr);
1186 initial_thread->last_resume_kind = resume_stop;
1187
1188 /* We must attach to every LWP. If /proc is mounted, use that to
1189 find them now. On the one hand, the inferior may be using raw
1190 clone instead of using pthreads. On the other hand, even if it
1191 is using pthreads, GDB may not be connected yet (thread_db needs
1192 to do symbol lookups, through qSymbol). Also, thread_db walks
1193 structures in the inferior's address space to find the list of
1194 threads/LWPs, and those structures may well be corrupted. Note
1195 that once thread_db is loaded, we'll still use it to list threads
1196 and associate pthread info with each LWP. */
1197 try
1198 {
1199 linux_proc_attach_tgid_threads (pid, attach_proc_task_lwp_callback);
1200 }
1201 catch (const gdb_exception_error &)
1202 {
1203 /* Make sure we do not deliver the SIGSTOP to the process. */
1204 initial_thread->last_resume_kind = resume_continue;
1205
1206 this->detach (proc);
1207 throw;
1208 }
1209
1210 /* GDB will shortly read the xml target description for this
1211 process, to figure out the process' architecture. But the target
1212 description is only filled in when the first process/thread in
1213 the thread group reports its initial PTRACE_ATTACH SIGSTOP. Do
1214 that now, otherwise, if GDB is fast enough, it could read the
1215 target description _before_ that initial stop. */
1216 if (non_stop)
1217 {
1218 struct lwp_info *lwp;
1219 int wstat, lwpid;
1220 ptid_t pid_ptid = ptid_t (pid);
1221
1222 lwpid = wait_for_event_filtered (pid_ptid, pid_ptid, &wstat, __WALL);
1223 gdb_assert (lwpid > 0);
1224
1225 lwp = find_lwp_pid (ptid_t (lwpid));
1226 gdb_assert (lwp != nullptr);
1227
1228 if (!WIFSTOPPED (wstat) || WSTOPSIG (wstat) != SIGSTOP)
1229 {
1230 lwp->status_pending_p = 1;
1231 lwp->status_pending = wstat;
1232 }
1233
1234 initial_thread->last_resume_kind = resume_continue;
1235
1236 async_file_mark ();
1237
1238 gdb_assert (proc->tdesc != NULL);
1239 }
1240
1241 return 0;
1242 }
1243
1244 static int
1245 last_thread_of_process_p (int pid)
1246 {
1247 bool seen_one = false;
1248
1249 thread_info *thread = find_thread (pid, [&] (thread_info *thr_arg)
1250 {
1251 if (!seen_one)
1252 {
1253 /* This is the first thread of this process we see. */
1254 seen_one = true;
1255 return false;
1256 }
1257 else
1258 {
1259 /* This is the second thread of this process we see. */
1260 return true;
1261 }
1262 });
1263
1264 return thread == NULL;
1265 }
1266
1267 /* Kill LWP. */
1268
1269 static void
1270 linux_kill_one_lwp (struct lwp_info *lwp)
1271 {
1272 thread_info *thr = lwp->thread;
1273 int pid = thr->id.lwp ();
1274
1275 /* PTRACE_KILL is unreliable. After stepping into a signal handler,
1276 there is no signal context, and ptrace(PTRACE_KILL) (or
1277 ptrace(PTRACE_CONT, SIGKILL), pretty much the same) acts like
1278 ptrace(CONT, pid, 0,0) and just resumes the tracee. A better
1279 alternative is to kill with SIGKILL. We only need one SIGKILL
1280 per process, not one for each thread. But since we still support
1281 support debugging programs using raw clone without CLONE_THREAD,
1282 we send one for each thread. For years, we used PTRACE_KILL
1283 only, so we're being a bit paranoid about some old kernels where
1284 PTRACE_KILL might work better (dubious if there are any such, but
1285 that's why it's paranoia), so we try SIGKILL first, PTRACE_KILL
1286 second, and so we're fine everywhere. */
1287
1288 errno = 0;
1289 kill_lwp (pid, SIGKILL);
1290 if (debug_threads)
1291 {
1292 int save_errno = errno;
1293
1294 threads_debug_printf ("kill_lwp (SIGKILL) %s, 0, 0 (%s)",
1295 target_pid_to_str (thr->id).c_str (),
1296 save_errno ? safe_strerror (save_errno) : "OK");
1297 }
1298
1299 errno = 0;
1300 ptrace (PTRACE_KILL, pid, (PTRACE_TYPE_ARG3) 0, (PTRACE_TYPE_ARG4) 0);
1301 if (debug_threads)
1302 {
1303 int save_errno = errno;
1304
1305 threads_debug_printf ("PTRACE_KILL %s, 0, 0 (%s)",
1306 target_pid_to_str (thr->id).c_str (),
1307 save_errno ? safe_strerror (save_errno) : "OK");
1308 }
1309 }
1310
1311 /* Kill LWP and wait for it to die. */
1312
1313 static void
1314 kill_wait_lwp (struct lwp_info *lwp)
1315 {
1316 thread_info *thr = lwp->thread;
1317 int pid = thr->id.pid ();
1318 int lwpid = thr->id.lwp ();
1319 int wstat;
1320 int res;
1321
1322 threads_debug_printf ("killing lwp %d, for pid: %d", lwpid, pid);
1323
1324 do
1325 {
1326 linux_kill_one_lwp (lwp);
1327
1328 /* Make sure it died. Notes:
1329
1330 - The loop is most likely unnecessary.
1331
1332 - We don't use wait_for_event as that could delete lwps
1333 while we're iterating over them. We're not interested in
1334 any pending status at this point, only in making sure all
1335 wait status on the kernel side are collected until the
1336 process is reaped.
1337
1338 - We don't use __WALL here as the __WALL emulation relies on
1339 SIGCHLD, and killing a stopped process doesn't generate
1340 one, nor an exit status.
1341 */
1342 res = my_waitpid (lwpid, &wstat, 0);
1343 if (res == -1 && errno == ECHILD)
1344 res = my_waitpid (lwpid, &wstat, __WCLONE);
1345 } while (res > 0 && WIFSTOPPED (wstat));
1346
1347 /* Even if it was stopped, the child may have already disappeared.
1348 E.g., if it was killed by SIGKILL. */
1349 if (res < 0 && errno != ECHILD)
1350 perror_with_name ("kill_wait_lwp");
1351 }
1352
1353 /* Callback for `for_each_thread'. Kills an lwp of a given process,
1354 except the leader. */
1355
1356 static void
1357 kill_one_lwp_callback (thread_info *thread, int pid)
1358 {
1359 struct lwp_info *lwp = get_thread_lwp (thread);
1360
1361 /* We avoid killing the first thread here, because of a Linux kernel (at
1362 least 2.6.0-test7 through 2.6.8-rc4) bug; if we kill the parent before
1363 the children get a chance to be reaped, it will remain a zombie
1364 forever. */
1365
1366 if (thread->id.lwp () == pid)
1367 {
1368 threads_debug_printf ("is last of process %s",
1369 target_pid_to_str (thread->id).c_str ());
1370 return;
1371 }
1372
1373 kill_wait_lwp (lwp);
1374 }
1375
1376 int
1377 linux_process_target::kill (process_info *process)
1378 {
1379 int pid = process->pid;
1380
1381 /* If we're killing a running inferior, make sure it is stopped
1382 first, as PTRACE_KILL will not work otherwise. */
1383 stop_all_lwps (0, NULL);
1384
1385 process->for_each_thread ([&] (thread_info *thread)
1386 {
1387 kill_one_lwp_callback (thread, pid);
1388 });
1389
1390 /* See the comment in linux_kill_one_lwp. We did not kill the first
1391 thread in the list, so do so now. */
1392 lwp_info *lwp = find_lwp_pid (ptid_t (pid));
1393
1394 if (lwp == NULL)
1395 threads_debug_printf ("cannot find lwp for pid: %d", pid);
1396 else
1397 kill_wait_lwp (lwp);
1398
1399 mourn (process);
1400
1401 /* Since we presently can only stop all lwps of all processes, we
1402 need to unstop lwps of other processes. */
1403 unstop_all_lwps (0, NULL);
1404 return 0;
1405 }
1406
1407 /* Get pending signal of THREAD, for detaching purposes. This is the
1408 signal the thread last stopped for, which we need to deliver to the
1409 thread when detaching, otherwise, it'd be suppressed/lost. */
1410
1411 static int
1412 get_detach_signal (thread_info *thread)
1413 {
1414 client_state &cs = get_client_state ();
1415 enum gdb_signal signo = GDB_SIGNAL_0;
1416 int status;
1417 struct lwp_info *lp = get_thread_lwp (thread);
1418
1419 if (lp->status_pending_p)
1420 status = lp->status_pending;
1421 else
1422 {
1423 /* If the thread had been suspended by gdbserver, and it stopped
1424 cleanly, then it'll have stopped with SIGSTOP. But we don't
1425 want to deliver that SIGSTOP. */
1426 if (thread->last_status.kind () != TARGET_WAITKIND_STOPPED
1427 || thread->last_status.sig () == GDB_SIGNAL_0)
1428 return 0;
1429
1430 /* Otherwise, we may need to deliver the signal we
1431 intercepted. */
1432 status = lp->last_status;
1433 }
1434
1435 if (!WIFSTOPPED (status))
1436 {
1437 threads_debug_printf ("lwp %s hasn't stopped: no pending signal",
1438 target_pid_to_str (thread->id).c_str ());
1439 return 0;
1440 }
1441
1442 /* Extended wait statuses aren't real SIGTRAPs. */
1443 if (WSTOPSIG (status) == SIGTRAP && linux_is_extended_waitstatus (status))
1444 {
1445 threads_debug_printf ("lwp %s had stopped with extended "
1446 "status: no pending signal",
1447 target_pid_to_str (thread->id).c_str ());
1448 return 0;
1449 }
1450
1451 signo = gdb_signal_from_host (WSTOPSIG (status));
1452
1453 if (cs.program_signals_p && !cs.program_signals[signo])
1454 {
1455 threads_debug_printf ("lwp %s had signal %s, but it is in nopass state",
1456 target_pid_to_str (thread->id).c_str (),
1457 gdb_signal_to_string (signo));
1458 return 0;
1459 }
1460 else if (!cs.program_signals_p
1461 /* If we have no way to know which signals GDB does not
1462 want to have passed to the program, assume
1463 SIGTRAP/SIGINT, which is GDB's default. */
1464 && (signo == GDB_SIGNAL_TRAP || signo == GDB_SIGNAL_INT))
1465 {
1466 threads_debug_printf ("lwp %s had signal %s, "
1467 "but we don't know if we should pass it. "
1468 "Default to not.",
1469 target_pid_to_str (thread->id).c_str (),
1470 gdb_signal_to_string (signo));
1471 return 0;
1472 }
1473 else
1474 {
1475 threads_debug_printf ("lwp %s has pending signal %s: delivering it",
1476 target_pid_to_str (thread->id).c_str (),
1477 gdb_signal_to_string (signo));
1478
1479 return WSTOPSIG (status);
1480 }
1481 }
1482
1483 void
1484 linux_process_target::detach_one_lwp (lwp_info *lwp)
1485 {
1486 thread_info *thread = lwp->thread;
1487 int sig;
1488
1489 /* If there is a pending SIGSTOP, get rid of it. */
1490 if (lwp->stop_expected)
1491 {
1492 threads_debug_printf ("Sending SIGCONT to %s",
1493 target_pid_to_str (thread->id).c_str ());
1494
1495 kill_lwp (thread->id.lwp (), SIGCONT);
1496 lwp->stop_expected = 0;
1497 }
1498
1499 /* Pass on any pending signal for this thread. */
1500 sig = get_detach_signal (thread);
1501
1502 /* Preparing to resume may try to write registers, and fail if the
1503 lwp is zombie. If that happens, ignore the error. We'll handle
1504 it below, when detach fails with ESRCH. */
1505 try
1506 {
1507 /* Flush any pending changes to the process's registers. */
1508 regcache_invalidate_thread (thread);
1509
1510 /* Finally, let it resume. */
1511 low_prepare_to_resume (lwp);
1512 }
1513 catch (const gdb_exception_error &ex)
1514 {
1515 if (!check_ptrace_stopped_lwp_gone (lwp))
1516 throw;
1517 }
1518
1519 int lwpid = thread->id.lwp ();
1520 if (ptrace (PTRACE_DETACH, lwpid, (PTRACE_TYPE_ARG3) 0,
1521 (PTRACE_TYPE_ARG4) (long) sig) < 0)
1522 {
1523 int save_errno = errno;
1524
1525 /* We know the thread exists, so ESRCH must mean the lwp is
1526 zombie. This can happen if one of the already-detached
1527 threads exits the whole thread group. In that case we're
1528 still attached, and must reap the lwp. */
1529 if (save_errno == ESRCH)
1530 {
1531 int ret, status;
1532
1533 ret = my_waitpid (lwpid, &status, __WALL);
1534 if (ret == -1)
1535 {
1536 warning (_("Couldn't reap LWP %d while detaching: %s"),
1537 lwpid, safe_strerror (errno));
1538 }
1539 else if (!WIFEXITED (status) && !WIFSIGNALED (status))
1540 {
1541 warning (_("Reaping LWP %d while detaching "
1542 "returned unexpected status 0x%x"),
1543 lwpid, status);
1544 }
1545 }
1546 else
1547 {
1548 error (_("Can't detach %s: %s"),
1549 target_pid_to_str (thread->id).c_str (),
1550 safe_strerror (save_errno));
1551 }
1552 }
1553 else
1554 threads_debug_printf ("PTRACE_DETACH (%s, %s, 0) (OK)",
1555 target_pid_to_str (thread->id).c_str (),
1556 strsignal (sig));
1557
1558 delete_lwp (lwp);
1559 }
1560
1561 int
1562 linux_process_target::detach (process_info *process)
1563 {
1564 struct lwp_info *main_lwp;
1565
1566 /* As there's a step over already in progress, let it finish first,
1567 otherwise nesting a stabilize_threads operation on top gets real
1568 messy. */
1569 complete_ongoing_step_over ();
1570
1571 /* Stop all threads before detaching. First, ptrace requires that
1572 the thread is stopped to successfully detach. Second, thread_db
1573 may need to uninstall thread event breakpoints from memory, which
1574 only works with a stopped process anyway. */
1575 stop_all_lwps (0, NULL);
1576
1577 #ifdef USE_THREAD_DB
1578 thread_db_detach (process);
1579 #endif
1580
1581 /* Stabilize threads (move out of jump pads). */
1582 target_stabilize_threads ();
1583
1584 /* Detach from the clone lwps first. If the thread group exits just
1585 while we're detaching, we must reap the clone lwps before we're
1586 able to reap the leader. */
1587 process->for_each_thread ([this] (thread_info *thread)
1588 {
1589 /* We don't actually detach from the thread group leader just yet.
1590 If the thread group exits, we must reap the zombie clone lwps
1591 before we're able to reap the leader. */
1592 if (thread->id.pid () == thread->id.lwp ())
1593 return;
1594
1595 lwp_info *lwp = get_thread_lwp (thread);
1596 detach_one_lwp (lwp);
1597 });
1598
1599 main_lwp = find_lwp_pid (ptid_t (process->pid));
1600 gdb_assert (main_lwp != nullptr);
1601 detach_one_lwp (main_lwp);
1602
1603 mourn (process);
1604
1605 /* Since we presently can only stop all lwps of all processes, we
1606 need to unstop lwps of other processes. */
1607 unstop_all_lwps (0, NULL);
1608 return 0;
1609 }
1610
1611 /* Remove all LWPs that belong to process PROC from the lwp list. */
1612
1613 void
1614 linux_process_target::mourn (process_info *process)
1615 {
1616 #ifdef USE_THREAD_DB
1617 thread_db_mourn (process);
1618 #endif
1619
1620 process->for_each_thread ([this] (thread_info *thread)
1621 {
1622 delete_lwp (get_thread_lwp (thread));
1623 });
1624
1625 this->remove_linux_process (process);
1626 }
1627
1628 void
1629 linux_process_target::join (int pid)
1630 {
1631 int status, ret;
1632
1633 do {
1634 ret = my_waitpid (pid, &status, 0);
1635 if (WIFEXITED (status) || WIFSIGNALED (status))
1636 break;
1637 } while (ret != -1 || errno != ECHILD);
1638 }
1639
1640 /* Return true if the given thread is still alive. */
1641
1642 bool
1643 linux_process_target::thread_alive (ptid_t ptid)
1644 {
1645 struct lwp_info *lwp = find_lwp_pid (ptid);
1646
1647 /* We assume we always know if a thread exits. If a whole process
1648 exited but we still haven't been able to report it to GDB, we'll
1649 hold on to the last lwp of the dead process. */
1650 if (lwp != NULL)
1651 return !lwp_is_marked_dead (lwp);
1652 else
1653 return 0;
1654 }
1655
1656 bool
1657 linux_process_target::thread_still_has_status_pending (thread_info *thread)
1658 {
1659 struct lwp_info *lp = get_thread_lwp (thread);
1660
1661 if (!lp->status_pending_p)
1662 return 0;
1663
1664 if (thread->last_resume_kind != resume_stop
1665 && (lp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
1666 || lp->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT))
1667 {
1668 CORE_ADDR pc;
1669 int discard = 0;
1670
1671 gdb_assert (lp->last_status != 0);
1672
1673 pc = get_pc (lp);
1674
1675 scoped_restore_current_thread restore_thread;
1676 switch_to_thread (thread);
1677
1678 if (pc != lp->stop_pc)
1679 {
1680 threads_debug_printf ("PC of %ld changed",
1681 thread->id.lwp ());
1682 discard = 1;
1683 }
1684
1685 if (discard)
1686 {
1687 threads_debug_printf ("discarding pending breakpoint status");
1688 lp->status_pending_p = 0;
1689 return 0;
1690 }
1691 }
1692
1693 return 1;
1694 }
1695
1696 /* Returns true if LWP is resumed from the client's perspective. */
1697
1698 static int
1699 lwp_resumed (struct lwp_info *lwp)
1700 {
1701 thread_info *thread = lwp->thread;
1702
1703 if (thread->last_resume_kind != resume_stop)
1704 return 1;
1705
1706 /* Did gdb send us a `vCont;t', but we haven't reported the
1707 corresponding stop to gdb yet? If so, the thread is still
1708 resumed/running from gdb's perspective. */
1709 if (thread->last_resume_kind == resume_stop
1710 && thread->last_status.kind () == TARGET_WAITKIND_IGNORE)
1711 return 1;
1712
1713 return 0;
1714 }
1715
1716 bool
1717 linux_process_target::status_pending_p_callback (thread_info *thread,
1718 ptid_t ptid)
1719 {
1720 struct lwp_info *lp = get_thread_lwp (thread);
1721
1722 /* Check if we're only interested in events from a specific process
1723 or a specific LWP. */
1724 if (!thread->id.matches (ptid))
1725 return 0;
1726
1727 if (!lwp_resumed (lp))
1728 return 0;
1729
1730 if (lp->status_pending_p
1731 && !thread_still_has_status_pending (thread))
1732 {
1733 resume_one_lwp (lp, lp->stepping, GDB_SIGNAL_0, NULL);
1734 return 0;
1735 }
1736
1737 return lp->status_pending_p;
1738 }
1739
1740 struct lwp_info *
1741 find_lwp_pid (ptid_t ptid)
1742 {
1743 long lwp = ptid.lwp () != 0 ? ptid.lwp () : ptid.pid ();
1744 thread_info *thread = find_thread ([lwp] (thread_info *thr_arg)
1745 {
1746 return thr_arg->id.lwp () == lwp;
1747 });
1748
1749 if (thread == NULL)
1750 return NULL;
1751
1752 return get_thread_lwp (thread);
1753 }
1754
1755 /* Return the number of known LWPs in PROCESS. */
1756
1757 static int
1758 num_lwps (process_info *process)
1759 {
1760 int count = 0;
1761
1762 process->for_each_thread ([&] (thread_info *thread)
1763 {
1764 count++;
1765 });
1766
1767 return count;
1768 }
1769
1770 /* See nat/linux-nat.h. */
1771
1772 struct lwp_info *
1773 iterate_over_lwps (ptid_t filter,
1774 gdb::function_view<iterate_over_lwps_ftype> callback)
1775 {
1776 thread_info *thread = find_thread (filter, [&] (thread_info *thr_arg)
1777 {
1778 lwp_info *lwp = get_thread_lwp (thr_arg);
1779
1780 return callback (lwp);
1781 });
1782
1783 if (thread == NULL)
1784 return NULL;
1785
1786 return get_thread_lwp (thread);
1787 }
1788
1789 bool
1790 linux_process_target::check_zombie_leaders ()
1791 {
1792 bool new_pending_event = false;
1793
1794 for_each_process ([&] (process_info *proc)
1795 {
1796 pid_t leader_pid = proc->pid;
1797 lwp_info *leader_lp = find_lwp_pid (ptid_t (leader_pid));
1798
1799 threads_debug_printf ("leader_pid=%d, leader_lp!=NULL=%d, "
1800 "num_lwps=%d, zombie=%d",
1801 leader_pid, leader_lp!= NULL, num_lwps (proc),
1802 linux_proc_pid_is_zombie (leader_pid));
1803
1804 if (leader_lp != NULL && !leader_lp->stopped
1805 /* Check if there are other threads in the group, as we may
1806 have raced with the inferior simply exiting. Note this
1807 isn't a watertight check. If the inferior is
1808 multi-threaded and is exiting, it may be we see the
1809 leader as zombie before we reap all the non-leader
1810 threads. See comments below. */
1811 && !last_thread_of_process_p (leader_pid)
1812 && linux_proc_pid_is_zombie (leader_pid))
1813 {
1814 /* A zombie leader in a multi-threaded program can mean one
1815 of three things:
1816
1817 #1 - Only the leader exited, not the whole program, e.g.,
1818 with pthread_exit. Since we can't reap the leader's exit
1819 status until all other threads are gone and reaped too,
1820 we want to delete the zombie leader right away, as it
1821 can't be debugged, we can't read its registers, etc.
1822 This is the main reason we check for zombie leaders
1823 disappearing.
1824
1825 #2 - The whole thread-group/process exited (a group exit,
1826 via e.g. exit(3), and there is (or will be shortly) an
1827 exit reported for each thread in the process, and then
1828 finally an exit for the leader once the non-leaders are
1829 reaped.
1830
1831 #3 - There are 3 or more threads in the group, and a
1832 thread other than the leader exec'd. See comments on
1833 exec events at the top of the file.
1834
1835 Ideally we would never delete the leader for case #2.
1836 Instead, we want to collect the exit status of each
1837 non-leader thread, and then finally collect the exit
1838 status of the leader as normal and use its exit code as
1839 whole-process exit code. Unfortunately, there's no
1840 race-free way to distinguish cases #1 and #2. We can't
1841 assume the exit events for the non-leaders threads are
1842 already pending in the kernel, nor can we assume the
1843 non-leader threads are in zombie state already. Between
1844 the leader becoming zombie and the non-leaders exiting
1845 and becoming zombie themselves, there's a small time
1846 window, so such a check would be racy. Temporarily
1847 pausing all threads and checking to see if all threads
1848 exit or not before re-resuming them would work in the
1849 case that all threads are running right now, but it
1850 wouldn't work if some thread is currently already
1851 ptrace-stopped, e.g., due to scheduler-locking.
1852
1853 So what we do is we delete the leader anyhow, and then
1854 later on when we see its exit status, we re-add it back.
1855 We also make sure that we only report a whole-process
1856 exit when we see the leader exiting, as opposed to when
1857 the last LWP in the LWP list exits, which can be a
1858 non-leader if we deleted the leader here. */
1859 threads_debug_printf ("Thread group leader %d zombie "
1860 "(it exited, or another thread execd), "
1861 "deleting it.",
1862 leader_pid);
1863
1864 thread_info *leader_thread = leader_lp->thread;
1865 if (report_exit_events_for (leader_thread))
1866 {
1867 mark_lwp_dead (leader_lp, W_EXITCODE (0, 0), true);
1868 new_pending_event = true;
1869 }
1870 else
1871 delete_lwp (leader_lp);
1872 }
1873 });
1874
1875 return new_pending_event;
1876 }
1877
1878 /* Callback for `find_thread'. Returns the first LWP that is not
1879 stopped. */
1880
1881 static bool
1882 not_stopped_callback (thread_info *thread, ptid_t filter)
1883 {
1884 if (!thread->id.matches (filter))
1885 return false;
1886
1887 lwp_info *lwp = get_thread_lwp (thread);
1888
1889 return !lwp->stopped;
1890 }
1891
1892 /* Increment LWP's suspend count. */
1893
1894 static void
1895 lwp_suspended_inc (struct lwp_info *lwp)
1896 {
1897 lwp->suspended++;
1898
1899 if (lwp->suspended > 4)
1900 threads_debug_printf
1901 ("LWP %ld has a suspiciously high suspend count, suspended=%d",
1902 lwp->thread->id.lwp (), lwp->suspended);
1903 }
1904
1905 /* Decrement LWP's suspend count. */
1906
1907 static void
1908 lwp_suspended_decr (struct lwp_info *lwp)
1909 {
1910 lwp->suspended--;
1911
1912 if (lwp->suspended < 0)
1913 {
1914 thread_info *thread = lwp->thread;
1915
1916 internal_error ("unsuspend LWP %ld, suspended=%d\n", thread->id.lwp (),
1917 lwp->suspended);
1918 }
1919 }
1920
1921 /* This function should only be called if the LWP got a SIGTRAP.
1922
1923 Handle any tracepoint steps or hits. Return true if a tracepoint
1924 event was handled, 0 otherwise. */
1925
1926 static int
1927 handle_tracepoints (struct lwp_info *lwp)
1928 {
1929 thread_info *tinfo = lwp->thread;
1930 int tpoint_related_event = 0;
1931
1932 gdb_assert (lwp->suspended == 0);
1933
1934 /* If this tracepoint hit causes a tracing stop, we'll immediately
1935 uninsert tracepoints. To do this, we temporarily pause all
1936 threads, unpatch away, and then unpause threads. We need to make
1937 sure the unpausing doesn't resume LWP too. */
1938 lwp_suspended_inc (lwp);
1939
1940 /* And we need to be sure that any all-threads-stopping doesn't try
1941 to move threads out of the jump pads, as it could deadlock the
1942 inferior (LWP could be in the jump pad, maybe even holding the
1943 lock.) */
1944
1945 /* Do any necessary step collect actions. */
1946 tpoint_related_event |= tracepoint_finished_step (tinfo, lwp->stop_pc);
1947
1948 tpoint_related_event |= handle_tracepoint_bkpts (tinfo, lwp->stop_pc);
1949
1950 /* See if we just hit a tracepoint and do its main collect
1951 actions. */
1952 tpoint_related_event |= tracepoint_was_hit (tinfo, lwp->stop_pc);
1953
1954 lwp_suspended_decr (lwp);
1955
1956 gdb_assert (lwp->suspended == 0);
1957 gdb_assert (!stabilizing_threads
1958 || (lwp->collecting_fast_tracepoint
1959 != fast_tpoint_collect_result::not_collecting));
1960
1961 if (tpoint_related_event)
1962 {
1963 threads_debug_printf ("got a tracepoint event");
1964 return 1;
1965 }
1966
1967 return 0;
1968 }
1969
1970 fast_tpoint_collect_result
1971 linux_process_target::linux_fast_tracepoint_collecting
1972 (lwp_info *lwp, fast_tpoint_collect_status *status)
1973 {
1974 CORE_ADDR thread_area;
1975 thread_info *thread = lwp->thread;
1976
1977 /* Get the thread area address. This is used to recognize which
1978 thread is which when tracing with the in-process agent library.
1979 We don't read anything from the address, and treat it as opaque;
1980 it's the address itself that we assume is unique per-thread. */
1981 if (low_get_thread_area (thread->id.lwp (), &thread_area) == -1)
1982 return fast_tpoint_collect_result::not_collecting;
1983
1984 return fast_tracepoint_collecting (thread_area, lwp->stop_pc, status);
1985 }
1986
1987 int
1988 linux_process_target::low_get_thread_area (int lwpid, CORE_ADDR *addrp)
1989 {
1990 return -1;
1991 }
1992
1993 bool
1994 linux_process_target::maybe_move_out_of_jump_pad (lwp_info *lwp, int *wstat)
1995 {
1996 scoped_restore_current_thread restore_thread;
1997 switch_to_thread (lwp->thread);
1998
1999 if ((wstat == NULL
2000 || (WIFSTOPPED (*wstat) && WSTOPSIG (*wstat) != SIGTRAP))
2001 && supports_fast_tracepoints ()
2002 && agent_loaded_p ())
2003 {
2004 struct fast_tpoint_collect_status status;
2005
2006 threads_debug_printf
2007 ("Checking whether LWP %ld needs to move out of the jump pad.",
2008 current_thread->id.lwp ());
2009
2010 fast_tpoint_collect_result r
2011 = linux_fast_tracepoint_collecting (lwp, &status);
2012
2013 if (wstat == NULL
2014 || (WSTOPSIG (*wstat) != SIGILL
2015 && WSTOPSIG (*wstat) != SIGFPE
2016 && WSTOPSIG (*wstat) != SIGSEGV
2017 && WSTOPSIG (*wstat) != SIGBUS))
2018 {
2019 lwp->collecting_fast_tracepoint = r;
2020
2021 if (r != fast_tpoint_collect_result::not_collecting)
2022 {
2023 if (r == fast_tpoint_collect_result::before_insn
2024 && lwp->exit_jump_pad_bkpt == NULL)
2025 {
2026 /* Haven't executed the original instruction yet.
2027 Set breakpoint there, and wait till it's hit,
2028 then single-step until exiting the jump pad. */
2029 lwp->exit_jump_pad_bkpt
2030 = set_breakpoint_at (status.adjusted_insn_addr, NULL);
2031 }
2032
2033 threads_debug_printf
2034 ("Checking whether LWP %ld needs to move out of the jump pad..."
2035 " it does", current_thread->id.lwp ());
2036
2037 return true;
2038 }
2039 }
2040 else
2041 {
2042 /* If we get a synchronous signal while collecting, *and*
2043 while executing the (relocated) original instruction,
2044 reset the PC to point at the tpoint address, before
2045 reporting to GDB. Otherwise, it's an IPA lib bug: just
2046 report the signal to GDB, and pray for the best. */
2047
2048 lwp->collecting_fast_tracepoint
2049 = fast_tpoint_collect_result::not_collecting;
2050
2051 if (r != fast_tpoint_collect_result::not_collecting
2052 && (status.adjusted_insn_addr <= lwp->stop_pc
2053 && lwp->stop_pc < status.adjusted_insn_addr_end))
2054 {
2055 siginfo_t info;
2056 struct regcache *regcache;
2057
2058 /* The si_addr on a few signals references the address
2059 of the faulting instruction. Adjust that as
2060 well. */
2061 if ((WSTOPSIG (*wstat) == SIGILL
2062 || WSTOPSIG (*wstat) == SIGFPE
2063 || WSTOPSIG (*wstat) == SIGBUS
2064 || WSTOPSIG (*wstat) == SIGSEGV)
2065 && ptrace (PTRACE_GETSIGINFO, current_thread->id.lwp (),
2066 (PTRACE_TYPE_ARG3) 0, &info) == 0
2067 /* Final check just to make sure we don't clobber
2068 the siginfo of non-kernel-sent signals. */
2069 && (uintptr_t) info.si_addr == lwp->stop_pc)
2070 {
2071 info.si_addr = (void *) (uintptr_t) status.tpoint_addr;
2072 ptrace (PTRACE_SETSIGINFO, current_thread->id.lwp (),
2073 (PTRACE_TYPE_ARG3) 0, &info);
2074 }
2075
2076 regcache = get_thread_regcache (current_thread);
2077 low_set_pc (regcache, status.tpoint_addr);
2078 lwp->stop_pc = status.tpoint_addr;
2079
2080 /* Cancel any fast tracepoint lock this thread was
2081 holding. */
2082 force_unlock_trace_buffer ();
2083 }
2084
2085 if (lwp->exit_jump_pad_bkpt != NULL)
2086 {
2087 threads_debug_printf
2088 ("Cancelling fast exit-jump-pad: removing bkpt."
2089 "stopping all threads momentarily.");
2090
2091 stop_all_lwps (1, lwp);
2092
2093 delete_breakpoint (lwp->exit_jump_pad_bkpt);
2094 lwp->exit_jump_pad_bkpt = NULL;
2095
2096 unstop_all_lwps (1, lwp);
2097
2098 gdb_assert (lwp->suspended >= 0);
2099 }
2100 }
2101 }
2102
2103 threads_debug_printf
2104 ("Checking whether LWP %ld needs to move out of the jump pad... no",
2105 current_thread->id.lwp ());
2106
2107 return false;
2108 }
2109
2110 /* Enqueue one signal in the "signals to report later when out of the
2111 jump pad" list. */
2112
2113 static void
2114 enqueue_one_deferred_signal (struct lwp_info *lwp, int *wstat)
2115 {
2116 thread_info *thread = lwp->thread;
2117
2118 threads_debug_printf ("Deferring signal %d for LWP %ld.",
2119 WSTOPSIG (*wstat), thread->id.lwp ());
2120
2121 if (debug_threads)
2122 {
2123 for (const auto &sig : lwp->pending_signals_to_report)
2124 threads_debug_printf (" Already queued %d", sig.signal);
2125
2126 threads_debug_printf (" (no more currently queued signals)");
2127 }
2128
2129 /* Don't enqueue non-RT signals if they are already in the deferred
2130 queue. (SIGSTOP being the easiest signal to see ending up here
2131 twice) */
2132 if (WSTOPSIG (*wstat) < __SIGRTMIN)
2133 {
2134 for (const auto &sig : lwp->pending_signals_to_report)
2135 {
2136 if (sig.signal == WSTOPSIG (*wstat))
2137 {
2138 threads_debug_printf
2139 ("Not requeuing already queued non-RT signal %d for LWP %ld",
2140 sig.signal, thread->id.lwp ());
2141 return;
2142 }
2143 }
2144 }
2145
2146 lwp->pending_signals_to_report.emplace_back (WSTOPSIG (*wstat));
2147
2148 ptrace (PTRACE_GETSIGINFO, thread->id.lwp (), (PTRACE_TYPE_ARG3) 0,
2149 &lwp->pending_signals_to_report.back ().info);
2150 }
2151
2152 /* Dequeue one signal from the "signals to report later when out of
2153 the jump pad" list. */
2154
2155 static int
2156 dequeue_one_deferred_signal (struct lwp_info *lwp, int *wstat)
2157 {
2158 thread_info *thread = lwp->thread;
2159
2160 if (!lwp->pending_signals_to_report.empty ())
2161 {
2162 const pending_signal &p_sig = lwp->pending_signals_to_report.front ();
2163
2164 *wstat = W_STOPCODE (p_sig.signal);
2165 if (p_sig.info.si_signo != 0)
2166 ptrace (PTRACE_SETSIGINFO, thread->id.lwp (), (PTRACE_TYPE_ARG3) 0,
2167 &p_sig.info);
2168
2169 lwp->pending_signals_to_report.pop_front ();
2170
2171 threads_debug_printf ("Reporting deferred signal %d for LWP %ld.",
2172 WSTOPSIG (*wstat), thread->id.lwp ());
2173
2174 if (debug_threads)
2175 {
2176 for (const auto &sig : lwp->pending_signals_to_report)
2177 threads_debug_printf (" Still queued %d", sig.signal);
2178
2179 threads_debug_printf (" (no more queued signals)");
2180 }
2181
2182 return 1;
2183 }
2184
2185 return 0;
2186 }
2187
2188 bool
2189 linux_process_target::check_stopped_by_watchpoint (lwp_info *child)
2190 {
2191 scoped_restore_current_thread restore_thread;
2192 switch_to_thread (child->thread);
2193
2194 if (low_stopped_by_watchpoint ())
2195 {
2196 child->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
2197 child->stopped_data_address = low_stopped_data_address ();
2198 }
2199
2200 return child->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
2201 }
2202
2203 bool
2204 linux_process_target::low_stopped_by_watchpoint ()
2205 {
2206 return false;
2207 }
2208
2209 CORE_ADDR
2210 linux_process_target::low_stopped_data_address ()
2211 {
2212 return 0;
2213 }
2214
2215 /* Return the ptrace options that we want to try to enable. */
2216
2217 static int
2218 linux_low_ptrace_options (int attached)
2219 {
2220 client_state &cs = get_client_state ();
2221 int options = 0;
2222
2223 if (!attached)
2224 options |= PTRACE_O_EXITKILL;
2225
2226 if (cs.report_fork_events)
2227 options |= PTRACE_O_TRACEFORK;
2228
2229 if (cs.report_vfork_events)
2230 options |= (PTRACE_O_TRACEVFORK | PTRACE_O_TRACEVFORKDONE);
2231
2232 if (cs.report_exec_events)
2233 options |= PTRACE_O_TRACEEXEC;
2234
2235 options |= PTRACE_O_TRACESYSGOOD;
2236
2237 return options;
2238 }
2239
2240 void
2241 linux_process_target::filter_event (int lwpid, int wstat)
2242 {
2243 struct lwp_info *child;
2244 thread_info *thread;
2245 int have_stop_pc = 0;
2246
2247 child = find_lwp_pid (ptid_t (lwpid));
2248
2249 /* Check for events reported by anything not in our LWP list. */
2250 if (child == nullptr)
2251 {
2252 if (WIFSTOPPED (wstat))
2253 {
2254 if (WSTOPSIG (wstat) == SIGTRAP
2255 && linux_ptrace_get_extended_event (wstat) == PTRACE_EVENT_EXEC)
2256 {
2257 /* A non-leader thread exec'ed after we've seen the
2258 leader zombie, and removed it from our lists (in
2259 check_zombie_leaders). The non-leader thread changes
2260 its tid to the tgid. */
2261 threads_debug_printf
2262 ("Re-adding thread group leader LWP %d after exec.",
2263 lwpid);
2264
2265 child = add_lwp (ptid_t (lwpid, lwpid));
2266 child->stopped = 1;
2267 switch_to_thread (child->thread);
2268 }
2269 else
2270 {
2271 /* A process we are controlling has forked and the new
2272 child's stop was reported to us by the kernel. Save
2273 its PID and go back to waiting for the fork event to
2274 be reported - the stopped process might be returned
2275 from waitpid before or after the fork event is. */
2276 threads_debug_printf
2277 ("Saving LWP %d status %s in stopped_pids list",
2278 lwpid, status_to_str (wstat).c_str ());
2279 add_to_pid_list (&stopped_pids, lwpid, wstat);
2280 }
2281 }
2282 else
2283 {
2284 /* Don't report an event for the exit of an LWP not in our
2285 list, i.e. not part of any inferior we're debugging.
2286 This can happen if we detach from a program we originally
2287 forked and then it exits. However, note that we may have
2288 earlier deleted a leader of an inferior we're debugging,
2289 in check_zombie_leaders. Re-add it back here if so. */
2290 find_process ([&] (process_info *proc)
2291 {
2292 if (proc->pid == lwpid)
2293 {
2294 threads_debug_printf
2295 ("Re-adding thread group leader LWP %d after exit.",
2296 lwpid);
2297
2298 child = add_lwp (ptid_t (lwpid, lwpid));
2299 return true;
2300 }
2301 return false;
2302 });
2303 }
2304
2305 if (child == nullptr)
2306 return;
2307 }
2308
2309 thread = child->thread;
2310
2311 child->stopped = 1;
2312
2313 child->last_status = wstat;
2314
2315 /* Check if the thread has exited. */
2316 if ((WIFEXITED (wstat) || WIFSIGNALED (wstat)))
2317 {
2318 threads_debug_printf ("%d exited", lwpid);
2319
2320 if (finish_step_over (child))
2321 {
2322 /* Unsuspend all other LWPs, and set them back running again. */
2323 unsuspend_all_lwps (child);
2324 }
2325
2326 /* If this is not the leader LWP, then the exit signal was not
2327 the end of the debugged application and should be ignored,
2328 unless GDB wants to hear about thread exits. */
2329 if (report_exit_events_for (thread) || is_leader (thread))
2330 {
2331 /* Since events are serialized to GDB core, and we can't
2332 report this one right now. Leave the status pending for
2333 the next time we're able to report it. */
2334 mark_lwp_dead (child, wstat, false);
2335 return;
2336 }
2337 else
2338 {
2339 delete_lwp (child);
2340 return;
2341 }
2342 }
2343
2344 gdb_assert (WIFSTOPPED (wstat));
2345
2346 if (WIFSTOPPED (wstat))
2347 {
2348 /* Architecture-specific setup after inferior is running. */
2349 process_info *proc = find_process_pid (thread->id.pid ());
2350
2351 if (proc->tdesc == NULL)
2352 {
2353 if (proc->attached)
2354 {
2355 /* This needs to happen after we have attached to the
2356 inferior and it is stopped for the first time, but
2357 before we access any inferior registers. */
2358 arch_setup_thread (thread);
2359 }
2360 else
2361 {
2362 /* The process is started, but GDBserver will do
2363 architecture-specific setup after the program stops at
2364 the first instruction. */
2365 child->status_pending_p = 1;
2366 child->status_pending = wstat;
2367 return;
2368 }
2369 }
2370 }
2371
2372 if (WIFSTOPPED (wstat) && child->must_set_ptrace_flags)
2373 {
2374 process_info *proc = find_process_pid (thread->id.pid ());
2375 int options = linux_low_ptrace_options (proc->attached);
2376
2377 linux_enable_event_reporting (lwpid, options);
2378 child->must_set_ptrace_flags = 0;
2379 }
2380
2381 /* Always update syscall_state, even if it will be filtered later. */
2382 if (WIFSTOPPED (wstat) && WSTOPSIG (wstat) == SYSCALL_SIGTRAP)
2383 {
2384 child->syscall_state
2385 = (child->syscall_state == TARGET_WAITKIND_SYSCALL_ENTRY
2386 ? TARGET_WAITKIND_SYSCALL_RETURN
2387 : TARGET_WAITKIND_SYSCALL_ENTRY);
2388 }
2389 else
2390 {
2391 /* Almost all other ptrace-stops are known to be outside of system
2392 calls, with further exceptions in handle_extended_wait. */
2393 child->syscall_state = TARGET_WAITKIND_IGNORE;
2394 }
2395
2396 /* Be careful to not overwrite stop_pc until save_stop_reason is
2397 called. */
2398 if (WIFSTOPPED (wstat) && WSTOPSIG (wstat) == SIGTRAP
2399 && linux_is_extended_waitstatus (wstat))
2400 {
2401 child->stop_pc = get_pc (child);
2402 if (handle_extended_wait (&child, wstat))
2403 {
2404 /* The event has been handled, so just return without
2405 reporting it. */
2406 return;
2407 }
2408 }
2409
2410 if (linux_wstatus_maybe_breakpoint (wstat))
2411 {
2412 if (save_stop_reason (child))
2413 have_stop_pc = 1;
2414 }
2415
2416 if (!have_stop_pc)
2417 child->stop_pc = get_pc (child);
2418
2419 if (WIFSTOPPED (wstat) && WSTOPSIG (wstat) == SIGSTOP
2420 && child->stop_expected)
2421 {
2422 threads_debug_printf ("Expected stop.");
2423
2424 child->stop_expected = 0;
2425
2426 if (thread->last_resume_kind == resume_stop)
2427 {
2428 /* We want to report the stop to the core. Treat the
2429 SIGSTOP as a normal event. */
2430 threads_debug_printf ("resume_stop SIGSTOP caught for %s.",
2431 target_pid_to_str (thread->id).c_str ());
2432 }
2433 else if (stopping_threads != NOT_STOPPING_THREADS)
2434 {
2435 /* Stopping threads. We don't want this SIGSTOP to end up
2436 pending. */
2437 threads_debug_printf ("SIGSTOP caught for %s while stopping threads.",
2438 target_pid_to_str (thread->id).c_str ());
2439 return;
2440 }
2441 else
2442 {
2443 /* This is a delayed SIGSTOP. Filter out the event. */
2444 threads_debug_printf ("%s %s, 0, 0 (discard delayed SIGSTOP)",
2445 child->stepping ? "step" : "continue",
2446 target_pid_to_str (thread->id).c_str ());
2447
2448 resume_one_lwp (child, child->stepping, 0, NULL);
2449 return;
2450 }
2451 }
2452
2453 child->status_pending_p = 1;
2454 child->status_pending = wstat;
2455 return;
2456 }
2457
2458 bool
2459 linux_process_target::maybe_hw_step (thread_info *thread)
2460 {
2461 if (supports_hardware_single_step ())
2462 return true;
2463 else
2464 {
2465 /* GDBserver must insert single-step breakpoint for software
2466 single step. */
2467 gdb_assert (has_single_step_breakpoints (thread));
2468 return false;
2469 }
2470 }
2471
2472 void
2473 linux_process_target::resume_stopped_resumed_lwps (thread_info *thread)
2474 {
2475 struct lwp_info *lp = get_thread_lwp (thread);
2476
2477 if (lp->stopped
2478 && !lp->suspended
2479 && !lp->status_pending_p
2480 && thread->last_status.kind () == TARGET_WAITKIND_IGNORE)
2481 {
2482 int step = 0;
2483
2484 if (thread->last_resume_kind == resume_step)
2485 {
2486 if (supports_software_single_step ())
2487 install_software_single_step_breakpoints (lp);
2488
2489 step = maybe_hw_step (thread);
2490 }
2491
2492 threads_debug_printf ("resuming stopped-resumed LWP %s at %s: step=%d",
2493 target_pid_to_str (thread->id).c_str (),
2494 paddress (lp->stop_pc), step);
2495
2496 resume_one_lwp (lp, step, GDB_SIGNAL_0, NULL);
2497 }
2498 }
2499
2500 int
2501 linux_process_target::wait_for_event_filtered (ptid_t wait_ptid,
2502 ptid_t filter_ptid,
2503 int *wstatp, int options)
2504 {
2505 thread_info *event_thread;
2506 struct lwp_info *event_child, *requested_child;
2507 sigset_t block_mask, prev_mask;
2508
2509 retry:
2510 /* N.B. event_thread points to the thread_info struct that contains
2511 event_child. Keep them in sync. */
2512 event_thread = NULL;
2513 event_child = NULL;
2514 requested_child = NULL;
2515
2516 /* Check for a lwp with a pending status. */
2517
2518 if (filter_ptid == minus_one_ptid || filter_ptid.is_pid ())
2519 {
2520 event_thread = find_thread_in_random ([&] (thread_info *thread)
2521 {
2522 return status_pending_p_callback (thread, filter_ptid);
2523 });
2524
2525 if (event_thread != NULL)
2526 {
2527 event_child = get_thread_lwp (event_thread);
2528 threads_debug_printf ("Got a pending child %ld", event_thread->id.lwp ());
2529 }
2530 }
2531 else if (filter_ptid != null_ptid)
2532 {
2533 requested_child = find_lwp_pid (filter_ptid);
2534 gdb_assert (requested_child != nullptr);
2535
2536 if (stopping_threads == NOT_STOPPING_THREADS
2537 && requested_child->status_pending_p
2538 && (requested_child->collecting_fast_tracepoint
2539 != fast_tpoint_collect_result::not_collecting))
2540 {
2541 enqueue_one_deferred_signal (requested_child,
2542 &requested_child->status_pending);
2543 requested_child->status_pending_p = 0;
2544 requested_child->status_pending = 0;
2545 resume_one_lwp (requested_child, 0, 0, NULL);
2546 }
2547
2548 if (requested_child->suspended
2549 && requested_child->status_pending_p)
2550 {
2551 internal_error ("requesting an event out of a"
2552 " suspended child?");
2553 }
2554
2555 if (requested_child->status_pending_p)
2556 {
2557 event_child = requested_child;
2558 event_thread = event_child->thread;
2559 }
2560 }
2561
2562 if (event_child != NULL)
2563 {
2564 threads_debug_printf ("Got an event from pending child %ld (%04x)",
2565 event_thread->id.lwp (),
2566 event_child->status_pending);
2567
2568 *wstatp = event_child->status_pending;
2569 event_child->status_pending_p = 0;
2570 event_child->status_pending = 0;
2571 switch_to_thread (event_thread);
2572 return event_thread->id.lwp ();
2573 }
2574
2575 /* But if we don't find a pending event, we'll have to wait.
2576
2577 We only enter this loop if no process has a pending wait status.
2578 Thus any action taken in response to a wait status inside this
2579 loop is responding as soon as we detect the status, not after any
2580 pending events. */
2581
2582 /* Make sure SIGCHLD is blocked until the sigsuspend below. Block
2583 all signals while here. */
2584 sigfillset (&block_mask);
2585 gdb_sigmask (SIG_BLOCK, &block_mask, &prev_mask);
2586
2587 /* Always pull all events out of the kernel. We'll randomly select
2588 an event LWP out of all that have events, to prevent
2589 starvation. */
2590 while (event_child == NULL)
2591 {
2592 pid_t ret = 0;
2593
2594 /* Always use -1 and WNOHANG, due to couple of a kernel/ptrace
2595 quirks:
2596
2597 - If the thread group leader exits while other threads in the
2598 thread group still exist, waitpid(TGID, ...) hangs. That
2599 waitpid won't return an exit status until the other threads
2600 in the group are reaped.
2601
2602 - When a non-leader thread execs, that thread just vanishes
2603 without reporting an exit (so we'd hang if we waited for it
2604 explicitly in that case). The exec event is reported to
2605 the TGID pid. */
2606 errno = 0;
2607 ret = my_waitpid (-1, wstatp, options | WNOHANG);
2608
2609 threads_debug_printf ("waitpid(-1, ...) returned %d, %s",
2610 ret, errno ? safe_strerror (errno) : "ERRNO-OK");
2611
2612 if (ret > 0)
2613 {
2614 threads_debug_printf ("waitpid %ld received %s",
2615 (long) ret, status_to_str (*wstatp).c_str ());
2616
2617 /* Filter all events. IOW, leave all events pending. We'll
2618 randomly select an event LWP out of all that have events
2619 below. */
2620 filter_event (ret, *wstatp);
2621 /* Retry until nothing comes out of waitpid. A single
2622 SIGCHLD can indicate more than one child stopped. */
2623 continue;
2624 }
2625
2626 /* Now that we've pulled all events out of the kernel, resume
2627 LWPs that don't have an interesting event to report. */
2628 if (stopping_threads == NOT_STOPPING_THREADS)
2629 for_each_thread ([this] (thread_info *thread)
2630 {
2631 resume_stopped_resumed_lwps (thread);
2632 });
2633
2634 /* ... and find an LWP with a status to report to the core, if
2635 any. */
2636 event_thread = find_thread_in_random ([&] (thread_info *thread)
2637 {
2638 return status_pending_p_callback (thread, filter_ptid);
2639 });
2640
2641 if (event_thread != NULL)
2642 {
2643 event_child = get_thread_lwp (event_thread);
2644 *wstatp = event_child->status_pending;
2645 event_child->status_pending_p = 0;
2646 event_child->status_pending = 0;
2647 break;
2648 }
2649
2650 /* Check for zombie thread group leaders. Those can't be reaped
2651 until all other threads in the thread group are. */
2652 if (check_zombie_leaders ())
2653 goto retry;
2654
2655 auto not_stopped = [&] (thread_info *thread)
2656 {
2657 return not_stopped_callback (thread, wait_ptid);
2658 };
2659
2660 /* If there are no resumed children left in the set of LWPs we
2661 want to wait for, bail. We can't just block in
2662 waitpid/sigsuspend, because lwps might have been left stopped
2663 in trace-stop state, and we'd be stuck forever waiting for
2664 their status to change (which would only happen if we resumed
2665 them). Even if WNOHANG is set, this return code is preferred
2666 over 0 (below), as it is more detailed. */
2667 if (find_thread (not_stopped) == NULL)
2668 {
2669 threads_debug_printf ("exit (no unwaited-for LWP)");
2670
2671 gdb_sigmask (SIG_SETMASK, &prev_mask, NULL);
2672 return -1;
2673 }
2674
2675 /* No interesting event to report to the caller. */
2676 if ((options & WNOHANG))
2677 {
2678 threads_debug_printf ("WNOHANG set, no event found");
2679
2680 gdb_sigmask (SIG_SETMASK, &prev_mask, NULL);
2681 return 0;
2682 }
2683
2684 /* Block until we get an event reported with SIGCHLD. */
2685 threads_debug_printf ("sigsuspend'ing");
2686
2687 sigsuspend (&prev_mask);
2688 gdb_sigmask (SIG_SETMASK, &prev_mask, NULL);
2689 goto retry;
2690 }
2691
2692 gdb_sigmask (SIG_SETMASK, &prev_mask, NULL);
2693
2694 switch_to_thread (event_thread);
2695
2696 return event_thread->id.lwp ();
2697 }
2698
2699 int
2700 linux_process_target::wait_for_event (ptid_t ptid, int *wstatp, int options)
2701 {
2702 return wait_for_event_filtered (ptid, ptid, wstatp, options);
2703 }
2704
2705 /* Select one LWP out of those that have events pending. */
2706
2707 static void
2708 select_event_lwp (struct lwp_info **orig_lp)
2709 {
2710 thread_info *event_thread = NULL;
2711
2712 /* In all-stop, give preference to the LWP that is being
2713 single-stepped. There will be at most one, and it's the LWP that
2714 the core is most interested in. If we didn't do this, then we'd
2715 have to handle pending step SIGTRAPs somehow in case the core
2716 later continues the previously-stepped thread, otherwise we'd
2717 report the pending SIGTRAP, and the core, not having stepped the
2718 thread, wouldn't understand what the trap was for, and therefore
2719 would report it to the user as a random signal. */
2720 if (!non_stop)
2721 {
2722 event_thread = find_thread ([] (thread_info *thread)
2723 {
2724 lwp_info *lp = get_thread_lwp (thread);
2725
2726 return (thread->last_status.kind () == TARGET_WAITKIND_IGNORE
2727 && thread->last_resume_kind == resume_step
2728 && lp->status_pending_p);
2729 });
2730
2731 if (event_thread != NULL)
2732 threads_debug_printf
2733 ("Select single-step %s",
2734 target_pid_to_str (event_thread->id).c_str ());
2735 }
2736 if (event_thread == NULL)
2737 {
2738 /* No single-stepping LWP. Select one at random, out of those
2739 which have had events. */
2740
2741 event_thread = find_thread_in_random ([&] (thread_info *thread)
2742 {
2743 lwp_info *lp = get_thread_lwp (thread);
2744
2745 /* Only resumed LWPs that have an event pending. */
2746 return (thread->last_status.kind () == TARGET_WAITKIND_IGNORE
2747 && lp->status_pending_p);
2748 });
2749 }
2750
2751 if (event_thread != NULL)
2752 {
2753 struct lwp_info *event_lp = get_thread_lwp (event_thread);
2754
2755 /* Switch the event LWP. */
2756 *orig_lp = event_lp;
2757 }
2758 }
2759
2760 /* Decrement the suspend count of all LWPs, except EXCEPT, if non
2761 NULL. */
2762
2763 static void
2764 unsuspend_all_lwps (struct lwp_info *except)
2765 {
2766 for_each_thread ([&] (thread_info *thread)
2767 {
2768 lwp_info *lwp = get_thread_lwp (thread);
2769
2770 if (lwp != except)
2771 lwp_suspended_decr (lwp);
2772 });
2773 }
2774
2775 static bool lwp_running (thread_info *thread);
2776
2777 /* Stabilize threads (move out of jump pads).
2778
2779 If a thread is midway collecting a fast tracepoint, we need to
2780 finish the collection and move it out of the jump pad before
2781 reporting the signal.
2782
2783 This avoids recursion while collecting (when a signal arrives
2784 midway, and the signal handler itself collects), which would trash
2785 the trace buffer. In case the user set a breakpoint in a signal
2786 handler, this avoids the backtrace showing the jump pad, etc..
2787 Most importantly, there are certain things we can't do safely if
2788 threads are stopped in a jump pad (or in its callee's). For
2789 example:
2790
2791 - starting a new trace run. A thread still collecting the
2792 previous run, could trash the trace buffer when resumed. The trace
2793 buffer control structures would have been reset but the thread had
2794 no way to tell. The thread could even midway memcpy'ing to the
2795 buffer, which would mean that when resumed, it would clobber the
2796 trace buffer that had been set for a new run.
2797
2798 - we can't rewrite/reuse the jump pads for new tracepoints
2799 safely. Say you do tstart while a thread is stopped midway while
2800 collecting. When the thread is later resumed, it finishes the
2801 collection, and returns to the jump pad, to execute the original
2802 instruction that was under the tracepoint jump at the time the
2803 older run had been started. If the jump pad had been rewritten
2804 since for something else in the new run, the thread would now
2805 execute the wrong / random instructions. */
2806
2807 void
2808 linux_process_target::stabilize_threads ()
2809 {
2810 thread_info *thread_stuck = find_thread ([this] (thread_info *thread)
2811 {
2812 return stuck_in_jump_pad (thread);
2813 });
2814
2815 if (thread_stuck != NULL)
2816 {
2817 threads_debug_printf ("can't stabilize, LWP %ld is stuck in jump pad",
2818 thread_stuck->id.lwp ());
2819 return;
2820 }
2821
2822 scoped_restore_current_thread restore_thread;
2823
2824 stabilizing_threads = 1;
2825
2826 /* Kick 'em all. */
2827 for_each_thread ([this] (thread_info *thread)
2828 {
2829 move_out_of_jump_pad (thread);
2830 });
2831
2832 /* Loop until all are stopped out of the jump pads. */
2833 while (find_thread (lwp_running) != NULL)
2834 {
2835 struct target_waitstatus ourstatus;
2836 struct lwp_info *lwp;
2837 int wstat;
2838
2839 /* Note that we go through the full wait even loop. While
2840 moving threads out of jump pad, we need to be able to step
2841 over internal breakpoints and such. */
2842 wait_1 (minus_one_ptid, &ourstatus, 0);
2843
2844 if (ourstatus.kind () == TARGET_WAITKIND_STOPPED)
2845 {
2846 lwp = get_thread_lwp (current_thread);
2847
2848 /* Lock it. */
2849 lwp_suspended_inc (lwp);
2850
2851 if (ourstatus.sig () != GDB_SIGNAL_0
2852 || current_thread->last_resume_kind == resume_stop)
2853 {
2854 wstat = W_STOPCODE (gdb_signal_to_host (ourstatus.sig ()));
2855 enqueue_one_deferred_signal (lwp, &wstat);
2856 }
2857 }
2858 }
2859
2860 unsuspend_all_lwps (NULL);
2861
2862 stabilizing_threads = 0;
2863
2864 if (debug_threads)
2865 {
2866 thread_stuck = find_thread ([this] (thread_info *thread)
2867 {
2868 return stuck_in_jump_pad (thread);
2869 });
2870
2871 if (thread_stuck != NULL)
2872 threads_debug_printf
2873 ("couldn't stabilize, LWP %ld got stuck in jump pad",
2874 thread_stuck->id.lwp ());
2875 }
2876 }
2877
2878 /* Convenience function that is called when the kernel reports an
2879 event that is not passed out to GDB. */
2880
2881 static ptid_t
2882 ignore_event (struct target_waitstatus *ourstatus)
2883 {
2884 /* If we got an event, there may still be others, as a single
2885 SIGCHLD can indicate more than one child stopped. This forces
2886 another target_wait call. */
2887 async_file_mark ();
2888
2889 ourstatus->set_ignore ();
2890 return null_ptid;
2891 }
2892
2893 ptid_t
2894 linux_process_target::filter_exit_event (lwp_info *event_child,
2895 target_waitstatus *ourstatus)
2896 {
2897 thread_info *thread = event_child->thread;
2898 ptid_t ptid = thread->id;
2899
2900 if (ourstatus->kind () == TARGET_WAITKIND_THREAD_EXITED)
2901 {
2902 /* We're reporting a thread exit for the leader. The exit was
2903 detected by check_zombie_leaders. */
2904 gdb_assert (is_leader (thread));
2905 gdb_assert (report_exit_events_for (thread));
2906
2907 delete_lwp (event_child);
2908 return ptid;
2909 }
2910
2911 /* Note we must filter TARGET_WAITKIND_SIGNALLED as well, otherwise
2912 if a non-leader thread exits with a signal, we'd report it to the
2913 core which would interpret it as the whole-process exiting.
2914 There is no TARGET_WAITKIND_THREAD_SIGNALLED event kind. */
2915 if (ourstatus->kind () != TARGET_WAITKIND_EXITED
2916 && ourstatus->kind () != TARGET_WAITKIND_SIGNALLED)
2917 return ptid;
2918
2919 if (!is_leader (thread))
2920 {
2921 if (report_exit_events_for (thread))
2922 ourstatus->set_thread_exited (0);
2923 else
2924 ourstatus->set_ignore ();
2925
2926 delete_lwp (event_child);
2927 }
2928 return ptid;
2929 }
2930
2931 /* Returns 1 if GDB is interested in any event_child syscalls. */
2932
2933 static int
2934 gdb_catching_syscalls_p (struct lwp_info *event_child)
2935 {
2936 return !event_child->thread->process ()->syscalls_to_catch.empty ();
2937 }
2938
2939 bool
2940 linux_process_target::gdb_catch_this_syscall (lwp_info *event_child)
2941 {
2942 int sysno;
2943 thread_info *thread = event_child->thread;
2944 process_info *proc = thread->process ();
2945
2946 if (proc->syscalls_to_catch.empty ())
2947 return false;
2948
2949 if (proc->syscalls_to_catch[0] == ANY_SYSCALL)
2950 return true;
2951
2952 get_syscall_trapinfo (event_child, &sysno);
2953
2954 for (int iter : proc->syscalls_to_catch)
2955 if (iter == sysno)
2956 return true;
2957
2958 return false;
2959 }
2960
2961 ptid_t
2962 linux_process_target::wait_1 (ptid_t ptid, target_waitstatus *ourstatus,
2963 target_wait_flags target_options)
2964 {
2965 THREADS_SCOPED_DEBUG_ENTER_EXIT;
2966
2967 client_state &cs = get_client_state ();
2968 int w;
2969 struct lwp_info *event_child;
2970 int options;
2971 int pid;
2972 int step_over_finished;
2973 int bp_explains_trap;
2974 int maybe_internal_trap;
2975 int report_to_gdb;
2976 int trace_event;
2977 int in_step_range;
2978
2979 threads_debug_printf ("[%s]", target_pid_to_str (ptid).c_str ());
2980
2981 /* Translate generic target options into linux options. */
2982 options = __WALL;
2983 if (target_options & TARGET_WNOHANG)
2984 options |= WNOHANG;
2985
2986 bp_explains_trap = 0;
2987 trace_event = 0;
2988 in_step_range = 0;
2989 ourstatus->set_ignore ();
2990
2991 bool was_any_resumed = any_resumed ();
2992
2993 if (step_over_bkpt == null_ptid)
2994 pid = wait_for_event (ptid, &w, options);
2995 else
2996 {
2997 threads_debug_printf ("step_over_bkpt set [%s], doing a blocking wait",
2998 target_pid_to_str (step_over_bkpt).c_str ());
2999 pid = wait_for_event (step_over_bkpt, &w, options & ~WNOHANG);
3000 }
3001
3002 if (pid == 0 || (pid == -1 && !was_any_resumed))
3003 {
3004 gdb_assert (target_options & TARGET_WNOHANG);
3005
3006 threads_debug_printf ("ret = null_ptid, TARGET_WAITKIND_IGNORE");
3007
3008 ourstatus->set_ignore ();
3009 return null_ptid;
3010 }
3011 else if (pid == -1)
3012 {
3013 threads_debug_printf ("ret = null_ptid, TARGET_WAITKIND_NO_RESUMED");
3014
3015 ourstatus->set_no_resumed ();
3016 return null_ptid;
3017 }
3018
3019 event_child = get_thread_lwp (current_thread);
3020
3021 /* wait_for_event only returns an exit status for the last
3022 child of a process. Report it. */
3023 if (WIFEXITED (w) || WIFSIGNALED (w))
3024 {
3025 if (WIFEXITED (w))
3026 {
3027 /* If we already have the exit recorded in waitstatus, use
3028 it. This will happen when we detect a zombie leader,
3029 when we had GDB_THREAD_OPTION_EXIT enabled for it. We
3030 want to report its exit as TARGET_WAITKIND_THREAD_EXITED,
3031 as the whole process hasn't exited yet. */
3032 const target_waitstatus &ws = event_child->waitstatus;
3033 if (ws.kind () != TARGET_WAITKIND_IGNORE)
3034 {
3035 gdb_assert (ws.kind () == TARGET_WAITKIND_EXITED
3036 || ws.kind () == TARGET_WAITKIND_THREAD_EXITED);
3037 *ourstatus = ws;
3038 }
3039 else
3040 ourstatus->set_exited (WEXITSTATUS (w));
3041
3042 threads_debug_printf
3043 ("ret = %s, exited with retcode %d",
3044 target_pid_to_str (current_thread->id).c_str (),
3045 WEXITSTATUS (w));
3046 }
3047 else
3048 {
3049 ourstatus->set_signalled (gdb_signal_from_host (WTERMSIG (w)));
3050
3051 threads_debug_printf
3052 ("ret = %s, terminated with signal %d",
3053 target_pid_to_str (current_thread->id).c_str (),
3054 WTERMSIG (w));
3055 }
3056
3057 return filter_exit_event (event_child, ourstatus);
3058 }
3059
3060 /* If step-over executes a breakpoint instruction, in the case of a
3061 hardware single step it means a gdb/gdbserver breakpoint had been
3062 planted on top of a permanent breakpoint, in the case of a software
3063 single step it may just mean that gdbserver hit the reinsert breakpoint.
3064 The PC has been adjusted by save_stop_reason to point at
3065 the breakpoint address.
3066 So in the case of the hardware single step advance the PC manually
3067 past the breakpoint and in the case of software single step advance only
3068 if it's not the single_step_breakpoint we are hitting.
3069 This avoids that a program would keep trapping a permanent breakpoint
3070 forever. */
3071 if (step_over_bkpt != null_ptid
3072 && event_child->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
3073 && (event_child->stepping
3074 || !single_step_breakpoint_inserted_here (event_child->stop_pc)))
3075 {
3076 int increment_pc = 0;
3077 int breakpoint_kind = 0;
3078 CORE_ADDR stop_pc = event_child->stop_pc;
3079
3080 breakpoint_kind = breakpoint_kind_from_current_state (&stop_pc);
3081 sw_breakpoint_from_kind (breakpoint_kind, &increment_pc);
3082
3083 threads_debug_printf
3084 ("step-over for %s executed software breakpoint",
3085 target_pid_to_str (current_thread->id).c_str ());
3086
3087 if (increment_pc != 0)
3088 {
3089 struct regcache *regcache
3090 = get_thread_regcache (current_thread);
3091
3092 event_child->stop_pc += increment_pc;
3093 low_set_pc (regcache, event_child->stop_pc);
3094
3095 if (!low_breakpoint_at (event_child->stop_pc))
3096 event_child->stop_reason = TARGET_STOPPED_BY_NO_REASON;
3097 }
3098 }
3099
3100 /* If this event was not handled before, and is not a SIGTRAP, we
3101 report it. SIGILL and SIGSEGV are also treated as traps in case
3102 a breakpoint is inserted at the current PC. If this target does
3103 not support internal breakpoints at all, we also report the
3104 SIGTRAP without further processing; it's of no concern to us. */
3105 maybe_internal_trap
3106 = (low_supports_breakpoints ()
3107 && (WSTOPSIG (w) == SIGTRAP
3108 || ((WSTOPSIG (w) == SIGILL
3109 || WSTOPSIG (w) == SIGSEGV)
3110 && low_breakpoint_at (event_child->stop_pc))));
3111
3112 if (maybe_internal_trap)
3113 {
3114 /* Handle anything that requires bookkeeping before deciding to
3115 report the event or continue waiting. */
3116
3117 /* First check if we can explain the SIGTRAP with an internal
3118 breakpoint, or if we should possibly report the event to GDB.
3119 Do this before anything that may remove or insert a
3120 breakpoint. */
3121 bp_explains_trap = breakpoint_inserted_here (event_child->stop_pc);
3122
3123 /* We have a SIGTRAP, possibly a step-over dance has just
3124 finished. If so, tweak the state machine accordingly,
3125 reinsert breakpoints and delete any single-step
3126 breakpoints. */
3127 step_over_finished = finish_step_over (event_child);
3128
3129 /* Now invoke the callbacks of any internal breakpoints there. */
3130 check_breakpoints (event_child->stop_pc);
3131
3132 /* Handle tracepoint data collecting. This may overflow the
3133 trace buffer, and cause a tracing stop, removing
3134 breakpoints. */
3135 trace_event = handle_tracepoints (event_child);
3136
3137 if (bp_explains_trap)
3138 threads_debug_printf ("Hit a gdbserver breakpoint.");
3139 }
3140 else
3141 {
3142 /* We have some other signal, possibly a step-over dance was in
3143 progress, and it should be cancelled too. */
3144 step_over_finished = finish_step_over (event_child);
3145 }
3146
3147 /* We have all the data we need. Either report the event to GDB, or
3148 resume threads and keep waiting for more. */
3149
3150 /* If we're collecting a fast tracepoint, finish the collection and
3151 move out of the jump pad before delivering a signal. See
3152 linux_stabilize_threads. */
3153
3154 if (WIFSTOPPED (w)
3155 && WSTOPSIG (w) != SIGTRAP
3156 && supports_fast_tracepoints ()
3157 && agent_loaded_p ())
3158 {
3159 threads_debug_printf ("Got signal %d for LWP %ld. Check if we need "
3160 "to defer or adjust it.",
3161 WSTOPSIG (w), current_thread->id.lwp ());
3162
3163 /* Allow debugging the jump pad itself. */
3164 if (current_thread->last_resume_kind != resume_step
3165 && maybe_move_out_of_jump_pad (event_child, &w))
3166 {
3167 enqueue_one_deferred_signal (event_child, &w);
3168
3169 threads_debug_printf ("Signal %d for LWP %ld deferred (in jump pad)",
3170 WSTOPSIG (w), current_thread->id.lwp ());
3171
3172 resume_one_lwp (event_child, 0, 0, NULL);
3173
3174 return ignore_event (ourstatus);
3175 }
3176 }
3177
3178 if (event_child->collecting_fast_tracepoint
3179 != fast_tpoint_collect_result::not_collecting)
3180 {
3181 threads_debug_printf
3182 ("LWP %ld was trying to move out of the jump pad (%d). "
3183 "Check if we're already there.",
3184 current_thread->id.lwp (),
3185 (int) event_child->collecting_fast_tracepoint);
3186
3187 trace_event = 1;
3188
3189 event_child->collecting_fast_tracepoint
3190 = linux_fast_tracepoint_collecting (event_child, NULL);
3191
3192 if (event_child->collecting_fast_tracepoint
3193 != fast_tpoint_collect_result::before_insn)
3194 {
3195 /* No longer need this breakpoint. */
3196 if (event_child->exit_jump_pad_bkpt != NULL)
3197 {
3198 threads_debug_printf
3199 ("No longer need exit-jump-pad bkpt; removing it."
3200 "stopping all threads momentarily.");
3201
3202 /* Other running threads could hit this breakpoint.
3203 We don't handle moribund locations like GDB does,
3204 instead we always pause all threads when removing
3205 breakpoints, so that any step-over or
3206 decr_pc_after_break adjustment is always taken
3207 care of while the breakpoint is still
3208 inserted. */
3209 stop_all_lwps (1, event_child);
3210
3211 delete_breakpoint (event_child->exit_jump_pad_bkpt);
3212 event_child->exit_jump_pad_bkpt = NULL;
3213
3214 unstop_all_lwps (1, event_child);
3215
3216 gdb_assert (event_child->suspended >= 0);
3217 }
3218 }
3219
3220 if (event_child->collecting_fast_tracepoint
3221 == fast_tpoint_collect_result::not_collecting)
3222 {
3223 threads_debug_printf
3224 ("fast tracepoint finished collecting successfully.");
3225
3226 /* We may have a deferred signal to report. */
3227 if (dequeue_one_deferred_signal (event_child, &w))
3228 threads_debug_printf ("dequeued one signal.");
3229 else
3230 {
3231 threads_debug_printf ("no deferred signals.");
3232
3233 if (stabilizing_threads)
3234 {
3235 ourstatus->set_stopped (GDB_SIGNAL_0);
3236
3237 threads_debug_printf
3238 ("ret = %s, stopped while stabilizing threads",
3239 target_pid_to_str (current_thread->id).c_str ());
3240
3241 return current_thread->id;
3242 }
3243 }
3244 }
3245 }
3246
3247 /* Check whether GDB would be interested in this event. */
3248
3249 /* Check if GDB is interested in this syscall. */
3250 if (WIFSTOPPED (w)
3251 && WSTOPSIG (w) == SYSCALL_SIGTRAP
3252 && !gdb_catch_this_syscall (event_child))
3253 {
3254 threads_debug_printf ("Ignored syscall for LWP %ld.",
3255 current_thread->id.lwp ());
3256
3257 resume_one_lwp (event_child, event_child->stepping, 0, NULL);
3258
3259 return ignore_event (ourstatus);
3260 }
3261
3262 /* If GDB is not interested in this signal, don't stop other
3263 threads, and don't report it to GDB. Just resume the inferior
3264 right away. We do this for threading-related signals as well as
3265 any that GDB specifically requested we ignore. But never ignore
3266 SIGSTOP if we sent it ourselves, and do not ignore signals when
3267 stepping - they may require special handling to skip the signal
3268 handler. Also never ignore signals that could be caused by a
3269 breakpoint. */
3270 if (WIFSTOPPED (w)
3271 && current_thread->last_resume_kind != resume_step
3272 && (
3273 #if defined (USE_THREAD_DB) && !defined (__ANDROID__)
3274 (current_process ()->priv->thread_db != NULL
3275 && (WSTOPSIG (w) == __SIGRTMIN
3276 || WSTOPSIG (w) == __SIGRTMIN + 1))
3277 ||
3278 #endif
3279 (cs.pass_signals[gdb_signal_from_host (WSTOPSIG (w))]
3280 && !(WSTOPSIG (w) == SIGSTOP
3281 && current_thread->last_resume_kind == resume_stop)
3282 && !linux_wstatus_maybe_breakpoint (w))))
3283 {
3284 siginfo_t info, *info_p;
3285
3286 threads_debug_printf ("Ignored signal %d for LWP %ld.",
3287 WSTOPSIG (w), current_thread->id.lwp ());
3288
3289 if (ptrace (PTRACE_GETSIGINFO, current_thread->id.lwp (),
3290 (PTRACE_TYPE_ARG3) 0, &info) == 0)
3291 info_p = &info;
3292 else
3293 info_p = NULL;
3294
3295 if (step_over_finished)
3296 {
3297 /* We cancelled this thread's step-over above. We still
3298 need to unsuspend all other LWPs, and set them back
3299 running again while the signal handler runs. */
3300 unsuspend_all_lwps (event_child);
3301
3302 /* Enqueue the pending signal info so that proceed_all_lwps
3303 doesn't lose it. */
3304 enqueue_pending_signal (event_child, WSTOPSIG (w), info_p);
3305
3306 proceed_all_lwps ();
3307 }
3308 else
3309 {
3310 resume_one_lwp (event_child, event_child->stepping,
3311 WSTOPSIG (w), info_p);
3312 }
3313
3314 return ignore_event (ourstatus);
3315 }
3316
3317 /* Note that all addresses are always "out of the step range" when
3318 there's no range to begin with. */
3319 in_step_range = lwp_in_step_range (event_child);
3320
3321 /* If GDB wanted this thread to single step, and the thread is out
3322 of the step range, we always want to report the SIGTRAP, and let
3323 GDB handle it. Watchpoints should always be reported. So should
3324 signals we can't explain. A SIGTRAP we can't explain could be a
3325 GDB breakpoint --- we may or not support Z0 breakpoints. If we
3326 do, we're be able to handle GDB breakpoints on top of internal
3327 breakpoints, by handling the internal breakpoint and still
3328 reporting the event to GDB. If we don't, we're out of luck, GDB
3329 won't see the breakpoint hit. If we see a single-step event but
3330 the thread should be continuing, don't pass the trap to gdb.
3331 That indicates that we had previously finished a single-step but
3332 left the single-step pending -- see
3333 complete_ongoing_step_over. */
3334 report_to_gdb = (!maybe_internal_trap
3335 || (current_thread->last_resume_kind == resume_step
3336 && !in_step_range)
3337 || event_child->stop_reason == TARGET_STOPPED_BY_WATCHPOINT
3338 || (!in_step_range
3339 && !bp_explains_trap
3340 && !trace_event
3341 && !step_over_finished
3342 && !(current_thread->last_resume_kind == resume_continue
3343 && event_child->stop_reason == TARGET_STOPPED_BY_SINGLE_STEP))
3344 || (gdb_breakpoint_here (event_child->stop_pc)
3345 && gdb_condition_true_at_breakpoint (event_child->stop_pc)
3346 && gdb_no_commands_at_breakpoint (event_child->stop_pc))
3347 || event_child->waitstatus.kind () != TARGET_WAITKIND_IGNORE);
3348
3349 run_breakpoint_commands (event_child->stop_pc);
3350
3351 /* We found no reason GDB would want us to stop. We either hit one
3352 of our own breakpoints, or finished an internal step GDB
3353 shouldn't know about. */
3354 if (!report_to_gdb)
3355 {
3356 if (bp_explains_trap)
3357 threads_debug_printf ("Hit a gdbserver breakpoint.");
3358
3359 if (step_over_finished)
3360 threads_debug_printf ("Step-over finished.");
3361
3362 if (trace_event)
3363 threads_debug_printf ("Tracepoint event.");
3364
3365 if (lwp_in_step_range (event_child))
3366 threads_debug_printf ("Range stepping pc 0x%s [0x%s, 0x%s).",
3367 paddress (event_child->stop_pc),
3368 paddress (event_child->step_range_start),
3369 paddress (event_child->step_range_end));
3370
3371 /* We're not reporting this breakpoint to GDB, so apply the
3372 decr_pc_after_break adjustment to the inferior's regcache
3373 ourselves. */
3374
3375 if (low_supports_breakpoints ())
3376 {
3377 struct regcache *regcache
3378 = get_thread_regcache (current_thread);
3379 low_set_pc (regcache, event_child->stop_pc);
3380 }
3381
3382 if (step_over_finished)
3383 {
3384 /* If we have finished stepping over a breakpoint, we've
3385 stopped and suspended all LWPs momentarily except the
3386 stepping one. This is where we resume them all again.
3387 We're going to keep waiting, so use proceed, which
3388 handles stepping over the next breakpoint. */
3389 unsuspend_all_lwps (event_child);
3390 }
3391 else
3392 {
3393 /* Remove the single-step breakpoints if any. Note that
3394 there isn't single-step breakpoint if we finished stepping
3395 over. */
3396 if (supports_software_single_step ()
3397 && has_single_step_breakpoints (current_thread))
3398 {
3399 stop_all_lwps (0, event_child);
3400 delete_single_step_breakpoints (current_thread);
3401 unstop_all_lwps (0, event_child);
3402 }
3403 }
3404
3405 threads_debug_printf ("proceeding all threads.");
3406
3407 proceed_all_lwps ();
3408
3409 return ignore_event (ourstatus);
3410 }
3411
3412 if (debug_threads)
3413 {
3414 if (event_child->waitstatus.kind () != TARGET_WAITKIND_IGNORE)
3415 threads_debug_printf ("LWP %ld: extended event with waitstatus %s",
3416 event_child->thread->id.lwp (),
3417 event_child->waitstatus.to_string ().c_str ());
3418
3419 if (current_thread->last_resume_kind == resume_step)
3420 {
3421 if (event_child->step_range_start == event_child->step_range_end)
3422 threads_debug_printf
3423 ("GDB wanted to single-step, reporting event.");
3424 else if (!lwp_in_step_range (event_child))
3425 threads_debug_printf ("Out of step range, reporting event.");
3426 }
3427
3428 if (event_child->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
3429 threads_debug_printf ("Stopped by watchpoint.");
3430 else if (gdb_breakpoint_here (event_child->stop_pc))
3431 threads_debug_printf ("Stopped by GDB breakpoint.");
3432 }
3433
3434 threads_debug_printf ("Hit a non-gdbserver trap event.");
3435
3436 /* Alright, we're going to report a stop. */
3437
3438 /* Remove single-step breakpoints. */
3439 if (supports_software_single_step ())
3440 {
3441 /* Remove single-step breakpoints or not. It it is true, stop all
3442 lwps, so that other threads won't hit the breakpoint in the
3443 staled memory. */
3444 int remove_single_step_breakpoints_p = 0;
3445
3446 if (non_stop)
3447 {
3448 remove_single_step_breakpoints_p
3449 = has_single_step_breakpoints (current_thread);
3450 }
3451 else
3452 {
3453 /* In all-stop, a stop reply cancels all previous resume
3454 requests. Delete all single-step breakpoints. */
3455
3456 find_thread ([&] (thread_info *thread) {
3457 if (has_single_step_breakpoints (thread))
3458 {
3459 remove_single_step_breakpoints_p = 1;
3460 return true;
3461 }
3462
3463 return false;
3464 });
3465 }
3466
3467 if (remove_single_step_breakpoints_p)
3468 {
3469 /* If we remove single-step breakpoints from memory, stop all lwps,
3470 so that other threads won't hit the breakpoint in the staled
3471 memory. */
3472 stop_all_lwps (0, event_child);
3473
3474 if (non_stop)
3475 {
3476 gdb_assert (has_single_step_breakpoints (current_thread));
3477 delete_single_step_breakpoints (current_thread);
3478 }
3479 else
3480 {
3481 for_each_thread ([] (thread_info *thread){
3482 if (has_single_step_breakpoints (thread))
3483 delete_single_step_breakpoints (thread);
3484 });
3485 }
3486
3487 unstop_all_lwps (0, event_child);
3488 }
3489 }
3490
3491 if (!stabilizing_threads)
3492 {
3493 /* In all-stop, stop all threads. */
3494 if (!non_stop)
3495 stop_all_lwps (0, NULL);
3496
3497 if (step_over_finished)
3498 {
3499 if (!non_stop)
3500 {
3501 /* If we were doing a step-over, all other threads but
3502 the stepping one had been paused in start_step_over,
3503 with their suspend counts incremented. We don't want
3504 to do a full unstop/unpause, because we're in
3505 all-stop mode (so we want threads stopped), but we
3506 still need to unsuspend the other threads, to
3507 decrement their `suspended' count back. */
3508 unsuspend_all_lwps (event_child);
3509 }
3510 else
3511 {
3512 /* If we just finished a step-over, then all threads had
3513 been momentarily paused. In all-stop, that's fine,
3514 we want threads stopped by now anyway. In non-stop,
3515 we need to re-resume threads that GDB wanted to be
3516 running. */
3517 unstop_all_lwps (1, event_child);
3518 }
3519 }
3520
3521 /* If we're not waiting for a specific LWP, choose an event LWP
3522 from among those that have had events. Giving equal priority
3523 to all LWPs that have had events helps prevent
3524 starvation. */
3525 if (ptid == minus_one_ptid)
3526 {
3527 event_child->status_pending_p = 1;
3528 event_child->status_pending = w;
3529
3530 select_event_lwp (&event_child);
3531
3532 /* current_thread and event_child must stay in sync. */
3533 switch_to_thread (event_child->thread);
3534
3535 event_child->status_pending_p = 0;
3536 w = event_child->status_pending;
3537 }
3538
3539
3540 /* Stabilize threads (move out of jump pads). */
3541 if (!non_stop)
3542 target_stabilize_threads ();
3543 }
3544 else
3545 {
3546 /* If we just finished a step-over, then all threads had been
3547 momentarily paused. In all-stop, that's fine, we want
3548 threads stopped by now anyway. In non-stop, we need to
3549 re-resume threads that GDB wanted to be running. */
3550 if (step_over_finished)
3551 unstop_all_lwps (1, event_child);
3552 }
3553
3554 /* At this point, we haven't set OURSTATUS. This is where we do it. */
3555 gdb_assert (ourstatus->kind () == TARGET_WAITKIND_IGNORE);
3556
3557 if (event_child->waitstatus.kind () != TARGET_WAITKIND_IGNORE)
3558 {
3559 /* If the reported event is an exit, fork, vfork, clone or exec,
3560 let GDB know. */
3561
3562 /* Break the unreported fork/vfork/clone relationship chain. */
3563 if (is_new_child_status (event_child->waitstatus.kind ()))
3564 {
3565 event_child->relative->relative = NULL;
3566 event_child->relative = NULL;
3567 }
3568
3569 *ourstatus = event_child->waitstatus;
3570 /* Clear the event lwp's waitstatus since we handled it already. */
3571 event_child->waitstatus.set_ignore ();
3572 }
3573 else
3574 {
3575 /* The LWP stopped due to a plain signal or a syscall signal. Either way,
3576 event_child->waitstatus wasn't filled in with the details, so look at
3577 the wait status W. */
3578 if (WSTOPSIG (w) == SYSCALL_SIGTRAP)
3579 {
3580 int syscall_number;
3581
3582 get_syscall_trapinfo (event_child, &syscall_number);
3583 if (event_child->syscall_state == TARGET_WAITKIND_SYSCALL_ENTRY)
3584 ourstatus->set_syscall_entry (syscall_number);
3585 else if (event_child->syscall_state == TARGET_WAITKIND_SYSCALL_RETURN)
3586 ourstatus->set_syscall_return (syscall_number);
3587 else
3588 gdb_assert_not_reached ("unexpected syscall state");
3589 }
3590 else if (current_thread->last_resume_kind == resume_stop
3591 && WSTOPSIG (w) == SIGSTOP)
3592 {
3593 /* A thread that has been requested to stop by GDB with vCont;t,
3594 and it stopped cleanly, so report as SIG0. The use of
3595 SIGSTOP is an implementation detail. */
3596 ourstatus->set_stopped (GDB_SIGNAL_0);
3597 }
3598 else
3599 ourstatus->set_stopped (gdb_signal_from_host (WSTOPSIG (w)));
3600 }
3601
3602 /* Now that we've selected our final event LWP, un-adjust its PC if
3603 it was a software breakpoint, and the client doesn't know we can
3604 adjust the breakpoint ourselves. */
3605 if (event_child->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
3606 && !cs.swbreak_feature)
3607 {
3608 int decr_pc = low_decr_pc_after_break ();
3609
3610 if (decr_pc != 0)
3611 {
3612 struct regcache *regcache
3613 = get_thread_regcache (current_thread);
3614 low_set_pc (regcache, event_child->stop_pc + decr_pc);
3615 }
3616 }
3617
3618 gdb_assert (step_over_bkpt == null_ptid);
3619
3620 threads_debug_printf ("ret = %s, %s",
3621 target_pid_to_str (current_thread->id).c_str (),
3622 ourstatus->to_string ().c_str ());
3623
3624 return filter_exit_event (event_child, ourstatus);
3625 }
3626
3627 /* Get rid of any pending event in the pipe. */
3628 static void
3629 async_file_flush (void)
3630 {
3631 linux_event_pipe.flush ();
3632 }
3633
3634 /* Put something in the pipe, so the event loop wakes up. */
3635 static void
3636 async_file_mark (void)
3637 {
3638 linux_event_pipe.mark ();
3639 }
3640
3641 ptid_t
3642 linux_process_target::wait (ptid_t ptid,
3643 target_waitstatus *ourstatus,
3644 target_wait_flags target_options)
3645 {
3646 ptid_t event_ptid;
3647
3648 /* Flush the async file first. */
3649 if (target_is_async_p ())
3650 async_file_flush ();
3651
3652 do
3653 {
3654 event_ptid = wait_1 (ptid, ourstatus, target_options);
3655 }
3656 while ((target_options & TARGET_WNOHANG) == 0
3657 && ourstatus->kind () == TARGET_WAITKIND_IGNORE);
3658
3659 /* If at least one stop was reported, there may be more. A single
3660 SIGCHLD can signal more than one child stop. */
3661 if (target_is_async_p ()
3662 && (target_options & TARGET_WNOHANG) != 0
3663 && event_ptid != null_ptid)
3664 async_file_mark ();
3665
3666 return event_ptid;
3667 }
3668
3669 /* Send a signal to an LWP. */
3670
3671 static int
3672 kill_lwp (unsigned long lwpid, int signo)
3673 {
3674 int ret;
3675
3676 errno = 0;
3677 ret = syscall (__NR_tkill, lwpid, signo);
3678 if (errno == ENOSYS)
3679 {
3680 /* If tkill fails, then we are not using nptl threads, a
3681 configuration we no longer support. */
3682 perror_with_name (("tkill"));
3683 }
3684 return ret;
3685 }
3686
3687 void
3688 linux_stop_lwp (struct lwp_info *lwp)
3689 {
3690 send_sigstop (lwp);
3691 }
3692
3693 static void
3694 send_sigstop (struct lwp_info *lwp)
3695 {
3696 int pid = lwp->thread->id.lwp ();
3697
3698 /* If we already have a pending stop signal for this process, don't
3699 send another. */
3700 if (lwp->stop_expected)
3701 {
3702 threads_debug_printf ("Have pending sigstop for lwp %d", pid);
3703
3704 return;
3705 }
3706
3707 threads_debug_printf ("Sending sigstop to lwp %d", pid);
3708
3709 lwp->stop_expected = 1;
3710 kill_lwp (pid, SIGSTOP);
3711 }
3712
3713 static void
3714 send_sigstop (thread_info *thread, lwp_info *except)
3715 {
3716 struct lwp_info *lwp = get_thread_lwp (thread);
3717
3718 /* Ignore EXCEPT. */
3719 if (lwp == except)
3720 return;
3721
3722 if (lwp->stopped)
3723 return;
3724
3725 send_sigstop (lwp);
3726 }
3727
3728 /* Increment the suspend count of an LWP, and stop it, if not stopped
3729 yet. */
3730 static void
3731 suspend_and_send_sigstop (thread_info *thread, lwp_info *except)
3732 {
3733 struct lwp_info *lwp = get_thread_lwp (thread);
3734
3735 /* Ignore EXCEPT. */
3736 if (lwp == except)
3737 return;
3738
3739 lwp_suspended_inc (lwp);
3740
3741 send_sigstop (thread, except);
3742 }
3743
3744 /* Mark LWP dead, with WSTAT as exit status pending to report later.
3745 If THREAD_EVENT is true, interpret WSTAT as a thread exit event
3746 instead of a process exit event. This is meaningful for the leader
3747 thread, as we normally report a process-wide exit event when we see
3748 the leader exit, and a thread exit event when we see any other
3749 thread exit. */
3750
3751 static void
3752 mark_lwp_dead (struct lwp_info *lwp, int wstat, bool thread_event)
3753 {
3754 /* Store the exit status for later. */
3755 lwp->status_pending_p = 1;
3756 lwp->status_pending = wstat;
3757
3758 /* Store in waitstatus as well, as there's nothing else to process
3759 for this event. */
3760 if (WIFEXITED (wstat))
3761 {
3762 if (thread_event)
3763 lwp->waitstatus.set_thread_exited (WEXITSTATUS (wstat));
3764 else
3765 lwp->waitstatus.set_exited (WEXITSTATUS (wstat));
3766 }
3767 else if (WIFSIGNALED (wstat))
3768 {
3769 gdb_assert (!thread_event);
3770 lwp->waitstatus.set_signalled (gdb_signal_from_host (WTERMSIG (wstat)));
3771 }
3772 else
3773 gdb_assert_not_reached ("unknown status kind");
3774
3775 /* Prevent trying to stop it. */
3776 lwp->stopped = 1;
3777
3778 /* No further stops are expected from a dead lwp. */
3779 lwp->stop_expected = 0;
3780 }
3781
3782 /* Return true if LWP has exited already, and has a pending exit event
3783 to report to GDB. */
3784
3785 static int
3786 lwp_is_marked_dead (struct lwp_info *lwp)
3787 {
3788 return (lwp->status_pending_p
3789 && (WIFEXITED (lwp->status_pending)
3790 || WIFSIGNALED (lwp->status_pending)));
3791 }
3792
3793 void
3794 linux_process_target::wait_for_sigstop ()
3795 {
3796 thread_info *saved_thread;
3797 ptid_t saved_tid;
3798 int wstat;
3799 int ret;
3800
3801 saved_thread = current_thread;
3802 if (saved_thread != NULL)
3803 saved_tid = saved_thread->id;
3804 else
3805 saved_tid = null_ptid; /* avoid bogus unused warning */
3806
3807 scoped_restore_current_thread restore_thread;
3808
3809 threads_debug_printf ("pulling events");
3810
3811 /* Passing NULL_PTID as filter indicates we want all events to be
3812 left pending. Eventually this returns when there are no
3813 unwaited-for children left. */
3814 ret = wait_for_event_filtered (minus_one_ptid, null_ptid, &wstat, __WALL);
3815 gdb_assert (ret == -1);
3816
3817 if (saved_thread == NULL || mythread_alive (saved_tid))
3818 return;
3819 else
3820 {
3821 threads_debug_printf ("Previously current thread died.");
3822
3823 /* We can't change the current inferior behind GDB's back,
3824 otherwise, a subsequent command may apply to the wrong
3825 process. */
3826 restore_thread.dont_restore ();
3827 switch_to_thread (nullptr);
3828 }
3829 }
3830
3831 bool
3832 linux_process_target::stuck_in_jump_pad (thread_info *thread)
3833 {
3834 struct lwp_info *lwp = get_thread_lwp (thread);
3835
3836 if (lwp->suspended != 0)
3837 {
3838 internal_error ("LWP %ld is suspended, suspended=%d\n",
3839 thread->id.lwp (), lwp->suspended);
3840 }
3841 gdb_assert (lwp->stopped);
3842
3843 /* Allow debugging the jump pad, gdb_collect, etc.. */
3844 return (supports_fast_tracepoints ()
3845 && agent_loaded_p ()
3846 && (gdb_breakpoint_here (lwp->stop_pc)
3847 || lwp->stop_reason == TARGET_STOPPED_BY_WATCHPOINT
3848 || thread->last_resume_kind == resume_step)
3849 && (linux_fast_tracepoint_collecting (lwp, NULL)
3850 != fast_tpoint_collect_result::not_collecting));
3851 }
3852
3853 void
3854 linux_process_target::move_out_of_jump_pad (thread_info *thread)
3855 {
3856 struct lwp_info *lwp = get_thread_lwp (thread);
3857 int *wstat;
3858
3859 if (lwp->suspended != 0)
3860 {
3861 internal_error ("LWP %ld is suspended, suspended=%d\n",
3862 thread->id.lwp (), lwp->suspended);
3863 }
3864 gdb_assert (lwp->stopped);
3865
3866 /* For gdb_breakpoint_here. */
3867 scoped_restore_current_thread restore_thread;
3868 switch_to_thread (thread);
3869
3870 wstat = lwp->status_pending_p ? &lwp->status_pending : NULL;
3871
3872 /* Allow debugging the jump pad, gdb_collect, etc. */
3873 if (!gdb_breakpoint_here (lwp->stop_pc)
3874 && lwp->stop_reason != TARGET_STOPPED_BY_WATCHPOINT
3875 && thread->last_resume_kind != resume_step
3876 && maybe_move_out_of_jump_pad (lwp, wstat))
3877 {
3878 threads_debug_printf ("LWP %ld needs stabilizing (in jump pad)",
3879 thread->id.lwp ());
3880
3881 if (wstat)
3882 {
3883 lwp->status_pending_p = 0;
3884 enqueue_one_deferred_signal (lwp, wstat);
3885
3886 threads_debug_printf ("Signal %d for LWP %ld deferred (in jump pad",
3887 WSTOPSIG (*wstat), thread->id.lwp ());
3888 }
3889
3890 resume_one_lwp (lwp, 0, 0, NULL);
3891 }
3892 else
3893 lwp_suspended_inc (lwp);
3894 }
3895
3896 static bool
3897 lwp_running (thread_info *thread)
3898 {
3899 struct lwp_info *lwp = get_thread_lwp (thread);
3900
3901 if (lwp_is_marked_dead (lwp))
3902 return false;
3903
3904 return !lwp->stopped;
3905 }
3906
3907 void
3908 linux_process_target::stop_all_lwps (int suspend, lwp_info *except)
3909 {
3910 /* Should not be called recursively. */
3911 gdb_assert (stopping_threads == NOT_STOPPING_THREADS);
3912
3913 THREADS_SCOPED_DEBUG_ENTER_EXIT;
3914
3915 threads_debug_printf
3916 ("%s, except=%s", suspend ? "stop-and-suspend" : "stop",
3917 (except != NULL
3918 ? target_pid_to_str (except->thread->id).c_str ()
3919 : "none"));
3920
3921 stopping_threads = (suspend
3922 ? STOPPING_AND_SUSPENDING_THREADS
3923 : STOPPING_THREADS);
3924
3925 if (suspend)
3926 for_each_thread ([&] (thread_info *thread)
3927 {
3928 suspend_and_send_sigstop (thread, except);
3929 });
3930 else
3931 for_each_thread ([&] (thread_info *thread)
3932 {
3933 send_sigstop (thread, except);
3934 });
3935
3936 wait_for_sigstop ();
3937 stopping_threads = NOT_STOPPING_THREADS;
3938
3939 threads_debug_printf ("setting stopping_threads back to !stopping");
3940 }
3941
3942 /* Enqueue one signal in the chain of signals which need to be
3943 delivered to this process on next resume. */
3944
3945 static void
3946 enqueue_pending_signal (struct lwp_info *lwp, int signal, siginfo_t *info)
3947 {
3948 lwp->pending_signals.emplace_back (signal);
3949 if (info == nullptr)
3950 memset (&lwp->pending_signals.back ().info, 0, sizeof (siginfo_t));
3951 else
3952 lwp->pending_signals.back ().info = *info;
3953 }
3954
3955 void
3956 linux_process_target::install_software_single_step_breakpoints (lwp_info *lwp)
3957 {
3958 thread_info *thread = lwp->thread;
3959 regcache *regcache = get_thread_regcache (thread);
3960
3961 scoped_restore_current_thread restore_thread;
3962
3963 switch_to_thread (thread);
3964 std::vector<CORE_ADDR> next_pcs = low_get_next_pcs (regcache);
3965
3966 for (CORE_ADDR pc : next_pcs)
3967 set_single_step_breakpoint (pc, current_thread->id);
3968 }
3969
3970 int
3971 linux_process_target::single_step (lwp_info* lwp)
3972 {
3973 int step = 0;
3974
3975 if (supports_hardware_single_step ())
3976 {
3977 step = 1;
3978 }
3979 else if (supports_software_single_step ())
3980 {
3981 install_software_single_step_breakpoints (lwp);
3982 step = 0;
3983 }
3984 else
3985 threads_debug_printf ("stepping is not implemented on this target");
3986
3987 return step;
3988 }
3989
3990 /* The signal can be delivered to the inferior if we are not trying to
3991 finish a fast tracepoint collect. Since signal can be delivered in
3992 the step-over, the program may go to signal handler and trap again
3993 after return from the signal handler. We can live with the spurious
3994 double traps. */
3995
3996 static int
3997 lwp_signal_can_be_delivered (struct lwp_info *lwp)
3998 {
3999 return (lwp->collecting_fast_tracepoint
4000 == fast_tpoint_collect_result::not_collecting);
4001 }
4002
4003 void
4004 linux_process_target::resume_one_lwp_throw (lwp_info *lwp, int step,
4005 int signal, siginfo_t *info)
4006 {
4007 thread_info *thread = lwp->thread;
4008 int ptrace_request;
4009
4010 /* Note that target description may not be initialised
4011 (proc->tdesc == NULL) at this point because the program hasn't
4012 stopped at the first instruction yet. It means GDBserver skips
4013 the extra traps from the wrapper program (see option --wrapper).
4014 Code in this function that requires register access should be
4015 guarded by proc->tdesc == NULL or something else. */
4016
4017 if (lwp->stopped == 0)
4018 return;
4019
4020 gdb_assert (lwp->waitstatus.kind () == TARGET_WAITKIND_IGNORE);
4021
4022 fast_tpoint_collect_result fast_tp_collecting
4023 = lwp->collecting_fast_tracepoint;
4024
4025 gdb_assert (!stabilizing_threads
4026 || (fast_tp_collecting
4027 != fast_tpoint_collect_result::not_collecting));
4028
4029 /* Cancel actions that rely on GDB not changing the PC (e.g., the
4030 user used the "jump" command, or "set $pc = foo"). */
4031 if (thread->while_stepping != NULL && lwp->stop_pc != get_pc (lwp))
4032 {
4033 /* Collecting 'while-stepping' actions doesn't make sense
4034 anymore. */
4035 release_while_stepping_state_list (thread);
4036 }
4037
4038 /* If we have pending signals or status, and a new signal, enqueue the
4039 signal. Also enqueue the signal if it can't be delivered to the
4040 inferior right now. */
4041 if (signal != 0
4042 && (lwp->status_pending_p
4043 || !lwp->pending_signals.empty ()
4044 || !lwp_signal_can_be_delivered (lwp)))
4045 {
4046 enqueue_pending_signal (lwp, signal, info);
4047
4048 /* Postpone any pending signal. It was enqueued above. */
4049 signal = 0;
4050 }
4051
4052 if (lwp->status_pending_p)
4053 {
4054 threads_debug_printf
4055 ("Not resuming lwp %ld (%s, stop %s); has pending status",
4056 thread->id.lwp (), step ? "step" : "continue",
4057 lwp->stop_expected ? "expected" : "not expected");
4058 return;
4059 }
4060
4061 scoped_restore_current_thread restore_thread;
4062 switch_to_thread (thread);
4063
4064 /* This bit needs some thinking about. If we get a signal that
4065 we must report while a single-step reinsert is still pending,
4066 we often end up resuming the thread. It might be better to
4067 (ew) allow a stack of pending events; then we could be sure that
4068 the reinsert happened right away and not lose any signals.
4069
4070 Making this stack would also shrink the window in which breakpoints are
4071 uninserted (see comment in linux_wait_for_lwp) but not enough for
4072 complete correctness, so it won't solve that problem. It may be
4073 worthwhile just to solve this one, however. */
4074 if (lwp->bp_reinsert != 0)
4075 {
4076 threads_debug_printf (" pending reinsert at 0x%s",
4077 paddress (lwp->bp_reinsert));
4078
4079 if (supports_hardware_single_step ())
4080 {
4081 if (fast_tp_collecting == fast_tpoint_collect_result::not_collecting)
4082 {
4083 if (step == 0)
4084 warning ("BAD - reinserting but not stepping.");
4085 if (lwp->suspended)
4086 warning ("BAD - reinserting and suspended(%d).",
4087 lwp->suspended);
4088 }
4089 }
4090
4091 step = maybe_hw_step (thread);
4092 }
4093
4094 if (fast_tp_collecting == fast_tpoint_collect_result::before_insn)
4095 threads_debug_printf
4096 ("lwp %ld wants to get out of fast tracepoint jump pad "
4097 "(exit-jump-pad-bkpt)", thread->id.lwp ());
4098
4099 else if (fast_tp_collecting == fast_tpoint_collect_result::at_insn)
4100 {
4101 threads_debug_printf
4102 ("lwp %ld wants to get out of fast tracepoint jump pad single-stepping",
4103 thread->id.lwp ());
4104
4105 if (supports_hardware_single_step ())
4106 step = 1;
4107 else
4108 {
4109 internal_error ("moving out of jump pad single-stepping"
4110 " not implemented on this target");
4111 }
4112 }
4113
4114 /* If we have while-stepping actions in this thread set it stepping.
4115 If we have a signal to deliver, it may or may not be set to
4116 SIG_IGN, we don't know. Assume so, and allow collecting
4117 while-stepping into a signal handler. A possible smart thing to
4118 do would be to set an internal breakpoint at the signal return
4119 address, continue, and carry on catching this while-stepping
4120 action only when that breakpoint is hit. A future
4121 enhancement. */
4122 if (thread->while_stepping != NULL)
4123 {
4124 threads_debug_printf
4125 ("lwp %ld has a while-stepping action -> forcing step.",
4126 thread->id.lwp ());
4127
4128 step = single_step (lwp);
4129 }
4130
4131 if (thread->process ()->tdesc != nullptr && low_supports_breakpoints ())
4132 {
4133 regcache *regcache = get_thread_regcache (current_thread);
4134
4135 lwp->stop_pc = low_get_pc (regcache);
4136
4137 threads_debug_printf (" %s from pc 0x%lx", step ? "step" : "continue",
4138 (long) lwp->stop_pc);
4139 }
4140
4141 /* If we have pending signals, consume one if it can be delivered to
4142 the inferior. */
4143 if (!lwp->pending_signals.empty () && lwp_signal_can_be_delivered (lwp))
4144 {
4145 const pending_signal &p_sig = lwp->pending_signals.front ();
4146
4147 signal = p_sig.signal;
4148 if (p_sig.info.si_signo != 0)
4149 ptrace (PTRACE_SETSIGINFO, thread->id.lwp (), (PTRACE_TYPE_ARG3) 0,
4150 &p_sig.info);
4151
4152 lwp->pending_signals.pop_front ();
4153 }
4154
4155 threads_debug_printf ("Resuming lwp %ld (%s, signal %d, stop %s)",
4156 thread->id.lwp (), step ? "step" : "continue", signal,
4157 lwp->stop_expected ? "expected" : "not expected");
4158
4159 low_prepare_to_resume (lwp);
4160
4161 regcache_invalidate_thread (thread);
4162 errno = 0;
4163 lwp->stepping = step;
4164 if (step)
4165 ptrace_request = PTRACE_SINGLESTEP;
4166 else if (gdb_catching_syscalls_p (lwp))
4167 ptrace_request = PTRACE_SYSCALL;
4168 else
4169 ptrace_request = PTRACE_CONT;
4170 ptrace (ptrace_request,
4171 thread->id.lwp (),
4172 (PTRACE_TYPE_ARG3) 0,
4173 /* Coerce to a uintptr_t first to avoid potential gcc warning
4174 of coercing an 8 byte integer to a 4 byte pointer. */
4175 (PTRACE_TYPE_ARG4) (uintptr_t) signal);
4176
4177 if (errno)
4178 {
4179 int saved_errno = errno;
4180
4181 threads_debug_printf ("ptrace errno = %d (%s)",
4182 saved_errno, strerror (saved_errno));
4183
4184 errno = saved_errno;
4185 perror_with_name ("resuming thread");
4186 }
4187
4188 /* Successfully resumed. Clear state that no longer makes sense,
4189 and mark the LWP as running. Must not do this before resuming
4190 otherwise if that fails other code will be confused. E.g., we'd
4191 later try to stop the LWP and hang forever waiting for a stop
4192 status. Note that we must not throw after this is cleared,
4193 otherwise handle_zombie_lwp_error would get confused. */
4194 lwp->stopped = 0;
4195 lwp->stop_reason = TARGET_STOPPED_BY_NO_REASON;
4196 }
4197
4198 void
4199 linux_process_target::low_prepare_to_resume (lwp_info *lwp)
4200 {
4201 /* Nop. */
4202 }
4203
4204 /* Called when we try to resume a stopped LWP and that errors out. If
4205 the LWP is no longer in ptrace-stopped state (meaning it's zombie,
4206 or about to become), discard the error, clear any pending status
4207 the LWP may have, and return true (we'll collect the exit status
4208 soon enough). Otherwise, return false. */
4209
4210 static int
4211 check_ptrace_stopped_lwp_gone (struct lwp_info *lp)
4212 {
4213 thread_info *thread = lp->thread;
4214
4215 /* If we get an error after resuming the LWP successfully, we'd
4216 confuse !T state for the LWP being gone. */
4217 gdb_assert (lp->stopped);
4218
4219 /* We can't just check whether the LWP is in 'Z (Zombie)' state,
4220 because even if ptrace failed with ESRCH, the tracee may be "not
4221 yet fully dead", but already refusing ptrace requests. In that
4222 case the tracee has 'R (Running)' state for a little bit
4223 (observed in Linux 3.18). See also the note on ESRCH in the
4224 ptrace(2) man page. Instead, check whether the LWP has any state
4225 other than ptrace-stopped. */
4226
4227 /* Don't assume anything if /proc/PID/status can't be read. */
4228 if (linux_proc_pid_is_trace_stopped_nowarn (thread->id.lwp ()) == 0)
4229 {
4230 lp->stop_reason = TARGET_STOPPED_BY_NO_REASON;
4231 lp->status_pending_p = 0;
4232 return 1;
4233 }
4234 return 0;
4235 }
4236
4237 void
4238 linux_process_target::resume_one_lwp (lwp_info *lwp, int step, int signal,
4239 siginfo_t *info)
4240 {
4241 try
4242 {
4243 resume_one_lwp_throw (lwp, step, signal, info);
4244 }
4245 catch (const gdb_exception_error &ex)
4246 {
4247 if (check_ptrace_stopped_lwp_gone (lwp))
4248 {
4249 /* This could because we tried to resume an LWP after its leader
4250 exited. Mark it as resumed, so we can collect an exit event
4251 from it. */
4252 lwp->stopped = 0;
4253 lwp->stop_reason = TARGET_STOPPED_BY_NO_REASON;
4254 }
4255 else
4256 throw;
4257 }
4258 }
4259
4260 /* This function is called once per thread via for_each_thread.
4261 We look up which resume request applies to THREAD and mark it with a
4262 pointer to the appropriate resume request.
4263
4264 This algorithm is O(threads * resume elements), but resume elements
4265 is small (and will remain small at least until GDB supports thread
4266 suspension). */
4267
4268 static void
4269 linux_set_resume_request (thread_info *thread, thread_resume *resume, size_t n)
4270 {
4271 struct lwp_info *lwp = get_thread_lwp (thread);
4272
4273 for (int ndx = 0; ndx < n; ndx++)
4274 {
4275 ptid_t ptid = resume[ndx].thread;
4276 if (ptid == minus_one_ptid
4277 || ptid == thread->id
4278 /* Handle both 'pPID' and 'pPID.-1' as meaning 'all threads
4279 of PID'. */
4280 || (ptid.pid () == thread->id.pid ()
4281 && (ptid.is_pid ()
4282 || ptid.lwp () == -1)))
4283 {
4284 if (resume[ndx].kind == resume_stop
4285 && thread->last_resume_kind == resume_stop)
4286 {
4287 threads_debug_printf
4288 ("already %s LWP %ld at GDB's request",
4289 (thread->last_status.kind () == TARGET_WAITKIND_STOPPED
4290 ? "stopped" : "stopping"),
4291 thread->id.lwp ());
4292
4293 continue;
4294 }
4295
4296 /* Ignore (wildcard) resume requests for already-resumed
4297 threads. */
4298 if (resume[ndx].kind != resume_stop
4299 && thread->last_resume_kind != resume_stop)
4300 {
4301 threads_debug_printf
4302 ("already %s LWP %ld at GDB's request",
4303 (thread->last_resume_kind == resume_step
4304 ? "stepping" : "continuing"),
4305 thread->id.lwp ());
4306 continue;
4307 }
4308
4309 /* Don't let wildcard resumes resume fork/vfork/clone
4310 children that GDB does not yet know are new children. */
4311 if (lwp->relative != NULL)
4312 {
4313 struct lwp_info *rel = lwp->relative;
4314
4315 if (rel->status_pending_p
4316 && is_new_child_status (rel->waitstatus.kind ()))
4317 {
4318 threads_debug_printf
4319 ("not resuming LWP %ld: has queued stop reply",
4320 thread->id.lwp ());
4321 continue;
4322 }
4323 }
4324
4325 /* If the thread has a pending event that has already been
4326 reported to GDBserver core, but GDB has not pulled the
4327 event out of the vStopped queue yet, likewise, ignore the
4328 (wildcard) resume request. */
4329 if (in_queued_stop_replies (thread->id))
4330 {
4331 threads_debug_printf
4332 ("not resuming LWP %ld: has queued stop reply",
4333 thread->id.lwp ());
4334 continue;
4335 }
4336
4337 lwp->resume = &resume[ndx];
4338 thread->last_resume_kind = lwp->resume->kind;
4339
4340 lwp->step_range_start = lwp->resume->step_range_start;
4341 lwp->step_range_end = lwp->resume->step_range_end;
4342
4343 /* If we had a deferred signal to report, dequeue one now.
4344 This can happen if LWP gets more than one signal while
4345 trying to get out of a jump pad. */
4346 if (lwp->stopped
4347 && !lwp->status_pending_p
4348 && dequeue_one_deferred_signal (lwp, &lwp->status_pending))
4349 {
4350 lwp->status_pending_p = 1;
4351
4352 threads_debug_printf
4353 ("Dequeueing deferred signal %d for LWP %ld, "
4354 "leaving status pending.",
4355 WSTOPSIG (lwp->status_pending),
4356 thread->id.lwp ());
4357 }
4358
4359 return;
4360 }
4361 }
4362
4363 /* No resume action for this thread. */
4364 lwp->resume = NULL;
4365 }
4366
4367 bool
4368 linux_process_target::resume_status_pending (thread_info *thread)
4369 {
4370 struct lwp_info *lwp = get_thread_lwp (thread);
4371
4372 /* LWPs which will not be resumed are not interesting, because
4373 we might not wait for them next time through linux_wait. */
4374 if (lwp->resume == NULL)
4375 return false;
4376
4377 return thread_still_has_status_pending (thread);
4378 }
4379
4380 bool
4381 linux_process_target::thread_needs_step_over (thread_info *thread)
4382 {
4383 struct lwp_info *lwp = get_thread_lwp (thread);
4384 CORE_ADDR pc;
4385
4386 /* GDBserver is skipping the extra traps from the wrapper program,
4387 don't have to do step over. */
4388 if (thread->process ()->tdesc == nullptr)
4389 return false;
4390
4391 /* LWPs which will not be resumed are not interesting, because we
4392 might not wait for them next time through linux_wait. */
4393
4394 if (!lwp->stopped)
4395 {
4396 threads_debug_printf ("Need step over [LWP %ld]? Ignoring, not stopped",
4397 thread->id.lwp ());
4398 return false;
4399 }
4400
4401 if (thread->last_resume_kind == resume_stop)
4402 {
4403 threads_debug_printf
4404 ("Need step over [LWP %ld]? Ignoring, should remain stopped",
4405 thread->id.lwp ());
4406 return false;
4407 }
4408
4409 gdb_assert (lwp->suspended >= 0);
4410
4411 if (lwp->suspended)
4412 {
4413 threads_debug_printf ("Need step over [LWP %ld]? Ignoring, suspended",
4414 thread->id.lwp ());
4415 return false;
4416 }
4417
4418 if (lwp->status_pending_p)
4419 {
4420 threads_debug_printf
4421 ("Need step over [LWP %ld]? Ignoring, has pending status.",
4422 thread->id.lwp ());
4423 return false;
4424 }
4425
4426 /* Note: PC, not STOP_PC. Either GDB has adjusted the PC already,
4427 or we have. */
4428 pc = get_pc (lwp);
4429
4430 /* If the PC has changed since we stopped, then don't do anything,
4431 and let the breakpoint/tracepoint be hit. This happens if, for
4432 instance, GDB handled the decr_pc_after_break subtraction itself,
4433 GDB is OOL stepping this thread, or the user has issued a "jump"
4434 command, or poked thread's registers herself. */
4435 if (pc != lwp->stop_pc)
4436 {
4437 threads_debug_printf
4438 ("Need step over [LWP %ld]? Cancelling, PC was changed. "
4439 "Old stop_pc was 0x%s, PC is now 0x%s", thread->id.lwp (),
4440 paddress (lwp->stop_pc), paddress (pc));
4441 return false;
4442 }
4443
4444 /* On software single step target, resume the inferior with signal
4445 rather than stepping over. */
4446 if (supports_software_single_step ()
4447 && !lwp->pending_signals.empty ()
4448 && lwp_signal_can_be_delivered (lwp))
4449 {
4450 threads_debug_printf
4451 ("Need step over [LWP %ld]? Ignoring, has pending signals.",
4452 thread->id.lwp ());
4453
4454 return false;
4455 }
4456
4457 scoped_restore_current_thread restore_thread;
4458 switch_to_thread (thread);
4459
4460 /* We can only step over breakpoints we know about. */
4461 if (breakpoint_here (pc) || fast_tracepoint_jump_here (pc))
4462 {
4463 /* Don't step over a breakpoint that GDB expects to hit
4464 though. If the condition is being evaluated on the target's side
4465 and it evaluate to false, step over this breakpoint as well. */
4466 if (gdb_breakpoint_here (pc)
4467 && gdb_condition_true_at_breakpoint (pc)
4468 && gdb_no_commands_at_breakpoint (pc))
4469 {
4470 threads_debug_printf ("Need step over [LWP %ld]? yes, but found"
4471 " GDB breakpoint at 0x%s; skipping step over",
4472 thread->id.lwp (), paddress (pc));
4473
4474 return false;
4475 }
4476 else
4477 {
4478 threads_debug_printf ("Need step over [LWP %ld]? yes, "
4479 "found breakpoint at 0x%s",
4480 thread->id.lwp (), paddress (pc));
4481
4482 /* We've found an lwp that needs stepping over --- return 1 so
4483 that find_thread stops looking. */
4484 return true;
4485 }
4486 }
4487
4488 threads_debug_printf
4489 ("Need step over [LWP %ld]? No, no breakpoint found at 0x%s",
4490 thread->id.lwp (), paddress (pc));
4491
4492 return false;
4493 }
4494
4495 void
4496 linux_process_target::start_step_over (lwp_info *lwp)
4497 {
4498 thread_info *thread = lwp->thread;
4499 CORE_ADDR pc;
4500
4501 threads_debug_printf ("Starting step-over on LWP %ld. Stopping all threads",
4502 thread->id.lwp ());
4503
4504 stop_all_lwps (1, lwp);
4505
4506 if (lwp->suspended != 0)
4507 {
4508 internal_error ("LWP %ld suspended=%d\n", thread->id.lwp (),
4509 lwp->suspended);
4510 }
4511
4512 threads_debug_printf ("Done stopping all threads for step-over.");
4513
4514 /* Note, we should always reach here with an already adjusted PC,
4515 either by GDB (if we're resuming due to GDB's request), or by our
4516 caller, if we just finished handling an internal breakpoint GDB
4517 shouldn't care about. */
4518 pc = get_pc (lwp);
4519
4520 bool step = false;
4521 {
4522 scoped_restore_current_thread restore_thread;
4523 switch_to_thread (thread);
4524
4525 lwp->bp_reinsert = pc;
4526 uninsert_breakpoints_at (pc);
4527 uninsert_fast_tracepoint_jumps_at (pc);
4528
4529 step = single_step (lwp);
4530 }
4531
4532 resume_one_lwp (lwp, step, 0, NULL);
4533
4534 /* Require next event from this LWP. */
4535 step_over_bkpt = thread->id;
4536 }
4537
4538 bool
4539 linux_process_target::finish_step_over (lwp_info *lwp)
4540 {
4541 if (lwp->bp_reinsert != 0)
4542 {
4543 scoped_restore_current_thread restore_thread;
4544
4545 threads_debug_printf ("Finished step over.");
4546
4547 switch_to_thread (lwp->thread);
4548
4549 /* Reinsert any breakpoint at LWP->BP_REINSERT. Note that there
4550 may be no breakpoint to reinsert there by now. */
4551 reinsert_breakpoints_at (lwp->bp_reinsert);
4552 reinsert_fast_tracepoint_jumps_at (lwp->bp_reinsert);
4553
4554 lwp->bp_reinsert = 0;
4555
4556 /* Delete any single-step breakpoints. No longer needed. We
4557 don't have to worry about other threads hitting this trap,
4558 and later not being able to explain it, because we were
4559 stepping over a breakpoint, and we hold all threads but
4560 LWP stopped while doing that. */
4561 if (!supports_hardware_single_step ())
4562 {
4563 gdb_assert (has_single_step_breakpoints (current_thread));
4564 delete_single_step_breakpoints (current_thread);
4565 }
4566
4567 step_over_bkpt = null_ptid;
4568 return true;
4569 }
4570 else
4571 return false;
4572 }
4573
4574 void
4575 linux_process_target::complete_ongoing_step_over ()
4576 {
4577 if (step_over_bkpt != null_ptid)
4578 {
4579 struct lwp_info *lwp;
4580 int wstat;
4581 int ret;
4582
4583 threads_debug_printf ("detach: step over in progress, finish it first");
4584
4585 /* Passing NULL_PTID as filter indicates we want all events to
4586 be left pending. Eventually this returns when there are no
4587 unwaited-for children left. */
4588 ret = wait_for_event_filtered (minus_one_ptid, null_ptid, &wstat,
4589 __WALL);
4590 gdb_assert (ret == -1);
4591
4592 lwp = find_lwp_pid (step_over_bkpt);
4593 if (lwp != NULL)
4594 {
4595 finish_step_over (lwp);
4596
4597 /* If we got our step SIGTRAP, don't leave it pending,
4598 otherwise we would report it to GDB as a spurious
4599 SIGTRAP. */
4600 gdb_assert (lwp->status_pending_p);
4601 if (WIFSTOPPED (lwp->status_pending)
4602 && WSTOPSIG (lwp->status_pending) == SIGTRAP)
4603 {
4604 thread_info *thread = lwp->thread;
4605 if (thread->last_resume_kind != resume_step)
4606 {
4607 threads_debug_printf ("detach: discard step-over SIGTRAP");
4608
4609 lwp->status_pending_p = 0;
4610 lwp->status_pending = 0;
4611 resume_one_lwp (lwp, lwp->stepping, 0, NULL);
4612 }
4613 else
4614 threads_debug_printf
4615 ("detach: resume_step, not discarding step-over SIGTRAP");
4616 }
4617 }
4618 step_over_bkpt = null_ptid;
4619 unsuspend_all_lwps (lwp);
4620 }
4621 }
4622
4623 void
4624 linux_process_target::resume_one_thread (thread_info *thread,
4625 bool leave_all_stopped)
4626 {
4627 struct lwp_info *lwp = get_thread_lwp (thread);
4628 int leave_pending;
4629
4630 if (lwp->resume == NULL)
4631 return;
4632
4633 if (lwp->resume->kind == resume_stop)
4634 {
4635 threads_debug_printf ("resume_stop request for LWP %ld",
4636 thread->id.lwp ());
4637
4638 if (!lwp->stopped)
4639 {
4640 threads_debug_printf ("stopping LWP %ld", thread->id.lwp ());
4641
4642 /* Stop the thread, and wait for the event asynchronously,
4643 through the event loop. */
4644 send_sigstop (lwp);
4645 }
4646 else
4647 {
4648 threads_debug_printf ("already stopped LWP %ld", thread->id.lwp ());
4649
4650 /* The LWP may have been stopped in an internal event that
4651 was not meant to be notified back to GDB (e.g., gdbserver
4652 breakpoint), so we should be reporting a stop event in
4653 this case too. */
4654
4655 /* If the thread already has a pending SIGSTOP, this is a
4656 no-op. Otherwise, something later will presumably resume
4657 the thread and this will cause it to cancel any pending
4658 operation, due to last_resume_kind == resume_stop. If
4659 the thread already has a pending status to report, we
4660 will still report it the next time we wait - see
4661 status_pending_p_callback. */
4662
4663 /* If we already have a pending signal to report, then
4664 there's no need to queue a SIGSTOP, as this means we're
4665 midway through moving the LWP out of the jumppad, and we
4666 will report the pending signal as soon as that is
4667 finished. */
4668 if (lwp->pending_signals_to_report.empty ())
4669 send_sigstop (lwp);
4670 }
4671
4672 /* For stop requests, we're done. */
4673 lwp->resume = NULL;
4674 thread->last_status.set_ignore ();
4675 return;
4676 }
4677
4678 /* If this thread which is about to be resumed has a pending status,
4679 then don't resume it - we can just report the pending status.
4680 Likewise if it is suspended, because e.g., another thread is
4681 stepping past a breakpoint. Make sure to queue any signals that
4682 would otherwise be sent. In all-stop mode, we do this decision
4683 based on if *any* thread has a pending status. If there's a
4684 thread that needs the step-over-breakpoint dance, then don't
4685 resume any other thread but that particular one. */
4686 leave_pending = (lwp->suspended
4687 || lwp->status_pending_p
4688 || leave_all_stopped);
4689
4690 /* If we have a new signal, enqueue the signal. */
4691 if (lwp->resume->sig != 0)
4692 {
4693 siginfo_t info, *info_p;
4694
4695 /* If this is the same signal we were previously stopped by,
4696 make sure to queue its siginfo. */
4697 if (WIFSTOPPED (lwp->last_status)
4698 && WSTOPSIG (lwp->last_status) == lwp->resume->sig
4699 && ptrace (PTRACE_GETSIGINFO, thread->id.lwp (),
4700 (PTRACE_TYPE_ARG3) 0, &info) == 0)
4701 info_p = &info;
4702 else
4703 info_p = NULL;
4704
4705 enqueue_pending_signal (lwp, lwp->resume->sig, info_p);
4706 }
4707
4708 if (!leave_pending)
4709 {
4710 threads_debug_printf ("resuming LWP %ld", thread->id.lwp ());
4711
4712 proceed_one_lwp (thread, NULL);
4713 }
4714 else
4715 threads_debug_printf ("leaving LWP %ld stopped", thread->id.lwp ());
4716
4717 thread->last_status.set_ignore ();
4718 lwp->resume = NULL;
4719 }
4720
4721 void
4722 linux_process_target::resume (thread_resume *resume_info, size_t n)
4723 {
4724 thread_info *need_step_over = NULL;
4725
4726 THREADS_SCOPED_DEBUG_ENTER_EXIT;
4727
4728 for_each_thread ([&] (thread_info *thread)
4729 {
4730 linux_set_resume_request (thread, resume_info, n);
4731 });
4732
4733 /* If there is a thread which would otherwise be resumed, which has
4734 a pending status, then don't resume any threads - we can just
4735 report the pending status. Make sure to queue any signals that
4736 would otherwise be sent. In non-stop mode, we'll apply this
4737 logic to each thread individually. We consume all pending events
4738 before considering to start a step-over (in all-stop). */
4739 bool any_pending = false;
4740 if (!non_stop)
4741 any_pending = find_thread ([this] (thread_info *thread)
4742 {
4743 return resume_status_pending (thread);
4744 }) != nullptr;
4745
4746 /* If there is a thread which would otherwise be resumed, which is
4747 stopped at a breakpoint that needs stepping over, then don't
4748 resume any threads - have it step over the breakpoint with all
4749 other threads stopped, then resume all threads again. Make sure
4750 to queue any signals that would otherwise be delivered or
4751 queued. */
4752 if (!any_pending && low_supports_breakpoints ())
4753 need_step_over = find_thread ([this] (thread_info *thread)
4754 {
4755 return thread_needs_step_over (thread);
4756 });
4757
4758 bool leave_all_stopped = (need_step_over != NULL || any_pending);
4759
4760 if (need_step_over != NULL)
4761 threads_debug_printf ("Not resuming all, need step over");
4762 else if (any_pending)
4763 threads_debug_printf ("Not resuming, all-stop and found "
4764 "an LWP with pending status");
4765 else
4766 threads_debug_printf ("Resuming, no pending status or step over needed");
4767
4768 /* Even if we're leaving threads stopped, queue all signals we'd
4769 otherwise deliver. */
4770 for_each_thread ([&] (thread_info *thread)
4771 {
4772 resume_one_thread (thread, leave_all_stopped);
4773 });
4774
4775 if (need_step_over)
4776 start_step_over (get_thread_lwp (need_step_over));
4777
4778 /* We may have events that were pending that can/should be sent to
4779 the client now. Trigger a linux_wait call. */
4780 if (target_is_async_p ())
4781 async_file_mark ();
4782 }
4783
4784 void
4785 linux_process_target::proceed_one_lwp (thread_info *thread, lwp_info *except)
4786 {
4787 struct lwp_info *lwp = get_thread_lwp (thread);
4788 int step;
4789
4790 if (lwp == except)
4791 return;
4792
4793 threads_debug_printf ("lwp %ld", thread->id.lwp ());
4794
4795 if (!lwp->stopped)
4796 {
4797 threads_debug_printf (" LWP %ld already running", thread->id.lwp ());
4798 return;
4799 }
4800
4801 if (thread->last_resume_kind == resume_stop
4802 && thread->last_status.kind () != TARGET_WAITKIND_IGNORE)
4803 {
4804 threads_debug_printf (" client wants LWP to remain %ld stopped",
4805 thread->id.lwp ());
4806 return;
4807 }
4808
4809 if (lwp->status_pending_p)
4810 {
4811 threads_debug_printf (" LWP %ld has pending status, leaving stopped",
4812 thread->id.lwp ());
4813 return;
4814 }
4815
4816 gdb_assert (lwp->suspended >= 0);
4817
4818 if (lwp->suspended)
4819 {
4820 threads_debug_printf (" LWP %ld is suspended", thread->id.lwp ());
4821 return;
4822 }
4823
4824 if (thread->last_resume_kind == resume_stop
4825 && lwp->pending_signals_to_report.empty ()
4826 && (lwp->collecting_fast_tracepoint
4827 == fast_tpoint_collect_result::not_collecting))
4828 {
4829 /* We haven't reported this LWP as stopped yet (otherwise, the
4830 last_status.kind check above would catch it, and we wouldn't
4831 reach here. This LWP may have been momentarily paused by a
4832 stop_all_lwps call while handling for example, another LWP's
4833 step-over. In that case, the pending expected SIGSTOP signal
4834 that was queued at vCont;t handling time will have already
4835 been consumed by wait_for_sigstop, and so we need to requeue
4836 another one here. Note that if the LWP already has a SIGSTOP
4837 pending, this is a no-op. */
4838
4839 threads_debug_printf
4840 ("Client wants LWP %ld to stop. Making sure it has a SIGSTOP pending",
4841 thread->id.lwp ());
4842
4843 send_sigstop (lwp);
4844 }
4845
4846 if (thread->last_resume_kind == resume_step)
4847 {
4848 threads_debug_printf (" stepping LWP %ld, client wants it stepping",
4849 thread->id.lwp ());
4850
4851 /* If resume_step is requested by GDB, install single-step
4852 breakpoints when the thread is about to be actually resumed if
4853 the single-step breakpoints weren't removed. */
4854 if (supports_software_single_step ()
4855 && !has_single_step_breakpoints (thread))
4856 install_software_single_step_breakpoints (lwp);
4857
4858 step = maybe_hw_step (thread);
4859 }
4860 else if (lwp->bp_reinsert != 0)
4861 {
4862 threads_debug_printf (" stepping LWP %ld, reinsert set",
4863 thread->id.lwp ());
4864
4865 step = maybe_hw_step (thread);
4866 }
4867 else
4868 step = 0;
4869
4870 resume_one_lwp (lwp, step, 0, NULL);
4871 }
4872
4873 void
4874 linux_process_target::unsuspend_and_proceed_one_lwp (thread_info *thread,
4875 lwp_info *except)
4876 {
4877 struct lwp_info *lwp = get_thread_lwp (thread);
4878
4879 if (lwp == except)
4880 return;
4881
4882 lwp_suspended_decr (lwp);
4883
4884 proceed_one_lwp (thread, except);
4885 }
4886
4887 void
4888 linux_process_target::proceed_all_lwps ()
4889 {
4890 thread_info *need_step_over;
4891
4892 /* If there is a thread which would otherwise be resumed, which is
4893 stopped at a breakpoint that needs stepping over, then don't
4894 resume any threads - have it step over the breakpoint with all
4895 other threads stopped, then resume all threads again. */
4896
4897 if (low_supports_breakpoints ())
4898 {
4899 need_step_over = find_thread ([this] (thread_info *thread)
4900 {
4901 return thread_needs_step_over (thread);
4902 });
4903
4904 if (need_step_over != NULL)
4905 {
4906 threads_debug_printf ("found thread %ld needing a step-over",
4907 need_step_over->id.lwp ());
4908
4909 start_step_over (get_thread_lwp (need_step_over));
4910 return;
4911 }
4912 }
4913
4914 threads_debug_printf ("Proceeding, no step-over needed");
4915
4916 for_each_thread ([this] (thread_info *thread)
4917 {
4918 proceed_one_lwp (thread, NULL);
4919 });
4920 }
4921
4922 void
4923 linux_process_target::unstop_all_lwps (int unsuspend, lwp_info *except)
4924 {
4925 THREADS_SCOPED_DEBUG_ENTER_EXIT;
4926
4927 if (except)
4928 threads_debug_printf ("except=(LWP %ld)", except->thread->id.lwp ());
4929 else
4930 threads_debug_printf ("except=nullptr");
4931
4932 if (unsuspend)
4933 for_each_thread ([&] (thread_info *thread)
4934 {
4935 unsuspend_and_proceed_one_lwp (thread, except);
4936 });
4937 else
4938 for_each_thread ([&] (thread_info *thread)
4939 {
4940 proceed_one_lwp (thread, except);
4941 });
4942 }
4943
4944
4945 #ifdef HAVE_LINUX_REGSETS
4946
4947 #define use_linux_regsets 1
4948
4949 /* Returns true if REGSET has been disabled. */
4950
4951 static int
4952 regset_disabled (struct regsets_info *info, struct regset_info *regset)
4953 {
4954 return (info->disabled_regsets != NULL
4955 && info->disabled_regsets[regset - info->regsets]);
4956 }
4957
4958 /* Disable REGSET. */
4959
4960 static void
4961 disable_regset (struct regsets_info *info, struct regset_info *regset)
4962 {
4963 int dr_offset;
4964
4965 dr_offset = regset - info->regsets;
4966 if (info->disabled_regsets == NULL)
4967 info->disabled_regsets = (char *) xcalloc (1, info->num_regsets);
4968 info->disabled_regsets[dr_offset] = 1;
4969 }
4970
4971 static int
4972 regsets_fetch_inferior_registers (struct regsets_info *regsets_info,
4973 struct regcache *regcache)
4974 {
4975 struct regset_info *regset;
4976 int saw_general_regs = 0;
4977 int pid = current_thread->id.lwp ();
4978 struct iovec iov;
4979
4980 for (regset = regsets_info->regsets; regset->size >= 0; regset++)
4981 {
4982 void *buf, *data;
4983 int nt_type, res;
4984
4985 if (regset->size == 0 || regset_disabled (regsets_info, regset))
4986 continue;
4987
4988 buf = xmalloc (regset->size);
4989
4990 nt_type = regset->nt_type;
4991 if (nt_type)
4992 {
4993 iov.iov_base = buf;
4994 iov.iov_len = regset->size;
4995 data = (void *) &iov;
4996 }
4997 else
4998 data = buf;
4999
5000 #ifndef __sparc__
5001 res = ptrace (regset->get_request, pid,
5002 (PTRACE_TYPE_ARG3) (long) nt_type, data);
5003 #else
5004 res = ptrace (regset->get_request, pid, data, nt_type);
5005 #endif
5006 if (res < 0)
5007 {
5008 if (errno == EIO
5009 || (errno == EINVAL
5010 && (regset->type == OPTIONAL_REGS
5011 || regset->type == OPTIONAL_RUNTIME_REGS)))
5012 {
5013 /* If we get EIO on a regset, or an EINVAL and the regset is
5014 optional, do not try it again for this process mode.
5015 Even if the regset can be enabled at runtime it is safe
5016 to deactivate the regset in case of EINVAL, as we know
5017 the regset itself was the invalid argument of the ptrace
5018 call which means that it's unsupported by the kernel. */
5019 disable_regset (regsets_info, regset);
5020 }
5021 else if (errno == ENODATA
5022 || (errno == ENODEV
5023 && regset->type == OPTIONAL_RUNTIME_REGS)
5024 || errno == ESRCH)
5025 {
5026 /* ENODATA or ENODEV may be returned if the regset is
5027 currently not "active". For ENODEV we additionally check
5028 if the register set is of type OPTIONAL_RUNTIME_REGS.
5029 This can happen in normal operation, so suppress the
5030 warning in this case.
5031 ESRCH should mean the process is already gone at this
5032 point, in which case we simply ignore attempts to read
5033 its registers. */
5034 }
5035 else
5036 {
5037 char s[256];
5038 sprintf (s, "ptrace(regsets_fetch_inferior_registers) PID=%d",
5039 pid);
5040 perror (s);
5041 }
5042 }
5043 else
5044 {
5045 if (regset->type == GENERAL_REGS)
5046 saw_general_regs = 1;
5047 regset->store_function (regcache, buf);
5048 }
5049 free (buf);
5050 }
5051 if (saw_general_regs)
5052 return 0;
5053 else
5054 return 1;
5055 }
5056
5057 static int
5058 regsets_store_inferior_registers (struct regsets_info *regsets_info,
5059 struct regcache *regcache)
5060 {
5061 struct regset_info *regset;
5062 int saw_general_regs = 0;
5063 int pid = current_thread->id.lwp ();
5064 struct iovec iov;
5065
5066 for (regset = regsets_info->regsets; regset->size >= 0; regset++)
5067 {
5068 void *buf, *data;
5069 int nt_type, res;
5070
5071 if (regset->size == 0 || regset_disabled (regsets_info, regset)
5072 || regset->fill_function == NULL)
5073 continue;
5074
5075 buf = xmalloc (regset->size);
5076
5077 /* First fill the buffer with the current register set contents,
5078 in case there are any items in the kernel's regset that are
5079 not in gdbserver's regcache. */
5080
5081 nt_type = regset->nt_type;
5082 if (nt_type)
5083 {
5084 iov.iov_base = buf;
5085 iov.iov_len = regset->size;
5086 data = (void *) &iov;
5087 }
5088 else
5089 data = buf;
5090
5091 #ifndef __sparc__
5092 res = ptrace (regset->get_request, pid,
5093 (PTRACE_TYPE_ARG3) (long) nt_type, data);
5094 #else
5095 res = ptrace (regset->get_request, pid, data, nt_type);
5096 #endif
5097
5098 if (res == 0)
5099 {
5100 /* Then overlay our cached registers on that. */
5101 regset->fill_function (regcache, buf);
5102
5103 /* Only now do we write the register set. */
5104 #ifndef __sparc__
5105 res = ptrace (regset->set_request, pid,
5106 (PTRACE_TYPE_ARG3) (long) nt_type, data);
5107 #else
5108 res = ptrace (regset->set_request, pid, data, nt_type);
5109 #endif
5110 }
5111
5112 if (res < 0)
5113 {
5114 if (errno == EIO
5115 || (errno == EINVAL
5116 && (regset->type == OPTIONAL_REGS
5117 || regset->type == OPTIONAL_RUNTIME_REGS)))
5118 {
5119 /* If we get EIO on a regset, or an EINVAL and the regset is
5120 optional, do not try it again for this process mode.
5121 Even if the regset can be enabled at runtime it is safe
5122 to deactivate the regset in case of EINVAL, as we know
5123 the regset itself was the invalid argument of the ptrace
5124 call which means that it's unsupported by the kernel. */
5125 disable_regset (regsets_info, regset);
5126 }
5127 else if (errno == ENODEV
5128 && regset->type == OPTIONAL_RUNTIME_REGS)
5129 {
5130 /* If we get ENODEV on a regset and the regset can be
5131 enabled at runtime try it again for this process mode.
5132 This can happen in normal operation, so suppress the
5133 warning in this case. */
5134 }
5135 else if (errno == ESRCH)
5136 {
5137 /* At this point, ESRCH should mean the process is
5138 already gone, in which case we simply ignore attempts
5139 to change its registers. See also the related
5140 comment in resume_one_lwp. */
5141 free (buf);
5142 return 0;
5143 }
5144 else
5145 {
5146 perror ("Warning: ptrace(regsets_store_inferior_registers)");
5147 }
5148 }
5149 else if (regset->type == GENERAL_REGS)
5150 saw_general_regs = 1;
5151 free (buf);
5152 }
5153 if (saw_general_regs)
5154 return 0;
5155 else
5156 return 1;
5157 }
5158
5159 #else /* !HAVE_LINUX_REGSETS */
5160
5161 #define use_linux_regsets 0
5162 #define regsets_fetch_inferior_registers(regsets_info, regcache) 1
5163 #define regsets_store_inferior_registers(regsets_info, regcache) 1
5164
5165 #endif
5166
5167 /* Return 1 if register REGNO is supported by one of the regset ptrace
5168 calls or 0 if it has to be transferred individually. */
5169
5170 static int
5171 linux_register_in_regsets (const struct regs_info *regs_info, int regno)
5172 {
5173 unsigned char mask = 1 << (regno % 8);
5174 size_t index = regno / 8;
5175
5176 return (use_linux_regsets
5177 && (regs_info->regset_bitmap == NULL
5178 || (regs_info->regset_bitmap[index] & mask) != 0));
5179 }
5180
5181 #ifdef HAVE_LINUX_USRREGS
5182
5183 static int
5184 register_addr (const struct usrregs_info *usrregs, int regnum)
5185 {
5186 int addr;
5187
5188 if (regnum < 0 || regnum >= usrregs->num_regs)
5189 error ("Invalid register number %d.", regnum);
5190
5191 addr = usrregs->regmap[regnum];
5192
5193 return addr;
5194 }
5195
5196
5197 void
5198 linux_process_target::fetch_register (const usrregs_info *usrregs,
5199 regcache *regcache, int regno)
5200 {
5201 CORE_ADDR regaddr;
5202 int i, size;
5203 char *buf;
5204
5205 if (regno >= usrregs->num_regs)
5206 return;
5207 if (low_cannot_fetch_register (regno))
5208 return;
5209
5210 regaddr = register_addr (usrregs, regno);
5211 if (regaddr == -1)
5212 return;
5213
5214 size = ((register_size (regcache->tdesc, regno)
5215 + sizeof (PTRACE_XFER_TYPE) - 1)
5216 & -sizeof (PTRACE_XFER_TYPE));
5217 buf = (char *) alloca (size);
5218
5219 int pid = current_thread->id.lwp ();
5220
5221 for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
5222 {
5223 errno = 0;
5224 *(PTRACE_XFER_TYPE *) (buf + i) =
5225 ptrace (PTRACE_PEEKUSER, pid,
5226 /* Coerce to a uintptr_t first to avoid potential gcc warning
5227 of coercing an 8 byte integer to a 4 byte pointer. */
5228 (PTRACE_TYPE_ARG3) (uintptr_t) regaddr, (PTRACE_TYPE_ARG4) 0);
5229 regaddr += sizeof (PTRACE_XFER_TYPE);
5230 if (errno != 0)
5231 {
5232 /* Mark register REGNO unavailable. */
5233 supply_register (regcache, regno, NULL);
5234 return;
5235 }
5236 }
5237
5238 low_supply_ptrace_register (regcache, regno, buf);
5239 }
5240
5241 void
5242 linux_process_target::store_register (const usrregs_info *usrregs,
5243 regcache *regcache, int regno)
5244 {
5245 CORE_ADDR regaddr;
5246 int i, size;
5247 char *buf;
5248
5249 if (regno >= usrregs->num_regs)
5250 return;
5251 if (low_cannot_store_register (regno))
5252 return;
5253
5254 regaddr = register_addr (usrregs, regno);
5255 if (regaddr == -1)
5256 return;
5257
5258 size = ((register_size (regcache->tdesc, regno)
5259 + sizeof (PTRACE_XFER_TYPE) - 1)
5260 & -sizeof (PTRACE_XFER_TYPE));
5261 buf = (char *) alloca (size);
5262 memset (buf, 0, size);
5263
5264 low_collect_ptrace_register (regcache, regno, buf);
5265
5266 int pid = current_thread->id.lwp ();
5267
5268 for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
5269 {
5270 errno = 0;
5271 ptrace (PTRACE_POKEUSER, pid,
5272 /* Coerce to a uintptr_t first to avoid potential gcc warning
5273 about coercing an 8 byte integer to a 4 byte pointer. */
5274 (PTRACE_TYPE_ARG3) (uintptr_t) regaddr,
5275 (PTRACE_TYPE_ARG4) *(PTRACE_XFER_TYPE *) (buf + i));
5276 if (errno != 0)
5277 {
5278 /* At this point, ESRCH should mean the process is
5279 already gone, in which case we simply ignore attempts
5280 to change its registers. See also the related
5281 comment in resume_one_lwp. */
5282 if (errno == ESRCH)
5283 return;
5284
5285
5286 if (!low_cannot_store_register (regno))
5287 error ("writing register %d: %s", regno, safe_strerror (errno));
5288 }
5289 regaddr += sizeof (PTRACE_XFER_TYPE);
5290 }
5291 }
5292 #endif /* HAVE_LINUX_USRREGS */
5293
5294 void
5295 linux_process_target::low_collect_ptrace_register (regcache *regcache,
5296 int regno, char *buf)
5297 {
5298 collect_register (regcache, regno, buf);
5299 }
5300
5301 void
5302 linux_process_target::low_supply_ptrace_register (regcache *regcache,
5303 int regno, const char *buf)
5304 {
5305 supply_register (regcache, regno, buf);
5306 }
5307
5308 void
5309 linux_process_target::usr_fetch_inferior_registers (const regs_info *regs_info,
5310 regcache *regcache,
5311 int regno, int all)
5312 {
5313 #ifdef HAVE_LINUX_USRREGS
5314 struct usrregs_info *usr = regs_info->usrregs;
5315
5316 if (regno == -1)
5317 {
5318 for (regno = 0; regno < usr->num_regs; regno++)
5319 if (all || !linux_register_in_regsets (regs_info, regno))
5320 fetch_register (usr, regcache, regno);
5321 }
5322 else
5323 fetch_register (usr, regcache, regno);
5324 #endif
5325 }
5326
5327 void
5328 linux_process_target::usr_store_inferior_registers (const regs_info *regs_info,
5329 regcache *regcache,
5330 int regno, int all)
5331 {
5332 #ifdef HAVE_LINUX_USRREGS
5333 struct usrregs_info *usr = regs_info->usrregs;
5334
5335 if (regno == -1)
5336 {
5337 for (regno = 0; regno < usr->num_regs; regno++)
5338 if (all || !linux_register_in_regsets (regs_info, regno))
5339 store_register (usr, regcache, regno);
5340 }
5341 else
5342 store_register (usr, regcache, regno);
5343 #endif
5344 }
5345
5346 void
5347 linux_process_target::fetch_registers (regcache *regcache, int regno)
5348 {
5349 int use_regsets;
5350 int all = 0;
5351 const regs_info *regs_info = get_regs_info ();
5352
5353 if (regno == -1)
5354 {
5355 if (regs_info->usrregs != NULL)
5356 for (regno = 0; regno < regs_info->usrregs->num_regs; regno++)
5357 low_fetch_register (regcache, regno);
5358
5359 all = regsets_fetch_inferior_registers (regs_info->regsets_info, regcache);
5360 if (regs_info->usrregs != NULL)
5361 usr_fetch_inferior_registers (regs_info, regcache, -1, all);
5362 }
5363 else
5364 {
5365 if (low_fetch_register (regcache, regno))
5366 return;
5367
5368 use_regsets = linux_register_in_regsets (regs_info, regno);
5369 if (use_regsets)
5370 all = regsets_fetch_inferior_registers (regs_info->regsets_info,
5371 regcache);
5372 if ((!use_regsets || all) && regs_info->usrregs != NULL)
5373 usr_fetch_inferior_registers (regs_info, regcache, regno, 1);
5374 }
5375 }
5376
5377 void
5378 linux_process_target::store_registers (regcache *regcache, int regno)
5379 {
5380 int use_regsets;
5381 int all = 0;
5382 const regs_info *regs_info = get_regs_info ();
5383
5384 if (regno == -1)
5385 {
5386 all = regsets_store_inferior_registers (regs_info->regsets_info,
5387 regcache);
5388 if (regs_info->usrregs != NULL)
5389 usr_store_inferior_registers (regs_info, regcache, regno, all);
5390 }
5391 else
5392 {
5393 use_regsets = linux_register_in_regsets (regs_info, regno);
5394 if (use_regsets)
5395 all = regsets_store_inferior_registers (regs_info->regsets_info,
5396 regcache);
5397 if ((!use_regsets || all) && regs_info->usrregs != NULL)
5398 usr_store_inferior_registers (regs_info, regcache, regno, 1);
5399 }
5400 }
5401
5402 bool
5403 linux_process_target::low_fetch_register (regcache *regcache, int regno)
5404 {
5405 return false;
5406 }
5407
5408 /* A wrapper for the read_memory target op. */
5409
5410 static int
5411 linux_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
5412 {
5413 return the_target->read_memory (memaddr, myaddr, len);
5414 }
5415
5416
5417 /* Helper for read_memory/write_memory using /proc/PID/mem. Because
5418 we can use a single read/write call, this can be much more
5419 efficient than banging away at PTRACE_PEEKTEXT. Also, unlike
5420 PTRACE_PEEKTEXT/PTRACE_POKETEXT, this works with running threads.
5421 One an only one of READBUF and WRITEBUF is non-null. If READBUF is
5422 not null, then we're reading, otherwise we're writing. */
5423
5424 static int
5425 proc_xfer_memory (CORE_ADDR memaddr, unsigned char *readbuf,
5426 const gdb_byte *writebuf, int len)
5427 {
5428 gdb_assert ((readbuf == nullptr) != (writebuf == nullptr));
5429
5430 process_info *proc = current_process ();
5431
5432 int fd = proc->priv->mem_fd;
5433 if (fd == -1)
5434 return EIO;
5435
5436 while (len > 0)
5437 {
5438 int bytes;
5439
5440 /* Use pread64/pwrite64 if available, since they save a syscall
5441 and can handle 64-bit offsets even on 32-bit platforms (for
5442 instance, SPARC debugging a SPARC64 application). But only
5443 use them if the offset isn't so high that when cast to off_t
5444 it'd be negative, as seen on SPARC64. pread64/pwrite64
5445 outright reject such offsets. lseek does not. */
5446 #ifdef HAVE_PREAD64
5447 if ((off_t) memaddr >= 0)
5448 bytes = (readbuf != nullptr
5449 ? pread64 (fd, readbuf, len, memaddr)
5450 : pwrite64 (fd, writebuf, len, memaddr));
5451 else
5452 #endif
5453 {
5454 bytes = -1;
5455 if (lseek (fd, memaddr, SEEK_SET) != -1)
5456 bytes = (readbuf != nullptr
5457 ? read (fd, readbuf, len)
5458 : write (fd, writebuf, len));
5459 }
5460
5461 if (bytes < 0)
5462 return errno;
5463 else if (bytes == 0)
5464 {
5465 /* EOF means the address space is gone, the whole process
5466 exited or execed. */
5467 return EIO;
5468 }
5469
5470 memaddr += bytes;
5471 if (readbuf != nullptr)
5472 readbuf += bytes;
5473 else
5474 writebuf += bytes;
5475 len -= bytes;
5476 }
5477
5478 return 0;
5479 }
5480
5481 int
5482 linux_process_target::read_memory (CORE_ADDR memaddr,
5483 unsigned char *myaddr, int len)
5484 {
5485 return proc_xfer_memory (memaddr, myaddr, nullptr, len);
5486 }
5487
5488 /* Copy LEN bytes of data from debugger memory at MYADDR to inferior's
5489 memory at MEMADDR. On failure (cannot write to the inferior)
5490 returns the value of errno. Always succeeds if LEN is zero. */
5491
5492 int
5493 linux_process_target::write_memory (CORE_ADDR memaddr,
5494 const unsigned char *myaddr, int len)
5495 {
5496 if (debug_threads)
5497 {
5498 /* Dump up to four bytes. */
5499 char str[4 * 2 + 1];
5500 char *p = str;
5501 int dump = len < 4 ? len : 4;
5502
5503 for (int i = 0; i < dump; i++)
5504 {
5505 sprintf (p, "%02x", myaddr[i]);
5506 p += 2;
5507 }
5508 *p = '\0';
5509
5510 threads_debug_printf ("Writing %s to 0x%08lx in process %d",
5511 str, (long) memaddr, current_process ()->pid);
5512 }
5513
5514 return proc_xfer_memory (memaddr, nullptr, myaddr, len);
5515 }
5516
5517 void
5518 linux_process_target::look_up_symbols ()
5519 {
5520 #ifdef USE_THREAD_DB
5521 struct process_info *proc = current_process ();
5522
5523 if (proc->priv->thread_db != NULL)
5524 return;
5525
5526 thread_db_init ();
5527 #endif
5528 }
5529
5530 void
5531 linux_process_target::request_interrupt ()
5532 {
5533 /* Send a SIGINT to the process group. This acts just like the user
5534 typed a ^C on the controlling terminal. */
5535 int res = ::kill (-signal_pid, SIGINT);
5536 if (res == -1)
5537 warning (_("Sending SIGINT to process group of pid %ld failed: %s"),
5538 signal_pid, safe_strerror (errno));
5539 }
5540
5541 bool
5542 linux_process_target::supports_read_auxv ()
5543 {
5544 return true;
5545 }
5546
5547 /* Copy LEN bytes from inferior's auxiliary vector starting at OFFSET
5548 to debugger memory starting at MYADDR. */
5549
5550 int
5551 linux_process_target::read_auxv (int pid, CORE_ADDR offset,
5552 unsigned char *myaddr, unsigned int len)
5553 {
5554 char filename[PATH_MAX];
5555 int fd, n;
5556
5557 xsnprintf (filename, sizeof filename, "/proc/%d/auxv", pid);
5558
5559 fd = open (filename, O_RDONLY);
5560 if (fd < 0)
5561 return -1;
5562
5563 if (offset != (CORE_ADDR) 0
5564 && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
5565 n = -1;
5566 else
5567 n = read (fd, myaddr, len);
5568
5569 close (fd);
5570
5571 return n;
5572 }
5573
5574 int
5575 linux_process_target::insert_point (enum raw_bkpt_type type, CORE_ADDR addr,
5576 int size, raw_breakpoint *bp)
5577 {
5578 if (type == raw_bkpt_type_sw)
5579 return insert_memory_breakpoint (bp);
5580 else
5581 return low_insert_point (type, addr, size, bp);
5582 }
5583
5584 int
5585 linux_process_target::low_insert_point (raw_bkpt_type type, CORE_ADDR addr,
5586 int size, raw_breakpoint *bp)
5587 {
5588 /* Unsupported (see target.h). */
5589 return 1;
5590 }
5591
5592 int
5593 linux_process_target::remove_point (enum raw_bkpt_type type, CORE_ADDR addr,
5594 int size, raw_breakpoint *bp)
5595 {
5596 if (type == raw_bkpt_type_sw)
5597 return remove_memory_breakpoint (bp);
5598 else
5599 return low_remove_point (type, addr, size, bp);
5600 }
5601
5602 int
5603 linux_process_target::low_remove_point (raw_bkpt_type type, CORE_ADDR addr,
5604 int size, raw_breakpoint *bp)
5605 {
5606 /* Unsupported (see target.h). */
5607 return 1;
5608 }
5609
5610 /* Implement the stopped_by_sw_breakpoint target_ops
5611 method. */
5612
5613 bool
5614 linux_process_target::stopped_by_sw_breakpoint ()
5615 {
5616 struct lwp_info *lwp = get_thread_lwp (current_thread);
5617
5618 return (lwp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
5619 }
5620
5621 /* Implement the supports_stopped_by_sw_breakpoint target_ops
5622 method. */
5623
5624 bool
5625 linux_process_target::supports_stopped_by_sw_breakpoint ()
5626 {
5627 return true;
5628 }
5629
5630 /* Implement the stopped_by_hw_breakpoint target_ops
5631 method. */
5632
5633 bool
5634 linux_process_target::stopped_by_hw_breakpoint ()
5635 {
5636 struct lwp_info *lwp = get_thread_lwp (current_thread);
5637
5638 return (lwp->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
5639 }
5640
5641 /* Implement the supports_stopped_by_hw_breakpoint target_ops
5642 method. */
5643
5644 bool
5645 linux_process_target::supports_stopped_by_hw_breakpoint ()
5646 {
5647 return true;
5648 }
5649
5650 /* Implement the supports_hardware_single_step target_ops method. */
5651
5652 bool
5653 linux_process_target::supports_hardware_single_step ()
5654 {
5655 return true;
5656 }
5657
5658 bool
5659 linux_process_target::stopped_by_watchpoint ()
5660 {
5661 struct lwp_info *lwp = get_thread_lwp (current_thread);
5662
5663 return lwp->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
5664 }
5665
5666 CORE_ADDR
5667 linux_process_target::stopped_data_address ()
5668 {
5669 struct lwp_info *lwp = get_thread_lwp (current_thread);
5670
5671 return lwp->stopped_data_address;
5672 }
5673
5674 /* This is only used for targets that define PT_TEXT_ADDR,
5675 PT_DATA_ADDR and PT_TEXT_END_ADDR. If those are not defined, supposedly
5676 the target has different ways of acquiring this information, like
5677 loadmaps. */
5678
5679 bool
5680 linux_process_target::supports_read_offsets ()
5681 {
5682 #ifdef SUPPORTS_READ_OFFSETS
5683 return true;
5684 #else
5685 return false;
5686 #endif
5687 }
5688
5689 /* Under uClinux, programs are loaded at non-zero offsets, which we need
5690 to tell gdb about. */
5691
5692 int
5693 linux_process_target::read_offsets (CORE_ADDR *text_p, CORE_ADDR *data_p)
5694 {
5695 #ifdef SUPPORTS_READ_OFFSETS
5696 unsigned long text, text_end, data;
5697 int pid = current_thread->id.lwp ();
5698
5699 errno = 0;
5700
5701 text = ptrace (PTRACE_PEEKUSER, pid, (PTRACE_TYPE_ARG3) PT_TEXT_ADDR,
5702 (PTRACE_TYPE_ARG4) 0);
5703 text_end = ptrace (PTRACE_PEEKUSER, pid, (PTRACE_TYPE_ARG3) PT_TEXT_END_ADDR,
5704 (PTRACE_TYPE_ARG4) 0);
5705 data = ptrace (PTRACE_PEEKUSER, pid, (PTRACE_TYPE_ARG3) PT_DATA_ADDR,
5706 (PTRACE_TYPE_ARG4) 0);
5707
5708 if (errno == 0)
5709 {
5710 /* Both text and data offsets produced at compile-time (and so
5711 used by gdb) are relative to the beginning of the program,
5712 with the data segment immediately following the text segment.
5713 However, the actual runtime layout in memory may put the data
5714 somewhere else, so when we send gdb a data base-address, we
5715 use the real data base address and subtract the compile-time
5716 data base-address from it (which is just the length of the
5717 text segment). BSS immediately follows data in both
5718 cases. */
5719 *text_p = text;
5720 *data_p = data - (text_end - text);
5721
5722 return 1;
5723 }
5724 return 0;
5725 #else
5726 gdb_assert_not_reached ("target op read_offsets not supported");
5727 #endif
5728 }
5729
5730 bool
5731 linux_process_target::supports_get_tls_address ()
5732 {
5733 #ifdef USE_THREAD_DB
5734 return true;
5735 #else
5736 return false;
5737 #endif
5738 }
5739
5740 int
5741 linux_process_target::get_tls_address (thread_info *thread,
5742 CORE_ADDR offset,
5743 CORE_ADDR load_module,
5744 CORE_ADDR *address)
5745 {
5746 #ifdef USE_THREAD_DB
5747 return thread_db_get_tls_address (thread, offset, load_module, address);
5748 #else
5749 return -1;
5750 #endif
5751 }
5752
5753 bool
5754 linux_process_target::supports_qxfer_osdata ()
5755 {
5756 return true;
5757 }
5758
5759 int
5760 linux_process_target::qxfer_osdata (const char *annex,
5761 unsigned char *readbuf,
5762 unsigned const char *writebuf,
5763 CORE_ADDR offset, int len)
5764 {
5765 return linux_common_xfer_osdata (annex, readbuf, offset, len);
5766 }
5767
5768 void
5769 linux_process_target::siginfo_fixup (siginfo_t *siginfo,
5770 gdb_byte *inf_siginfo, int direction)
5771 {
5772 bool done = low_siginfo_fixup (siginfo, inf_siginfo, direction);
5773
5774 /* If there was no callback, or the callback didn't do anything,
5775 then just do a straight memcpy. */
5776 if (!done)
5777 {
5778 if (direction == 1)
5779 memcpy (siginfo, inf_siginfo, sizeof (siginfo_t));
5780 else
5781 memcpy (inf_siginfo, siginfo, sizeof (siginfo_t));
5782 }
5783 }
5784
5785 bool
5786 linux_process_target::low_siginfo_fixup (siginfo_t *native, gdb_byte *inf,
5787 int direction)
5788 {
5789 return false;
5790 }
5791
5792 bool
5793 linux_process_target::supports_qxfer_siginfo ()
5794 {
5795 return true;
5796 }
5797
5798 int
5799 linux_process_target::qxfer_siginfo (const char *annex,
5800 unsigned char *readbuf,
5801 unsigned const char *writebuf,
5802 CORE_ADDR offset, int len)
5803 {
5804 siginfo_t siginfo;
5805 gdb_byte inf_siginfo[sizeof (siginfo_t)];
5806
5807 if (current_thread == NULL)
5808 return -1;
5809
5810 int pid = current_thread->id.lwp ();
5811
5812 threads_debug_printf ("%s siginfo for lwp %d.",
5813 readbuf != NULL ? "Reading" : "Writing",
5814 pid);
5815
5816 if (offset >= sizeof (siginfo))
5817 return -1;
5818
5819 if (ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo) != 0)
5820 return -1;
5821
5822 /* When GDBSERVER is built as a 64-bit application, ptrace writes into
5823 SIGINFO an object with 64-bit layout. Since debugging a 32-bit
5824 inferior with a 64-bit GDBSERVER should look the same as debugging it
5825 with a 32-bit GDBSERVER, we need to convert it. */
5826 siginfo_fixup (&siginfo, inf_siginfo, 0);
5827
5828 if (offset + len > sizeof (siginfo))
5829 len = sizeof (siginfo) - offset;
5830
5831 if (readbuf != NULL)
5832 memcpy (readbuf, inf_siginfo + offset, len);
5833 else
5834 {
5835 memcpy (inf_siginfo + offset, writebuf, len);
5836
5837 /* Convert back to ptrace layout before flushing it out. */
5838 siginfo_fixup (&siginfo, inf_siginfo, 1);
5839
5840 if (ptrace (PTRACE_SETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo) != 0)
5841 return -1;
5842 }
5843
5844 return len;
5845 }
5846
5847 /* SIGCHLD handler that serves two purposes: In non-stop/async mode,
5848 so we notice when children change state; as the handler for the
5849 sigsuspend in my_waitpid. */
5850
5851 static void
5852 sigchld_handler (int signo)
5853 {
5854 int old_errno = errno;
5855
5856 if (debug_threads)
5857 {
5858 do
5859 {
5860 /* Use the async signal safe debug function. */
5861 if (debug_write ("sigchld_handler\n",
5862 sizeof ("sigchld_handler\n") - 1) < 0)
5863 break; /* just ignore */
5864 } while (0);
5865 }
5866
5867 if (target_is_async_p ())
5868 async_file_mark (); /* trigger a linux_wait */
5869
5870 errno = old_errno;
5871 }
5872
5873 bool
5874 linux_process_target::supports_non_stop ()
5875 {
5876 return true;
5877 }
5878
5879 bool
5880 linux_process_target::async (bool enable)
5881 {
5882 bool previous = target_is_async_p ();
5883
5884 threads_debug_printf ("async (%d), previous=%d",
5885 enable, previous);
5886
5887 if (previous != enable)
5888 {
5889 sigset_t mask;
5890 sigemptyset (&mask);
5891 sigaddset (&mask, SIGCHLD);
5892
5893 gdb_sigmask (SIG_BLOCK, &mask, NULL);
5894
5895 if (enable)
5896 {
5897 if (!linux_event_pipe.open_pipe ())
5898 {
5899 gdb_sigmask (SIG_UNBLOCK, &mask, NULL);
5900
5901 warning ("creating event pipe failed.");
5902 return previous;
5903 }
5904
5905 /* Register the event loop handler. */
5906 add_file_handler (linux_event_pipe.event_fd (),
5907 handle_target_event, NULL,
5908 "linux-low");
5909
5910 /* Always trigger a linux_wait. */
5911 async_file_mark ();
5912 }
5913 else
5914 {
5915 delete_file_handler (linux_event_pipe.event_fd ());
5916
5917 linux_event_pipe.close_pipe ();
5918 }
5919
5920 gdb_sigmask (SIG_UNBLOCK, &mask, NULL);
5921 }
5922
5923 return previous;
5924 }
5925
5926 int
5927 linux_process_target::start_non_stop (bool nonstop)
5928 {
5929 /* Register or unregister from event-loop accordingly. */
5930 target_async (nonstop);
5931
5932 if (target_is_async_p () != (nonstop != false))
5933 return -1;
5934
5935 return 0;
5936 }
5937
5938 bool
5939 linux_process_target::supports_multi_process ()
5940 {
5941 return true;
5942 }
5943
5944 /* Check if fork events are supported. */
5945
5946 bool
5947 linux_process_target::supports_fork_events ()
5948 {
5949 return true;
5950 }
5951
5952 /* Check if vfork events are supported. */
5953
5954 bool
5955 linux_process_target::supports_vfork_events ()
5956 {
5957 return true;
5958 }
5959
5960 /* Return the set of supported thread options. */
5961
5962 gdb_thread_options
5963 linux_process_target::supported_thread_options ()
5964 {
5965 return GDB_THREAD_OPTION_CLONE | GDB_THREAD_OPTION_EXIT;
5966 }
5967
5968 /* Check if exec events are supported. */
5969
5970 bool
5971 linux_process_target::supports_exec_events ()
5972 {
5973 return true;
5974 }
5975
5976 /* Target hook for 'handle_new_gdb_connection'. Causes a reset of the
5977 ptrace flags for all inferiors. This is in case the new GDB connection
5978 doesn't support the same set of events that the previous one did. */
5979
5980 void
5981 linux_process_target::handle_new_gdb_connection ()
5982 {
5983 /* Request that all the lwps reset their ptrace options. */
5984 for_each_thread ([] (thread_info *thread)
5985 {
5986 struct lwp_info *lwp = get_thread_lwp (thread);
5987
5988 if (!lwp->stopped)
5989 {
5990 /* Stop the lwp so we can modify its ptrace options. */
5991 lwp->must_set_ptrace_flags = 1;
5992 linux_stop_lwp (lwp);
5993 }
5994 else
5995 {
5996 /* Already stopped; go ahead and set the ptrace options. */
5997 process_info *proc = find_process_pid (thread->id.pid ());
5998 int options = linux_low_ptrace_options (proc->attached);
5999
6000 linux_enable_event_reporting (thread->id.lwp (), options);
6001 lwp->must_set_ptrace_flags = 0;
6002 }
6003 });
6004 }
6005
6006 int
6007 linux_process_target::handle_monitor_command (char *mon)
6008 {
6009 #ifdef USE_THREAD_DB
6010 return thread_db_handle_monitor_command (mon);
6011 #else
6012 return 0;
6013 #endif
6014 }
6015
6016 int
6017 linux_process_target::core_of_thread (ptid_t ptid)
6018 {
6019 return linux_common_core_of_thread (ptid);
6020 }
6021
6022 bool
6023 linux_process_target::supports_disable_randomization ()
6024 {
6025 return true;
6026 }
6027
6028 bool
6029 linux_process_target::supports_agent ()
6030 {
6031 return true;
6032 }
6033
6034 bool
6035 linux_process_target::supports_range_stepping ()
6036 {
6037 if (supports_software_single_step ())
6038 return true;
6039
6040 return low_supports_range_stepping ();
6041 }
6042
6043 bool
6044 linux_process_target::low_supports_range_stepping ()
6045 {
6046 return false;
6047 }
6048
6049 bool
6050 linux_process_target::supports_pid_to_exec_file ()
6051 {
6052 return true;
6053 }
6054
6055 const char *
6056 linux_process_target::pid_to_exec_file (int pid)
6057 {
6058 return linux_proc_pid_to_exec_file (pid, linux_ns_same (pid, LINUX_NS_MNT));
6059 }
6060
6061 bool
6062 linux_process_target::supports_multifs ()
6063 {
6064 return true;
6065 }
6066
6067 int
6068 linux_process_target::multifs_open (int pid, const char *filename,
6069 int flags, mode_t mode)
6070 {
6071 return linux_mntns_open_cloexec (pid, filename, flags, mode);
6072 }
6073
6074 int
6075 linux_process_target::multifs_lstat (int pid, const char *filename, struct stat *sb)
6076 {
6077 return linux_mntns_lstat (pid, filename, sb);
6078 }
6079
6080 int
6081 linux_process_target::multifs_unlink (int pid, const char *filename)
6082 {
6083 return linux_mntns_unlink (pid, filename);
6084 }
6085
6086 ssize_t
6087 linux_process_target::multifs_readlink (int pid, const char *filename,
6088 char *buf, size_t bufsiz)
6089 {
6090 return linux_mntns_readlink (pid, filename, buf, bufsiz);
6091 }
6092
6093 #if defined PT_GETDSBT || defined PTRACE_GETFDPIC
6094 struct target_loadseg
6095 {
6096 /* Core address to which the segment is mapped. */
6097 Elf32_Addr addr;
6098 /* VMA recorded in the program header. */
6099 Elf32_Addr p_vaddr;
6100 /* Size of this segment in memory. */
6101 Elf32_Word p_memsz;
6102 };
6103
6104 # if defined PT_GETDSBT
6105 struct target_loadmap
6106 {
6107 /* Protocol version number, must be zero. */
6108 Elf32_Word version;
6109 /* Pointer to the DSBT table, its size, and the DSBT index. */
6110 unsigned *dsbt_table;
6111 unsigned dsbt_size, dsbt_index;
6112 /* Number of segments in this map. */
6113 Elf32_Word nsegs;
6114 /* The actual memory map. */
6115 struct target_loadseg segs[/*nsegs*/];
6116 };
6117 # define LINUX_LOADMAP PT_GETDSBT
6118 # define LINUX_LOADMAP_EXEC PTRACE_GETDSBT_EXEC
6119 # define LINUX_LOADMAP_INTERP PTRACE_GETDSBT_INTERP
6120 # else
6121 struct target_loadmap
6122 {
6123 /* Protocol version number, must be zero. */
6124 Elf32_Half version;
6125 /* Number of segments in this map. */
6126 Elf32_Half nsegs;
6127 /* The actual memory map. */
6128 struct target_loadseg segs[/*nsegs*/];
6129 };
6130 # define LINUX_LOADMAP PTRACE_GETFDPIC
6131 # define LINUX_LOADMAP_EXEC PTRACE_GETFDPIC_EXEC
6132 # define LINUX_LOADMAP_INTERP PTRACE_GETFDPIC_INTERP
6133 # endif
6134
6135 bool
6136 linux_process_target::supports_read_loadmap ()
6137 {
6138 return true;
6139 }
6140
6141 int
6142 linux_process_target::read_loadmap (const char *annex, CORE_ADDR offset,
6143 unsigned char *myaddr, unsigned int len)
6144 {
6145 int pid = current_thread->id.lwp ();
6146 int addr = -1;
6147 struct target_loadmap *data = NULL;
6148 unsigned int actual_length, copy_length;
6149
6150 if (strcmp (annex, "exec") == 0)
6151 addr = (int) LINUX_LOADMAP_EXEC;
6152 else if (strcmp (annex, "interp") == 0)
6153 addr = (int) LINUX_LOADMAP_INTERP;
6154 else
6155 return -1;
6156
6157 if (ptrace (LINUX_LOADMAP, pid, addr, &data) != 0)
6158 return -1;
6159
6160 if (data == NULL)
6161 return -1;
6162
6163 actual_length = sizeof (struct target_loadmap)
6164 + sizeof (struct target_loadseg) * data->nsegs;
6165
6166 if (offset < 0 || offset > actual_length)
6167 return -1;
6168
6169 copy_length = actual_length - offset < len ? actual_length - offset : len;
6170 memcpy (myaddr, (char *) data + offset, copy_length);
6171 return copy_length;
6172 }
6173 #endif /* defined PT_GETDSBT || defined PTRACE_GETFDPIC */
6174
6175 bool
6176 linux_process_target::supports_catch_syscall ()
6177 {
6178 return low_supports_catch_syscall ();
6179 }
6180
6181 bool
6182 linux_process_target::low_supports_catch_syscall ()
6183 {
6184 return false;
6185 }
6186
6187 CORE_ADDR
6188 linux_process_target::read_pc (regcache *regcache)
6189 {
6190 if (!low_supports_breakpoints ())
6191 return 0;
6192
6193 return low_get_pc (regcache);
6194 }
6195
6196 void
6197 linux_process_target::write_pc (regcache *regcache, CORE_ADDR pc)
6198 {
6199 gdb_assert (low_supports_breakpoints ());
6200
6201 low_set_pc (regcache, pc);
6202 }
6203
6204 bool
6205 linux_process_target::supports_thread_stopped ()
6206 {
6207 return true;
6208 }
6209
6210 bool
6211 linux_process_target::thread_stopped (thread_info *thread)
6212 {
6213 return get_thread_lwp (thread)->stopped;
6214 }
6215
6216 bool
6217 linux_process_target::any_resumed ()
6218 {
6219 bool any_resumed;
6220
6221 auto status_pending_p_any = [&] (thread_info *thread)
6222 {
6223 return status_pending_p_callback (thread, minus_one_ptid);
6224 };
6225
6226 auto not_stopped = [&] (thread_info *thread)
6227 {
6228 return not_stopped_callback (thread, minus_one_ptid);
6229 };
6230
6231 /* Find a resumed LWP, if any. */
6232 if (find_thread (status_pending_p_any) != NULL)
6233 any_resumed = 1;
6234 else if (find_thread (not_stopped) != NULL)
6235 any_resumed = 1;
6236 else
6237 any_resumed = 0;
6238
6239 return any_resumed;
6240 }
6241
6242 /* This exposes stop-all-threads functionality to other modules. */
6243
6244 void
6245 linux_process_target::pause_all (bool freeze)
6246 {
6247 stop_all_lwps (freeze, NULL);
6248 }
6249
6250 /* This exposes unstop-all-threads functionality to other gdbserver
6251 modules. */
6252
6253 void
6254 linux_process_target::unpause_all (bool unfreeze)
6255 {
6256 unstop_all_lwps (unfreeze, NULL);
6257 }
6258
6259 /* Extract &phdr and num_phdr in the inferior. Return 0 on success. */
6260
6261 static int
6262 get_phdr_phnum_from_proc_auxv (const int pid, const int is_elf64,
6263 CORE_ADDR *phdr_memaddr, int *num_phdr)
6264 {
6265 char filename[PATH_MAX];
6266 int fd;
6267 const int auxv_size = is_elf64
6268 ? sizeof (Elf64_auxv_t) : sizeof (Elf32_auxv_t);
6269 char buf[sizeof (Elf64_auxv_t)]; /* The larger of the two. */
6270
6271 xsnprintf (filename, sizeof filename, "/proc/%d/auxv", pid);
6272
6273 fd = open (filename, O_RDONLY);
6274 if (fd < 0)
6275 return 1;
6276
6277 *phdr_memaddr = 0;
6278 *num_phdr = 0;
6279 while (read (fd, buf, auxv_size) == auxv_size
6280 && (*phdr_memaddr == 0 || *num_phdr == 0))
6281 {
6282 if (is_elf64)
6283 {
6284 Elf64_auxv_t *const aux = (Elf64_auxv_t *) buf;
6285
6286 switch (aux->a_type)
6287 {
6288 case AT_PHDR:
6289 *phdr_memaddr = aux->a_un.a_val;
6290 break;
6291 case AT_PHNUM:
6292 *num_phdr = aux->a_un.a_val;
6293 break;
6294 }
6295 }
6296 else
6297 {
6298 Elf32_auxv_t *const aux = (Elf32_auxv_t *) buf;
6299
6300 switch (aux->a_type)
6301 {
6302 case AT_PHDR:
6303 *phdr_memaddr = aux->a_un.a_val;
6304 break;
6305 case AT_PHNUM:
6306 *num_phdr = aux->a_un.a_val;
6307 break;
6308 }
6309 }
6310 }
6311
6312 close (fd);
6313
6314 if (*phdr_memaddr == 0 || *num_phdr == 0)
6315 {
6316 warning ("Unexpected missing AT_PHDR and/or AT_PHNUM: "
6317 "phdr_memaddr = %ld, phdr_num = %d",
6318 (long) *phdr_memaddr, *num_phdr);
6319 return 2;
6320 }
6321
6322 return 0;
6323 }
6324
6325 /* Return &_DYNAMIC (via PT_DYNAMIC) in the inferior, or 0 if not present. */
6326
6327 static CORE_ADDR
6328 get_dynamic (const int pid, const int is_elf64)
6329 {
6330 CORE_ADDR phdr_memaddr, relocation;
6331 int num_phdr, i;
6332 unsigned char *phdr_buf;
6333 const int phdr_size = is_elf64 ? sizeof (Elf64_Phdr) : sizeof (Elf32_Phdr);
6334
6335 if (get_phdr_phnum_from_proc_auxv (pid, is_elf64, &phdr_memaddr, &num_phdr))
6336 return 0;
6337
6338 gdb_assert (num_phdr < 100); /* Basic sanity check. */
6339 phdr_buf = (unsigned char *) alloca (num_phdr * phdr_size);
6340
6341 if (linux_read_memory (phdr_memaddr, phdr_buf, num_phdr * phdr_size))
6342 return 0;
6343
6344 /* Compute relocation: it is expected to be 0 for "regular" executables,
6345 non-zero for PIE ones. */
6346 relocation = -1;
6347 for (i = 0; relocation == -1 && i < num_phdr; i++)
6348 if (is_elf64)
6349 {
6350 Elf64_Phdr *const p = (Elf64_Phdr *) (phdr_buf + i * phdr_size);
6351
6352 if (p->p_type == PT_PHDR)
6353 relocation = phdr_memaddr - p->p_vaddr;
6354 }
6355 else
6356 {
6357 Elf32_Phdr *const p = (Elf32_Phdr *) (phdr_buf + i * phdr_size);
6358
6359 if (p->p_type == PT_PHDR)
6360 relocation = phdr_memaddr - p->p_vaddr;
6361 }
6362
6363 if (relocation == -1)
6364 {
6365 /* PT_PHDR is optional, but necessary for PIE in general. Fortunately
6366 any real world executables, including PIE executables, have always
6367 PT_PHDR present. PT_PHDR is not present in some shared libraries or
6368 in fpc (Free Pascal 2.4) binaries but neither of those have a need for
6369 or present DT_DEBUG anyway (fpc binaries are statically linked).
6370
6371 Therefore if there exists DT_DEBUG there is always also PT_PHDR.
6372
6373 GDB could find RELOCATION also from AT_ENTRY - e_entry. */
6374
6375 return 0;
6376 }
6377
6378 for (i = 0; i < num_phdr; i++)
6379 {
6380 if (is_elf64)
6381 {
6382 Elf64_Phdr *const p = (Elf64_Phdr *) (phdr_buf + i * phdr_size);
6383
6384 if (p->p_type == PT_DYNAMIC)
6385 return p->p_vaddr + relocation;
6386 }
6387 else
6388 {
6389 Elf32_Phdr *const p = (Elf32_Phdr *) (phdr_buf + i * phdr_size);
6390
6391 if (p->p_type == PT_DYNAMIC)
6392 return p->p_vaddr + relocation;
6393 }
6394 }
6395
6396 return 0;
6397 }
6398
6399 /* Return &_r_debug in the inferior, or -1 if not present. Return value
6400 can be 0 if the inferior does not yet have the library list initialized.
6401 We look for DT_MIPS_RLD_MAP first. MIPS executables use this instead of
6402 DT_DEBUG, although they sometimes contain an unused DT_DEBUG entry too. */
6403
6404 static CORE_ADDR
6405 get_r_debug (const int pid, const int is_elf64)
6406 {
6407 CORE_ADDR dynamic_memaddr;
6408 const int dyn_size = is_elf64 ? sizeof (Elf64_Dyn) : sizeof (Elf32_Dyn);
6409 unsigned char buf[sizeof (Elf64_Dyn)]; /* The larger of the two. */
6410 CORE_ADDR map = -1;
6411
6412 dynamic_memaddr = get_dynamic (pid, is_elf64);
6413 if (dynamic_memaddr == 0)
6414 return map;
6415
6416 while (linux_read_memory (dynamic_memaddr, buf, dyn_size) == 0)
6417 {
6418 if (is_elf64)
6419 {
6420 Elf64_Dyn *const dyn = (Elf64_Dyn *) buf;
6421 #if defined DT_MIPS_RLD_MAP || defined DT_MIPS_RLD_MAP_REL
6422 union
6423 {
6424 Elf64_Xword map;
6425 unsigned char buf[sizeof (Elf64_Xword)];
6426 }
6427 rld_map;
6428 #endif
6429 #ifdef DT_MIPS_RLD_MAP
6430 if (dyn->d_tag == DT_MIPS_RLD_MAP)
6431 {
6432 if (linux_read_memory (dyn->d_un.d_val,
6433 rld_map.buf, sizeof (rld_map.buf)) == 0)
6434 return rld_map.map;
6435 else
6436 break;
6437 }
6438 #endif /* DT_MIPS_RLD_MAP */
6439 #ifdef DT_MIPS_RLD_MAP_REL
6440 if (dyn->d_tag == DT_MIPS_RLD_MAP_REL)
6441 {
6442 if (linux_read_memory (dyn->d_un.d_val + dynamic_memaddr,
6443 rld_map.buf, sizeof (rld_map.buf)) == 0)
6444 return rld_map.map;
6445 else
6446 break;
6447 }
6448 #endif /* DT_MIPS_RLD_MAP_REL */
6449
6450 if (dyn->d_tag == DT_DEBUG && map == -1)
6451 map = dyn->d_un.d_val;
6452
6453 if (dyn->d_tag == DT_NULL)
6454 break;
6455 }
6456 else
6457 {
6458 Elf32_Dyn *const dyn = (Elf32_Dyn *) buf;
6459 #if defined DT_MIPS_RLD_MAP || defined DT_MIPS_RLD_MAP_REL
6460 union
6461 {
6462 Elf32_Word map;
6463 unsigned char buf[sizeof (Elf32_Word)];
6464 }
6465 rld_map;
6466 #endif
6467 #ifdef DT_MIPS_RLD_MAP
6468 if (dyn->d_tag == DT_MIPS_RLD_MAP)
6469 {
6470 if (linux_read_memory (dyn->d_un.d_val,
6471 rld_map.buf, sizeof (rld_map.buf)) == 0)
6472 return rld_map.map;
6473 else
6474 break;
6475 }
6476 #endif /* DT_MIPS_RLD_MAP */
6477 #ifdef DT_MIPS_RLD_MAP_REL
6478 if (dyn->d_tag == DT_MIPS_RLD_MAP_REL)
6479 {
6480 if (linux_read_memory (dyn->d_un.d_val + dynamic_memaddr,
6481 rld_map.buf, sizeof (rld_map.buf)) == 0)
6482 return rld_map.map;
6483 else
6484 break;
6485 }
6486 #endif /* DT_MIPS_RLD_MAP_REL */
6487
6488 if (dyn->d_tag == DT_DEBUG && map == -1)
6489 map = dyn->d_un.d_val;
6490
6491 if (dyn->d_tag == DT_NULL)
6492 break;
6493 }
6494
6495 dynamic_memaddr += dyn_size;
6496 }
6497
6498 return map;
6499 }
6500
6501 /* Read one pointer from MEMADDR in the inferior. */
6502
6503 static int
6504 read_one_ptr (CORE_ADDR memaddr, CORE_ADDR *ptr, int ptr_size)
6505 {
6506 int ret;
6507
6508 /* Go through a union so this works on either big or little endian
6509 hosts, when the inferior's pointer size is smaller than the size
6510 of CORE_ADDR. It is assumed the inferior's endianness is the
6511 same of the superior's. */
6512 union
6513 {
6514 CORE_ADDR core_addr;
6515 unsigned int ui;
6516 unsigned char uc;
6517 } addr;
6518
6519 ret = linux_read_memory (memaddr, &addr.uc, ptr_size);
6520 if (ret == 0)
6521 {
6522 if (ptr_size == sizeof (CORE_ADDR))
6523 *ptr = addr.core_addr;
6524 else if (ptr_size == sizeof (unsigned int))
6525 *ptr = addr.ui;
6526 else
6527 gdb_assert_not_reached ("unhandled pointer size");
6528 }
6529 return ret;
6530 }
6531
6532 bool
6533 linux_process_target::supports_qxfer_libraries_svr4 ()
6534 {
6535 return true;
6536 }
6537
6538 struct link_map_offsets
6539 {
6540 /* Offset and size of r_debug.r_version. */
6541 int r_version_offset;
6542
6543 /* Offset and size of r_debug.r_map. */
6544 int r_map_offset;
6545
6546 /* Offset of r_debug_extended.r_next. */
6547 int r_next_offset;
6548
6549 /* Offset to l_addr field in struct link_map. */
6550 int l_addr_offset;
6551
6552 /* Offset to l_name field in struct link_map. */
6553 int l_name_offset;
6554
6555 /* Offset to l_ld field in struct link_map. */
6556 int l_ld_offset;
6557
6558 /* Offset to l_next field in struct link_map. */
6559 int l_next_offset;
6560
6561 /* Offset to l_prev field in struct link_map. */
6562 int l_prev_offset;
6563 };
6564
6565 static const link_map_offsets lmo_32bit_offsets =
6566 {
6567 0, /* r_version offset. */
6568 4, /* r_debug.r_map offset. */
6569 20, /* r_debug_extended.r_next. */
6570 0, /* l_addr offset in link_map. */
6571 4, /* l_name offset in link_map. */
6572 8, /* l_ld offset in link_map. */
6573 12, /* l_next offset in link_map. */
6574 16 /* l_prev offset in link_map. */
6575 };
6576
6577 static const link_map_offsets lmo_64bit_offsets =
6578 {
6579 0, /* r_version offset. */
6580 8, /* r_debug.r_map offset. */
6581 40, /* r_debug_extended.r_next. */
6582 0, /* l_addr offset in link_map. */
6583 8, /* l_name offset in link_map. */
6584 16, /* l_ld offset in link_map. */
6585 24, /* l_next offset in link_map. */
6586 32 /* l_prev offset in link_map. */
6587 };
6588
6589 /* Get the loaded shared libraries from one namespace. */
6590
6591 static void
6592 read_link_map (std::string &document, CORE_ADDR lmid, CORE_ADDR lm_addr,
6593 CORE_ADDR lm_prev, int ptr_size, const link_map_offsets *lmo)
6594 {
6595 CORE_ADDR l_name, l_addr, l_ld, l_next, l_prev;
6596
6597 while (lm_addr
6598 && read_one_ptr (lm_addr + lmo->l_name_offset,
6599 &l_name, ptr_size) == 0
6600 && read_one_ptr (lm_addr + lmo->l_addr_offset,
6601 &l_addr, ptr_size) == 0
6602 && read_one_ptr (lm_addr + lmo->l_ld_offset,
6603 &l_ld, ptr_size) == 0
6604 && read_one_ptr (lm_addr + lmo->l_prev_offset,
6605 &l_prev, ptr_size) == 0
6606 && read_one_ptr (lm_addr + lmo->l_next_offset,
6607 &l_next, ptr_size) == 0)
6608 {
6609 unsigned char libname[PATH_MAX];
6610
6611 if (lm_prev != l_prev)
6612 {
6613 warning ("Corrupted shared library list: 0x%s != 0x%s",
6614 paddress (lm_prev), paddress (l_prev));
6615 break;
6616 }
6617
6618 /* Not checking for error because reading may stop before we've got
6619 PATH_MAX worth of characters. */
6620 libname[0] = '\0';
6621 linux_read_memory (l_name, libname, sizeof (libname) - 1);
6622 libname[sizeof (libname) - 1] = '\0';
6623 if (libname[0] != '\0')
6624 {
6625 string_appendf (document, "<library name=\"");
6626 xml_escape_text_append (document, (char *) libname);
6627 string_appendf (document, "\" lm=\"0x%s\" l_addr=\"0x%s\" "
6628 "l_ld=\"0x%s\" lmid=\"0x%s\"/>",
6629 paddress (lm_addr), paddress (l_addr),
6630 paddress (l_ld), paddress (lmid));
6631 }
6632
6633 lm_prev = lm_addr;
6634 lm_addr = l_next;
6635 }
6636 }
6637
6638 /* Construct qXfer:libraries-svr4:read reply. */
6639
6640 int
6641 linux_process_target::qxfer_libraries_svr4 (const char *annex,
6642 unsigned char *readbuf,
6643 unsigned const char *writebuf,
6644 CORE_ADDR offset, int len)
6645 {
6646 struct process_info_private *const priv = current_process ()->priv;
6647 char filename[PATH_MAX];
6648 int is_elf64;
6649 unsigned int machine;
6650 CORE_ADDR lmid = 0, lm_addr = 0, lm_prev = 0;
6651
6652 if (writebuf != NULL)
6653 return -2;
6654 if (readbuf == NULL)
6655 return -1;
6656
6657 int pid = current_thread->id.lwp ();
6658 xsnprintf (filename, sizeof filename, "/proc/%d/exe", pid);
6659 is_elf64 = elf_64_file_p (filename, &machine);
6660 const link_map_offsets *lmo;
6661 int ptr_size;
6662 if (is_elf64)
6663 {
6664 lmo = &lmo_64bit_offsets;
6665 ptr_size = 8;
6666 }
6667 else
6668 {
6669 lmo = &lmo_32bit_offsets;
6670 ptr_size = 4;
6671 }
6672
6673 while (annex[0] != '\0')
6674 {
6675 const char *sep;
6676 CORE_ADDR *addrp;
6677 int name_len;
6678
6679 sep = strchr (annex, '=');
6680 if (sep == NULL)
6681 break;
6682
6683 name_len = sep - annex;
6684 if (name_len == 4 && startswith (annex, "lmid"))
6685 addrp = &lmid;
6686 else if (name_len == 5 && startswith (annex, "start"))
6687 addrp = &lm_addr;
6688 else if (name_len == 4 && startswith (annex, "prev"))
6689 addrp = &lm_prev;
6690 else
6691 {
6692 annex = strchr (sep, ';');
6693 if (annex == NULL)
6694 break;
6695 annex++;
6696 continue;
6697 }
6698
6699 annex = decode_address_to_semicolon (addrp, sep + 1);
6700 }
6701
6702 std::string document = "<library-list-svr4 version=\"1.0\"";
6703
6704 /* When the starting LM_ADDR is passed in the annex, only traverse that
6705 namespace, which is assumed to be identified by LMID.
6706
6707 Otherwise, start with R_DEBUG and traverse all namespaces we find. */
6708 if (lm_addr != 0)
6709 {
6710 document += ">";
6711 read_link_map (document, lmid, lm_addr, lm_prev, ptr_size, lmo);
6712 }
6713 else
6714 {
6715 if (lm_prev != 0)
6716 warning ("ignoring prev=0x%s without start", paddress (lm_prev));
6717
6718 /* We could interpret LMID as 'provide only the libraries for this
6719 namespace' but GDB is currently only providing lmid, start, and
6720 prev, or nothing. */
6721 if (lmid != 0)
6722 warning ("ignoring lmid=0x%s without start", paddress (lmid));
6723
6724 CORE_ADDR r_debug = priv->r_debug;
6725 if (r_debug == 0)
6726 r_debug = priv->r_debug = get_r_debug (pid, is_elf64);
6727
6728 /* We failed to find DT_DEBUG. Such situation will not change
6729 for this inferior - do not retry it. Report it to GDB as
6730 E01, see for the reasons at the GDB solib-svr4.c side. */
6731 if (r_debug == (CORE_ADDR) -1)
6732 return -1;
6733
6734 /* Terminate the header if we end up with an empty list. */
6735 if (r_debug == 0)
6736 document += ">";
6737
6738 while (r_debug != 0)
6739 {
6740 int r_version = 0;
6741 if (linux_read_memory (r_debug + lmo->r_version_offset,
6742 (unsigned char *) &r_version,
6743 sizeof (r_version)) != 0)
6744 {
6745 warning ("unable to read r_version from 0x%s",
6746 paddress (r_debug + lmo->r_version_offset));
6747 break;
6748 }
6749
6750 if (r_version < 1)
6751 {
6752 warning ("unexpected r_debug version %d", r_version);
6753 break;
6754 }
6755
6756 if (read_one_ptr (r_debug + lmo->r_map_offset, &lm_addr,
6757 ptr_size) != 0)
6758 {
6759 warning ("unable to read r_map from 0x%s",
6760 paddress (r_debug + lmo->r_map_offset));
6761 break;
6762 }
6763
6764 /* We read the entire namespace. */
6765 lm_prev = 0;
6766
6767 /* The first entry corresponds to the main executable unless the
6768 dynamic loader was loaded late by a static executable. But
6769 in such case the main executable does not have PT_DYNAMIC
6770 present and we would not have gotten here. */
6771 if (r_debug == priv->r_debug)
6772 {
6773 if (lm_addr != 0)
6774 string_appendf (document, " main-lm=\"0x%s\">",
6775 paddress (lm_addr));
6776 else
6777 document += ">";
6778
6779 lm_prev = lm_addr;
6780 if (read_one_ptr (lm_addr + lmo->l_next_offset,
6781 &lm_addr, ptr_size) != 0)
6782 {
6783 warning ("unable to read l_next from 0x%s",
6784 paddress (lm_addr + lmo->l_next_offset));
6785 break;
6786 }
6787 }
6788
6789 read_link_map (document, r_debug, lm_addr, lm_prev, ptr_size, lmo);
6790
6791 if (r_version < 2)
6792 break;
6793
6794 if (read_one_ptr (r_debug + lmo->r_next_offset, &r_debug,
6795 ptr_size) != 0)
6796 {
6797 warning ("unable to read r_next from 0x%s",
6798 paddress (r_debug + lmo->r_next_offset));
6799 break;
6800 }
6801 }
6802 }
6803
6804 document += "</library-list-svr4>";
6805
6806 int document_len = document.length ();
6807 if (offset < document_len)
6808 document_len -= offset;
6809 else
6810 document_len = 0;
6811 if (len > document_len)
6812 len = document_len;
6813
6814 memcpy (readbuf, document.data () + offset, len);
6815
6816 return len;
6817 }
6818
6819 #ifdef HAVE_LINUX_BTRACE
6820
6821 bool
6822 linux_process_target::supports_btrace ()
6823 {
6824 return true;
6825 }
6826
6827 btrace_target_info *
6828 linux_process_target::enable_btrace (thread_info *tp,
6829 const btrace_config *conf)
6830 {
6831 return linux_enable_btrace (tp->id, conf);
6832 }
6833
6834 /* See to_disable_btrace target method. */
6835
6836 int
6837 linux_process_target::disable_btrace (btrace_target_info *tinfo)
6838 {
6839 enum btrace_error err;
6840
6841 err = linux_disable_btrace (tinfo);
6842 return (err == BTRACE_ERR_NONE ? 0 : -1);
6843 }
6844
6845 /* Encode an Intel Processor Trace configuration. */
6846
6847 static void
6848 linux_low_encode_pt_config (std::string *buffer,
6849 const struct btrace_data_pt_config *config)
6850 {
6851 *buffer += "<pt-config>\n";
6852
6853 switch (config->cpu.vendor)
6854 {
6855 case CV_INTEL:
6856 string_xml_appendf (*buffer, "<cpu vendor=\"GenuineIntel\" family=\"%u\" "
6857 "model=\"%u\" stepping=\"%u\"/>\n",
6858 config->cpu.family, config->cpu.model,
6859 config->cpu.stepping);
6860 break;
6861
6862 default:
6863 break;
6864 }
6865
6866 *buffer += "</pt-config>\n";
6867 }
6868
6869 /* Encode a raw buffer. */
6870
6871 static void
6872 linux_low_encode_raw (std::string *buffer, const gdb_byte *data,
6873 unsigned int size)
6874 {
6875 if (size == 0)
6876 return;
6877
6878 /* We use hex encoding - see gdbsupport/rsp-low.h. */
6879 *buffer += "<raw>\n";
6880
6881 while (size-- > 0)
6882 {
6883 char elem[2];
6884
6885 elem[0] = tohex ((*data >> 4) & 0xf);
6886 elem[1] = tohex (*data++ & 0xf);
6887
6888 buffer->append (elem, 2);
6889 }
6890
6891 *buffer += "</raw>\n";
6892 }
6893
6894 /* See to_read_btrace target method. */
6895
6896 int
6897 linux_process_target::read_btrace (btrace_target_info *tinfo,
6898 std::string *buffer,
6899 enum btrace_read_type type)
6900 {
6901 struct btrace_data btrace;
6902 enum btrace_error err;
6903
6904 err = linux_read_btrace (&btrace, tinfo, type);
6905 if (err != BTRACE_ERR_NONE)
6906 {
6907 if (err == BTRACE_ERR_OVERFLOW)
6908 *buffer += "E.Overflow.";
6909 else
6910 *buffer += "E.Generic Error.";
6911
6912 return -1;
6913 }
6914
6915 switch (btrace.format)
6916 {
6917 case BTRACE_FORMAT_NONE:
6918 *buffer += "E.No Trace.";
6919 return -1;
6920
6921 case BTRACE_FORMAT_BTS:
6922 *buffer += "<!DOCTYPE btrace SYSTEM \"btrace.dtd\">\n";
6923 *buffer += "<btrace version=\"1.0\">\n";
6924
6925 for (const btrace_block &block : *btrace.variant.bts.blocks)
6926 string_xml_appendf (*buffer, "<block begin=\"0x%s\" end=\"0x%s\"/>\n",
6927 paddress (block.begin), paddress (block.end));
6928
6929 *buffer += "</btrace>\n";
6930 break;
6931
6932 case BTRACE_FORMAT_PT:
6933 *buffer += "<!DOCTYPE btrace SYSTEM \"btrace.dtd\">\n";
6934 *buffer += "<btrace version=\"1.0\">\n";
6935 *buffer += "<pt>\n";
6936
6937 linux_low_encode_pt_config (buffer, &btrace.variant.pt.config);
6938
6939 linux_low_encode_raw (buffer, btrace.variant.pt.data,
6940 btrace.variant.pt.size);
6941
6942 *buffer += "</pt>\n";
6943 *buffer += "</btrace>\n";
6944 break;
6945
6946 default:
6947 *buffer += "E.Unsupported Trace Format.";
6948 return -1;
6949 }
6950
6951 return 0;
6952 }
6953
6954 /* See to_btrace_conf target method. */
6955
6956 int
6957 linux_process_target::read_btrace_conf (const btrace_target_info *tinfo,
6958 std::string *buffer)
6959 {
6960 const struct btrace_config *conf;
6961
6962 *buffer += "<!DOCTYPE btrace-conf SYSTEM \"btrace-conf.dtd\">\n";
6963 *buffer += "<btrace-conf version=\"1.0\">\n";
6964
6965 conf = linux_btrace_conf (tinfo);
6966 if (conf != NULL)
6967 {
6968 switch (conf->format)
6969 {
6970 case BTRACE_FORMAT_NONE:
6971 break;
6972
6973 case BTRACE_FORMAT_BTS:
6974 string_xml_appendf (*buffer, "<bts");
6975 string_xml_appendf (*buffer, " size=\"0x%x\"", conf->bts.size);
6976 string_xml_appendf (*buffer, " />\n");
6977 break;
6978
6979 case BTRACE_FORMAT_PT:
6980 string_xml_appendf (*buffer, "<pt");
6981 string_xml_appendf (*buffer, " size=\"0x%x\"", conf->pt.size);
6982 string_xml_appendf (*buffer, "/>\n");
6983 string_xml_appendf (*buffer, " ptwrite=\"%s\"",
6984 conf->pt.ptwrite ? "yes" : "no");
6985 string_xml_appendf (*buffer, " event-tracing=\"%s\"",
6986 conf->pt.event_tracing ? "yes" : "no");
6987 string_xml_appendf (*buffer, "/>\n");
6988 break;
6989 }
6990 }
6991
6992 *buffer += "</btrace-conf>\n";
6993 return 0;
6994 }
6995 #endif /* HAVE_LINUX_BTRACE */
6996
6997 /* See nat/linux-nat.h. */
6998
6999 ptid_t
7000 current_lwp_ptid (void)
7001 {
7002 return current_thread->id;
7003 }
7004
7005 /* A helper function that copies NAME to DEST, replacing non-printable
7006 characters with '?'. Returns the original DEST as a
7007 convenience. */
7008
7009 static const char *
7010 replace_non_ascii (char *dest, const char *name)
7011 {
7012 const char *result = dest;
7013 while (*name != '\0')
7014 {
7015 if (!ISPRINT (*name))
7016 *dest++ = '?';
7017 else
7018 *dest++ = *name;
7019 ++name;
7020 }
7021 *dest = '\0';
7022 return result;
7023 }
7024
7025 const char *
7026 linux_process_target::thread_name (ptid_t thread)
7027 {
7028 static char dest[100];
7029
7030 const char *name = linux_proc_tid_get_name (thread);
7031 if (name == nullptr)
7032 return nullptr;
7033
7034 /* Linux limits the comm file to 16 bytes (including the trailing
7035 \0. If the program or thread name is set when using a multi-byte
7036 encoding, this might cause it to be truncated mid-character. In
7037 this situation, sending the truncated form in an XML <thread>
7038 response will cause a parse error in gdb. So, instead convert
7039 from the locale's encoding (we can't be sure this is the correct
7040 encoding, but it's as good a guess as we have) to UTF-8, but in a
7041 way that ignores any encoding errors. See PR remote/30618. */
7042 const char *cset = nl_langinfo (CODESET);
7043 iconv_t handle = iconv_open ("UTF-8//IGNORE", cset);
7044 if (handle == (iconv_t) -1)
7045 return replace_non_ascii (dest, name);
7046
7047 size_t inbytes = strlen (name);
7048 char *inbuf = const_cast<char *> (name);
7049 size_t outbytes = sizeof (dest);
7050 char *outbuf = dest;
7051 size_t result = iconv (handle, &inbuf, &inbytes, &outbuf, &outbytes);
7052
7053 if (result == (size_t) -1)
7054 {
7055 if (errno == E2BIG)
7056 outbuf = &dest[sizeof (dest) - 1];
7057 else if ((errno == EILSEQ || errno == EINVAL)
7058 && outbuf < &dest[sizeof (dest) - 2])
7059 *outbuf++ = '?';
7060 }
7061 *outbuf = '\0';
7062
7063 iconv_close (handle);
7064 return *dest == '\0' ? nullptr : dest;
7065 }
7066
7067 #if USE_THREAD_DB
7068 bool
7069 linux_process_target::thread_handle (ptid_t ptid, gdb_byte **handle,
7070 int *handle_len)
7071 {
7072 return thread_db_thread_handle (ptid, handle, handle_len);
7073 }
7074 #endif
7075
7076 thread_info *
7077 linux_process_target::thread_pending_parent (thread_info *thread)
7078 {
7079 lwp_info *parent = get_thread_lwp (thread)->pending_parent ();
7080
7081 if (parent == nullptr)
7082 return nullptr;
7083
7084 return parent->thread;
7085 }
7086
7087 thread_info *
7088 linux_process_target::thread_pending_child (thread_info *thread,
7089 target_waitkind *kind)
7090 {
7091 lwp_info *child = get_thread_lwp (thread)->pending_child (kind);
7092
7093 if (child == nullptr)
7094 return nullptr;
7095
7096 return child->thread;
7097 }
7098
7099 /* Default implementation of linux_target_ops method "set_pc" for
7100 32-bit pc register which is literally named "pc". */
7101
7102 void
7103 linux_set_pc_32bit (struct regcache *regcache, CORE_ADDR pc)
7104 {
7105 uint32_t newpc = pc;
7106
7107 supply_register_by_name (regcache, "pc", &newpc);
7108 }
7109
7110 /* Default implementation of linux_target_ops method "get_pc" for
7111 32-bit pc register which is literally named "pc". */
7112
7113 CORE_ADDR
7114 linux_get_pc_32bit (struct regcache *regcache)
7115 {
7116 uint32_t pc;
7117
7118 collect_register_by_name (regcache, "pc", &pc);
7119 threads_debug_printf ("stop pc is 0x%" PRIx32, pc);
7120 return pc;
7121 }
7122
7123 /* Default implementation of linux_target_ops method "set_pc" for
7124 64-bit pc register which is literally named "pc". */
7125
7126 void
7127 linux_set_pc_64bit (struct regcache *regcache, CORE_ADDR pc)
7128 {
7129 uint64_t newpc = pc;
7130
7131 supply_register_by_name (regcache, "pc", &newpc);
7132 }
7133
7134 /* Default implementation of linux_target_ops method "get_pc" for
7135 64-bit pc register which is literally named "pc". */
7136
7137 CORE_ADDR
7138 linux_get_pc_64bit (struct regcache *regcache)
7139 {
7140 uint64_t pc;
7141
7142 collect_register_by_name (regcache, "pc", &pc);
7143 threads_debug_printf ("stop pc is 0x%" PRIx64, pc);
7144 return pc;
7145 }
7146
7147 /* See linux-low.h. */
7148
7149 int
7150 linux_get_auxv (int pid, int wordsize, CORE_ADDR match, CORE_ADDR *valp)
7151 {
7152 gdb_byte *data = (gdb_byte *) alloca (2 * wordsize);
7153 int offset = 0;
7154
7155 gdb_assert (wordsize == 4 || wordsize == 8);
7156
7157 while (the_target->read_auxv (pid, offset, data, 2 * wordsize)
7158 == 2 * wordsize)
7159 {
7160 if (wordsize == 4)
7161 {
7162 uint32_t *data_p = (uint32_t *) data;
7163 if (data_p[0] == match)
7164 {
7165 *valp = data_p[1];
7166 return 1;
7167 }
7168 }
7169 else
7170 {
7171 uint64_t *data_p = (uint64_t *) data;
7172 if (data_p[0] == match)
7173 {
7174 *valp = data_p[1];
7175 return 1;
7176 }
7177 }
7178
7179 offset += 2 * wordsize;
7180 }
7181
7182 return 0;
7183 }
7184
7185 /* See linux-low.h. */
7186
7187 CORE_ADDR
7188 linux_get_hwcap (int pid, int wordsize)
7189 {
7190 CORE_ADDR hwcap = 0;
7191 linux_get_auxv (pid, wordsize, AT_HWCAP, &hwcap);
7192 return hwcap;
7193 }
7194
7195 /* See linux-low.h. */
7196
7197 CORE_ADDR
7198 linux_get_hwcap2 (int pid, int wordsize)
7199 {
7200 CORE_ADDR hwcap2 = 0;
7201 linux_get_auxv (pid, wordsize, AT_HWCAP2, &hwcap2);
7202 return hwcap2;
7203 }
7204
7205 #ifdef HAVE_LINUX_REGSETS
7206 void
7207 initialize_regsets_info (struct regsets_info *info)
7208 {
7209 for (info->num_regsets = 0;
7210 info->regsets[info->num_regsets].size >= 0;
7211 info->num_regsets++)
7212 ;
7213 }
7214 #endif
7215
7216 void
7217 initialize_low (void)
7218 {
7219 struct sigaction sigchld_action;
7220
7221 memset (&sigchld_action, 0, sizeof (sigchld_action));
7222 set_target_ops (the_linux_target);
7223
7224 linux_ptrace_init_warnings ();
7225 linux_proc_init_warnings ();
7226
7227 sigchld_action.sa_handler = sigchld_handler;
7228 sigemptyset (&sigchld_action.sa_mask);
7229 sigchld_action.sa_flags = SA_RESTART;
7230 sigaction (SIGCHLD, &sigchld_action, NULL);
7231
7232 initialize_low_arch ();
7233
7234 linux_check_ptrace_features ();
7235 }