]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/gdbserver/linux-low.c
Lazily allocate 'struct regsets_info'::disabled_regsets.
[thirdparty/binutils-gdb.git] / gdb / gdbserver / linux-low.c
1 /* Low level interface to ptrace, for the remote server for GDB.
2 Copyright (C) 1995-2013 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 "server.h"
20 #include "linux-low.h"
21 #include "linux-osdata.h"
22 #include "agent.h"
23
24 #include "gdb_wait.h"
25 #include <stdio.h>
26 #include <sys/param.h>
27 #include <sys/ptrace.h>
28 #include "linux-ptrace.h"
29 #include "linux-procfs.h"
30 #include <signal.h>
31 #include <sys/ioctl.h>
32 #include <fcntl.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <sys/syscall.h>
38 #include <sched.h>
39 #include <ctype.h>
40 #include <pwd.h>
41 #include <sys/types.h>
42 #include <dirent.h>
43 #include "gdb_stat.h"
44 #include <sys/vfs.h>
45 #include <sys/uio.h>
46 #ifndef ELFMAG0
47 /* Don't include <linux/elf.h> here. If it got included by gdb_proc_service.h
48 then ELFMAG0 will have been defined. If it didn't get included by
49 gdb_proc_service.h then including it will likely introduce a duplicate
50 definition of elf_fpregset_t. */
51 #include <elf.h>
52 #endif
53
54 #ifndef SPUFS_MAGIC
55 #define SPUFS_MAGIC 0x23c9b64e
56 #endif
57
58 #ifdef HAVE_PERSONALITY
59 # include <sys/personality.h>
60 # if !HAVE_DECL_ADDR_NO_RANDOMIZE
61 # define ADDR_NO_RANDOMIZE 0x0040000
62 # endif
63 #endif
64
65 #ifndef O_LARGEFILE
66 #define O_LARGEFILE 0
67 #endif
68
69 #ifndef W_STOPCODE
70 #define W_STOPCODE(sig) ((sig) << 8 | 0x7f)
71 #endif
72
73 /* This is the kernel's hard limit. Not to be confused with
74 SIGRTMIN. */
75 #ifndef __SIGRTMIN
76 #define __SIGRTMIN 32
77 #endif
78
79 #ifdef __UCLIBC__
80 #if !(defined(__UCLIBC_HAS_MMU__) || defined(__ARCH_HAS_MMU__))
81 /* PTRACE_TEXT_ADDR and friends. */
82 #include <asm/ptrace.h>
83 #define HAS_NOMMU
84 #endif
85 #endif
86
87 /* Some targets did not define these ptrace constants from the start,
88 so gdbserver defines them locally here. In the future, these may
89 be removed after they are added to asm/ptrace.h. */
90 #if !(defined(PT_TEXT_ADDR) \
91 || defined(PT_DATA_ADDR) \
92 || defined(PT_TEXT_END_ADDR))
93 #if defined(__mcoldfire__)
94 /* These are still undefined in 3.10 kernels. */
95 #define PT_TEXT_ADDR 49*4
96 #define PT_DATA_ADDR 50*4
97 #define PT_TEXT_END_ADDR 51*4
98 /* BFIN already defines these since at least 2.6.32 kernels. */
99 #elif defined(BFIN)
100 #define PT_TEXT_ADDR 220
101 #define PT_TEXT_END_ADDR 224
102 #define PT_DATA_ADDR 228
103 /* These are still undefined in 3.10 kernels. */
104 #elif defined(__TMS320C6X__)
105 #define PT_TEXT_ADDR (0x10000*4)
106 #define PT_DATA_ADDR (0x10004*4)
107 #define PT_TEXT_END_ADDR (0x10008*4)
108 #endif
109 #endif
110
111 #ifdef HAVE_LINUX_BTRACE
112 # include "linux-btrace.h"
113 #endif
114
115 #ifndef HAVE_ELF32_AUXV_T
116 /* Copied from glibc's elf.h. */
117 typedef struct
118 {
119 uint32_t a_type; /* Entry type */
120 union
121 {
122 uint32_t a_val; /* Integer value */
123 /* We use to have pointer elements added here. We cannot do that,
124 though, since it does not work when using 32-bit definitions
125 on 64-bit platforms and vice versa. */
126 } a_un;
127 } Elf32_auxv_t;
128 #endif
129
130 #ifndef HAVE_ELF64_AUXV_T
131 /* Copied from glibc's elf.h. */
132 typedef struct
133 {
134 uint64_t a_type; /* Entry type */
135 union
136 {
137 uint64_t a_val; /* Integer value */
138 /* We use to have pointer elements added here. We cannot do that,
139 though, since it does not work when using 32-bit definitions
140 on 64-bit platforms and vice versa. */
141 } a_un;
142 } Elf64_auxv_t;
143 #endif
144
145 /* ``all_threads'' is keyed by the LWP ID, which we use as the GDB protocol
146 representation of the thread ID.
147
148 ``all_lwps'' is keyed by the process ID - which on Linux is (presently)
149 the same as the LWP ID.
150
151 ``all_processes'' is keyed by the "overall process ID", which
152 GNU/Linux calls tgid, "thread group ID". */
153
154 struct inferior_list all_lwps;
155
156 /* A list of all unknown processes which receive stop signals. Some
157 other process will presumably claim each of these as forked
158 children momentarily. */
159
160 struct simple_pid_list
161 {
162 /* The process ID. */
163 int pid;
164
165 /* The status as reported by waitpid. */
166 int status;
167
168 /* Next in chain. */
169 struct simple_pid_list *next;
170 };
171 struct simple_pid_list *stopped_pids;
172
173 /* Trivial list manipulation functions to keep track of a list of new
174 stopped processes. */
175
176 static void
177 add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
178 {
179 struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
180
181 new_pid->pid = pid;
182 new_pid->status = status;
183 new_pid->next = *listp;
184 *listp = new_pid;
185 }
186
187 static int
188 pull_pid_from_list (struct simple_pid_list **listp, int pid, int *statusp)
189 {
190 struct simple_pid_list **p;
191
192 for (p = listp; *p != NULL; p = &(*p)->next)
193 if ((*p)->pid == pid)
194 {
195 struct simple_pid_list *next = (*p)->next;
196
197 *statusp = (*p)->status;
198 xfree (*p);
199 *p = next;
200 return 1;
201 }
202 return 0;
203 }
204
205 enum stopping_threads_kind
206 {
207 /* Not stopping threads presently. */
208 NOT_STOPPING_THREADS,
209
210 /* Stopping threads. */
211 STOPPING_THREADS,
212
213 /* Stopping and suspending threads. */
214 STOPPING_AND_SUSPENDING_THREADS
215 };
216
217 /* This is set while stop_all_lwps is in effect. */
218 enum stopping_threads_kind stopping_threads = NOT_STOPPING_THREADS;
219
220 /* FIXME make into a target method? */
221 int using_threads = 1;
222
223 /* True if we're presently stabilizing threads (moving them out of
224 jump pads). */
225 static int stabilizing_threads;
226
227 static void linux_resume_one_lwp (struct lwp_info *lwp,
228 int step, int signal, siginfo_t *info);
229 static void linux_resume (struct thread_resume *resume_info, size_t n);
230 static void stop_all_lwps (int suspend, struct lwp_info *except);
231 static void unstop_all_lwps (int unsuspend, struct lwp_info *except);
232 static int linux_wait_for_event (ptid_t ptid, int *wstat, int options);
233 static void *add_lwp (ptid_t ptid);
234 static int linux_stopped_by_watchpoint (void);
235 static void mark_lwp_dead (struct lwp_info *lwp, int wstat);
236 static void proceed_all_lwps (void);
237 static int finish_step_over (struct lwp_info *lwp);
238 static CORE_ADDR get_stop_pc (struct lwp_info *lwp);
239 static int kill_lwp (unsigned long lwpid, int signo);
240 static void linux_enable_event_reporting (int pid);
241
242 /* True if the low target can hardware single-step. Such targets
243 don't need a BREAKPOINT_REINSERT_ADDR callback. */
244
245 static int
246 can_hardware_single_step (void)
247 {
248 return (the_low_target.breakpoint_reinsert_addr == NULL);
249 }
250
251 /* True if the low target supports memory breakpoints. If so, we'll
252 have a GET_PC implementation. */
253
254 static int
255 supports_breakpoints (void)
256 {
257 return (the_low_target.get_pc != NULL);
258 }
259
260 /* Returns true if this target can support fast tracepoints. This
261 does not mean that the in-process agent has been loaded in the
262 inferior. */
263
264 static int
265 supports_fast_tracepoints (void)
266 {
267 return the_low_target.install_fast_tracepoint_jump_pad != NULL;
268 }
269
270 /* True if LWP is stopped in its stepping range. */
271
272 static int
273 lwp_in_step_range (struct lwp_info *lwp)
274 {
275 CORE_ADDR pc = lwp->stop_pc;
276
277 return (pc >= lwp->step_range_start && pc < lwp->step_range_end);
278 }
279
280 struct pending_signals
281 {
282 int signal;
283 siginfo_t info;
284 struct pending_signals *prev;
285 };
286
287 /* The read/write ends of the pipe registered as waitable file in the
288 event loop. */
289 static int linux_event_pipe[2] = { -1, -1 };
290
291 /* True if we're currently in async mode. */
292 #define target_is_async_p() (linux_event_pipe[0] != -1)
293
294 static void send_sigstop (struct lwp_info *lwp);
295 static void wait_for_sigstop (struct inferior_list_entry *entry);
296
297 /* Return non-zero if HEADER is a 64-bit ELF file. */
298
299 static int
300 elf_64_header_p (const Elf64_Ehdr *header, unsigned int *machine)
301 {
302 if (header->e_ident[EI_MAG0] == ELFMAG0
303 && header->e_ident[EI_MAG1] == ELFMAG1
304 && header->e_ident[EI_MAG2] == ELFMAG2
305 && header->e_ident[EI_MAG3] == ELFMAG3)
306 {
307 *machine = header->e_machine;
308 return header->e_ident[EI_CLASS] == ELFCLASS64;
309
310 }
311 *machine = EM_NONE;
312 return -1;
313 }
314
315 /* Return non-zero if FILE is a 64-bit ELF file,
316 zero if the file is not a 64-bit ELF file,
317 and -1 if the file is not accessible or doesn't exist. */
318
319 static int
320 elf_64_file_p (const char *file, unsigned int *machine)
321 {
322 Elf64_Ehdr header;
323 int fd;
324
325 fd = open (file, O_RDONLY);
326 if (fd < 0)
327 return -1;
328
329 if (read (fd, &header, sizeof (header)) != sizeof (header))
330 {
331 close (fd);
332 return 0;
333 }
334 close (fd);
335
336 return elf_64_header_p (&header, machine);
337 }
338
339 /* Accepts an integer PID; Returns true if the executable PID is
340 running is a 64-bit ELF file.. */
341
342 int
343 linux_pid_exe_is_elf_64_file (int pid, unsigned int *machine)
344 {
345 char file[MAXPATHLEN];
346
347 sprintf (file, "/proc/%d/exe", pid);
348 return elf_64_file_p (file, machine);
349 }
350
351 static void
352 delete_lwp (struct lwp_info *lwp)
353 {
354 remove_thread (get_lwp_thread (lwp));
355 remove_inferior (&all_lwps, &lwp->head);
356 free (lwp->arch_private);
357 free (lwp);
358 }
359
360 /* Add a process to the common process list, and set its private
361 data. */
362
363 static struct process_info *
364 linux_add_process (int pid, int attached)
365 {
366 struct process_info *proc;
367
368 proc = add_process (pid, attached);
369 proc->private = xcalloc (1, sizeof (*proc->private));
370
371 /* Set the arch when the first LWP stops. */
372 proc->private->new_inferior = 1;
373
374 if (the_low_target.new_process != NULL)
375 proc->private->arch_private = the_low_target.new_process ();
376
377 return proc;
378 }
379
380 /* Wrapper function for waitpid which handles EINTR, and emulates
381 __WALL for systems where that is not available. */
382
383 static int
384 my_waitpid (int pid, int *status, int flags)
385 {
386 int ret, out_errno;
387
388 if (debug_threads)
389 fprintf (stderr, "my_waitpid (%d, 0x%x)\n", pid, flags);
390
391 if (flags & __WALL)
392 {
393 sigset_t block_mask, org_mask, wake_mask;
394 int wnohang;
395
396 wnohang = (flags & WNOHANG) != 0;
397 flags &= ~(__WALL | __WCLONE);
398 flags |= WNOHANG;
399
400 /* Block all signals while here. This avoids knowing about
401 LinuxThread's signals. */
402 sigfillset (&block_mask);
403 sigprocmask (SIG_BLOCK, &block_mask, &org_mask);
404
405 /* ... except during the sigsuspend below. */
406 sigemptyset (&wake_mask);
407
408 while (1)
409 {
410 /* Since all signals are blocked, there's no need to check
411 for EINTR here. */
412 ret = waitpid (pid, status, flags);
413 out_errno = errno;
414
415 if (ret == -1 && out_errno != ECHILD)
416 break;
417 else if (ret > 0)
418 break;
419
420 if (flags & __WCLONE)
421 {
422 /* We've tried both flavors now. If WNOHANG is set,
423 there's nothing else to do, just bail out. */
424 if (wnohang)
425 break;
426
427 if (debug_threads)
428 fprintf (stderr, "blocking\n");
429
430 /* Block waiting for signals. */
431 sigsuspend (&wake_mask);
432 }
433
434 flags ^= __WCLONE;
435 }
436
437 sigprocmask (SIG_SETMASK, &org_mask, NULL);
438 }
439 else
440 {
441 do
442 ret = waitpid (pid, status, flags);
443 while (ret == -1 && errno == EINTR);
444 out_errno = errno;
445 }
446
447 if (debug_threads)
448 fprintf (stderr, "my_waitpid (%d, 0x%x): status(%x), %d\n",
449 pid, flags, status ? *status : -1, ret);
450
451 errno = out_errno;
452 return ret;
453 }
454
455 /* Handle a GNU/Linux extended wait response. If we see a clone
456 event, we need to add the new LWP to our list (and not report the
457 trap to higher layers). */
458
459 static void
460 handle_extended_wait (struct lwp_info *event_child, int wstat)
461 {
462 int event = wstat >> 16;
463 struct lwp_info *new_lwp;
464
465 if (event == PTRACE_EVENT_CLONE)
466 {
467 ptid_t ptid;
468 unsigned long new_pid;
469 int ret, status;
470
471 ptrace (PTRACE_GETEVENTMSG, lwpid_of (event_child), (PTRACE_ARG3_TYPE) 0,
472 &new_pid);
473
474 /* If we haven't already seen the new PID stop, wait for it now. */
475 if (!pull_pid_from_list (&stopped_pids, new_pid, &status))
476 {
477 /* The new child has a pending SIGSTOP. We can't affect it until it
478 hits the SIGSTOP, but we're already attached. */
479
480 ret = my_waitpid (new_pid, &status, __WALL);
481
482 if (ret == -1)
483 perror_with_name ("waiting for new child");
484 else if (ret != new_pid)
485 warning ("wait returned unexpected PID %d", ret);
486 else if (!WIFSTOPPED (status))
487 warning ("wait returned unexpected status 0x%x", status);
488 }
489
490 ptid = ptid_build (pid_of (event_child), new_pid, 0);
491 new_lwp = (struct lwp_info *) add_lwp (ptid);
492 add_thread (ptid, new_lwp);
493
494 /* Either we're going to immediately resume the new thread
495 or leave it stopped. linux_resume_one_lwp is a nop if it
496 thinks the thread is currently running, so set this first
497 before calling linux_resume_one_lwp. */
498 new_lwp->stopped = 1;
499
500 /* If we're suspending all threads, leave this one suspended
501 too. */
502 if (stopping_threads == STOPPING_AND_SUSPENDING_THREADS)
503 new_lwp->suspended = 1;
504
505 /* Normally we will get the pending SIGSTOP. But in some cases
506 we might get another signal delivered to the group first.
507 If we do get another signal, be sure not to lose it. */
508 if (WSTOPSIG (status) == SIGSTOP)
509 {
510 if (stopping_threads != NOT_STOPPING_THREADS)
511 new_lwp->stop_pc = get_stop_pc (new_lwp);
512 else
513 linux_resume_one_lwp (new_lwp, 0, 0, NULL);
514 }
515 else
516 {
517 new_lwp->stop_expected = 1;
518
519 if (stopping_threads != NOT_STOPPING_THREADS)
520 {
521 new_lwp->stop_pc = get_stop_pc (new_lwp);
522 new_lwp->status_pending_p = 1;
523 new_lwp->status_pending = status;
524 }
525 else
526 /* Pass the signal on. This is what GDB does - except
527 shouldn't we really report it instead? */
528 linux_resume_one_lwp (new_lwp, 0, WSTOPSIG (status), NULL);
529 }
530
531 /* Always resume the current thread. If we are stopping
532 threads, it will have a pending SIGSTOP; we may as well
533 collect it now. */
534 linux_resume_one_lwp (event_child, event_child->stepping, 0, NULL);
535 }
536 }
537
538 /* Return the PC as read from the regcache of LWP, without any
539 adjustment. */
540
541 static CORE_ADDR
542 get_pc (struct lwp_info *lwp)
543 {
544 struct thread_info *saved_inferior;
545 struct regcache *regcache;
546 CORE_ADDR pc;
547
548 if (the_low_target.get_pc == NULL)
549 return 0;
550
551 saved_inferior = current_inferior;
552 current_inferior = get_lwp_thread (lwp);
553
554 regcache = get_thread_regcache (current_inferior, 1);
555 pc = (*the_low_target.get_pc) (regcache);
556
557 if (debug_threads)
558 fprintf (stderr, "pc is 0x%lx\n", (long) pc);
559
560 current_inferior = saved_inferior;
561 return pc;
562 }
563
564 /* This function should only be called if LWP got a SIGTRAP.
565 The SIGTRAP could mean several things.
566
567 On i386, where decr_pc_after_break is non-zero:
568 If we were single-stepping this process using PTRACE_SINGLESTEP,
569 we will get only the one SIGTRAP (even if the instruction we
570 stepped over was a breakpoint). The value of $eip will be the
571 next instruction.
572 If we continue the process using PTRACE_CONT, we will get a
573 SIGTRAP when we hit a breakpoint. The value of $eip will be
574 the instruction after the breakpoint (i.e. needs to be
575 decremented). If we report the SIGTRAP to GDB, we must also
576 report the undecremented PC. If we cancel the SIGTRAP, we
577 must resume at the decremented PC.
578
579 (Presumably, not yet tested) On a non-decr_pc_after_break machine
580 with hardware or kernel single-step:
581 If we single-step over a breakpoint instruction, our PC will
582 point at the following instruction. If we continue and hit a
583 breakpoint instruction, our PC will point at the breakpoint
584 instruction. */
585
586 static CORE_ADDR
587 get_stop_pc (struct lwp_info *lwp)
588 {
589 CORE_ADDR stop_pc;
590
591 if (the_low_target.get_pc == NULL)
592 return 0;
593
594 stop_pc = get_pc (lwp);
595
596 if (WSTOPSIG (lwp->last_status) == SIGTRAP
597 && !lwp->stepping
598 && !lwp->stopped_by_watchpoint
599 && lwp->last_status >> 16 == 0)
600 stop_pc -= the_low_target.decr_pc_after_break;
601
602 if (debug_threads)
603 fprintf (stderr, "stop pc is 0x%lx\n", (long) stop_pc);
604
605 return stop_pc;
606 }
607
608 static void *
609 add_lwp (ptid_t ptid)
610 {
611 struct lwp_info *lwp;
612
613 lwp = (struct lwp_info *) xmalloc (sizeof (*lwp));
614 memset (lwp, 0, sizeof (*lwp));
615
616 lwp->head.id = ptid;
617
618 if (the_low_target.new_thread != NULL)
619 lwp->arch_private = the_low_target.new_thread ();
620
621 add_inferior_to_list (&all_lwps, &lwp->head);
622
623 return lwp;
624 }
625
626 /* Start an inferior process and returns its pid.
627 ALLARGS is a vector of program-name and args. */
628
629 static int
630 linux_create_inferior (char *program, char **allargs)
631 {
632 #ifdef HAVE_PERSONALITY
633 int personality_orig = 0, personality_set = 0;
634 #endif
635 struct lwp_info *new_lwp;
636 int pid;
637 ptid_t ptid;
638
639 #ifdef HAVE_PERSONALITY
640 if (disable_randomization)
641 {
642 errno = 0;
643 personality_orig = personality (0xffffffff);
644 if (errno == 0 && !(personality_orig & ADDR_NO_RANDOMIZE))
645 {
646 personality_set = 1;
647 personality (personality_orig | ADDR_NO_RANDOMIZE);
648 }
649 if (errno != 0 || (personality_set
650 && !(personality (0xffffffff) & ADDR_NO_RANDOMIZE)))
651 warning ("Error disabling address space randomization: %s",
652 strerror (errno));
653 }
654 #endif
655
656 #if defined(__UCLIBC__) && defined(HAS_NOMMU)
657 pid = vfork ();
658 #else
659 pid = fork ();
660 #endif
661 if (pid < 0)
662 perror_with_name ("fork");
663
664 if (pid == 0)
665 {
666 ptrace (PTRACE_TRACEME, 0, (PTRACE_ARG3_TYPE) 0, (PTRACE_ARG4_TYPE) 0);
667
668 #ifndef __ANDROID__ /* Bionic doesn't use SIGRTMIN the way glibc does. */
669 signal (__SIGRTMIN + 1, SIG_DFL);
670 #endif
671
672 setpgid (0, 0);
673
674 /* If gdbserver is connected to gdb via stdio, redirect the inferior's
675 stdout to stderr so that inferior i/o doesn't corrupt the connection.
676 Also, redirect stdin to /dev/null. */
677 if (remote_connection_is_stdio ())
678 {
679 close (0);
680 open ("/dev/null", O_RDONLY);
681 dup2 (2, 1);
682 if (write (2, "stdin/stdout redirected\n",
683 sizeof ("stdin/stdout redirected\n") - 1) < 0)
684 {
685 /* Errors ignored. */;
686 }
687 }
688
689 execv (program, allargs);
690 if (errno == ENOENT)
691 execvp (program, allargs);
692
693 fprintf (stderr, "Cannot exec %s: %s.\n", program,
694 strerror (errno));
695 fflush (stderr);
696 _exit (0177);
697 }
698
699 #ifdef HAVE_PERSONALITY
700 if (personality_set)
701 {
702 errno = 0;
703 personality (personality_orig);
704 if (errno != 0)
705 warning ("Error restoring address space randomization: %s",
706 strerror (errno));
707 }
708 #endif
709
710 linux_add_process (pid, 0);
711
712 ptid = ptid_build (pid, pid, 0);
713 new_lwp = add_lwp (ptid);
714 add_thread (ptid, new_lwp);
715 new_lwp->must_set_ptrace_flags = 1;
716
717 return pid;
718 }
719
720 /* Attach to an inferior process. */
721
722 static void
723 linux_attach_lwp_1 (unsigned long lwpid, int initial)
724 {
725 ptid_t ptid;
726 struct lwp_info *new_lwp;
727
728 if (ptrace (PTRACE_ATTACH, lwpid, (PTRACE_ARG3_TYPE) 0, (PTRACE_ARG4_TYPE) 0)
729 != 0)
730 {
731 struct buffer buffer;
732
733 if (!initial)
734 {
735 /* If we fail to attach to an LWP, just warn. */
736 fprintf (stderr, "Cannot attach to lwp %ld: %s (%d)\n", lwpid,
737 strerror (errno), errno);
738 fflush (stderr);
739 return;
740 }
741
742 /* If we fail to attach to a process, report an error. */
743 buffer_init (&buffer);
744 linux_ptrace_attach_warnings (lwpid, &buffer);
745 buffer_grow_str0 (&buffer, "");
746 error ("%sCannot attach to lwp %ld: %s (%d)", buffer_finish (&buffer),
747 lwpid, strerror (errno), errno);
748 }
749
750 if (initial)
751 /* If lwp is the tgid, we handle adding existing threads later.
752 Otherwise we just add lwp without bothering about any other
753 threads. */
754 ptid = ptid_build (lwpid, lwpid, 0);
755 else
756 {
757 /* Note that extracting the pid from the current inferior is
758 safe, since we're always called in the context of the same
759 process as this new thread. */
760 int pid = pid_of (get_thread_lwp (current_inferior));
761 ptid = ptid_build (pid, lwpid, 0);
762 }
763
764 new_lwp = (struct lwp_info *) add_lwp (ptid);
765 add_thread (ptid, new_lwp);
766
767 /* We need to wait for SIGSTOP before being able to make the next
768 ptrace call on this LWP. */
769 new_lwp->must_set_ptrace_flags = 1;
770
771 if (linux_proc_pid_is_stopped (lwpid))
772 {
773 if (debug_threads)
774 fprintf (stderr,
775 "Attached to a stopped process\n");
776
777 /* The process is definitely stopped. It is in a job control
778 stop, unless the kernel predates the TASK_STOPPED /
779 TASK_TRACED distinction, in which case it might be in a
780 ptrace stop. Make sure it is in a ptrace stop; from there we
781 can kill it, signal it, et cetera.
782
783 First make sure there is a pending SIGSTOP. Since we are
784 already attached, the process can not transition from stopped
785 to running without a PTRACE_CONT; so we know this signal will
786 go into the queue. The SIGSTOP generated by PTRACE_ATTACH is
787 probably already in the queue (unless this kernel is old
788 enough to use TASK_STOPPED for ptrace stops); but since
789 SIGSTOP is not an RT signal, it can only be queued once. */
790 kill_lwp (lwpid, SIGSTOP);
791
792 /* Finally, resume the stopped process. This will deliver the
793 SIGSTOP (or a higher priority signal, just like normal
794 PTRACE_ATTACH), which we'll catch later on. */
795 ptrace (PTRACE_CONT, lwpid, (PTRACE_ARG3_TYPE) 0, (PTRACE_ARG4_TYPE) 0);
796 }
797
798 /* The next time we wait for this LWP we'll see a SIGSTOP as PTRACE_ATTACH
799 brings it to a halt.
800
801 There are several cases to consider here:
802
803 1) gdbserver has already attached to the process and is being notified
804 of a new thread that is being created.
805 In this case we should ignore that SIGSTOP and resume the
806 process. This is handled below by setting stop_expected = 1,
807 and the fact that add_thread sets last_resume_kind ==
808 resume_continue.
809
810 2) This is the first thread (the process thread), and we're attaching
811 to it via attach_inferior.
812 In this case we want the process thread to stop.
813 This is handled by having linux_attach set last_resume_kind ==
814 resume_stop after we return.
815
816 If the pid we are attaching to is also the tgid, we attach to and
817 stop all the existing threads. Otherwise, we attach to pid and
818 ignore any other threads in the same group as this pid.
819
820 3) GDB is connecting to gdbserver and is requesting an enumeration of all
821 existing threads.
822 In this case we want the thread to stop.
823 FIXME: This case is currently not properly handled.
824 We should wait for the SIGSTOP but don't. Things work apparently
825 because enough time passes between when we ptrace (ATTACH) and when
826 gdb makes the next ptrace call on the thread.
827
828 On the other hand, if we are currently trying to stop all threads, we
829 should treat the new thread as if we had sent it a SIGSTOP. This works
830 because we are guaranteed that the add_lwp call above added us to the
831 end of the list, and so the new thread has not yet reached
832 wait_for_sigstop (but will). */
833 new_lwp->stop_expected = 1;
834 }
835
836 void
837 linux_attach_lwp (unsigned long lwpid)
838 {
839 linux_attach_lwp_1 (lwpid, 0);
840 }
841
842 /* Attach to PID. If PID is the tgid, attach to it and all
843 of its threads. */
844
845 static int
846 linux_attach (unsigned long pid)
847 {
848 /* Attach to PID. We will check for other threads
849 soon. */
850 linux_attach_lwp_1 (pid, 1);
851 linux_add_process (pid, 1);
852
853 if (!non_stop)
854 {
855 struct thread_info *thread;
856
857 /* Don't ignore the initial SIGSTOP if we just attached to this
858 process. It will be collected by wait shortly. */
859 thread = find_thread_ptid (ptid_build (pid, pid, 0));
860 thread->last_resume_kind = resume_stop;
861 }
862
863 if (linux_proc_get_tgid (pid) == pid)
864 {
865 DIR *dir;
866 char pathname[128];
867
868 sprintf (pathname, "/proc/%ld/task", pid);
869
870 dir = opendir (pathname);
871
872 if (!dir)
873 {
874 fprintf (stderr, "Could not open /proc/%ld/task.\n", pid);
875 fflush (stderr);
876 }
877 else
878 {
879 /* At this point we attached to the tgid. Scan the task for
880 existing threads. */
881 unsigned long lwp;
882 int new_threads_found;
883 int iterations = 0;
884 struct dirent *dp;
885
886 while (iterations < 2)
887 {
888 new_threads_found = 0;
889 /* Add all the other threads. While we go through the
890 threads, new threads may be spawned. Cycle through
891 the list of threads until we have done two iterations without
892 finding new threads. */
893 while ((dp = readdir (dir)) != NULL)
894 {
895 /* Fetch one lwp. */
896 lwp = strtoul (dp->d_name, NULL, 10);
897
898 /* Is this a new thread? */
899 if (lwp
900 && find_thread_ptid (ptid_build (pid, lwp, 0)) == NULL)
901 {
902 linux_attach_lwp_1 (lwp, 0);
903 new_threads_found++;
904
905 if (debug_threads)
906 fprintf (stderr, "\
907 Found and attached to new lwp %ld\n", lwp);
908 }
909 }
910
911 if (!new_threads_found)
912 iterations++;
913 else
914 iterations = 0;
915
916 rewinddir (dir);
917 }
918 closedir (dir);
919 }
920 }
921
922 return 0;
923 }
924
925 struct counter
926 {
927 int pid;
928 int count;
929 };
930
931 static int
932 second_thread_of_pid_p (struct inferior_list_entry *entry, void *args)
933 {
934 struct counter *counter = args;
935
936 if (ptid_get_pid (entry->id) == counter->pid)
937 {
938 if (++counter->count > 1)
939 return 1;
940 }
941
942 return 0;
943 }
944
945 static int
946 last_thread_of_process_p (struct thread_info *thread)
947 {
948 ptid_t ptid = ((struct inferior_list_entry *)thread)->id;
949 int pid = ptid_get_pid (ptid);
950 struct counter counter = { pid , 0 };
951
952 return (find_inferior (&all_threads,
953 second_thread_of_pid_p, &counter) == NULL);
954 }
955
956 /* Kill LWP. */
957
958 static void
959 linux_kill_one_lwp (struct lwp_info *lwp)
960 {
961 int pid = lwpid_of (lwp);
962
963 /* PTRACE_KILL is unreliable. After stepping into a signal handler,
964 there is no signal context, and ptrace(PTRACE_KILL) (or
965 ptrace(PTRACE_CONT, SIGKILL), pretty much the same) acts like
966 ptrace(CONT, pid, 0,0) and just resumes the tracee. A better
967 alternative is to kill with SIGKILL. We only need one SIGKILL
968 per process, not one for each thread. But since we still support
969 linuxthreads, and we also support debugging programs using raw
970 clone without CLONE_THREAD, we send one for each thread. For
971 years, we used PTRACE_KILL only, so we're being a bit paranoid
972 about some old kernels where PTRACE_KILL might work better
973 (dubious if there are any such, but that's why it's paranoia), so
974 we try SIGKILL first, PTRACE_KILL second, and so we're fine
975 everywhere. */
976
977 errno = 0;
978 kill (pid, SIGKILL);
979 if (debug_threads)
980 fprintf (stderr,
981 "LKL: kill (SIGKILL) %s, 0, 0 (%s)\n",
982 target_pid_to_str (ptid_of (lwp)),
983 errno ? strerror (errno) : "OK");
984
985 errno = 0;
986 ptrace (PTRACE_KILL, pid, (PTRACE_ARG3_TYPE) 0, (PTRACE_ARG4_TYPE) 0);
987 if (debug_threads)
988 fprintf (stderr,
989 "LKL: PTRACE_KILL %s, 0, 0 (%s)\n",
990 target_pid_to_str (ptid_of (lwp)),
991 errno ? strerror (errno) : "OK");
992 }
993
994 /* Callback for `find_inferior'. Kills an lwp of a given process,
995 except the leader. */
996
997 static int
998 kill_one_lwp_callback (struct inferior_list_entry *entry, void *args)
999 {
1000 struct thread_info *thread = (struct thread_info *) entry;
1001 struct lwp_info *lwp = get_thread_lwp (thread);
1002 int wstat;
1003 int pid = * (int *) args;
1004
1005 if (ptid_get_pid (entry->id) != pid)
1006 return 0;
1007
1008 /* We avoid killing the first thread here, because of a Linux kernel (at
1009 least 2.6.0-test7 through 2.6.8-rc4) bug; if we kill the parent before
1010 the children get a chance to be reaped, it will remain a zombie
1011 forever. */
1012
1013 if (lwpid_of (lwp) == pid)
1014 {
1015 if (debug_threads)
1016 fprintf (stderr, "lkop: is last of process %s\n",
1017 target_pid_to_str (entry->id));
1018 return 0;
1019 }
1020
1021 do
1022 {
1023 linux_kill_one_lwp (lwp);
1024
1025 /* Make sure it died. The loop is most likely unnecessary. */
1026 pid = linux_wait_for_event (lwp->head.id, &wstat, __WALL);
1027 } while (pid > 0 && WIFSTOPPED (wstat));
1028
1029 return 0;
1030 }
1031
1032 static int
1033 linux_kill (int pid)
1034 {
1035 struct process_info *process;
1036 struct lwp_info *lwp;
1037 int wstat;
1038 int lwpid;
1039
1040 process = find_process_pid (pid);
1041 if (process == NULL)
1042 return -1;
1043
1044 /* If we're killing a running inferior, make sure it is stopped
1045 first, as PTRACE_KILL will not work otherwise. */
1046 stop_all_lwps (0, NULL);
1047
1048 find_inferior (&all_threads, kill_one_lwp_callback , &pid);
1049
1050 /* See the comment in linux_kill_one_lwp. We did not kill the first
1051 thread in the list, so do so now. */
1052 lwp = find_lwp_pid (pid_to_ptid (pid));
1053
1054 if (lwp == NULL)
1055 {
1056 if (debug_threads)
1057 fprintf (stderr, "lk_1: cannot find lwp %ld, for pid: %d\n",
1058 lwpid_of (lwp), pid);
1059 }
1060 else
1061 {
1062 if (debug_threads)
1063 fprintf (stderr, "lk_1: killing lwp %ld, for pid: %d\n",
1064 lwpid_of (lwp), pid);
1065
1066 do
1067 {
1068 linux_kill_one_lwp (lwp);
1069
1070 /* Make sure it died. The loop is most likely unnecessary. */
1071 lwpid = linux_wait_for_event (lwp->head.id, &wstat, __WALL);
1072 } while (lwpid > 0 && WIFSTOPPED (wstat));
1073 }
1074
1075 the_target->mourn (process);
1076
1077 /* Since we presently can only stop all lwps of all processes, we
1078 need to unstop lwps of other processes. */
1079 unstop_all_lwps (0, NULL);
1080 return 0;
1081 }
1082
1083 /* Get pending signal of THREAD, for detaching purposes. This is the
1084 signal the thread last stopped for, which we need to deliver to the
1085 thread when detaching, otherwise, it'd be suppressed/lost. */
1086
1087 static int
1088 get_detach_signal (struct thread_info *thread)
1089 {
1090 enum gdb_signal signo = GDB_SIGNAL_0;
1091 int status;
1092 struct lwp_info *lp = get_thread_lwp (thread);
1093
1094 if (lp->status_pending_p)
1095 status = lp->status_pending;
1096 else
1097 {
1098 /* If the thread had been suspended by gdbserver, and it stopped
1099 cleanly, then it'll have stopped with SIGSTOP. But we don't
1100 want to deliver that SIGSTOP. */
1101 if (thread->last_status.kind != TARGET_WAITKIND_STOPPED
1102 || thread->last_status.value.sig == GDB_SIGNAL_0)
1103 return 0;
1104
1105 /* Otherwise, we may need to deliver the signal we
1106 intercepted. */
1107 status = lp->last_status;
1108 }
1109
1110 if (!WIFSTOPPED (status))
1111 {
1112 if (debug_threads)
1113 fprintf (stderr,
1114 "GPS: lwp %s hasn't stopped: no pending signal\n",
1115 target_pid_to_str (ptid_of (lp)));
1116 return 0;
1117 }
1118
1119 /* Extended wait statuses aren't real SIGTRAPs. */
1120 if (WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1121 {
1122 if (debug_threads)
1123 fprintf (stderr,
1124 "GPS: lwp %s had stopped with extended "
1125 "status: no pending signal\n",
1126 target_pid_to_str (ptid_of (lp)));
1127 return 0;
1128 }
1129
1130 signo = gdb_signal_from_host (WSTOPSIG (status));
1131
1132 if (program_signals_p && !program_signals[signo])
1133 {
1134 if (debug_threads)
1135 fprintf (stderr,
1136 "GPS: lwp %s had signal %s, but it is in nopass state\n",
1137 target_pid_to_str (ptid_of (lp)),
1138 gdb_signal_to_string (signo));
1139 return 0;
1140 }
1141 else if (!program_signals_p
1142 /* If we have no way to know which signals GDB does not
1143 want to have passed to the program, assume
1144 SIGTRAP/SIGINT, which is GDB's default. */
1145 && (signo == GDB_SIGNAL_TRAP || signo == GDB_SIGNAL_INT))
1146 {
1147 if (debug_threads)
1148 fprintf (stderr,
1149 "GPS: lwp %s had signal %s, "
1150 "but we don't know if we should pass it. Default to not.\n",
1151 target_pid_to_str (ptid_of (lp)),
1152 gdb_signal_to_string (signo));
1153 return 0;
1154 }
1155 else
1156 {
1157 if (debug_threads)
1158 fprintf (stderr,
1159 "GPS: lwp %s has pending signal %s: delivering it.\n",
1160 target_pid_to_str (ptid_of (lp)),
1161 gdb_signal_to_string (signo));
1162
1163 return WSTOPSIG (status);
1164 }
1165 }
1166
1167 static int
1168 linux_detach_one_lwp (struct inferior_list_entry *entry, void *args)
1169 {
1170 struct thread_info *thread = (struct thread_info *) entry;
1171 struct lwp_info *lwp = get_thread_lwp (thread);
1172 int pid = * (int *) args;
1173 int sig;
1174
1175 if (ptid_get_pid (entry->id) != pid)
1176 return 0;
1177
1178 /* If there is a pending SIGSTOP, get rid of it. */
1179 if (lwp->stop_expected)
1180 {
1181 if (debug_threads)
1182 fprintf (stderr,
1183 "Sending SIGCONT to %s\n",
1184 target_pid_to_str (ptid_of (lwp)));
1185
1186 kill_lwp (lwpid_of (lwp), SIGCONT);
1187 lwp->stop_expected = 0;
1188 }
1189
1190 /* Flush any pending changes to the process's registers. */
1191 regcache_invalidate_thread (get_lwp_thread (lwp));
1192
1193 /* Pass on any pending signal for this thread. */
1194 sig = get_detach_signal (thread);
1195
1196 /* Finally, let it resume. */
1197 if (the_low_target.prepare_to_resume != NULL)
1198 the_low_target.prepare_to_resume (lwp);
1199 if (ptrace (PTRACE_DETACH, lwpid_of (lwp), (PTRACE_ARG3_TYPE) 0,
1200 (PTRACE_ARG4_TYPE) (long) sig) < 0)
1201 error (_("Can't detach %s: %s"),
1202 target_pid_to_str (ptid_of (lwp)),
1203 strerror (errno));
1204
1205 delete_lwp (lwp);
1206 return 0;
1207 }
1208
1209 static int
1210 linux_detach (int pid)
1211 {
1212 struct process_info *process;
1213
1214 process = find_process_pid (pid);
1215 if (process == NULL)
1216 return -1;
1217
1218 /* Stop all threads before detaching. First, ptrace requires that
1219 the thread is stopped to sucessfully detach. Second, thread_db
1220 may need to uninstall thread event breakpoints from memory, which
1221 only works with a stopped process anyway. */
1222 stop_all_lwps (0, NULL);
1223
1224 #ifdef USE_THREAD_DB
1225 thread_db_detach (process);
1226 #endif
1227
1228 /* Stabilize threads (move out of jump pads). */
1229 stabilize_threads ();
1230
1231 find_inferior (&all_threads, linux_detach_one_lwp, &pid);
1232
1233 the_target->mourn (process);
1234
1235 /* Since we presently can only stop all lwps of all processes, we
1236 need to unstop lwps of other processes. */
1237 unstop_all_lwps (0, NULL);
1238 return 0;
1239 }
1240
1241 /* Remove all LWPs that belong to process PROC from the lwp list. */
1242
1243 static int
1244 delete_lwp_callback (struct inferior_list_entry *entry, void *proc)
1245 {
1246 struct lwp_info *lwp = (struct lwp_info *) entry;
1247 struct process_info *process = proc;
1248
1249 if (pid_of (lwp) == pid_of (process))
1250 delete_lwp (lwp);
1251
1252 return 0;
1253 }
1254
1255 static void
1256 linux_mourn (struct process_info *process)
1257 {
1258 struct process_info_private *priv;
1259
1260 #ifdef USE_THREAD_DB
1261 thread_db_mourn (process);
1262 #endif
1263
1264 find_inferior (&all_lwps, delete_lwp_callback, process);
1265
1266 /* Freeing all private data. */
1267 priv = process->private;
1268 free (priv->arch_private);
1269 free (priv);
1270 process->private = NULL;
1271
1272 remove_process (process);
1273 }
1274
1275 static void
1276 linux_join (int pid)
1277 {
1278 int status, ret;
1279
1280 do {
1281 ret = my_waitpid (pid, &status, 0);
1282 if (WIFEXITED (status) || WIFSIGNALED (status))
1283 break;
1284 } while (ret != -1 || errno != ECHILD);
1285 }
1286
1287 /* Return nonzero if the given thread is still alive. */
1288 static int
1289 linux_thread_alive (ptid_t ptid)
1290 {
1291 struct lwp_info *lwp = find_lwp_pid (ptid);
1292
1293 /* We assume we always know if a thread exits. If a whole process
1294 exited but we still haven't been able to report it to GDB, we'll
1295 hold on to the last lwp of the dead process. */
1296 if (lwp != NULL)
1297 return !lwp->dead;
1298 else
1299 return 0;
1300 }
1301
1302 /* Return 1 if this lwp has an interesting status pending. */
1303 static int
1304 status_pending_p_callback (struct inferior_list_entry *entry, void *arg)
1305 {
1306 struct lwp_info *lwp = (struct lwp_info *) entry;
1307 ptid_t ptid = * (ptid_t *) arg;
1308 struct thread_info *thread;
1309
1310 /* Check if we're only interested in events from a specific process
1311 or its lwps. */
1312 if (!ptid_equal (minus_one_ptid, ptid)
1313 && ptid_get_pid (ptid) != ptid_get_pid (lwp->head.id))
1314 return 0;
1315
1316 thread = get_lwp_thread (lwp);
1317
1318 /* If we got a `vCont;t', but we haven't reported a stop yet, do
1319 report any status pending the LWP may have. */
1320 if (thread->last_resume_kind == resume_stop
1321 && thread->last_status.kind != TARGET_WAITKIND_IGNORE)
1322 return 0;
1323
1324 return lwp->status_pending_p;
1325 }
1326
1327 static int
1328 same_lwp (struct inferior_list_entry *entry, void *data)
1329 {
1330 ptid_t ptid = *(ptid_t *) data;
1331 int lwp;
1332
1333 if (ptid_get_lwp (ptid) != 0)
1334 lwp = ptid_get_lwp (ptid);
1335 else
1336 lwp = ptid_get_pid (ptid);
1337
1338 if (ptid_get_lwp (entry->id) == lwp)
1339 return 1;
1340
1341 return 0;
1342 }
1343
1344 struct lwp_info *
1345 find_lwp_pid (ptid_t ptid)
1346 {
1347 return (struct lwp_info*) find_inferior (&all_lwps, same_lwp, &ptid);
1348 }
1349
1350 static struct lwp_info *
1351 linux_wait_for_lwp (ptid_t ptid, int *wstatp, int options)
1352 {
1353 int ret;
1354 int to_wait_for = -1;
1355 struct lwp_info *child = NULL;
1356
1357 if (debug_threads)
1358 fprintf (stderr, "linux_wait_for_lwp: %s\n", target_pid_to_str (ptid));
1359
1360 if (ptid_equal (ptid, minus_one_ptid))
1361 to_wait_for = -1; /* any child */
1362 else
1363 to_wait_for = ptid_get_lwp (ptid); /* this lwp only */
1364
1365 options |= __WALL;
1366
1367 retry:
1368
1369 ret = my_waitpid (to_wait_for, wstatp, options);
1370 if (ret == 0 || (ret == -1 && errno == ECHILD && (options & WNOHANG)))
1371 return NULL;
1372 else if (ret == -1)
1373 perror_with_name ("waitpid");
1374
1375 if (debug_threads
1376 && (!WIFSTOPPED (*wstatp)
1377 || (WSTOPSIG (*wstatp) != 32
1378 && WSTOPSIG (*wstatp) != 33)))
1379 fprintf (stderr, "Got an event from %d (%x)\n", ret, *wstatp);
1380
1381 child = find_lwp_pid (pid_to_ptid (ret));
1382
1383 /* If we didn't find a process, one of two things presumably happened:
1384 - A process we started and then detached from has exited. Ignore it.
1385 - A process we are controlling has forked and the new child's stop
1386 was reported to us by the kernel. Save its PID. */
1387 if (child == NULL && WIFSTOPPED (*wstatp))
1388 {
1389 add_to_pid_list (&stopped_pids, ret, *wstatp);
1390 goto retry;
1391 }
1392 else if (child == NULL)
1393 goto retry;
1394
1395 child->stopped = 1;
1396
1397 child->last_status = *wstatp;
1398
1399 if (WIFSTOPPED (*wstatp))
1400 {
1401 struct process_info *proc;
1402
1403 /* Architecture-specific setup after inferior is running. This
1404 needs to happen after we have attached to the inferior and it
1405 is stopped for the first time, but before we access any
1406 inferior registers. */
1407 proc = find_process_pid (pid_of (child));
1408 if (proc->private->new_inferior)
1409 {
1410 struct thread_info *saved_inferior;
1411
1412 saved_inferior = current_inferior;
1413 current_inferior = get_lwp_thread (child);
1414
1415 the_low_target.arch_setup ();
1416
1417 current_inferior = saved_inferior;
1418
1419 proc->private->new_inferior = 0;
1420 }
1421 }
1422
1423 /* Fetch the possibly triggered data watchpoint info and store it in
1424 CHILD.
1425
1426 On some archs, like x86, that use debug registers to set
1427 watchpoints, it's possible that the way to know which watched
1428 address trapped, is to check the register that is used to select
1429 which address to watch. Problem is, between setting the
1430 watchpoint and reading back which data address trapped, the user
1431 may change the set of watchpoints, and, as a consequence, GDB
1432 changes the debug registers in the inferior. To avoid reading
1433 back a stale stopped-data-address when that happens, we cache in
1434 LP the fact that a watchpoint trapped, and the corresponding data
1435 address, as soon as we see CHILD stop with a SIGTRAP. If GDB
1436 changes the debug registers meanwhile, we have the cached data we
1437 can rely on. */
1438
1439 if (WIFSTOPPED (*wstatp) && WSTOPSIG (*wstatp) == SIGTRAP)
1440 {
1441 if (the_low_target.stopped_by_watchpoint == NULL)
1442 {
1443 child->stopped_by_watchpoint = 0;
1444 }
1445 else
1446 {
1447 struct thread_info *saved_inferior;
1448
1449 saved_inferior = current_inferior;
1450 current_inferior = get_lwp_thread (child);
1451
1452 child->stopped_by_watchpoint
1453 = the_low_target.stopped_by_watchpoint ();
1454
1455 if (child->stopped_by_watchpoint)
1456 {
1457 if (the_low_target.stopped_data_address != NULL)
1458 child->stopped_data_address
1459 = the_low_target.stopped_data_address ();
1460 else
1461 child->stopped_data_address = 0;
1462 }
1463
1464 current_inferior = saved_inferior;
1465 }
1466 }
1467
1468 /* Store the STOP_PC, with adjustment applied. This depends on the
1469 architecture being defined already (so that CHILD has a valid
1470 regcache), and on LAST_STATUS being set (to check for SIGTRAP or
1471 not). */
1472 if (WIFSTOPPED (*wstatp))
1473 child->stop_pc = get_stop_pc (child);
1474
1475 if (debug_threads
1476 && WIFSTOPPED (*wstatp)
1477 && the_low_target.get_pc != NULL)
1478 {
1479 struct thread_info *saved_inferior = current_inferior;
1480 struct regcache *regcache;
1481 CORE_ADDR pc;
1482
1483 current_inferior = get_lwp_thread (child);
1484 regcache = get_thread_regcache (current_inferior, 1);
1485 pc = (*the_low_target.get_pc) (regcache);
1486 fprintf (stderr, "linux_wait_for_lwp: pc is 0x%lx\n", (long) pc);
1487 current_inferior = saved_inferior;
1488 }
1489
1490 return child;
1491 }
1492
1493 /* This function should only be called if the LWP got a SIGTRAP.
1494
1495 Handle any tracepoint steps or hits. Return true if a tracepoint
1496 event was handled, 0 otherwise. */
1497
1498 static int
1499 handle_tracepoints (struct lwp_info *lwp)
1500 {
1501 struct thread_info *tinfo = get_lwp_thread (lwp);
1502 int tpoint_related_event = 0;
1503
1504 /* If this tracepoint hit causes a tracing stop, we'll immediately
1505 uninsert tracepoints. To do this, we temporarily pause all
1506 threads, unpatch away, and then unpause threads. We need to make
1507 sure the unpausing doesn't resume LWP too. */
1508 lwp->suspended++;
1509
1510 /* And we need to be sure that any all-threads-stopping doesn't try
1511 to move threads out of the jump pads, as it could deadlock the
1512 inferior (LWP could be in the jump pad, maybe even holding the
1513 lock.) */
1514
1515 /* Do any necessary step collect actions. */
1516 tpoint_related_event |= tracepoint_finished_step (tinfo, lwp->stop_pc);
1517
1518 tpoint_related_event |= handle_tracepoint_bkpts (tinfo, lwp->stop_pc);
1519
1520 /* See if we just hit a tracepoint and do its main collect
1521 actions. */
1522 tpoint_related_event |= tracepoint_was_hit (tinfo, lwp->stop_pc);
1523
1524 lwp->suspended--;
1525
1526 gdb_assert (lwp->suspended == 0);
1527 gdb_assert (!stabilizing_threads || lwp->collecting_fast_tracepoint);
1528
1529 if (tpoint_related_event)
1530 {
1531 if (debug_threads)
1532 fprintf (stderr, "got a tracepoint event\n");
1533 return 1;
1534 }
1535
1536 return 0;
1537 }
1538
1539 /* Convenience wrapper. Returns true if LWP is presently collecting a
1540 fast tracepoint. */
1541
1542 static int
1543 linux_fast_tracepoint_collecting (struct lwp_info *lwp,
1544 struct fast_tpoint_collect_status *status)
1545 {
1546 CORE_ADDR thread_area;
1547
1548 if (the_low_target.get_thread_area == NULL)
1549 return 0;
1550
1551 /* Get the thread area address. This is used to recognize which
1552 thread is which when tracing with the in-process agent library.
1553 We don't read anything from the address, and treat it as opaque;
1554 it's the address itself that we assume is unique per-thread. */
1555 if ((*the_low_target.get_thread_area) (lwpid_of (lwp), &thread_area) == -1)
1556 return 0;
1557
1558 return fast_tracepoint_collecting (thread_area, lwp->stop_pc, status);
1559 }
1560
1561 /* The reason we resume in the caller, is because we want to be able
1562 to pass lwp->status_pending as WSTAT, and we need to clear
1563 status_pending_p before resuming, otherwise, linux_resume_one_lwp
1564 refuses to resume. */
1565
1566 static int
1567 maybe_move_out_of_jump_pad (struct lwp_info *lwp, int *wstat)
1568 {
1569 struct thread_info *saved_inferior;
1570
1571 saved_inferior = current_inferior;
1572 current_inferior = get_lwp_thread (lwp);
1573
1574 if ((wstat == NULL
1575 || (WIFSTOPPED (*wstat) && WSTOPSIG (*wstat) != SIGTRAP))
1576 && supports_fast_tracepoints ()
1577 && agent_loaded_p ())
1578 {
1579 struct fast_tpoint_collect_status status;
1580 int r;
1581
1582 if (debug_threads)
1583 fprintf (stderr, "\
1584 Checking whether LWP %ld needs to move out of the jump pad.\n",
1585 lwpid_of (lwp));
1586
1587 r = linux_fast_tracepoint_collecting (lwp, &status);
1588
1589 if (wstat == NULL
1590 || (WSTOPSIG (*wstat) != SIGILL
1591 && WSTOPSIG (*wstat) != SIGFPE
1592 && WSTOPSIG (*wstat) != SIGSEGV
1593 && WSTOPSIG (*wstat) != SIGBUS))
1594 {
1595 lwp->collecting_fast_tracepoint = r;
1596
1597 if (r != 0)
1598 {
1599 if (r == 1 && lwp->exit_jump_pad_bkpt == NULL)
1600 {
1601 /* Haven't executed the original instruction yet.
1602 Set breakpoint there, and wait till it's hit,
1603 then single-step until exiting the jump pad. */
1604 lwp->exit_jump_pad_bkpt
1605 = set_breakpoint_at (status.adjusted_insn_addr, NULL);
1606 }
1607
1608 if (debug_threads)
1609 fprintf (stderr, "\
1610 Checking whether LWP %ld needs to move out of the jump pad...it does\n",
1611 lwpid_of (lwp));
1612 current_inferior = saved_inferior;
1613
1614 return 1;
1615 }
1616 }
1617 else
1618 {
1619 /* If we get a synchronous signal while collecting, *and*
1620 while executing the (relocated) original instruction,
1621 reset the PC to point at the tpoint address, before
1622 reporting to GDB. Otherwise, it's an IPA lib bug: just
1623 report the signal to GDB, and pray for the best. */
1624
1625 lwp->collecting_fast_tracepoint = 0;
1626
1627 if (r != 0
1628 && (status.adjusted_insn_addr <= lwp->stop_pc
1629 && lwp->stop_pc < status.adjusted_insn_addr_end))
1630 {
1631 siginfo_t info;
1632 struct regcache *regcache;
1633
1634 /* The si_addr on a few signals references the address
1635 of the faulting instruction. Adjust that as
1636 well. */
1637 if ((WSTOPSIG (*wstat) == SIGILL
1638 || WSTOPSIG (*wstat) == SIGFPE
1639 || WSTOPSIG (*wstat) == SIGBUS
1640 || WSTOPSIG (*wstat) == SIGSEGV)
1641 && ptrace (PTRACE_GETSIGINFO, lwpid_of (lwp),
1642 (PTRACE_ARG3_TYPE) 0, &info) == 0
1643 /* Final check just to make sure we don't clobber
1644 the siginfo of non-kernel-sent signals. */
1645 && (uintptr_t) info.si_addr == lwp->stop_pc)
1646 {
1647 info.si_addr = (void *) (uintptr_t) status.tpoint_addr;
1648 ptrace (PTRACE_SETSIGINFO, lwpid_of (lwp),
1649 (PTRACE_ARG3_TYPE) 0, &info);
1650 }
1651
1652 regcache = get_thread_regcache (get_lwp_thread (lwp), 1);
1653 (*the_low_target.set_pc) (regcache, status.tpoint_addr);
1654 lwp->stop_pc = status.tpoint_addr;
1655
1656 /* Cancel any fast tracepoint lock this thread was
1657 holding. */
1658 force_unlock_trace_buffer ();
1659 }
1660
1661 if (lwp->exit_jump_pad_bkpt != NULL)
1662 {
1663 if (debug_threads)
1664 fprintf (stderr,
1665 "Cancelling fast exit-jump-pad: removing bkpt. "
1666 "stopping all threads momentarily.\n");
1667
1668 stop_all_lwps (1, lwp);
1669 cancel_breakpoints ();
1670
1671 delete_breakpoint (lwp->exit_jump_pad_bkpt);
1672 lwp->exit_jump_pad_bkpt = NULL;
1673
1674 unstop_all_lwps (1, lwp);
1675
1676 gdb_assert (lwp->suspended >= 0);
1677 }
1678 }
1679 }
1680
1681 if (debug_threads)
1682 fprintf (stderr, "\
1683 Checking whether LWP %ld needs to move out of the jump pad...no\n",
1684 lwpid_of (lwp));
1685
1686 current_inferior = saved_inferior;
1687 return 0;
1688 }
1689
1690 /* Enqueue one signal in the "signals to report later when out of the
1691 jump pad" list. */
1692
1693 static void
1694 enqueue_one_deferred_signal (struct lwp_info *lwp, int *wstat)
1695 {
1696 struct pending_signals *p_sig;
1697
1698 if (debug_threads)
1699 fprintf (stderr, "\
1700 Deferring signal %d for LWP %ld.\n", WSTOPSIG (*wstat), lwpid_of (lwp));
1701
1702 if (debug_threads)
1703 {
1704 struct pending_signals *sig;
1705
1706 for (sig = lwp->pending_signals_to_report;
1707 sig != NULL;
1708 sig = sig->prev)
1709 fprintf (stderr,
1710 " Already queued %d\n",
1711 sig->signal);
1712
1713 fprintf (stderr, " (no more currently queued signals)\n");
1714 }
1715
1716 /* Don't enqueue non-RT signals if they are already in the deferred
1717 queue. (SIGSTOP being the easiest signal to see ending up here
1718 twice) */
1719 if (WSTOPSIG (*wstat) < __SIGRTMIN)
1720 {
1721 struct pending_signals *sig;
1722
1723 for (sig = lwp->pending_signals_to_report;
1724 sig != NULL;
1725 sig = sig->prev)
1726 {
1727 if (sig->signal == WSTOPSIG (*wstat))
1728 {
1729 if (debug_threads)
1730 fprintf (stderr,
1731 "Not requeuing already queued non-RT signal %d"
1732 " for LWP %ld\n",
1733 sig->signal,
1734 lwpid_of (lwp));
1735 return;
1736 }
1737 }
1738 }
1739
1740 p_sig = xmalloc (sizeof (*p_sig));
1741 p_sig->prev = lwp->pending_signals_to_report;
1742 p_sig->signal = WSTOPSIG (*wstat);
1743 memset (&p_sig->info, 0, sizeof (siginfo_t));
1744 ptrace (PTRACE_GETSIGINFO, lwpid_of (lwp), (PTRACE_ARG3_TYPE) 0,
1745 &p_sig->info);
1746
1747 lwp->pending_signals_to_report = p_sig;
1748 }
1749
1750 /* Dequeue one signal from the "signals to report later when out of
1751 the jump pad" list. */
1752
1753 static int
1754 dequeue_one_deferred_signal (struct lwp_info *lwp, int *wstat)
1755 {
1756 if (lwp->pending_signals_to_report != NULL)
1757 {
1758 struct pending_signals **p_sig;
1759
1760 p_sig = &lwp->pending_signals_to_report;
1761 while ((*p_sig)->prev != NULL)
1762 p_sig = &(*p_sig)->prev;
1763
1764 *wstat = W_STOPCODE ((*p_sig)->signal);
1765 if ((*p_sig)->info.si_signo != 0)
1766 ptrace (PTRACE_SETSIGINFO, lwpid_of (lwp), (PTRACE_ARG3_TYPE) 0,
1767 &(*p_sig)->info);
1768 free (*p_sig);
1769 *p_sig = NULL;
1770
1771 if (debug_threads)
1772 fprintf (stderr, "Reporting deferred signal %d for LWP %ld.\n",
1773 WSTOPSIG (*wstat), lwpid_of (lwp));
1774
1775 if (debug_threads)
1776 {
1777 struct pending_signals *sig;
1778
1779 for (sig = lwp->pending_signals_to_report;
1780 sig != NULL;
1781 sig = sig->prev)
1782 fprintf (stderr,
1783 " Still queued %d\n",
1784 sig->signal);
1785
1786 fprintf (stderr, " (no more queued signals)\n");
1787 }
1788
1789 return 1;
1790 }
1791
1792 return 0;
1793 }
1794
1795 /* Arrange for a breakpoint to be hit again later. We don't keep the
1796 SIGTRAP status and don't forward the SIGTRAP signal to the LWP. We
1797 will handle the current event, eventually we will resume this LWP,
1798 and this breakpoint will trap again. */
1799
1800 static int
1801 cancel_breakpoint (struct lwp_info *lwp)
1802 {
1803 struct thread_info *saved_inferior;
1804
1805 /* There's nothing to do if we don't support breakpoints. */
1806 if (!supports_breakpoints ())
1807 return 0;
1808
1809 /* breakpoint_at reads from current inferior. */
1810 saved_inferior = current_inferior;
1811 current_inferior = get_lwp_thread (lwp);
1812
1813 if ((*the_low_target.breakpoint_at) (lwp->stop_pc))
1814 {
1815 if (debug_threads)
1816 fprintf (stderr,
1817 "CB: Push back breakpoint for %s\n",
1818 target_pid_to_str (ptid_of (lwp)));
1819
1820 /* Back up the PC if necessary. */
1821 if (the_low_target.decr_pc_after_break)
1822 {
1823 struct regcache *regcache
1824 = get_thread_regcache (current_inferior, 1);
1825 (*the_low_target.set_pc) (regcache, lwp->stop_pc);
1826 }
1827
1828 current_inferior = saved_inferior;
1829 return 1;
1830 }
1831 else
1832 {
1833 if (debug_threads)
1834 fprintf (stderr,
1835 "CB: No breakpoint found at %s for [%s]\n",
1836 paddress (lwp->stop_pc),
1837 target_pid_to_str (ptid_of (lwp)));
1838 }
1839
1840 current_inferior = saved_inferior;
1841 return 0;
1842 }
1843
1844 /* When the event-loop is doing a step-over, this points at the thread
1845 being stepped. */
1846 ptid_t step_over_bkpt;
1847
1848 /* Wait for an event from child PID. If PID is -1, wait for any
1849 child. Store the stop status through the status pointer WSTAT.
1850 OPTIONS is passed to the waitpid call. Return 0 if no child stop
1851 event was found and OPTIONS contains WNOHANG. Return the PID of
1852 the stopped child otherwise. */
1853
1854 static int
1855 linux_wait_for_event (ptid_t ptid, int *wstat, int options)
1856 {
1857 struct lwp_info *event_child, *requested_child;
1858 ptid_t wait_ptid;
1859
1860 event_child = NULL;
1861 requested_child = NULL;
1862
1863 /* Check for a lwp with a pending status. */
1864
1865 if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
1866 {
1867 event_child = (struct lwp_info *)
1868 find_inferior (&all_lwps, status_pending_p_callback, &ptid);
1869 if (debug_threads && event_child)
1870 fprintf (stderr, "Got a pending child %ld\n", lwpid_of (event_child));
1871 }
1872 else
1873 {
1874 requested_child = find_lwp_pid (ptid);
1875
1876 if (stopping_threads == NOT_STOPPING_THREADS
1877 && requested_child->status_pending_p
1878 && requested_child->collecting_fast_tracepoint)
1879 {
1880 enqueue_one_deferred_signal (requested_child,
1881 &requested_child->status_pending);
1882 requested_child->status_pending_p = 0;
1883 requested_child->status_pending = 0;
1884 linux_resume_one_lwp (requested_child, 0, 0, NULL);
1885 }
1886
1887 if (requested_child->suspended
1888 && requested_child->status_pending_p)
1889 fatal ("requesting an event out of a suspended child?");
1890
1891 if (requested_child->status_pending_p)
1892 event_child = requested_child;
1893 }
1894
1895 if (event_child != NULL)
1896 {
1897 if (debug_threads)
1898 fprintf (stderr, "Got an event from pending child %ld (%04x)\n",
1899 lwpid_of (event_child), event_child->status_pending);
1900 *wstat = event_child->status_pending;
1901 event_child->status_pending_p = 0;
1902 event_child->status_pending = 0;
1903 current_inferior = get_lwp_thread (event_child);
1904 return lwpid_of (event_child);
1905 }
1906
1907 if (ptid_is_pid (ptid))
1908 {
1909 /* A request to wait for a specific tgid. This is not possible
1910 with waitpid, so instead, we wait for any child, and leave
1911 children we're not interested in right now with a pending
1912 status to report later. */
1913 wait_ptid = minus_one_ptid;
1914 }
1915 else
1916 wait_ptid = ptid;
1917
1918 /* We only enter this loop if no process has a pending wait status. Thus
1919 any action taken in response to a wait status inside this loop is
1920 responding as soon as we detect the status, not after any pending
1921 events. */
1922 while (1)
1923 {
1924 event_child = linux_wait_for_lwp (wait_ptid, wstat, options);
1925
1926 if ((options & WNOHANG) && event_child == NULL)
1927 {
1928 if (debug_threads)
1929 fprintf (stderr, "WNOHANG set, no event found\n");
1930 return 0;
1931 }
1932
1933 if (event_child == NULL)
1934 error ("event from unknown child");
1935
1936 if (ptid_is_pid (ptid)
1937 && ptid_get_pid (ptid) != ptid_get_pid (ptid_of (event_child)))
1938 {
1939 if (! WIFSTOPPED (*wstat))
1940 mark_lwp_dead (event_child, *wstat);
1941 else
1942 {
1943 event_child->status_pending_p = 1;
1944 event_child->status_pending = *wstat;
1945 }
1946 continue;
1947 }
1948
1949 current_inferior = get_lwp_thread (event_child);
1950
1951 /* Check for thread exit. */
1952 if (! WIFSTOPPED (*wstat))
1953 {
1954 if (debug_threads)
1955 fprintf (stderr, "LWP %ld exiting\n", lwpid_of (event_child));
1956
1957 /* If the last thread is exiting, just return. */
1958 if (last_thread_of_process_p (current_inferior))
1959 {
1960 if (debug_threads)
1961 fprintf (stderr, "LWP %ld is last lwp of process\n",
1962 lwpid_of (event_child));
1963 return lwpid_of (event_child);
1964 }
1965
1966 if (!non_stop)
1967 {
1968 current_inferior = (struct thread_info *) all_threads.head;
1969 if (debug_threads)
1970 fprintf (stderr, "Current inferior is now %ld\n",
1971 lwpid_of (get_thread_lwp (current_inferior)));
1972 }
1973 else
1974 {
1975 current_inferior = NULL;
1976 if (debug_threads)
1977 fprintf (stderr, "Current inferior is now <NULL>\n");
1978 }
1979
1980 /* If we were waiting for this particular child to do something...
1981 well, it did something. */
1982 if (requested_child != NULL)
1983 {
1984 int lwpid = lwpid_of (event_child);
1985
1986 /* Cancel the step-over operation --- the thread that
1987 started it is gone. */
1988 if (finish_step_over (event_child))
1989 unstop_all_lwps (1, event_child);
1990 delete_lwp (event_child);
1991 return lwpid;
1992 }
1993
1994 delete_lwp (event_child);
1995
1996 /* Wait for a more interesting event. */
1997 continue;
1998 }
1999
2000 if (event_child->must_set_ptrace_flags)
2001 {
2002 linux_enable_event_reporting (lwpid_of (event_child));
2003 event_child->must_set_ptrace_flags = 0;
2004 }
2005
2006 if (WIFSTOPPED (*wstat) && WSTOPSIG (*wstat) == SIGTRAP
2007 && *wstat >> 16 != 0)
2008 {
2009 handle_extended_wait (event_child, *wstat);
2010 continue;
2011 }
2012
2013 if (WIFSTOPPED (*wstat)
2014 && WSTOPSIG (*wstat) == SIGSTOP
2015 && event_child->stop_expected)
2016 {
2017 int should_stop;
2018
2019 if (debug_threads)
2020 fprintf (stderr, "Expected stop.\n");
2021 event_child->stop_expected = 0;
2022
2023 should_stop = (current_inferior->last_resume_kind == resume_stop
2024 || stopping_threads != NOT_STOPPING_THREADS);
2025
2026 if (!should_stop)
2027 {
2028 linux_resume_one_lwp (event_child,
2029 event_child->stepping, 0, NULL);
2030 continue;
2031 }
2032 }
2033
2034 return lwpid_of (event_child);
2035 }
2036
2037 /* NOTREACHED */
2038 return 0;
2039 }
2040
2041 /* Count the LWP's that have had events. */
2042
2043 static int
2044 count_events_callback (struct inferior_list_entry *entry, void *data)
2045 {
2046 struct lwp_info *lp = (struct lwp_info *) entry;
2047 struct thread_info *thread = get_lwp_thread (lp);
2048 int *count = data;
2049
2050 gdb_assert (count != NULL);
2051
2052 /* Count only resumed LWPs that have a SIGTRAP event pending that
2053 should be reported to GDB. */
2054 if (thread->last_status.kind == TARGET_WAITKIND_IGNORE
2055 && thread->last_resume_kind != resume_stop
2056 && lp->status_pending_p
2057 && WIFSTOPPED (lp->status_pending)
2058 && WSTOPSIG (lp->status_pending) == SIGTRAP
2059 && !breakpoint_inserted_here (lp->stop_pc))
2060 (*count)++;
2061
2062 return 0;
2063 }
2064
2065 /* Select the LWP (if any) that is currently being single-stepped. */
2066
2067 static int
2068 select_singlestep_lwp_callback (struct inferior_list_entry *entry, void *data)
2069 {
2070 struct lwp_info *lp = (struct lwp_info *) entry;
2071 struct thread_info *thread = get_lwp_thread (lp);
2072
2073 if (thread->last_status.kind == TARGET_WAITKIND_IGNORE
2074 && thread->last_resume_kind == resume_step
2075 && lp->status_pending_p)
2076 return 1;
2077 else
2078 return 0;
2079 }
2080
2081 /* Select the Nth LWP that has had a SIGTRAP event that should be
2082 reported to GDB. */
2083
2084 static int
2085 select_event_lwp_callback (struct inferior_list_entry *entry, void *data)
2086 {
2087 struct lwp_info *lp = (struct lwp_info *) entry;
2088 struct thread_info *thread = get_lwp_thread (lp);
2089 int *selector = data;
2090
2091 gdb_assert (selector != NULL);
2092
2093 /* Select only resumed LWPs that have a SIGTRAP event pending. */
2094 if (thread->last_resume_kind != resume_stop
2095 && thread->last_status.kind == TARGET_WAITKIND_IGNORE
2096 && lp->status_pending_p
2097 && WIFSTOPPED (lp->status_pending)
2098 && WSTOPSIG (lp->status_pending) == SIGTRAP
2099 && !breakpoint_inserted_here (lp->stop_pc))
2100 if ((*selector)-- == 0)
2101 return 1;
2102
2103 return 0;
2104 }
2105
2106 static int
2107 cancel_breakpoints_callback (struct inferior_list_entry *entry, void *data)
2108 {
2109 struct lwp_info *lp = (struct lwp_info *) entry;
2110 struct thread_info *thread = get_lwp_thread (lp);
2111 struct lwp_info *event_lp = data;
2112
2113 /* Leave the LWP that has been elected to receive a SIGTRAP alone. */
2114 if (lp == event_lp)
2115 return 0;
2116
2117 /* If a LWP other than the LWP that we're reporting an event for has
2118 hit a GDB breakpoint (as opposed to some random trap signal),
2119 then just arrange for it to hit it again later. We don't keep
2120 the SIGTRAP status and don't forward the SIGTRAP signal to the
2121 LWP. We will handle the current event, eventually we will resume
2122 all LWPs, and this one will get its breakpoint trap again.
2123
2124 If we do not do this, then we run the risk that the user will
2125 delete or disable the breakpoint, but the LWP will have already
2126 tripped on it. */
2127
2128 if (thread->last_resume_kind != resume_stop
2129 && thread->last_status.kind == TARGET_WAITKIND_IGNORE
2130 && lp->status_pending_p
2131 && WIFSTOPPED (lp->status_pending)
2132 && WSTOPSIG (lp->status_pending) == SIGTRAP
2133 && !lp->stepping
2134 && !lp->stopped_by_watchpoint
2135 && cancel_breakpoint (lp))
2136 /* Throw away the SIGTRAP. */
2137 lp->status_pending_p = 0;
2138
2139 return 0;
2140 }
2141
2142 static void
2143 linux_cancel_breakpoints (void)
2144 {
2145 find_inferior (&all_lwps, cancel_breakpoints_callback, NULL);
2146 }
2147
2148 /* Select one LWP out of those that have events pending. */
2149
2150 static void
2151 select_event_lwp (struct lwp_info **orig_lp)
2152 {
2153 int num_events = 0;
2154 int random_selector;
2155 struct lwp_info *event_lp;
2156
2157 /* Give preference to any LWP that is being single-stepped. */
2158 event_lp
2159 = (struct lwp_info *) find_inferior (&all_lwps,
2160 select_singlestep_lwp_callback, NULL);
2161 if (event_lp != NULL)
2162 {
2163 if (debug_threads)
2164 fprintf (stderr,
2165 "SEL: Select single-step %s\n",
2166 target_pid_to_str (ptid_of (event_lp)));
2167 }
2168 else
2169 {
2170 /* No single-stepping LWP. Select one at random, out of those
2171 which have had SIGTRAP events. */
2172
2173 /* First see how many SIGTRAP events we have. */
2174 find_inferior (&all_lwps, count_events_callback, &num_events);
2175
2176 /* Now randomly pick a LWP out of those that have had a SIGTRAP. */
2177 random_selector = (int)
2178 ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
2179
2180 if (debug_threads && num_events > 1)
2181 fprintf (stderr,
2182 "SEL: Found %d SIGTRAP events, selecting #%d\n",
2183 num_events, random_selector);
2184
2185 event_lp = (struct lwp_info *) find_inferior (&all_lwps,
2186 select_event_lwp_callback,
2187 &random_selector);
2188 }
2189
2190 if (event_lp != NULL)
2191 {
2192 /* Switch the event LWP. */
2193 *orig_lp = event_lp;
2194 }
2195 }
2196
2197 /* Decrement the suspend count of an LWP. */
2198
2199 static int
2200 unsuspend_one_lwp (struct inferior_list_entry *entry, void *except)
2201 {
2202 struct lwp_info *lwp = (struct lwp_info *) entry;
2203
2204 /* Ignore EXCEPT. */
2205 if (lwp == except)
2206 return 0;
2207
2208 lwp->suspended--;
2209
2210 gdb_assert (lwp->suspended >= 0);
2211 return 0;
2212 }
2213
2214 /* Decrement the suspend count of all LWPs, except EXCEPT, if non
2215 NULL. */
2216
2217 static void
2218 unsuspend_all_lwps (struct lwp_info *except)
2219 {
2220 find_inferior (&all_lwps, unsuspend_one_lwp, except);
2221 }
2222
2223 static void move_out_of_jump_pad_callback (struct inferior_list_entry *entry);
2224 static int stuck_in_jump_pad_callback (struct inferior_list_entry *entry,
2225 void *data);
2226 static int lwp_running (struct inferior_list_entry *entry, void *data);
2227 static ptid_t linux_wait_1 (ptid_t ptid,
2228 struct target_waitstatus *ourstatus,
2229 int target_options);
2230
2231 /* Stabilize threads (move out of jump pads).
2232
2233 If a thread is midway collecting a fast tracepoint, we need to
2234 finish the collection and move it out of the jump pad before
2235 reporting the signal.
2236
2237 This avoids recursion while collecting (when a signal arrives
2238 midway, and the signal handler itself collects), which would trash
2239 the trace buffer. In case the user set a breakpoint in a signal
2240 handler, this avoids the backtrace showing the jump pad, etc..
2241 Most importantly, there are certain things we can't do safely if
2242 threads are stopped in a jump pad (or in its callee's). For
2243 example:
2244
2245 - starting a new trace run. A thread still collecting the
2246 previous run, could trash the trace buffer when resumed. The trace
2247 buffer control structures would have been reset but the thread had
2248 no way to tell. The thread could even midway memcpy'ing to the
2249 buffer, which would mean that when resumed, it would clobber the
2250 trace buffer that had been set for a new run.
2251
2252 - we can't rewrite/reuse the jump pads for new tracepoints
2253 safely. Say you do tstart while a thread is stopped midway while
2254 collecting. When the thread is later resumed, it finishes the
2255 collection, and returns to the jump pad, to execute the original
2256 instruction that was under the tracepoint jump at the time the
2257 older run had been started. If the jump pad had been rewritten
2258 since for something else in the new run, the thread would now
2259 execute the wrong / random instructions. */
2260
2261 static void
2262 linux_stabilize_threads (void)
2263 {
2264 struct thread_info *save_inferior;
2265 struct lwp_info *lwp_stuck;
2266
2267 lwp_stuck
2268 = (struct lwp_info *) find_inferior (&all_lwps,
2269 stuck_in_jump_pad_callback, NULL);
2270 if (lwp_stuck != NULL)
2271 {
2272 if (debug_threads)
2273 fprintf (stderr, "can't stabilize, LWP %ld is stuck in jump pad\n",
2274 lwpid_of (lwp_stuck));
2275 return;
2276 }
2277
2278 save_inferior = current_inferior;
2279
2280 stabilizing_threads = 1;
2281
2282 /* Kick 'em all. */
2283 for_each_inferior (&all_lwps, move_out_of_jump_pad_callback);
2284
2285 /* Loop until all are stopped out of the jump pads. */
2286 while (find_inferior (&all_lwps, lwp_running, NULL) != NULL)
2287 {
2288 struct target_waitstatus ourstatus;
2289 struct lwp_info *lwp;
2290 int wstat;
2291
2292 /* Note that we go through the full wait even loop. While
2293 moving threads out of jump pad, we need to be able to step
2294 over internal breakpoints and such. */
2295 linux_wait_1 (minus_one_ptid, &ourstatus, 0);
2296
2297 if (ourstatus.kind == TARGET_WAITKIND_STOPPED)
2298 {
2299 lwp = get_thread_lwp (current_inferior);
2300
2301 /* Lock it. */
2302 lwp->suspended++;
2303
2304 if (ourstatus.value.sig != GDB_SIGNAL_0
2305 || current_inferior->last_resume_kind == resume_stop)
2306 {
2307 wstat = W_STOPCODE (gdb_signal_to_host (ourstatus.value.sig));
2308 enqueue_one_deferred_signal (lwp, &wstat);
2309 }
2310 }
2311 }
2312
2313 find_inferior (&all_lwps, unsuspend_one_lwp, NULL);
2314
2315 stabilizing_threads = 0;
2316
2317 current_inferior = save_inferior;
2318
2319 if (debug_threads)
2320 {
2321 lwp_stuck
2322 = (struct lwp_info *) find_inferior (&all_lwps,
2323 stuck_in_jump_pad_callback, NULL);
2324 if (lwp_stuck != NULL)
2325 fprintf (stderr, "couldn't stabilize, LWP %ld got stuck in jump pad\n",
2326 lwpid_of (lwp_stuck));
2327 }
2328 }
2329
2330 /* Wait for process, returns status. */
2331
2332 static ptid_t
2333 linux_wait_1 (ptid_t ptid,
2334 struct target_waitstatus *ourstatus, int target_options)
2335 {
2336 int w;
2337 struct lwp_info *event_child;
2338 int options;
2339 int pid;
2340 int step_over_finished;
2341 int bp_explains_trap;
2342 int maybe_internal_trap;
2343 int report_to_gdb;
2344 int trace_event;
2345 int in_step_range;
2346
2347 /* Translate generic target options into linux options. */
2348 options = __WALL;
2349 if (target_options & TARGET_WNOHANG)
2350 options |= WNOHANG;
2351
2352 retry:
2353 bp_explains_trap = 0;
2354 trace_event = 0;
2355 in_step_range = 0;
2356 ourstatus->kind = TARGET_WAITKIND_IGNORE;
2357
2358 /* If we were only supposed to resume one thread, only wait for
2359 that thread - if it's still alive. If it died, however - which
2360 can happen if we're coming from the thread death case below -
2361 then we need to make sure we restart the other threads. We could
2362 pick a thread at random or restart all; restarting all is less
2363 arbitrary. */
2364 if (!non_stop
2365 && !ptid_equal (cont_thread, null_ptid)
2366 && !ptid_equal (cont_thread, minus_one_ptid))
2367 {
2368 struct thread_info *thread;
2369
2370 thread = (struct thread_info *) find_inferior_id (&all_threads,
2371 cont_thread);
2372
2373 /* No stepping, no signal - unless one is pending already, of course. */
2374 if (thread == NULL)
2375 {
2376 struct thread_resume resume_info;
2377 resume_info.thread = minus_one_ptid;
2378 resume_info.kind = resume_continue;
2379 resume_info.sig = 0;
2380 linux_resume (&resume_info, 1);
2381 }
2382 else
2383 ptid = cont_thread;
2384 }
2385
2386 if (ptid_equal (step_over_bkpt, null_ptid))
2387 pid = linux_wait_for_event (ptid, &w, options);
2388 else
2389 {
2390 if (debug_threads)
2391 fprintf (stderr, "step_over_bkpt set [%s], doing a blocking wait\n",
2392 target_pid_to_str (step_over_bkpt));
2393 pid = linux_wait_for_event (step_over_bkpt, &w, options & ~WNOHANG);
2394 }
2395
2396 if (pid == 0) /* only if TARGET_WNOHANG */
2397 return null_ptid;
2398
2399 event_child = get_thread_lwp (current_inferior);
2400
2401 /* If we are waiting for a particular child, and it exited,
2402 linux_wait_for_event will return its exit status. Similarly if
2403 the last child exited. If this is not the last child, however,
2404 do not report it as exited until there is a 'thread exited' response
2405 available in the remote protocol. Instead, just wait for another event.
2406 This should be safe, because if the thread crashed we will already
2407 have reported the termination signal to GDB; that should stop any
2408 in-progress stepping operations, etc.
2409
2410 Report the exit status of the last thread to exit. This matches
2411 LinuxThreads' behavior. */
2412
2413 if (last_thread_of_process_p (current_inferior))
2414 {
2415 if (WIFEXITED (w) || WIFSIGNALED (w))
2416 {
2417 if (WIFEXITED (w))
2418 {
2419 ourstatus->kind = TARGET_WAITKIND_EXITED;
2420 ourstatus->value.integer = WEXITSTATUS (w);
2421
2422 if (debug_threads)
2423 fprintf (stderr,
2424 "\nChild exited with retcode = %x \n",
2425 WEXITSTATUS (w));
2426 }
2427 else
2428 {
2429 ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
2430 ourstatus->value.sig = gdb_signal_from_host (WTERMSIG (w));
2431
2432 if (debug_threads)
2433 fprintf (stderr,
2434 "\nChild terminated with signal = %x \n",
2435 WTERMSIG (w));
2436
2437 }
2438
2439 return ptid_of (event_child);
2440 }
2441 }
2442 else
2443 {
2444 if (!WIFSTOPPED (w))
2445 goto retry;
2446 }
2447
2448 /* If this event was not handled before, and is not a SIGTRAP, we
2449 report it. SIGILL and SIGSEGV are also treated as traps in case
2450 a breakpoint is inserted at the current PC. If this target does
2451 not support internal breakpoints at all, we also report the
2452 SIGTRAP without further processing; it's of no concern to us. */
2453 maybe_internal_trap
2454 = (supports_breakpoints ()
2455 && (WSTOPSIG (w) == SIGTRAP
2456 || ((WSTOPSIG (w) == SIGILL
2457 || WSTOPSIG (w) == SIGSEGV)
2458 && (*the_low_target.breakpoint_at) (event_child->stop_pc))));
2459
2460 if (maybe_internal_trap)
2461 {
2462 /* Handle anything that requires bookkeeping before deciding to
2463 report the event or continue waiting. */
2464
2465 /* First check if we can explain the SIGTRAP with an internal
2466 breakpoint, or if we should possibly report the event to GDB.
2467 Do this before anything that may remove or insert a
2468 breakpoint. */
2469 bp_explains_trap = breakpoint_inserted_here (event_child->stop_pc);
2470
2471 /* We have a SIGTRAP, possibly a step-over dance has just
2472 finished. If so, tweak the state machine accordingly,
2473 reinsert breakpoints and delete any reinsert (software
2474 single-step) breakpoints. */
2475 step_over_finished = finish_step_over (event_child);
2476
2477 /* Now invoke the callbacks of any internal breakpoints there. */
2478 check_breakpoints (event_child->stop_pc);
2479
2480 /* Handle tracepoint data collecting. This may overflow the
2481 trace buffer, and cause a tracing stop, removing
2482 breakpoints. */
2483 trace_event = handle_tracepoints (event_child);
2484
2485 if (bp_explains_trap)
2486 {
2487 /* If we stepped or ran into an internal breakpoint, we've
2488 already handled it. So next time we resume (from this
2489 PC), we should step over it. */
2490 if (debug_threads)
2491 fprintf (stderr, "Hit a gdbserver breakpoint.\n");
2492
2493 if (breakpoint_here (event_child->stop_pc))
2494 event_child->need_step_over = 1;
2495 }
2496 }
2497 else
2498 {
2499 /* We have some other signal, possibly a step-over dance was in
2500 progress, and it should be cancelled too. */
2501 step_over_finished = finish_step_over (event_child);
2502 }
2503
2504 /* We have all the data we need. Either report the event to GDB, or
2505 resume threads and keep waiting for more. */
2506
2507 /* If we're collecting a fast tracepoint, finish the collection and
2508 move out of the jump pad before delivering a signal. See
2509 linux_stabilize_threads. */
2510
2511 if (WIFSTOPPED (w)
2512 && WSTOPSIG (w) != SIGTRAP
2513 && supports_fast_tracepoints ()
2514 && agent_loaded_p ())
2515 {
2516 if (debug_threads)
2517 fprintf (stderr,
2518 "Got signal %d for LWP %ld. Check if we need "
2519 "to defer or adjust it.\n",
2520 WSTOPSIG (w), lwpid_of (event_child));
2521
2522 /* Allow debugging the jump pad itself. */
2523 if (current_inferior->last_resume_kind != resume_step
2524 && maybe_move_out_of_jump_pad (event_child, &w))
2525 {
2526 enqueue_one_deferred_signal (event_child, &w);
2527
2528 if (debug_threads)
2529 fprintf (stderr,
2530 "Signal %d for LWP %ld deferred (in jump pad)\n",
2531 WSTOPSIG (w), lwpid_of (event_child));
2532
2533 linux_resume_one_lwp (event_child, 0, 0, NULL);
2534 goto retry;
2535 }
2536 }
2537
2538 if (event_child->collecting_fast_tracepoint)
2539 {
2540 if (debug_threads)
2541 fprintf (stderr, "\
2542 LWP %ld was trying to move out of the jump pad (%d). \
2543 Check if we're already there.\n",
2544 lwpid_of (event_child),
2545 event_child->collecting_fast_tracepoint);
2546
2547 trace_event = 1;
2548
2549 event_child->collecting_fast_tracepoint
2550 = linux_fast_tracepoint_collecting (event_child, NULL);
2551
2552 if (event_child->collecting_fast_tracepoint != 1)
2553 {
2554 /* No longer need this breakpoint. */
2555 if (event_child->exit_jump_pad_bkpt != NULL)
2556 {
2557 if (debug_threads)
2558 fprintf (stderr,
2559 "No longer need exit-jump-pad bkpt; removing it."
2560 "stopping all threads momentarily.\n");
2561
2562 /* Other running threads could hit this breakpoint.
2563 We don't handle moribund locations like GDB does,
2564 instead we always pause all threads when removing
2565 breakpoints, so that any step-over or
2566 decr_pc_after_break adjustment is always taken
2567 care of while the breakpoint is still
2568 inserted. */
2569 stop_all_lwps (1, event_child);
2570 cancel_breakpoints ();
2571
2572 delete_breakpoint (event_child->exit_jump_pad_bkpt);
2573 event_child->exit_jump_pad_bkpt = NULL;
2574
2575 unstop_all_lwps (1, event_child);
2576
2577 gdb_assert (event_child->suspended >= 0);
2578 }
2579 }
2580
2581 if (event_child->collecting_fast_tracepoint == 0)
2582 {
2583 if (debug_threads)
2584 fprintf (stderr,
2585 "fast tracepoint finished "
2586 "collecting successfully.\n");
2587
2588 /* We may have a deferred signal to report. */
2589 if (dequeue_one_deferred_signal (event_child, &w))
2590 {
2591 if (debug_threads)
2592 fprintf (stderr, "dequeued one signal.\n");
2593 }
2594 else
2595 {
2596 if (debug_threads)
2597 fprintf (stderr, "no deferred signals.\n");
2598
2599 if (stabilizing_threads)
2600 {
2601 ourstatus->kind = TARGET_WAITKIND_STOPPED;
2602 ourstatus->value.sig = GDB_SIGNAL_0;
2603 return ptid_of (event_child);
2604 }
2605 }
2606 }
2607 }
2608
2609 /* Check whether GDB would be interested in this event. */
2610
2611 /* If GDB is not interested in this signal, don't stop other
2612 threads, and don't report it to GDB. Just resume the inferior
2613 right away. We do this for threading-related signals as well as
2614 any that GDB specifically requested we ignore. But never ignore
2615 SIGSTOP if we sent it ourselves, and do not ignore signals when
2616 stepping - they may require special handling to skip the signal
2617 handler. */
2618 /* FIXME drow/2002-06-09: Get signal numbers from the inferior's
2619 thread library? */
2620 if (WIFSTOPPED (w)
2621 && current_inferior->last_resume_kind != resume_step
2622 && (
2623 #if defined (USE_THREAD_DB) && !defined (__ANDROID__)
2624 (current_process ()->private->thread_db != NULL
2625 && (WSTOPSIG (w) == __SIGRTMIN
2626 || WSTOPSIG (w) == __SIGRTMIN + 1))
2627 ||
2628 #endif
2629 (pass_signals[gdb_signal_from_host (WSTOPSIG (w))]
2630 && !(WSTOPSIG (w) == SIGSTOP
2631 && current_inferior->last_resume_kind == resume_stop))))
2632 {
2633 siginfo_t info, *info_p;
2634
2635 if (debug_threads)
2636 fprintf (stderr, "Ignored signal %d for LWP %ld.\n",
2637 WSTOPSIG (w), lwpid_of (event_child));
2638
2639 if (ptrace (PTRACE_GETSIGINFO, lwpid_of (event_child),
2640 (PTRACE_ARG3_TYPE) 0, &info) == 0)
2641 info_p = &info;
2642 else
2643 info_p = NULL;
2644 linux_resume_one_lwp (event_child, event_child->stepping,
2645 WSTOPSIG (w), info_p);
2646 goto retry;
2647 }
2648
2649 /* Note that all addresses are always "out of the step range" when
2650 there's no range to begin with. */
2651 in_step_range = lwp_in_step_range (event_child);
2652
2653 /* If GDB wanted this thread to single step, and the thread is out
2654 of the step range, we always want to report the SIGTRAP, and let
2655 GDB handle it. Watchpoints should always be reported. So should
2656 signals we can't explain. A SIGTRAP we can't explain could be a
2657 GDB breakpoint --- we may or not support Z0 breakpoints. If we
2658 do, we're be able to handle GDB breakpoints on top of internal
2659 breakpoints, by handling the internal breakpoint and still
2660 reporting the event to GDB. If we don't, we're out of luck, GDB
2661 won't see the breakpoint hit. */
2662 report_to_gdb = (!maybe_internal_trap
2663 || (current_inferior->last_resume_kind == resume_step
2664 && !in_step_range)
2665 || event_child->stopped_by_watchpoint
2666 || (!step_over_finished && !in_step_range
2667 && !bp_explains_trap && !trace_event)
2668 || (gdb_breakpoint_here (event_child->stop_pc)
2669 && gdb_condition_true_at_breakpoint (event_child->stop_pc)
2670 && gdb_no_commands_at_breakpoint (event_child->stop_pc)));
2671
2672 run_breakpoint_commands (event_child->stop_pc);
2673
2674 /* We found no reason GDB would want us to stop. We either hit one
2675 of our own breakpoints, or finished an internal step GDB
2676 shouldn't know about. */
2677 if (!report_to_gdb)
2678 {
2679 if (debug_threads)
2680 {
2681 if (bp_explains_trap)
2682 fprintf (stderr, "Hit a gdbserver breakpoint.\n");
2683 if (step_over_finished)
2684 fprintf (stderr, "Step-over finished.\n");
2685 if (trace_event)
2686 fprintf (stderr, "Tracepoint event.\n");
2687 if (lwp_in_step_range (event_child))
2688 fprintf (stderr, "Range stepping pc 0x%s [0x%s, 0x%s).\n",
2689 paddress (event_child->stop_pc),
2690 paddress (event_child->step_range_start),
2691 paddress (event_child->step_range_end));
2692 }
2693
2694 /* We're not reporting this breakpoint to GDB, so apply the
2695 decr_pc_after_break adjustment to the inferior's regcache
2696 ourselves. */
2697
2698 if (the_low_target.set_pc != NULL)
2699 {
2700 struct regcache *regcache
2701 = get_thread_regcache (get_lwp_thread (event_child), 1);
2702 (*the_low_target.set_pc) (regcache, event_child->stop_pc);
2703 }
2704
2705 /* We may have finished stepping over a breakpoint. If so,
2706 we've stopped and suspended all LWPs momentarily except the
2707 stepping one. This is where we resume them all again. We're
2708 going to keep waiting, so use proceed, which handles stepping
2709 over the next breakpoint. */
2710 if (debug_threads)
2711 fprintf (stderr, "proceeding all threads.\n");
2712
2713 if (step_over_finished)
2714 unsuspend_all_lwps (event_child);
2715
2716 proceed_all_lwps ();
2717 goto retry;
2718 }
2719
2720 if (debug_threads)
2721 {
2722 if (current_inferior->last_resume_kind == resume_step)
2723 {
2724 if (event_child->step_range_start == event_child->step_range_end)
2725 fprintf (stderr, "GDB wanted to single-step, reporting event.\n");
2726 else if (!lwp_in_step_range (event_child))
2727 fprintf (stderr, "Out of step range, reporting event.\n");
2728 }
2729 if (event_child->stopped_by_watchpoint)
2730 fprintf (stderr, "Stopped by watchpoint.\n");
2731 if (gdb_breakpoint_here (event_child->stop_pc))
2732 fprintf (stderr, "Stopped by GDB breakpoint.\n");
2733 if (debug_threads)
2734 fprintf (stderr, "Hit a non-gdbserver trap event.\n");
2735 }
2736
2737 /* Alright, we're going to report a stop. */
2738
2739 if (!non_stop && !stabilizing_threads)
2740 {
2741 /* In all-stop, stop all threads. */
2742 stop_all_lwps (0, NULL);
2743
2744 /* If we're not waiting for a specific LWP, choose an event LWP
2745 from among those that have had events. Giving equal priority
2746 to all LWPs that have had events helps prevent
2747 starvation. */
2748 if (ptid_equal (ptid, minus_one_ptid))
2749 {
2750 event_child->status_pending_p = 1;
2751 event_child->status_pending = w;
2752
2753 select_event_lwp (&event_child);
2754
2755 event_child->status_pending_p = 0;
2756 w = event_child->status_pending;
2757 }
2758
2759 /* Now that we've selected our final event LWP, cancel any
2760 breakpoints in other LWPs that have hit a GDB breakpoint.
2761 See the comment in cancel_breakpoints_callback to find out
2762 why. */
2763 find_inferior (&all_lwps, cancel_breakpoints_callback, event_child);
2764
2765 /* If we were going a step-over, all other threads but the stepping one
2766 had been paused in start_step_over, with their suspend counts
2767 incremented. We don't want to do a full unstop/unpause, because we're
2768 in all-stop mode (so we want threads stopped), but we still need to
2769 unsuspend the other threads, to decrement their `suspended' count
2770 back. */
2771 if (step_over_finished)
2772 unsuspend_all_lwps (event_child);
2773
2774 /* Stabilize threads (move out of jump pads). */
2775 stabilize_threads ();
2776 }
2777 else
2778 {
2779 /* If we just finished a step-over, then all threads had been
2780 momentarily paused. In all-stop, that's fine, we want
2781 threads stopped by now anyway. In non-stop, we need to
2782 re-resume threads that GDB wanted to be running. */
2783 if (step_over_finished)
2784 unstop_all_lwps (1, event_child);
2785 }
2786
2787 ourstatus->kind = TARGET_WAITKIND_STOPPED;
2788
2789 if (current_inferior->last_resume_kind == resume_stop
2790 && WSTOPSIG (w) == SIGSTOP)
2791 {
2792 /* A thread that has been requested to stop by GDB with vCont;t,
2793 and it stopped cleanly, so report as SIG0. The use of
2794 SIGSTOP is an implementation detail. */
2795 ourstatus->value.sig = GDB_SIGNAL_0;
2796 }
2797 else if (current_inferior->last_resume_kind == resume_stop
2798 && WSTOPSIG (w) != SIGSTOP)
2799 {
2800 /* A thread that has been requested to stop by GDB with vCont;t,
2801 but, it stopped for other reasons. */
2802 ourstatus->value.sig = gdb_signal_from_host (WSTOPSIG (w));
2803 }
2804 else
2805 {
2806 ourstatus->value.sig = gdb_signal_from_host (WSTOPSIG (w));
2807 }
2808
2809 gdb_assert (ptid_equal (step_over_bkpt, null_ptid));
2810
2811 if (debug_threads)
2812 fprintf (stderr, "linux_wait ret = %s, %d, %d\n",
2813 target_pid_to_str (ptid_of (event_child)),
2814 ourstatus->kind,
2815 ourstatus->value.sig);
2816
2817 return ptid_of (event_child);
2818 }
2819
2820 /* Get rid of any pending event in the pipe. */
2821 static void
2822 async_file_flush (void)
2823 {
2824 int ret;
2825 char buf;
2826
2827 do
2828 ret = read (linux_event_pipe[0], &buf, 1);
2829 while (ret >= 0 || (ret == -1 && errno == EINTR));
2830 }
2831
2832 /* Put something in the pipe, so the event loop wakes up. */
2833 static void
2834 async_file_mark (void)
2835 {
2836 int ret;
2837
2838 async_file_flush ();
2839
2840 do
2841 ret = write (linux_event_pipe[1], "+", 1);
2842 while (ret == 0 || (ret == -1 && errno == EINTR));
2843
2844 /* Ignore EAGAIN. If the pipe is full, the event loop will already
2845 be awakened anyway. */
2846 }
2847
2848 static ptid_t
2849 linux_wait (ptid_t ptid,
2850 struct target_waitstatus *ourstatus, int target_options)
2851 {
2852 ptid_t event_ptid;
2853
2854 if (debug_threads)
2855 fprintf (stderr, "linux_wait: [%s]\n", target_pid_to_str (ptid));
2856
2857 /* Flush the async file first. */
2858 if (target_is_async_p ())
2859 async_file_flush ();
2860
2861 event_ptid = linux_wait_1 (ptid, ourstatus, target_options);
2862
2863 /* If at least one stop was reported, there may be more. A single
2864 SIGCHLD can signal more than one child stop. */
2865 if (target_is_async_p ()
2866 && (target_options & TARGET_WNOHANG) != 0
2867 && !ptid_equal (event_ptid, null_ptid))
2868 async_file_mark ();
2869
2870 return event_ptid;
2871 }
2872
2873 /* Send a signal to an LWP. */
2874
2875 static int
2876 kill_lwp (unsigned long lwpid, int signo)
2877 {
2878 /* Use tkill, if possible, in case we are using nptl threads. If tkill
2879 fails, then we are not using nptl threads and we should be using kill. */
2880
2881 #ifdef __NR_tkill
2882 {
2883 static int tkill_failed;
2884
2885 if (!tkill_failed)
2886 {
2887 int ret;
2888
2889 errno = 0;
2890 ret = syscall (__NR_tkill, lwpid, signo);
2891 if (errno != ENOSYS)
2892 return ret;
2893 tkill_failed = 1;
2894 }
2895 }
2896 #endif
2897
2898 return kill (lwpid, signo);
2899 }
2900
2901 void
2902 linux_stop_lwp (struct lwp_info *lwp)
2903 {
2904 send_sigstop (lwp);
2905 }
2906
2907 static void
2908 send_sigstop (struct lwp_info *lwp)
2909 {
2910 int pid;
2911
2912 pid = lwpid_of (lwp);
2913
2914 /* If we already have a pending stop signal for this process, don't
2915 send another. */
2916 if (lwp->stop_expected)
2917 {
2918 if (debug_threads)
2919 fprintf (stderr, "Have pending sigstop for lwp %d\n", pid);
2920
2921 return;
2922 }
2923
2924 if (debug_threads)
2925 fprintf (stderr, "Sending sigstop to lwp %d\n", pid);
2926
2927 lwp->stop_expected = 1;
2928 kill_lwp (pid, SIGSTOP);
2929 }
2930
2931 static int
2932 send_sigstop_callback (struct inferior_list_entry *entry, void *except)
2933 {
2934 struct lwp_info *lwp = (struct lwp_info *) entry;
2935
2936 /* Ignore EXCEPT. */
2937 if (lwp == except)
2938 return 0;
2939
2940 if (lwp->stopped)
2941 return 0;
2942
2943 send_sigstop (lwp);
2944 return 0;
2945 }
2946
2947 /* Increment the suspend count of an LWP, and stop it, if not stopped
2948 yet. */
2949 static int
2950 suspend_and_send_sigstop_callback (struct inferior_list_entry *entry,
2951 void *except)
2952 {
2953 struct lwp_info *lwp = (struct lwp_info *) entry;
2954
2955 /* Ignore EXCEPT. */
2956 if (lwp == except)
2957 return 0;
2958
2959 lwp->suspended++;
2960
2961 return send_sigstop_callback (entry, except);
2962 }
2963
2964 static void
2965 mark_lwp_dead (struct lwp_info *lwp, int wstat)
2966 {
2967 /* It's dead, really. */
2968 lwp->dead = 1;
2969
2970 /* Store the exit status for later. */
2971 lwp->status_pending_p = 1;
2972 lwp->status_pending = wstat;
2973
2974 /* Prevent trying to stop it. */
2975 lwp->stopped = 1;
2976
2977 /* No further stops are expected from a dead lwp. */
2978 lwp->stop_expected = 0;
2979 }
2980
2981 static void
2982 wait_for_sigstop (struct inferior_list_entry *entry)
2983 {
2984 struct lwp_info *lwp = (struct lwp_info *) entry;
2985 struct thread_info *saved_inferior;
2986 int wstat;
2987 ptid_t saved_tid;
2988 ptid_t ptid;
2989 int pid;
2990
2991 if (lwp->stopped)
2992 {
2993 if (debug_threads)
2994 fprintf (stderr, "wait_for_sigstop: LWP %ld already stopped\n",
2995 lwpid_of (lwp));
2996 return;
2997 }
2998
2999 saved_inferior = current_inferior;
3000 if (saved_inferior != NULL)
3001 saved_tid = ((struct inferior_list_entry *) saved_inferior)->id;
3002 else
3003 saved_tid = null_ptid; /* avoid bogus unused warning */
3004
3005 ptid = lwp->head.id;
3006
3007 if (debug_threads)
3008 fprintf (stderr, "wait_for_sigstop: pulling one event\n");
3009
3010 pid = linux_wait_for_event (ptid, &wstat, __WALL);
3011
3012 /* If we stopped with a non-SIGSTOP signal, save it for later
3013 and record the pending SIGSTOP. If the process exited, just
3014 return. */
3015 if (WIFSTOPPED (wstat))
3016 {
3017 if (debug_threads)
3018 fprintf (stderr, "LWP %ld stopped with signal %d\n",
3019 lwpid_of (lwp), WSTOPSIG (wstat));
3020
3021 if (WSTOPSIG (wstat) != SIGSTOP)
3022 {
3023 if (debug_threads)
3024 fprintf (stderr, "LWP %ld stopped with non-sigstop status %06x\n",
3025 lwpid_of (lwp), wstat);
3026
3027 lwp->status_pending_p = 1;
3028 lwp->status_pending = wstat;
3029 }
3030 }
3031 else
3032 {
3033 if (debug_threads)
3034 fprintf (stderr, "Process %d exited while stopping LWPs\n", pid);
3035
3036 lwp = find_lwp_pid (pid_to_ptid (pid));
3037 if (lwp)
3038 {
3039 /* Leave this status pending for the next time we're able to
3040 report it. In the mean time, we'll report this lwp as
3041 dead to GDB, so GDB doesn't try to read registers and
3042 memory from it. This can only happen if this was the
3043 last thread of the process; otherwise, PID is removed
3044 from the thread tables before linux_wait_for_event
3045 returns. */
3046 mark_lwp_dead (lwp, wstat);
3047 }
3048 }
3049
3050 if (saved_inferior == NULL || linux_thread_alive (saved_tid))
3051 current_inferior = saved_inferior;
3052 else
3053 {
3054 if (debug_threads)
3055 fprintf (stderr, "Previously current thread died.\n");
3056
3057 if (non_stop)
3058 {
3059 /* We can't change the current inferior behind GDB's back,
3060 otherwise, a subsequent command may apply to the wrong
3061 process. */
3062 current_inferior = NULL;
3063 }
3064 else
3065 {
3066 /* Set a valid thread as current. */
3067 set_desired_inferior (0);
3068 }
3069 }
3070 }
3071
3072 /* Returns true if LWP ENTRY is stopped in a jump pad, and we can't
3073 move it out, because we need to report the stop event to GDB. For
3074 example, if the user puts a breakpoint in the jump pad, it's
3075 because she wants to debug it. */
3076
3077 static int
3078 stuck_in_jump_pad_callback (struct inferior_list_entry *entry, void *data)
3079 {
3080 struct lwp_info *lwp = (struct lwp_info *) entry;
3081 struct thread_info *thread = get_lwp_thread (lwp);
3082
3083 gdb_assert (lwp->suspended == 0);
3084 gdb_assert (lwp->stopped);
3085
3086 /* Allow debugging the jump pad, gdb_collect, etc.. */
3087 return (supports_fast_tracepoints ()
3088 && agent_loaded_p ()
3089 && (gdb_breakpoint_here (lwp->stop_pc)
3090 || lwp->stopped_by_watchpoint
3091 || thread->last_resume_kind == resume_step)
3092 && linux_fast_tracepoint_collecting (lwp, NULL));
3093 }
3094
3095 static void
3096 move_out_of_jump_pad_callback (struct inferior_list_entry *entry)
3097 {
3098 struct lwp_info *lwp = (struct lwp_info *) entry;
3099 struct thread_info *thread = get_lwp_thread (lwp);
3100 int *wstat;
3101
3102 gdb_assert (lwp->suspended == 0);
3103 gdb_assert (lwp->stopped);
3104
3105 wstat = lwp->status_pending_p ? &lwp->status_pending : NULL;
3106
3107 /* Allow debugging the jump pad, gdb_collect, etc. */
3108 if (!gdb_breakpoint_here (lwp->stop_pc)
3109 && !lwp->stopped_by_watchpoint
3110 && thread->last_resume_kind != resume_step
3111 && maybe_move_out_of_jump_pad (lwp, wstat))
3112 {
3113 if (debug_threads)
3114 fprintf (stderr,
3115 "LWP %ld needs stabilizing (in jump pad)\n",
3116 lwpid_of (lwp));
3117
3118 if (wstat)
3119 {
3120 lwp->status_pending_p = 0;
3121 enqueue_one_deferred_signal (lwp, wstat);
3122
3123 if (debug_threads)
3124 fprintf (stderr,
3125 "Signal %d for LWP %ld deferred "
3126 "(in jump pad)\n",
3127 WSTOPSIG (*wstat), lwpid_of (lwp));
3128 }
3129
3130 linux_resume_one_lwp (lwp, 0, 0, NULL);
3131 }
3132 else
3133 lwp->suspended++;
3134 }
3135
3136 static int
3137 lwp_running (struct inferior_list_entry *entry, void *data)
3138 {
3139 struct lwp_info *lwp = (struct lwp_info *) entry;
3140
3141 if (lwp->dead)
3142 return 0;
3143 if (lwp->stopped)
3144 return 0;
3145 return 1;
3146 }
3147
3148 /* Stop all lwps that aren't stopped yet, except EXCEPT, if not NULL.
3149 If SUSPEND, then also increase the suspend count of every LWP,
3150 except EXCEPT. */
3151
3152 static void
3153 stop_all_lwps (int suspend, struct lwp_info *except)
3154 {
3155 /* Should not be called recursively. */
3156 gdb_assert (stopping_threads == NOT_STOPPING_THREADS);
3157
3158 stopping_threads = (suspend
3159 ? STOPPING_AND_SUSPENDING_THREADS
3160 : STOPPING_THREADS);
3161
3162 if (suspend)
3163 find_inferior (&all_lwps, suspend_and_send_sigstop_callback, except);
3164 else
3165 find_inferior (&all_lwps, send_sigstop_callback, except);
3166 for_each_inferior (&all_lwps, wait_for_sigstop);
3167 stopping_threads = NOT_STOPPING_THREADS;
3168 }
3169
3170 /* Resume execution of the inferior process.
3171 If STEP is nonzero, single-step it.
3172 If SIGNAL is nonzero, give it that signal. */
3173
3174 static void
3175 linux_resume_one_lwp (struct lwp_info *lwp,
3176 int step, int signal, siginfo_t *info)
3177 {
3178 struct thread_info *saved_inferior;
3179 int fast_tp_collecting;
3180
3181 if (lwp->stopped == 0)
3182 return;
3183
3184 fast_tp_collecting = lwp->collecting_fast_tracepoint;
3185
3186 gdb_assert (!stabilizing_threads || fast_tp_collecting);
3187
3188 /* Cancel actions that rely on GDB not changing the PC (e.g., the
3189 user used the "jump" command, or "set $pc = foo"). */
3190 if (lwp->stop_pc != get_pc (lwp))
3191 {
3192 /* Collecting 'while-stepping' actions doesn't make sense
3193 anymore. */
3194 release_while_stepping_state_list (get_lwp_thread (lwp));
3195 }
3196
3197 /* If we have pending signals or status, and a new signal, enqueue the
3198 signal. Also enqueue the signal if we are waiting to reinsert a
3199 breakpoint; it will be picked up again below. */
3200 if (signal != 0
3201 && (lwp->status_pending_p
3202 || lwp->pending_signals != NULL
3203 || lwp->bp_reinsert != 0
3204 || fast_tp_collecting))
3205 {
3206 struct pending_signals *p_sig;
3207 p_sig = xmalloc (sizeof (*p_sig));
3208 p_sig->prev = lwp->pending_signals;
3209 p_sig->signal = signal;
3210 if (info == NULL)
3211 memset (&p_sig->info, 0, sizeof (siginfo_t));
3212 else
3213 memcpy (&p_sig->info, info, sizeof (siginfo_t));
3214 lwp->pending_signals = p_sig;
3215 }
3216
3217 if (lwp->status_pending_p)
3218 {
3219 if (debug_threads)
3220 fprintf (stderr, "Not resuming lwp %ld (%s, signal %d, stop %s);"
3221 " has pending status\n",
3222 lwpid_of (lwp), step ? "step" : "continue", signal,
3223 lwp->stop_expected ? "expected" : "not expected");
3224 return;
3225 }
3226
3227 saved_inferior = current_inferior;
3228 current_inferior = get_lwp_thread (lwp);
3229
3230 if (debug_threads)
3231 fprintf (stderr, "Resuming lwp %ld (%s, signal %d, stop %s)\n",
3232 lwpid_of (lwp), step ? "step" : "continue", signal,
3233 lwp->stop_expected ? "expected" : "not expected");
3234
3235 /* This bit needs some thinking about. If we get a signal that
3236 we must report while a single-step reinsert is still pending,
3237 we often end up resuming the thread. It might be better to
3238 (ew) allow a stack of pending events; then we could be sure that
3239 the reinsert happened right away and not lose any signals.
3240
3241 Making this stack would also shrink the window in which breakpoints are
3242 uninserted (see comment in linux_wait_for_lwp) but not enough for
3243 complete correctness, so it won't solve that problem. It may be
3244 worthwhile just to solve this one, however. */
3245 if (lwp->bp_reinsert != 0)
3246 {
3247 if (debug_threads)
3248 fprintf (stderr, " pending reinsert at 0x%s\n",
3249 paddress (lwp->bp_reinsert));
3250
3251 if (can_hardware_single_step ())
3252 {
3253 if (fast_tp_collecting == 0)
3254 {
3255 if (step == 0)
3256 fprintf (stderr, "BAD - reinserting but not stepping.\n");
3257 if (lwp->suspended)
3258 fprintf (stderr, "BAD - reinserting and suspended(%d).\n",
3259 lwp->suspended);
3260 }
3261
3262 step = 1;
3263 }
3264
3265 /* Postpone any pending signal. It was enqueued above. */
3266 signal = 0;
3267 }
3268
3269 if (fast_tp_collecting == 1)
3270 {
3271 if (debug_threads)
3272 fprintf (stderr, "\
3273 lwp %ld wants to get out of fast tracepoint jump pad (exit-jump-pad-bkpt)\n",
3274 lwpid_of (lwp));
3275
3276 /* Postpone any pending signal. It was enqueued above. */
3277 signal = 0;
3278 }
3279 else if (fast_tp_collecting == 2)
3280 {
3281 if (debug_threads)
3282 fprintf (stderr, "\
3283 lwp %ld wants to get out of fast tracepoint jump pad single-stepping\n",
3284 lwpid_of (lwp));
3285
3286 if (can_hardware_single_step ())
3287 step = 1;
3288 else
3289 fatal ("moving out of jump pad single-stepping"
3290 " not implemented on this target");
3291
3292 /* Postpone any pending signal. It was enqueued above. */
3293 signal = 0;
3294 }
3295
3296 /* If we have while-stepping actions in this thread set it stepping.
3297 If we have a signal to deliver, it may or may not be set to
3298 SIG_IGN, we don't know. Assume so, and allow collecting
3299 while-stepping into a signal handler. A possible smart thing to
3300 do would be to set an internal breakpoint at the signal return
3301 address, continue, and carry on catching this while-stepping
3302 action only when that breakpoint is hit. A future
3303 enhancement. */
3304 if (get_lwp_thread (lwp)->while_stepping != NULL
3305 && can_hardware_single_step ())
3306 {
3307 if (debug_threads)
3308 fprintf (stderr,
3309 "lwp %ld has a while-stepping action -> forcing step.\n",
3310 lwpid_of (lwp));
3311 step = 1;
3312 }
3313
3314 if (debug_threads && the_low_target.get_pc != NULL)
3315 {
3316 struct regcache *regcache = get_thread_regcache (current_inferior, 1);
3317 CORE_ADDR pc = (*the_low_target.get_pc) (regcache);
3318 fprintf (stderr, " resuming from pc 0x%lx\n", (long) pc);
3319 }
3320
3321 /* If we have pending signals, consume one unless we are trying to
3322 reinsert a breakpoint or we're trying to finish a fast tracepoint
3323 collect. */
3324 if (lwp->pending_signals != NULL
3325 && lwp->bp_reinsert == 0
3326 && fast_tp_collecting == 0)
3327 {
3328 struct pending_signals **p_sig;
3329
3330 p_sig = &lwp->pending_signals;
3331 while ((*p_sig)->prev != NULL)
3332 p_sig = &(*p_sig)->prev;
3333
3334 signal = (*p_sig)->signal;
3335 if ((*p_sig)->info.si_signo != 0)
3336 ptrace (PTRACE_SETSIGINFO, lwpid_of (lwp), (PTRACE_ARG3_TYPE) 0,
3337 &(*p_sig)->info);
3338
3339 free (*p_sig);
3340 *p_sig = NULL;
3341 }
3342
3343 if (the_low_target.prepare_to_resume != NULL)
3344 the_low_target.prepare_to_resume (lwp);
3345
3346 regcache_invalidate_thread (get_lwp_thread (lwp));
3347 errno = 0;
3348 lwp->stopped = 0;
3349 lwp->stopped_by_watchpoint = 0;
3350 lwp->stepping = step;
3351 ptrace (step ? PTRACE_SINGLESTEP : PTRACE_CONT, lwpid_of (lwp),
3352 (PTRACE_ARG3_TYPE) 0,
3353 /* Coerce to a uintptr_t first to avoid potential gcc warning
3354 of coercing an 8 byte integer to a 4 byte pointer. */
3355 (PTRACE_ARG4_TYPE) (uintptr_t) signal);
3356
3357 current_inferior = saved_inferior;
3358 if (errno)
3359 {
3360 /* ESRCH from ptrace either means that the thread was already
3361 running (an error) or that it is gone (a race condition). If
3362 it's gone, we will get a notification the next time we wait,
3363 so we can ignore the error. We could differentiate these
3364 two, but it's tricky without waiting; the thread still exists
3365 as a zombie, so sending it signal 0 would succeed. So just
3366 ignore ESRCH. */
3367 if (errno == ESRCH)
3368 return;
3369
3370 perror_with_name ("ptrace");
3371 }
3372 }
3373
3374 struct thread_resume_array
3375 {
3376 struct thread_resume *resume;
3377 size_t n;
3378 };
3379
3380 /* This function is called once per thread. We look up the thread
3381 in RESUME_PTR, and mark the thread with a pointer to the appropriate
3382 resume request.
3383
3384 This algorithm is O(threads * resume elements), but resume elements
3385 is small (and will remain small at least until GDB supports thread
3386 suspension). */
3387 static int
3388 linux_set_resume_request (struct inferior_list_entry *entry, void *arg)
3389 {
3390 struct lwp_info *lwp;
3391 struct thread_info *thread;
3392 int ndx;
3393 struct thread_resume_array *r;
3394
3395 thread = (struct thread_info *) entry;
3396 lwp = get_thread_lwp (thread);
3397 r = arg;
3398
3399 for (ndx = 0; ndx < r->n; ndx++)
3400 {
3401 ptid_t ptid = r->resume[ndx].thread;
3402 if (ptid_equal (ptid, minus_one_ptid)
3403 || ptid_equal (ptid, entry->id)
3404 /* Handle both 'pPID' and 'pPID.-1' as meaning 'all threads
3405 of PID'. */
3406 || (ptid_get_pid (ptid) == pid_of (lwp)
3407 && (ptid_is_pid (ptid)
3408 || ptid_get_lwp (ptid) == -1)))
3409 {
3410 if (r->resume[ndx].kind == resume_stop
3411 && thread->last_resume_kind == resume_stop)
3412 {
3413 if (debug_threads)
3414 fprintf (stderr, "already %s LWP %ld at GDB's request\n",
3415 thread->last_status.kind == TARGET_WAITKIND_STOPPED
3416 ? "stopped"
3417 : "stopping",
3418 lwpid_of (lwp));
3419
3420 continue;
3421 }
3422
3423 lwp->resume = &r->resume[ndx];
3424 thread->last_resume_kind = lwp->resume->kind;
3425
3426 lwp->step_range_start = lwp->resume->step_range_start;
3427 lwp->step_range_end = lwp->resume->step_range_end;
3428
3429 /* If we had a deferred signal to report, dequeue one now.
3430 This can happen if LWP gets more than one signal while
3431 trying to get out of a jump pad. */
3432 if (lwp->stopped
3433 && !lwp->status_pending_p
3434 && dequeue_one_deferred_signal (lwp, &lwp->status_pending))
3435 {
3436 lwp->status_pending_p = 1;
3437
3438 if (debug_threads)
3439 fprintf (stderr,
3440 "Dequeueing deferred signal %d for LWP %ld, "
3441 "leaving status pending.\n",
3442 WSTOPSIG (lwp->status_pending), lwpid_of (lwp));
3443 }
3444
3445 return 0;
3446 }
3447 }
3448
3449 /* No resume action for this thread. */
3450 lwp->resume = NULL;
3451
3452 return 0;
3453 }
3454
3455
3456 /* Set *FLAG_P if this lwp has an interesting status pending. */
3457 static int
3458 resume_status_pending_p (struct inferior_list_entry *entry, void *flag_p)
3459 {
3460 struct lwp_info *lwp = (struct lwp_info *) entry;
3461
3462 /* LWPs which will not be resumed are not interesting, because
3463 we might not wait for them next time through linux_wait. */
3464 if (lwp->resume == NULL)
3465 return 0;
3466
3467 if (lwp->status_pending_p)
3468 * (int *) flag_p = 1;
3469
3470 return 0;
3471 }
3472
3473 /* Return 1 if this lwp that GDB wants running is stopped at an
3474 internal breakpoint that we need to step over. It assumes that any
3475 required STOP_PC adjustment has already been propagated to the
3476 inferior's regcache. */
3477
3478 static int
3479 need_step_over_p (struct inferior_list_entry *entry, void *dummy)
3480 {
3481 struct lwp_info *lwp = (struct lwp_info *) entry;
3482 struct thread_info *thread;
3483 struct thread_info *saved_inferior;
3484 CORE_ADDR pc;
3485
3486 /* LWPs which will not be resumed are not interesting, because we
3487 might not wait for them next time through linux_wait. */
3488
3489 if (!lwp->stopped)
3490 {
3491 if (debug_threads)
3492 fprintf (stderr,
3493 "Need step over [LWP %ld]? Ignoring, not stopped\n",
3494 lwpid_of (lwp));
3495 return 0;
3496 }
3497
3498 thread = get_lwp_thread (lwp);
3499
3500 if (thread->last_resume_kind == resume_stop)
3501 {
3502 if (debug_threads)
3503 fprintf (stderr,
3504 "Need step over [LWP %ld]? Ignoring, should remain stopped\n",
3505 lwpid_of (lwp));
3506 return 0;
3507 }
3508
3509 gdb_assert (lwp->suspended >= 0);
3510
3511 if (lwp->suspended)
3512 {
3513 if (debug_threads)
3514 fprintf (stderr,
3515 "Need step over [LWP %ld]? Ignoring, suspended\n",
3516 lwpid_of (lwp));
3517 return 0;
3518 }
3519
3520 if (!lwp->need_step_over)
3521 {
3522 if (debug_threads)
3523 fprintf (stderr,
3524 "Need step over [LWP %ld]? No\n", lwpid_of (lwp));
3525 }
3526
3527 if (lwp->status_pending_p)
3528 {
3529 if (debug_threads)
3530 fprintf (stderr,
3531 "Need step over [LWP %ld]? Ignoring, has pending status.\n",
3532 lwpid_of (lwp));
3533 return 0;
3534 }
3535
3536 /* Note: PC, not STOP_PC. Either GDB has adjusted the PC already,
3537 or we have. */
3538 pc = get_pc (lwp);
3539
3540 /* If the PC has changed since we stopped, then don't do anything,
3541 and let the breakpoint/tracepoint be hit. This happens if, for
3542 instance, GDB handled the decr_pc_after_break subtraction itself,
3543 GDB is OOL stepping this thread, or the user has issued a "jump"
3544 command, or poked thread's registers herself. */
3545 if (pc != lwp->stop_pc)
3546 {
3547 if (debug_threads)
3548 fprintf (stderr,
3549 "Need step over [LWP %ld]? Cancelling, PC was changed. "
3550 "Old stop_pc was 0x%s, PC is now 0x%s\n",
3551 lwpid_of (lwp), paddress (lwp->stop_pc), paddress (pc));
3552
3553 lwp->need_step_over = 0;
3554 return 0;
3555 }
3556
3557 saved_inferior = current_inferior;
3558 current_inferior = thread;
3559
3560 /* We can only step over breakpoints we know about. */
3561 if (breakpoint_here (pc) || fast_tracepoint_jump_here (pc))
3562 {
3563 /* Don't step over a breakpoint that GDB expects to hit
3564 though. If the condition is being evaluated on the target's side
3565 and it evaluate to false, step over this breakpoint as well. */
3566 if (gdb_breakpoint_here (pc)
3567 && gdb_condition_true_at_breakpoint (pc)
3568 && gdb_no_commands_at_breakpoint (pc))
3569 {
3570 if (debug_threads)
3571 fprintf (stderr,
3572 "Need step over [LWP %ld]? yes, but found"
3573 " GDB breakpoint at 0x%s; skipping step over\n",
3574 lwpid_of (lwp), paddress (pc));
3575
3576 current_inferior = saved_inferior;
3577 return 0;
3578 }
3579 else
3580 {
3581 if (debug_threads)
3582 fprintf (stderr,
3583 "Need step over [LWP %ld]? yes, "
3584 "found breakpoint at 0x%s\n",
3585 lwpid_of (lwp), paddress (pc));
3586
3587 /* We've found an lwp that needs stepping over --- return 1 so
3588 that find_inferior stops looking. */
3589 current_inferior = saved_inferior;
3590
3591 /* If the step over is cancelled, this is set again. */
3592 lwp->need_step_over = 0;
3593 return 1;
3594 }
3595 }
3596
3597 current_inferior = saved_inferior;
3598
3599 if (debug_threads)
3600 fprintf (stderr,
3601 "Need step over [LWP %ld]? No, no breakpoint found at 0x%s\n",
3602 lwpid_of (lwp), paddress (pc));
3603
3604 return 0;
3605 }
3606
3607 /* Start a step-over operation on LWP. When LWP stopped at a
3608 breakpoint, to make progress, we need to remove the breakpoint out
3609 of the way. If we let other threads run while we do that, they may
3610 pass by the breakpoint location and miss hitting it. To avoid
3611 that, a step-over momentarily stops all threads while LWP is
3612 single-stepped while the breakpoint is temporarily uninserted from
3613 the inferior. When the single-step finishes, we reinsert the
3614 breakpoint, and let all threads that are supposed to be running,
3615 run again.
3616
3617 On targets that don't support hardware single-step, we don't
3618 currently support full software single-stepping. Instead, we only
3619 support stepping over the thread event breakpoint, by asking the
3620 low target where to place a reinsert breakpoint. Since this
3621 routine assumes the breakpoint being stepped over is a thread event
3622 breakpoint, it usually assumes the return address of the current
3623 function is a good enough place to set the reinsert breakpoint. */
3624
3625 static int
3626 start_step_over (struct lwp_info *lwp)
3627 {
3628 struct thread_info *saved_inferior;
3629 CORE_ADDR pc;
3630 int step;
3631
3632 if (debug_threads)
3633 fprintf (stderr,
3634 "Starting step-over on LWP %ld. Stopping all threads\n",
3635 lwpid_of (lwp));
3636
3637 stop_all_lwps (1, lwp);
3638 gdb_assert (lwp->suspended == 0);
3639
3640 if (debug_threads)
3641 fprintf (stderr, "Done stopping all threads for step-over.\n");
3642
3643 /* Note, we should always reach here with an already adjusted PC,
3644 either by GDB (if we're resuming due to GDB's request), or by our
3645 caller, if we just finished handling an internal breakpoint GDB
3646 shouldn't care about. */
3647 pc = get_pc (lwp);
3648
3649 saved_inferior = current_inferior;
3650 current_inferior = get_lwp_thread (lwp);
3651
3652 lwp->bp_reinsert = pc;
3653 uninsert_breakpoints_at (pc);
3654 uninsert_fast_tracepoint_jumps_at (pc);
3655
3656 if (can_hardware_single_step ())
3657 {
3658 step = 1;
3659 }
3660 else
3661 {
3662 CORE_ADDR raddr = (*the_low_target.breakpoint_reinsert_addr) ();
3663 set_reinsert_breakpoint (raddr);
3664 step = 0;
3665 }
3666
3667 current_inferior = saved_inferior;
3668
3669 linux_resume_one_lwp (lwp, step, 0, NULL);
3670
3671 /* Require next event from this LWP. */
3672 step_over_bkpt = lwp->head.id;
3673 return 1;
3674 }
3675
3676 /* Finish a step-over. Reinsert the breakpoint we had uninserted in
3677 start_step_over, if still there, and delete any reinsert
3678 breakpoints we've set, on non hardware single-step targets. */
3679
3680 static int
3681 finish_step_over (struct lwp_info *lwp)
3682 {
3683 if (lwp->bp_reinsert != 0)
3684 {
3685 if (debug_threads)
3686 fprintf (stderr, "Finished step over.\n");
3687
3688 /* Reinsert any breakpoint at LWP->BP_REINSERT. Note that there
3689 may be no breakpoint to reinsert there by now. */
3690 reinsert_breakpoints_at (lwp->bp_reinsert);
3691 reinsert_fast_tracepoint_jumps_at (lwp->bp_reinsert);
3692
3693 lwp->bp_reinsert = 0;
3694
3695 /* Delete any software-single-step reinsert breakpoints. No
3696 longer needed. We don't have to worry about other threads
3697 hitting this trap, and later not being able to explain it,
3698 because we were stepping over a breakpoint, and we hold all
3699 threads but LWP stopped while doing that. */
3700 if (!can_hardware_single_step ())
3701 delete_reinsert_breakpoints ();
3702
3703 step_over_bkpt = null_ptid;
3704 return 1;
3705 }
3706 else
3707 return 0;
3708 }
3709
3710 /* This function is called once per thread. We check the thread's resume
3711 request, which will tell us whether to resume, step, or leave the thread
3712 stopped; and what signal, if any, it should be sent.
3713
3714 For threads which we aren't explicitly told otherwise, we preserve
3715 the stepping flag; this is used for stepping over gdbserver-placed
3716 breakpoints.
3717
3718 If pending_flags was set in any thread, we queue any needed
3719 signals, since we won't actually resume. We already have a pending
3720 event to report, so we don't need to preserve any step requests;
3721 they should be re-issued if necessary. */
3722
3723 static int
3724 linux_resume_one_thread (struct inferior_list_entry *entry, void *arg)
3725 {
3726 struct lwp_info *lwp;
3727 struct thread_info *thread;
3728 int step;
3729 int leave_all_stopped = * (int *) arg;
3730 int leave_pending;
3731
3732 thread = (struct thread_info *) entry;
3733 lwp = get_thread_lwp (thread);
3734
3735 if (lwp->resume == NULL)
3736 return 0;
3737
3738 if (lwp->resume->kind == resume_stop)
3739 {
3740 if (debug_threads)
3741 fprintf (stderr, "resume_stop request for LWP %ld\n", lwpid_of (lwp));
3742
3743 if (!lwp->stopped)
3744 {
3745 if (debug_threads)
3746 fprintf (stderr, "stopping LWP %ld\n", lwpid_of (lwp));
3747
3748 /* Stop the thread, and wait for the event asynchronously,
3749 through the event loop. */
3750 send_sigstop (lwp);
3751 }
3752 else
3753 {
3754 if (debug_threads)
3755 fprintf (stderr, "already stopped LWP %ld\n",
3756 lwpid_of (lwp));
3757
3758 /* The LWP may have been stopped in an internal event that
3759 was not meant to be notified back to GDB (e.g., gdbserver
3760 breakpoint), so we should be reporting a stop event in
3761 this case too. */
3762
3763 /* If the thread already has a pending SIGSTOP, this is a
3764 no-op. Otherwise, something later will presumably resume
3765 the thread and this will cause it to cancel any pending
3766 operation, due to last_resume_kind == resume_stop. If
3767 the thread already has a pending status to report, we
3768 will still report it the next time we wait - see
3769 status_pending_p_callback. */
3770
3771 /* If we already have a pending signal to report, then
3772 there's no need to queue a SIGSTOP, as this means we're
3773 midway through moving the LWP out of the jumppad, and we
3774 will report the pending signal as soon as that is
3775 finished. */
3776 if (lwp->pending_signals_to_report == NULL)
3777 send_sigstop (lwp);
3778 }
3779
3780 /* For stop requests, we're done. */
3781 lwp->resume = NULL;
3782 thread->last_status.kind = TARGET_WAITKIND_IGNORE;
3783 return 0;
3784 }
3785
3786 /* If this thread which is about to be resumed has a pending status,
3787 then don't resume any threads - we can just report the pending
3788 status. Make sure to queue any signals that would otherwise be
3789 sent. In all-stop mode, we do this decision based on if *any*
3790 thread has a pending status. If there's a thread that needs the
3791 step-over-breakpoint dance, then don't resume any other thread
3792 but that particular one. */
3793 leave_pending = (lwp->status_pending_p || leave_all_stopped);
3794
3795 if (!leave_pending)
3796 {
3797 if (debug_threads)
3798 fprintf (stderr, "resuming LWP %ld\n", lwpid_of (lwp));
3799
3800 step = (lwp->resume->kind == resume_step);
3801 linux_resume_one_lwp (lwp, step, lwp->resume->sig, NULL);
3802 }
3803 else
3804 {
3805 if (debug_threads)
3806 fprintf (stderr, "leaving LWP %ld stopped\n", lwpid_of (lwp));
3807
3808 /* If we have a new signal, enqueue the signal. */
3809 if (lwp->resume->sig != 0)
3810 {
3811 struct pending_signals *p_sig;
3812 p_sig = xmalloc (sizeof (*p_sig));
3813 p_sig->prev = lwp->pending_signals;
3814 p_sig->signal = lwp->resume->sig;
3815 memset (&p_sig->info, 0, sizeof (siginfo_t));
3816
3817 /* If this is the same signal we were previously stopped by,
3818 make sure to queue its siginfo. We can ignore the return
3819 value of ptrace; if it fails, we'll skip
3820 PTRACE_SETSIGINFO. */
3821 if (WIFSTOPPED (lwp->last_status)
3822 && WSTOPSIG (lwp->last_status) == lwp->resume->sig)
3823 ptrace (PTRACE_GETSIGINFO, lwpid_of (lwp), (PTRACE_ARG3_TYPE) 0,
3824 &p_sig->info);
3825
3826 lwp->pending_signals = p_sig;
3827 }
3828 }
3829
3830 thread->last_status.kind = TARGET_WAITKIND_IGNORE;
3831 lwp->resume = NULL;
3832 return 0;
3833 }
3834
3835 static void
3836 linux_resume (struct thread_resume *resume_info, size_t n)
3837 {
3838 struct thread_resume_array array = { resume_info, n };
3839 struct lwp_info *need_step_over = NULL;
3840 int any_pending;
3841 int leave_all_stopped;
3842
3843 find_inferior (&all_threads, linux_set_resume_request, &array);
3844
3845 /* If there is a thread which would otherwise be resumed, which has
3846 a pending status, then don't resume any threads - we can just
3847 report the pending status. Make sure to queue any signals that
3848 would otherwise be sent. In non-stop mode, we'll apply this
3849 logic to each thread individually. We consume all pending events
3850 before considering to start a step-over (in all-stop). */
3851 any_pending = 0;
3852 if (!non_stop)
3853 find_inferior (&all_lwps, resume_status_pending_p, &any_pending);
3854
3855 /* If there is a thread which would otherwise be resumed, which is
3856 stopped at a breakpoint that needs stepping over, then don't
3857 resume any threads - have it step over the breakpoint with all
3858 other threads stopped, then resume all threads again. Make sure
3859 to queue any signals that would otherwise be delivered or
3860 queued. */
3861 if (!any_pending && supports_breakpoints ())
3862 need_step_over
3863 = (struct lwp_info *) find_inferior (&all_lwps,
3864 need_step_over_p, NULL);
3865
3866 leave_all_stopped = (need_step_over != NULL || any_pending);
3867
3868 if (debug_threads)
3869 {
3870 if (need_step_over != NULL)
3871 fprintf (stderr, "Not resuming all, need step over\n");
3872 else if (any_pending)
3873 fprintf (stderr,
3874 "Not resuming, all-stop and found "
3875 "an LWP with pending status\n");
3876 else
3877 fprintf (stderr, "Resuming, no pending status or step over needed\n");
3878 }
3879
3880 /* Even if we're leaving threads stopped, queue all signals we'd
3881 otherwise deliver. */
3882 find_inferior (&all_threads, linux_resume_one_thread, &leave_all_stopped);
3883
3884 if (need_step_over)
3885 start_step_over (need_step_over);
3886 }
3887
3888 /* This function is called once per thread. We check the thread's
3889 last resume request, which will tell us whether to resume, step, or
3890 leave the thread stopped. Any signal the client requested to be
3891 delivered has already been enqueued at this point.
3892
3893 If any thread that GDB wants running is stopped at an internal
3894 breakpoint that needs stepping over, we start a step-over operation
3895 on that particular thread, and leave all others stopped. */
3896
3897 static int
3898 proceed_one_lwp (struct inferior_list_entry *entry, void *except)
3899 {
3900 struct lwp_info *lwp = (struct lwp_info *) entry;
3901 struct thread_info *thread;
3902 int step;
3903
3904 if (lwp == except)
3905 return 0;
3906
3907 if (debug_threads)
3908 fprintf (stderr,
3909 "proceed_one_lwp: lwp %ld\n", lwpid_of (lwp));
3910
3911 if (!lwp->stopped)
3912 {
3913 if (debug_threads)
3914 fprintf (stderr, " LWP %ld already running\n", lwpid_of (lwp));
3915 return 0;
3916 }
3917
3918 thread = get_lwp_thread (lwp);
3919
3920 if (thread->last_resume_kind == resume_stop
3921 && thread->last_status.kind != TARGET_WAITKIND_IGNORE)
3922 {
3923 if (debug_threads)
3924 fprintf (stderr, " client wants LWP to remain %ld stopped\n",
3925 lwpid_of (lwp));
3926 return 0;
3927 }
3928
3929 if (lwp->status_pending_p)
3930 {
3931 if (debug_threads)
3932 fprintf (stderr, " LWP %ld has pending status, leaving stopped\n",
3933 lwpid_of (lwp));
3934 return 0;
3935 }
3936
3937 gdb_assert (lwp->suspended >= 0);
3938
3939 if (lwp->suspended)
3940 {
3941 if (debug_threads)
3942 fprintf (stderr, " LWP %ld is suspended\n", lwpid_of (lwp));
3943 return 0;
3944 }
3945
3946 if (thread->last_resume_kind == resume_stop
3947 && lwp->pending_signals_to_report == NULL
3948 && lwp->collecting_fast_tracepoint == 0)
3949 {
3950 /* We haven't reported this LWP as stopped yet (otherwise, the
3951 last_status.kind check above would catch it, and we wouldn't
3952 reach here. This LWP may have been momentarily paused by a
3953 stop_all_lwps call while handling for example, another LWP's
3954 step-over. In that case, the pending expected SIGSTOP signal
3955 that was queued at vCont;t handling time will have already
3956 been consumed by wait_for_sigstop, and so we need to requeue
3957 another one here. Note that if the LWP already has a SIGSTOP
3958 pending, this is a no-op. */
3959
3960 if (debug_threads)
3961 fprintf (stderr,
3962 "Client wants LWP %ld to stop. "
3963 "Making sure it has a SIGSTOP pending\n",
3964 lwpid_of (lwp));
3965
3966 send_sigstop (lwp);
3967 }
3968
3969 step = thread->last_resume_kind == resume_step;
3970 linux_resume_one_lwp (lwp, step, 0, NULL);
3971 return 0;
3972 }
3973
3974 static int
3975 unsuspend_and_proceed_one_lwp (struct inferior_list_entry *entry, void *except)
3976 {
3977 struct lwp_info *lwp = (struct lwp_info *) entry;
3978
3979 if (lwp == except)
3980 return 0;
3981
3982 lwp->suspended--;
3983 gdb_assert (lwp->suspended >= 0);
3984
3985 return proceed_one_lwp (entry, except);
3986 }
3987
3988 /* When we finish a step-over, set threads running again. If there's
3989 another thread that may need a step-over, now's the time to start
3990 it. Eventually, we'll move all threads past their breakpoints. */
3991
3992 static void
3993 proceed_all_lwps (void)
3994 {
3995 struct lwp_info *need_step_over;
3996
3997 /* If there is a thread which would otherwise be resumed, which is
3998 stopped at a breakpoint that needs stepping over, then don't
3999 resume any threads - have it step over the breakpoint with all
4000 other threads stopped, then resume all threads again. */
4001
4002 if (supports_breakpoints ())
4003 {
4004 need_step_over
4005 = (struct lwp_info *) find_inferior (&all_lwps,
4006 need_step_over_p, NULL);
4007
4008 if (need_step_over != NULL)
4009 {
4010 if (debug_threads)
4011 fprintf (stderr, "proceed_all_lwps: found "
4012 "thread %ld needing a step-over\n",
4013 lwpid_of (need_step_over));
4014
4015 start_step_over (need_step_over);
4016 return;
4017 }
4018 }
4019
4020 if (debug_threads)
4021 fprintf (stderr, "Proceeding, no step-over needed\n");
4022
4023 find_inferior (&all_lwps, proceed_one_lwp, NULL);
4024 }
4025
4026 /* Stopped LWPs that the client wanted to be running, that don't have
4027 pending statuses, are set to run again, except for EXCEPT, if not
4028 NULL. This undoes a stop_all_lwps call. */
4029
4030 static void
4031 unstop_all_lwps (int unsuspend, struct lwp_info *except)
4032 {
4033 if (debug_threads)
4034 {
4035 if (except)
4036 fprintf (stderr,
4037 "unstopping all lwps, except=(LWP %ld)\n", lwpid_of (except));
4038 else
4039 fprintf (stderr,
4040 "unstopping all lwps\n");
4041 }
4042
4043 if (unsuspend)
4044 find_inferior (&all_lwps, unsuspend_and_proceed_one_lwp, except);
4045 else
4046 find_inferior (&all_lwps, proceed_one_lwp, except);
4047 }
4048
4049
4050 #ifdef HAVE_LINUX_REGSETS
4051
4052 #define use_linux_regsets 1
4053
4054 /* Returns true if REGSET has been disabled. */
4055
4056 static int
4057 regset_disabled (struct regsets_info *info, struct regset_info *regset)
4058 {
4059 return (info->disabled_regsets != NULL
4060 && info->disabled_regsets[regset - info->regsets]);
4061 }
4062
4063 /* Disable REGSET. */
4064
4065 static void
4066 disable_regset (struct regsets_info *info, struct regset_info *regset)
4067 {
4068 int dr_offset;
4069
4070 dr_offset = regset - info->regsets;
4071 if (info->disabled_regsets == NULL)
4072 info->disabled_regsets = xcalloc (1, info->num_regsets);
4073 info->disabled_regsets[dr_offset] = 1;
4074 }
4075
4076 static int
4077 regsets_fetch_inferior_registers (struct regsets_info *regsets_info,
4078 struct regcache *regcache)
4079 {
4080 struct regset_info *regset;
4081 int saw_general_regs = 0;
4082 int pid;
4083 struct iovec iov;
4084
4085 regset = regsets_info->regsets;
4086
4087 pid = lwpid_of (get_thread_lwp (current_inferior));
4088 while (regset->size >= 0)
4089 {
4090 void *buf, *data;
4091 int nt_type, res;
4092
4093 if (regset->size == 0 || regset_disabled (regsets_info, regset))
4094 {
4095 regset ++;
4096 continue;
4097 }
4098
4099 buf = xmalloc (regset->size);
4100
4101 nt_type = regset->nt_type;
4102 if (nt_type)
4103 {
4104 iov.iov_base = buf;
4105 iov.iov_len = regset->size;
4106 data = (void *) &iov;
4107 }
4108 else
4109 data = buf;
4110
4111 #ifndef __sparc__
4112 res = ptrace (regset->get_request, pid,
4113 (PTRACE_ARG3_TYPE) (long) nt_type, data);
4114 #else
4115 res = ptrace (regset->get_request, pid, data, nt_type);
4116 #endif
4117 if (res < 0)
4118 {
4119 if (errno == EIO)
4120 {
4121 /* If we get EIO on a regset, do not try it again for
4122 this process mode. */
4123 disable_regset (regsets_info, regset);
4124 free (buf);
4125 continue;
4126 }
4127 else
4128 {
4129 char s[256];
4130 sprintf (s, "ptrace(regsets_fetch_inferior_registers) PID=%d",
4131 pid);
4132 perror (s);
4133 }
4134 }
4135 else if (regset->type == GENERAL_REGS)
4136 saw_general_regs = 1;
4137 regset->store_function (regcache, buf);
4138 regset ++;
4139 free (buf);
4140 }
4141 if (saw_general_regs)
4142 return 0;
4143 else
4144 return 1;
4145 }
4146
4147 static int
4148 regsets_store_inferior_registers (struct regsets_info *regsets_info,
4149 struct regcache *regcache)
4150 {
4151 struct regset_info *regset;
4152 int saw_general_regs = 0;
4153 int pid;
4154 struct iovec iov;
4155
4156 regset = regsets_info->regsets;
4157
4158 pid = lwpid_of (get_thread_lwp (current_inferior));
4159 while (regset->size >= 0)
4160 {
4161 void *buf, *data;
4162 int nt_type, res;
4163
4164 if (regset->size == 0 || regset_disabled (regsets_info, regset))
4165 {
4166 regset ++;
4167 continue;
4168 }
4169
4170 buf = xmalloc (regset->size);
4171
4172 /* First fill the buffer with the current register set contents,
4173 in case there are any items in the kernel's regset that are
4174 not in gdbserver's regcache. */
4175
4176 nt_type = regset->nt_type;
4177 if (nt_type)
4178 {
4179 iov.iov_base = buf;
4180 iov.iov_len = regset->size;
4181 data = (void *) &iov;
4182 }
4183 else
4184 data = buf;
4185
4186 #ifndef __sparc__
4187 res = ptrace (regset->get_request, pid,
4188 (PTRACE_ARG3_TYPE) (long) nt_type, data);
4189 #else
4190 res = ptrace (regset->get_request, pid, data, nt_type);
4191 #endif
4192
4193 if (res == 0)
4194 {
4195 /* Then overlay our cached registers on that. */
4196 regset->fill_function (regcache, buf);
4197
4198 /* Only now do we write the register set. */
4199 #ifndef __sparc__
4200 res = ptrace (regset->set_request, pid,
4201 (PTRACE_ARG3_TYPE) (long) nt_type, data);
4202 #else
4203 res = ptrace (regset->set_request, pid, data, nt_type);
4204 #endif
4205 }
4206
4207 if (res < 0)
4208 {
4209 if (errno == EIO)
4210 {
4211 /* If we get EIO on a regset, do not try it again for
4212 this process mode. */
4213 disable_regset (regsets_info, regset);
4214 free (buf);
4215 continue;
4216 }
4217 else if (errno == ESRCH)
4218 {
4219 /* At this point, ESRCH should mean the process is
4220 already gone, in which case we simply ignore attempts
4221 to change its registers. See also the related
4222 comment in linux_resume_one_lwp. */
4223 free (buf);
4224 return 0;
4225 }
4226 else
4227 {
4228 perror ("Warning: ptrace(regsets_store_inferior_registers)");
4229 }
4230 }
4231 else if (regset->type == GENERAL_REGS)
4232 saw_general_regs = 1;
4233 regset ++;
4234 free (buf);
4235 }
4236 if (saw_general_regs)
4237 return 0;
4238 else
4239 return 1;
4240 }
4241
4242 #else /* !HAVE_LINUX_REGSETS */
4243
4244 #define use_linux_regsets 0
4245 #define regsets_fetch_inferior_registers(regsets_info, regcache) 1
4246 #define regsets_store_inferior_registers(regsets_info, regcache) 1
4247
4248 #endif
4249
4250 /* Return 1 if register REGNO is supported by one of the regset ptrace
4251 calls or 0 if it has to be transferred individually. */
4252
4253 static int
4254 linux_register_in_regsets (const struct regs_info *regs_info, int regno)
4255 {
4256 unsigned char mask = 1 << (regno % 8);
4257 size_t index = regno / 8;
4258
4259 return (use_linux_regsets
4260 && (regs_info->regset_bitmap == NULL
4261 || (regs_info->regset_bitmap[index] & mask) != 0));
4262 }
4263
4264 #ifdef HAVE_LINUX_USRREGS
4265
4266 int
4267 register_addr (const struct usrregs_info *usrregs, int regnum)
4268 {
4269 int addr;
4270
4271 if (regnum < 0 || regnum >= usrregs->num_regs)
4272 error ("Invalid register number %d.", regnum);
4273
4274 addr = usrregs->regmap[regnum];
4275
4276 return addr;
4277 }
4278
4279 /* Fetch one register. */
4280 static void
4281 fetch_register (const struct usrregs_info *usrregs,
4282 struct regcache *regcache, int regno)
4283 {
4284 CORE_ADDR regaddr;
4285 int i, size;
4286 char *buf;
4287 int pid;
4288
4289 if (regno >= usrregs->num_regs)
4290 return;
4291 if ((*the_low_target.cannot_fetch_register) (regno))
4292 return;
4293
4294 regaddr = register_addr (usrregs, regno);
4295 if (regaddr == -1)
4296 return;
4297
4298 size = ((register_size (regcache->tdesc, regno)
4299 + sizeof (PTRACE_XFER_TYPE) - 1)
4300 & -sizeof (PTRACE_XFER_TYPE));
4301 buf = alloca (size);
4302
4303 pid = lwpid_of (get_thread_lwp (current_inferior));
4304 for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
4305 {
4306 errno = 0;
4307 *(PTRACE_XFER_TYPE *) (buf + i) =
4308 ptrace (PTRACE_PEEKUSER, pid,
4309 /* Coerce to a uintptr_t first to avoid potential gcc warning
4310 of coercing an 8 byte integer to a 4 byte pointer. */
4311 (PTRACE_ARG3_TYPE) (uintptr_t) regaddr, (PTRACE_ARG4_TYPE) 0);
4312 regaddr += sizeof (PTRACE_XFER_TYPE);
4313 if (errno != 0)
4314 error ("reading register %d: %s", regno, strerror (errno));
4315 }
4316
4317 if (the_low_target.supply_ptrace_register)
4318 the_low_target.supply_ptrace_register (regcache, regno, buf);
4319 else
4320 supply_register (regcache, regno, buf);
4321 }
4322
4323 /* Store one register. */
4324 static void
4325 store_register (const struct usrregs_info *usrregs,
4326 struct regcache *regcache, int regno)
4327 {
4328 CORE_ADDR regaddr;
4329 int i, size;
4330 char *buf;
4331 int pid;
4332
4333 if (regno >= usrregs->num_regs)
4334 return;
4335 if ((*the_low_target.cannot_store_register) (regno))
4336 return;
4337
4338 regaddr = register_addr (usrregs, regno);
4339 if (regaddr == -1)
4340 return;
4341
4342 size = ((register_size (regcache->tdesc, regno)
4343 + sizeof (PTRACE_XFER_TYPE) - 1)
4344 & -sizeof (PTRACE_XFER_TYPE));
4345 buf = alloca (size);
4346 memset (buf, 0, size);
4347
4348 if (the_low_target.collect_ptrace_register)
4349 the_low_target.collect_ptrace_register (regcache, regno, buf);
4350 else
4351 collect_register (regcache, regno, buf);
4352
4353 pid = lwpid_of (get_thread_lwp (current_inferior));
4354 for (i = 0; i < size; i += sizeof (PTRACE_XFER_TYPE))
4355 {
4356 errno = 0;
4357 ptrace (PTRACE_POKEUSER, pid,
4358 /* Coerce to a uintptr_t first to avoid potential gcc warning
4359 about coercing an 8 byte integer to a 4 byte pointer. */
4360 (PTRACE_ARG3_TYPE) (uintptr_t) regaddr,
4361 (PTRACE_ARG4_TYPE) *(PTRACE_XFER_TYPE *) (buf + i));
4362 if (errno != 0)
4363 {
4364 /* At this point, ESRCH should mean the process is
4365 already gone, in which case we simply ignore attempts
4366 to change its registers. See also the related
4367 comment in linux_resume_one_lwp. */
4368 if (errno == ESRCH)
4369 return;
4370
4371 if ((*the_low_target.cannot_store_register) (regno) == 0)
4372 error ("writing register %d: %s", regno, strerror (errno));
4373 }
4374 regaddr += sizeof (PTRACE_XFER_TYPE);
4375 }
4376 }
4377
4378 /* Fetch all registers, or just one, from the child process.
4379 If REGNO is -1, do this for all registers, skipping any that are
4380 assumed to have been retrieved by regsets_fetch_inferior_registers,
4381 unless ALL is non-zero.
4382 Otherwise, REGNO specifies which register (so we can save time). */
4383 static void
4384 usr_fetch_inferior_registers (const struct regs_info *regs_info,
4385 struct regcache *regcache, int regno, int all)
4386 {
4387 struct usrregs_info *usr = regs_info->usrregs;
4388
4389 if (regno == -1)
4390 {
4391 for (regno = 0; regno < usr->num_regs; regno++)
4392 if (all || !linux_register_in_regsets (regs_info, regno))
4393 fetch_register (usr, regcache, regno);
4394 }
4395 else
4396 fetch_register (usr, regcache, regno);
4397 }
4398
4399 /* Store our register values back into the inferior.
4400 If REGNO is -1, do this for all registers, skipping any that are
4401 assumed to have been saved by regsets_store_inferior_registers,
4402 unless ALL is non-zero.
4403 Otherwise, REGNO specifies which register (so we can save time). */
4404 static void
4405 usr_store_inferior_registers (const struct regs_info *regs_info,
4406 struct regcache *regcache, int regno, int all)
4407 {
4408 struct usrregs_info *usr = regs_info->usrregs;
4409
4410 if (regno == -1)
4411 {
4412 for (regno = 0; regno < usr->num_regs; regno++)
4413 if (all || !linux_register_in_regsets (regs_info, regno))
4414 store_register (usr, regcache, regno);
4415 }
4416 else
4417 store_register (usr, regcache, regno);
4418 }
4419
4420 #else /* !HAVE_LINUX_USRREGS */
4421
4422 #define usr_fetch_inferior_registers(regs_info, regcache, regno, all) do {} while (0)
4423 #define usr_store_inferior_registers(regs_info, regcache, regno, all) do {} while (0)
4424
4425 #endif
4426
4427
4428 void
4429 linux_fetch_registers (struct regcache *regcache, int regno)
4430 {
4431 int use_regsets;
4432 int all = 0;
4433 const struct regs_info *regs_info = (*the_low_target.regs_info) ();
4434
4435 if (regno == -1)
4436 {
4437 if (the_low_target.fetch_register != NULL
4438 && regs_info->usrregs != NULL)
4439 for (regno = 0; regno < regs_info->usrregs->num_regs; regno++)
4440 (*the_low_target.fetch_register) (regcache, regno);
4441
4442 all = regsets_fetch_inferior_registers (regs_info->regsets_info, regcache);
4443 if (regs_info->usrregs != NULL)
4444 usr_fetch_inferior_registers (regs_info, regcache, -1, all);
4445 }
4446 else
4447 {
4448 if (the_low_target.fetch_register != NULL
4449 && (*the_low_target.fetch_register) (regcache, regno))
4450 return;
4451
4452 use_regsets = linux_register_in_regsets (regs_info, regno);
4453 if (use_regsets)
4454 all = regsets_fetch_inferior_registers (regs_info->regsets_info,
4455 regcache);
4456 if ((!use_regsets || all) && regs_info->usrregs != NULL)
4457 usr_fetch_inferior_registers (regs_info, regcache, regno, 1);
4458 }
4459 }
4460
4461 void
4462 linux_store_registers (struct regcache *regcache, int regno)
4463 {
4464 int use_regsets;
4465 int all = 0;
4466 const struct regs_info *regs_info = (*the_low_target.regs_info) ();
4467
4468 if (regno == -1)
4469 {
4470 all = regsets_store_inferior_registers (regs_info->regsets_info,
4471 regcache);
4472 if (regs_info->usrregs != NULL)
4473 usr_store_inferior_registers (regs_info, regcache, regno, all);
4474 }
4475 else
4476 {
4477 use_regsets = linux_register_in_regsets (regs_info, regno);
4478 if (use_regsets)
4479 all = regsets_store_inferior_registers (regs_info->regsets_info,
4480 regcache);
4481 if ((!use_regsets || all) && regs_info->usrregs != NULL)
4482 usr_store_inferior_registers (regs_info, regcache, regno, 1);
4483 }
4484 }
4485
4486
4487 /* Copy LEN bytes from inferior's memory starting at MEMADDR
4488 to debugger memory starting at MYADDR. */
4489
4490 static int
4491 linux_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
4492 {
4493 int pid = lwpid_of (get_thread_lwp (current_inferior));
4494 register PTRACE_XFER_TYPE *buffer;
4495 register CORE_ADDR addr;
4496 register int count;
4497 char filename[64];
4498 register int i;
4499 int ret;
4500 int fd;
4501
4502 /* Try using /proc. Don't bother for one word. */
4503 if (len >= 3 * sizeof (long))
4504 {
4505 int bytes;
4506
4507 /* We could keep this file open and cache it - possibly one per
4508 thread. That requires some juggling, but is even faster. */
4509 sprintf (filename, "/proc/%d/mem", pid);
4510 fd = open (filename, O_RDONLY | O_LARGEFILE);
4511 if (fd == -1)
4512 goto no_proc;
4513
4514 /* If pread64 is available, use it. It's faster if the kernel
4515 supports it (only one syscall), and it's 64-bit safe even on
4516 32-bit platforms (for instance, SPARC debugging a SPARC64
4517 application). */
4518 #ifdef HAVE_PREAD64
4519 bytes = pread64 (fd, myaddr, len, memaddr);
4520 #else
4521 bytes = -1;
4522 if (lseek (fd, memaddr, SEEK_SET) != -1)
4523 bytes = read (fd, myaddr, len);
4524 #endif
4525
4526 close (fd);
4527 if (bytes == len)
4528 return 0;
4529
4530 /* Some data was read, we'll try to get the rest with ptrace. */
4531 if (bytes > 0)
4532 {
4533 memaddr += bytes;
4534 myaddr += bytes;
4535 len -= bytes;
4536 }
4537 }
4538
4539 no_proc:
4540 /* Round starting address down to longword boundary. */
4541 addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
4542 /* Round ending address up; get number of longwords that makes. */
4543 count = ((((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
4544 / sizeof (PTRACE_XFER_TYPE));
4545 /* Allocate buffer of that many longwords. */
4546 buffer = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
4547
4548 /* Read all the longwords */
4549 errno = 0;
4550 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
4551 {
4552 /* Coerce the 3rd arg to a uintptr_t first to avoid potential gcc warning
4553 about coercing an 8 byte integer to a 4 byte pointer. */
4554 buffer[i] = ptrace (PTRACE_PEEKTEXT, pid,
4555 (PTRACE_ARG3_TYPE) (uintptr_t) addr,
4556 (PTRACE_ARG4_TYPE) 0);
4557 if (errno)
4558 break;
4559 }
4560 ret = errno;
4561
4562 /* Copy appropriate bytes out of the buffer. */
4563 if (i > 0)
4564 {
4565 i *= sizeof (PTRACE_XFER_TYPE);
4566 i -= memaddr & (sizeof (PTRACE_XFER_TYPE) - 1);
4567 memcpy (myaddr,
4568 (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)),
4569 i < len ? i : len);
4570 }
4571
4572 return ret;
4573 }
4574
4575 /* Copy LEN bytes of data from debugger memory at MYADDR to inferior's
4576 memory at MEMADDR. On failure (cannot write to the inferior)
4577 returns the value of errno. Always succeeds if LEN is zero. */
4578
4579 static int
4580 linux_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
4581 {
4582 register int i;
4583 /* Round starting address down to longword boundary. */
4584 register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
4585 /* Round ending address up; get number of longwords that makes. */
4586 register int count
4587 = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
4588 / sizeof (PTRACE_XFER_TYPE);
4589
4590 /* Allocate buffer of that many longwords. */
4591 register PTRACE_XFER_TYPE *buffer = (PTRACE_XFER_TYPE *)
4592 alloca (count * sizeof (PTRACE_XFER_TYPE));
4593
4594 int pid = lwpid_of (get_thread_lwp (current_inferior));
4595
4596 if (len == 0)
4597 {
4598 /* Zero length write always succeeds. */
4599 return 0;
4600 }
4601
4602 if (debug_threads)
4603 {
4604 /* Dump up to four bytes. */
4605 unsigned int val = * (unsigned int *) myaddr;
4606 if (len == 1)
4607 val = val & 0xff;
4608 else if (len == 2)
4609 val = val & 0xffff;
4610 else if (len == 3)
4611 val = val & 0xffffff;
4612 fprintf (stderr, "Writing %0*x to 0x%08lx\n", 2 * ((len < 4) ? len : 4),
4613 val, (long)memaddr);
4614 }
4615
4616 /* Fill start and end extra bytes of buffer with existing memory data. */
4617
4618 errno = 0;
4619 /* Coerce the 3rd arg to a uintptr_t first to avoid potential gcc warning
4620 about coercing an 8 byte integer to a 4 byte pointer. */
4621 buffer[0] = ptrace (PTRACE_PEEKTEXT, pid,
4622 (PTRACE_ARG3_TYPE) (uintptr_t) addr,
4623 (PTRACE_ARG4_TYPE) 0);
4624 if (errno)
4625 return errno;
4626
4627 if (count > 1)
4628 {
4629 errno = 0;
4630 buffer[count - 1]
4631 = ptrace (PTRACE_PEEKTEXT, pid,
4632 /* Coerce to a uintptr_t first to avoid potential gcc warning
4633 about coercing an 8 byte integer to a 4 byte pointer. */
4634 (PTRACE_ARG3_TYPE) (uintptr_t) (addr + (count - 1)
4635 * sizeof (PTRACE_XFER_TYPE)),
4636 (PTRACE_ARG4_TYPE) 0);
4637 if (errno)
4638 return errno;
4639 }
4640
4641 /* Copy data to be written over corresponding part of buffer. */
4642
4643 memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)),
4644 myaddr, len);
4645
4646 /* Write the entire buffer. */
4647
4648 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE))
4649 {
4650 errno = 0;
4651 ptrace (PTRACE_POKETEXT, pid,
4652 /* Coerce to a uintptr_t first to avoid potential gcc warning
4653 about coercing an 8 byte integer to a 4 byte pointer. */
4654 (PTRACE_ARG3_TYPE) (uintptr_t) addr,
4655 (PTRACE_ARG4_TYPE) buffer[i]);
4656 if (errno)
4657 return errno;
4658 }
4659
4660 return 0;
4661 }
4662
4663 /* Non-zero if the kernel supports PTRACE_O_TRACEFORK. */
4664 static int linux_supports_tracefork_flag;
4665
4666 static void
4667 linux_enable_event_reporting (int pid)
4668 {
4669 if (!linux_supports_tracefork_flag)
4670 return;
4671
4672 ptrace (PTRACE_SETOPTIONS, pid, (PTRACE_ARG3_TYPE) 0,
4673 (PTRACE_ARG4_TYPE) PTRACE_O_TRACECLONE);
4674 }
4675
4676 /* Helper functions for linux_test_for_tracefork, called via clone (). */
4677
4678 static int
4679 linux_tracefork_grandchild (void *arg)
4680 {
4681 _exit (0);
4682 }
4683
4684 #define STACK_SIZE 4096
4685
4686 static int
4687 linux_tracefork_child (void *arg)
4688 {
4689 ptrace (PTRACE_TRACEME, 0, (PTRACE_ARG3_TYPE) 0, (PTRACE_ARG4_TYPE) 0);
4690 kill (getpid (), SIGSTOP);
4691
4692 #if !(defined(__UCLIBC__) && defined(HAS_NOMMU))
4693
4694 if (fork () == 0)
4695 linux_tracefork_grandchild (NULL);
4696
4697 #else /* defined(__UCLIBC__) && defined(HAS_NOMMU) */
4698
4699 #ifdef __ia64__
4700 __clone2 (linux_tracefork_grandchild, arg, STACK_SIZE,
4701 CLONE_VM | SIGCHLD, NULL);
4702 #else
4703 clone (linux_tracefork_grandchild, (char *) arg + STACK_SIZE,
4704 CLONE_VM | SIGCHLD, NULL);
4705 #endif
4706
4707 #endif /* defined(__UCLIBC__) && defined(HAS_NOMMU) */
4708
4709 _exit (0);
4710 }
4711
4712 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events. Make
4713 sure that we can enable the option, and that it had the desired
4714 effect. */
4715
4716 static void
4717 linux_test_for_tracefork (void)
4718 {
4719 int child_pid, ret, status;
4720 long second_pid;
4721 #if defined(__UCLIBC__) && defined(HAS_NOMMU)
4722 char *stack = xmalloc (STACK_SIZE * 4);
4723 #endif /* defined(__UCLIBC__) && defined(HAS_NOMMU) */
4724
4725 linux_supports_tracefork_flag = 0;
4726
4727 #if !(defined(__UCLIBC__) && defined(HAS_NOMMU))
4728
4729 child_pid = fork ();
4730 if (child_pid == 0)
4731 linux_tracefork_child (NULL);
4732
4733 #else /* defined(__UCLIBC__) && defined(HAS_NOMMU) */
4734
4735 /* Use CLONE_VM instead of fork, to support uClinux (no MMU). */
4736 #ifdef __ia64__
4737 child_pid = __clone2 (linux_tracefork_child, stack, STACK_SIZE,
4738 CLONE_VM | SIGCHLD, stack + STACK_SIZE * 2);
4739 #else /* !__ia64__ */
4740 child_pid = clone (linux_tracefork_child, stack + STACK_SIZE,
4741 CLONE_VM | SIGCHLD, stack + STACK_SIZE * 2);
4742 #endif /* !__ia64__ */
4743
4744 #endif /* defined(__UCLIBC__) && defined(HAS_NOMMU) */
4745
4746 if (child_pid == -1)
4747 perror_with_name ("clone");
4748
4749 ret = my_waitpid (child_pid, &status, 0);
4750 if (ret == -1)
4751 perror_with_name ("waitpid");
4752 else if (ret != child_pid)
4753 error ("linux_test_for_tracefork: waitpid: unexpected result %d.", ret);
4754 if (! WIFSTOPPED (status))
4755 error ("linux_test_for_tracefork: waitpid: unexpected status %d.", status);
4756
4757 ret = ptrace (PTRACE_SETOPTIONS, child_pid, (PTRACE_ARG3_TYPE) 0,
4758 (PTRACE_ARG4_TYPE) PTRACE_O_TRACEFORK);
4759 if (ret != 0)
4760 {
4761 ret = ptrace (PTRACE_KILL, child_pid, (PTRACE_ARG3_TYPE) 0,
4762 (PTRACE_ARG4_TYPE) 0);
4763 if (ret != 0)
4764 {
4765 warning ("linux_test_for_tracefork: failed to kill child");
4766 return;
4767 }
4768
4769 ret = my_waitpid (child_pid, &status, 0);
4770 if (ret != child_pid)
4771 warning ("linux_test_for_tracefork: failed to wait for killed child");
4772 else if (!WIFSIGNALED (status))
4773 warning ("linux_test_for_tracefork: unexpected wait status 0x%x from "
4774 "killed child", status);
4775
4776 return;
4777 }
4778
4779 ret = ptrace (PTRACE_CONT, child_pid, (PTRACE_ARG3_TYPE) 0,
4780 (PTRACE_ARG4_TYPE) 0);
4781 if (ret != 0)
4782 warning ("linux_test_for_tracefork: failed to resume child");
4783
4784 ret = my_waitpid (child_pid, &status, 0);
4785
4786 if (ret == child_pid && WIFSTOPPED (status)
4787 && status >> 16 == PTRACE_EVENT_FORK)
4788 {
4789 second_pid = 0;
4790 ret = ptrace (PTRACE_GETEVENTMSG, child_pid, (PTRACE_ARG3_TYPE) 0,
4791 &second_pid);
4792 if (ret == 0 && second_pid != 0)
4793 {
4794 int second_status;
4795
4796 linux_supports_tracefork_flag = 1;
4797 my_waitpid (second_pid, &second_status, 0);
4798 ret = ptrace (PTRACE_KILL, second_pid, (PTRACE_ARG3_TYPE) 0,
4799 (PTRACE_ARG4_TYPE) 0);
4800 if (ret != 0)
4801 warning ("linux_test_for_tracefork: failed to kill second child");
4802 my_waitpid (second_pid, &status, 0);
4803 }
4804 }
4805 else
4806 warning ("linux_test_for_tracefork: unexpected result from waitpid "
4807 "(%d, status 0x%x)", ret, status);
4808
4809 do
4810 {
4811 ret = ptrace (PTRACE_KILL, child_pid, (PTRACE_ARG3_TYPE) 0,
4812 (PTRACE_ARG4_TYPE) 0);
4813 if (ret != 0)
4814 warning ("linux_test_for_tracefork: failed to kill child");
4815 my_waitpid (child_pid, &status, 0);
4816 }
4817 while (WIFSTOPPED (status));
4818
4819 #if defined(__UCLIBC__) && defined(HAS_NOMMU)
4820 free (stack);
4821 #endif /* defined(__UCLIBC__) && defined(HAS_NOMMU) */
4822 }
4823
4824
4825 static void
4826 linux_look_up_symbols (void)
4827 {
4828 #ifdef USE_THREAD_DB
4829 struct process_info *proc = current_process ();
4830
4831 if (proc->private->thread_db != NULL)
4832 return;
4833
4834 /* If the kernel supports tracing forks then it also supports tracing
4835 clones, and then we don't need to use the magic thread event breakpoint
4836 to learn about threads. */
4837 thread_db_init (!linux_supports_tracefork_flag);
4838 #endif
4839 }
4840
4841 static void
4842 linux_request_interrupt (void)
4843 {
4844 extern unsigned long signal_pid;
4845
4846 if (!ptid_equal (cont_thread, null_ptid)
4847 && !ptid_equal (cont_thread, minus_one_ptid))
4848 {
4849 struct lwp_info *lwp;
4850 int lwpid;
4851
4852 lwp = get_thread_lwp (current_inferior);
4853 lwpid = lwpid_of (lwp);
4854 kill_lwp (lwpid, SIGINT);
4855 }
4856 else
4857 kill_lwp (signal_pid, SIGINT);
4858 }
4859
4860 /* Copy LEN bytes from inferior's auxiliary vector starting at OFFSET
4861 to debugger memory starting at MYADDR. */
4862
4863 static int
4864 linux_read_auxv (CORE_ADDR offset, unsigned char *myaddr, unsigned int len)
4865 {
4866 char filename[PATH_MAX];
4867 int fd, n;
4868 int pid = lwpid_of (get_thread_lwp (current_inferior));
4869
4870 xsnprintf (filename, sizeof filename, "/proc/%d/auxv", pid);
4871
4872 fd = open (filename, O_RDONLY);
4873 if (fd < 0)
4874 return -1;
4875
4876 if (offset != (CORE_ADDR) 0
4877 && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
4878 n = -1;
4879 else
4880 n = read (fd, myaddr, len);
4881
4882 close (fd);
4883
4884 return n;
4885 }
4886
4887 /* These breakpoint and watchpoint related wrapper functions simply
4888 pass on the function call if the target has registered a
4889 corresponding function. */
4890
4891 static int
4892 linux_insert_point (char type, CORE_ADDR addr, int len)
4893 {
4894 if (the_low_target.insert_point != NULL)
4895 return the_low_target.insert_point (type, addr, len);
4896 else
4897 /* Unsupported (see target.h). */
4898 return 1;
4899 }
4900
4901 static int
4902 linux_remove_point (char type, CORE_ADDR addr, int len)
4903 {
4904 if (the_low_target.remove_point != NULL)
4905 return the_low_target.remove_point (type, addr, len);
4906 else
4907 /* Unsupported (see target.h). */
4908 return 1;
4909 }
4910
4911 static int
4912 linux_stopped_by_watchpoint (void)
4913 {
4914 struct lwp_info *lwp = get_thread_lwp (current_inferior);
4915
4916 return lwp->stopped_by_watchpoint;
4917 }
4918
4919 static CORE_ADDR
4920 linux_stopped_data_address (void)
4921 {
4922 struct lwp_info *lwp = get_thread_lwp (current_inferior);
4923
4924 return lwp->stopped_data_address;
4925 }
4926
4927 #if defined(__UCLIBC__) && defined(HAS_NOMMU) \
4928 && defined(PT_TEXT_ADDR) && defined(PT_DATA_ADDR) \
4929 && defined(PT_TEXT_END_ADDR)
4930
4931 /* This is only used for targets that define PT_TEXT_ADDR,
4932 PT_DATA_ADDR and PT_TEXT_END_ADDR. If those are not defined, supposedly
4933 the target has different ways of acquiring this information, like
4934 loadmaps. */
4935
4936 /* Under uClinux, programs are loaded at non-zero offsets, which we need
4937 to tell gdb about. */
4938
4939 static int
4940 linux_read_offsets (CORE_ADDR *text_p, CORE_ADDR *data_p)
4941 {
4942 unsigned long text, text_end, data;
4943 int pid = lwpid_of (get_thread_lwp (current_inferior));
4944
4945 errno = 0;
4946
4947 text = ptrace (PTRACE_PEEKUSER, pid, (PTRACE_ARG3_TYPE) PT_TEXT_ADDR,
4948 (PTRACE_ARG4_TYPE) 0);
4949 text_end = ptrace (PTRACE_PEEKUSER, pid, (PTRACE_ARG3_TYPE) PT_TEXT_END_ADDR,
4950 (PTRACE_ARG4_TYPE) 0);
4951 data = ptrace (PTRACE_PEEKUSER, pid, (PTRACE_ARG3_TYPE) PT_DATA_ADDR,
4952 (PTRACE_ARG4_TYPE) 0);
4953
4954 if (errno == 0)
4955 {
4956 /* Both text and data offsets produced at compile-time (and so
4957 used by gdb) are relative to the beginning of the program,
4958 with the data segment immediately following the text segment.
4959 However, the actual runtime layout in memory may put the data
4960 somewhere else, so when we send gdb a data base-address, we
4961 use the real data base address and subtract the compile-time
4962 data base-address from it (which is just the length of the
4963 text segment). BSS immediately follows data in both
4964 cases. */
4965 *text_p = text;
4966 *data_p = data - (text_end - text);
4967
4968 return 1;
4969 }
4970 return 0;
4971 }
4972 #endif
4973
4974 static int
4975 linux_qxfer_osdata (const char *annex,
4976 unsigned char *readbuf, unsigned const char *writebuf,
4977 CORE_ADDR offset, int len)
4978 {
4979 return linux_common_xfer_osdata (annex, readbuf, offset, len);
4980 }
4981
4982 /* Convert a native/host siginfo object, into/from the siginfo in the
4983 layout of the inferiors' architecture. */
4984
4985 static void
4986 siginfo_fixup (siginfo_t *siginfo, void *inf_siginfo, int direction)
4987 {
4988 int done = 0;
4989
4990 if (the_low_target.siginfo_fixup != NULL)
4991 done = the_low_target.siginfo_fixup (siginfo, inf_siginfo, direction);
4992
4993 /* If there was no callback, or the callback didn't do anything,
4994 then just do a straight memcpy. */
4995 if (!done)
4996 {
4997 if (direction == 1)
4998 memcpy (siginfo, inf_siginfo, sizeof (siginfo_t));
4999 else
5000 memcpy (inf_siginfo, siginfo, sizeof (siginfo_t));
5001 }
5002 }
5003
5004 static int
5005 linux_xfer_siginfo (const char *annex, unsigned char *readbuf,
5006 unsigned const char *writebuf, CORE_ADDR offset, int len)
5007 {
5008 int pid;
5009 siginfo_t siginfo;
5010 char inf_siginfo[sizeof (siginfo_t)];
5011
5012 if (current_inferior == NULL)
5013 return -1;
5014
5015 pid = lwpid_of (get_thread_lwp (current_inferior));
5016
5017 if (debug_threads)
5018 fprintf (stderr, "%s siginfo for lwp %d.\n",
5019 readbuf != NULL ? "Reading" : "Writing",
5020 pid);
5021
5022 if (offset >= sizeof (siginfo))
5023 return -1;
5024
5025 if (ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_ARG3_TYPE) 0, &siginfo) != 0)
5026 return -1;
5027
5028 /* When GDBSERVER is built as a 64-bit application, ptrace writes into
5029 SIGINFO an object with 64-bit layout. Since debugging a 32-bit
5030 inferior with a 64-bit GDBSERVER should look the same as debugging it
5031 with a 32-bit GDBSERVER, we need to convert it. */
5032 siginfo_fixup (&siginfo, inf_siginfo, 0);
5033
5034 if (offset + len > sizeof (siginfo))
5035 len = sizeof (siginfo) - offset;
5036
5037 if (readbuf != NULL)
5038 memcpy (readbuf, inf_siginfo + offset, len);
5039 else
5040 {
5041 memcpy (inf_siginfo + offset, writebuf, len);
5042
5043 /* Convert back to ptrace layout before flushing it out. */
5044 siginfo_fixup (&siginfo, inf_siginfo, 1);
5045
5046 if (ptrace (PTRACE_SETSIGINFO, pid, (PTRACE_ARG3_TYPE) 0, &siginfo) != 0)
5047 return -1;
5048 }
5049
5050 return len;
5051 }
5052
5053 /* SIGCHLD handler that serves two purposes: In non-stop/async mode,
5054 so we notice when children change state; as the handler for the
5055 sigsuspend in my_waitpid. */
5056
5057 static void
5058 sigchld_handler (int signo)
5059 {
5060 int old_errno = errno;
5061
5062 if (debug_threads)
5063 {
5064 do
5065 {
5066 /* fprintf is not async-signal-safe, so call write
5067 directly. */
5068 if (write (2, "sigchld_handler\n",
5069 sizeof ("sigchld_handler\n") - 1) < 0)
5070 break; /* just ignore */
5071 } while (0);
5072 }
5073
5074 if (target_is_async_p ())
5075 async_file_mark (); /* trigger a linux_wait */
5076
5077 errno = old_errno;
5078 }
5079
5080 static int
5081 linux_supports_non_stop (void)
5082 {
5083 return 1;
5084 }
5085
5086 static int
5087 linux_async (int enable)
5088 {
5089 int previous = (linux_event_pipe[0] != -1);
5090
5091 if (debug_threads)
5092 fprintf (stderr, "linux_async (%d), previous=%d\n",
5093 enable, previous);
5094
5095 if (previous != enable)
5096 {
5097 sigset_t mask;
5098 sigemptyset (&mask);
5099 sigaddset (&mask, SIGCHLD);
5100
5101 sigprocmask (SIG_BLOCK, &mask, NULL);
5102
5103 if (enable)
5104 {
5105 if (pipe (linux_event_pipe) == -1)
5106 fatal ("creating event pipe failed.");
5107
5108 fcntl (linux_event_pipe[0], F_SETFL, O_NONBLOCK);
5109 fcntl (linux_event_pipe[1], F_SETFL, O_NONBLOCK);
5110
5111 /* Register the event loop handler. */
5112 add_file_handler (linux_event_pipe[0],
5113 handle_target_event, NULL);
5114
5115 /* Always trigger a linux_wait. */
5116 async_file_mark ();
5117 }
5118 else
5119 {
5120 delete_file_handler (linux_event_pipe[0]);
5121
5122 close (linux_event_pipe[0]);
5123 close (linux_event_pipe[1]);
5124 linux_event_pipe[0] = -1;
5125 linux_event_pipe[1] = -1;
5126 }
5127
5128 sigprocmask (SIG_UNBLOCK, &mask, NULL);
5129 }
5130
5131 return previous;
5132 }
5133
5134 static int
5135 linux_start_non_stop (int nonstop)
5136 {
5137 /* Register or unregister from event-loop accordingly. */
5138 linux_async (nonstop);
5139 return 0;
5140 }
5141
5142 static int
5143 linux_supports_multi_process (void)
5144 {
5145 return 1;
5146 }
5147
5148 static int
5149 linux_supports_disable_randomization (void)
5150 {
5151 #ifdef HAVE_PERSONALITY
5152 return 1;
5153 #else
5154 return 0;
5155 #endif
5156 }
5157
5158 static int
5159 linux_supports_agent (void)
5160 {
5161 return 1;
5162 }
5163
5164 static int
5165 linux_supports_range_stepping (void)
5166 {
5167 if (*the_low_target.supports_range_stepping == NULL)
5168 return 0;
5169
5170 return (*the_low_target.supports_range_stepping) ();
5171 }
5172
5173 /* Enumerate spufs IDs for process PID. */
5174 static int
5175 spu_enumerate_spu_ids (long pid, unsigned char *buf, CORE_ADDR offset, int len)
5176 {
5177 int pos = 0;
5178 int written = 0;
5179 char path[128];
5180 DIR *dir;
5181 struct dirent *entry;
5182
5183 sprintf (path, "/proc/%ld/fd", pid);
5184 dir = opendir (path);
5185 if (!dir)
5186 return -1;
5187
5188 rewinddir (dir);
5189 while ((entry = readdir (dir)) != NULL)
5190 {
5191 struct stat st;
5192 struct statfs stfs;
5193 int fd;
5194
5195 fd = atoi (entry->d_name);
5196 if (!fd)
5197 continue;
5198
5199 sprintf (path, "/proc/%ld/fd/%d", pid, fd);
5200 if (stat (path, &st) != 0)
5201 continue;
5202 if (!S_ISDIR (st.st_mode))
5203 continue;
5204
5205 if (statfs (path, &stfs) != 0)
5206 continue;
5207 if (stfs.f_type != SPUFS_MAGIC)
5208 continue;
5209
5210 if (pos >= offset && pos + 4 <= offset + len)
5211 {
5212 *(unsigned int *)(buf + pos - offset) = fd;
5213 written += 4;
5214 }
5215 pos += 4;
5216 }
5217
5218 closedir (dir);
5219 return written;
5220 }
5221
5222 /* Implements the to_xfer_partial interface for the TARGET_OBJECT_SPU
5223 object type, using the /proc file system. */
5224 static int
5225 linux_qxfer_spu (const char *annex, unsigned char *readbuf,
5226 unsigned const char *writebuf,
5227 CORE_ADDR offset, int len)
5228 {
5229 long pid = lwpid_of (get_thread_lwp (current_inferior));
5230 char buf[128];
5231 int fd = 0;
5232 int ret = 0;
5233
5234 if (!writebuf && !readbuf)
5235 return -1;
5236
5237 if (!*annex)
5238 {
5239 if (!readbuf)
5240 return -1;
5241 else
5242 return spu_enumerate_spu_ids (pid, readbuf, offset, len);
5243 }
5244
5245 sprintf (buf, "/proc/%ld/fd/%s", pid, annex);
5246 fd = open (buf, writebuf? O_WRONLY : O_RDONLY);
5247 if (fd <= 0)
5248 return -1;
5249
5250 if (offset != 0
5251 && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
5252 {
5253 close (fd);
5254 return 0;
5255 }
5256
5257 if (writebuf)
5258 ret = write (fd, writebuf, (size_t) len);
5259 else
5260 ret = read (fd, readbuf, (size_t) len);
5261
5262 close (fd);
5263 return ret;
5264 }
5265
5266 #if defined PT_GETDSBT || defined PTRACE_GETFDPIC
5267 struct target_loadseg
5268 {
5269 /* Core address to which the segment is mapped. */
5270 Elf32_Addr addr;
5271 /* VMA recorded in the program header. */
5272 Elf32_Addr p_vaddr;
5273 /* Size of this segment in memory. */
5274 Elf32_Word p_memsz;
5275 };
5276
5277 # if defined PT_GETDSBT
5278 struct target_loadmap
5279 {
5280 /* Protocol version number, must be zero. */
5281 Elf32_Word version;
5282 /* Pointer to the DSBT table, its size, and the DSBT index. */
5283 unsigned *dsbt_table;
5284 unsigned dsbt_size, dsbt_index;
5285 /* Number of segments in this map. */
5286 Elf32_Word nsegs;
5287 /* The actual memory map. */
5288 struct target_loadseg segs[/*nsegs*/];
5289 };
5290 # define LINUX_LOADMAP PT_GETDSBT
5291 # define LINUX_LOADMAP_EXEC PTRACE_GETDSBT_EXEC
5292 # define LINUX_LOADMAP_INTERP PTRACE_GETDSBT_INTERP
5293 # else
5294 struct target_loadmap
5295 {
5296 /* Protocol version number, must be zero. */
5297 Elf32_Half version;
5298 /* Number of segments in this map. */
5299 Elf32_Half nsegs;
5300 /* The actual memory map. */
5301 struct target_loadseg segs[/*nsegs*/];
5302 };
5303 # define LINUX_LOADMAP PTRACE_GETFDPIC
5304 # define LINUX_LOADMAP_EXEC PTRACE_GETFDPIC_EXEC
5305 # define LINUX_LOADMAP_INTERP PTRACE_GETFDPIC_INTERP
5306 # endif
5307
5308 static int
5309 linux_read_loadmap (const char *annex, CORE_ADDR offset,
5310 unsigned char *myaddr, unsigned int len)
5311 {
5312 int pid = lwpid_of (get_thread_lwp (current_inferior));
5313 int addr = -1;
5314 struct target_loadmap *data = NULL;
5315 unsigned int actual_length, copy_length;
5316
5317 if (strcmp (annex, "exec") == 0)
5318 addr = (int) LINUX_LOADMAP_EXEC;
5319 else if (strcmp (annex, "interp") == 0)
5320 addr = (int) LINUX_LOADMAP_INTERP;
5321 else
5322 return -1;
5323
5324 if (ptrace (LINUX_LOADMAP, pid, addr, &data) != 0)
5325 return -1;
5326
5327 if (data == NULL)
5328 return -1;
5329
5330 actual_length = sizeof (struct target_loadmap)
5331 + sizeof (struct target_loadseg) * data->nsegs;
5332
5333 if (offset < 0 || offset > actual_length)
5334 return -1;
5335
5336 copy_length = actual_length - offset < len ? actual_length - offset : len;
5337 memcpy (myaddr, (char *) data + offset, copy_length);
5338 return copy_length;
5339 }
5340 #else
5341 # define linux_read_loadmap NULL
5342 #endif /* defined PT_GETDSBT || defined PTRACE_GETFDPIC */
5343
5344 static void
5345 linux_process_qsupported (const char *query)
5346 {
5347 if (the_low_target.process_qsupported != NULL)
5348 the_low_target.process_qsupported (query);
5349 }
5350
5351 static int
5352 linux_supports_tracepoints (void)
5353 {
5354 if (*the_low_target.supports_tracepoints == NULL)
5355 return 0;
5356
5357 return (*the_low_target.supports_tracepoints) ();
5358 }
5359
5360 static CORE_ADDR
5361 linux_read_pc (struct regcache *regcache)
5362 {
5363 if (the_low_target.get_pc == NULL)
5364 return 0;
5365
5366 return (*the_low_target.get_pc) (regcache);
5367 }
5368
5369 static void
5370 linux_write_pc (struct regcache *regcache, CORE_ADDR pc)
5371 {
5372 gdb_assert (the_low_target.set_pc != NULL);
5373
5374 (*the_low_target.set_pc) (regcache, pc);
5375 }
5376
5377 static int
5378 linux_thread_stopped (struct thread_info *thread)
5379 {
5380 return get_thread_lwp (thread)->stopped;
5381 }
5382
5383 /* This exposes stop-all-threads functionality to other modules. */
5384
5385 static void
5386 linux_pause_all (int freeze)
5387 {
5388 stop_all_lwps (freeze, NULL);
5389 }
5390
5391 /* This exposes unstop-all-threads functionality to other gdbserver
5392 modules. */
5393
5394 static void
5395 linux_unpause_all (int unfreeze)
5396 {
5397 unstop_all_lwps (unfreeze, NULL);
5398 }
5399
5400 static int
5401 linux_prepare_to_access_memory (void)
5402 {
5403 /* Neither ptrace nor /proc/PID/mem allow accessing memory through a
5404 running LWP. */
5405 if (non_stop)
5406 linux_pause_all (1);
5407 return 0;
5408 }
5409
5410 static void
5411 linux_done_accessing_memory (void)
5412 {
5413 /* Neither ptrace nor /proc/PID/mem allow accessing memory through a
5414 running LWP. */
5415 if (non_stop)
5416 linux_unpause_all (1);
5417 }
5418
5419 static int
5420 linux_install_fast_tracepoint_jump_pad (CORE_ADDR tpoint, CORE_ADDR tpaddr,
5421 CORE_ADDR collector,
5422 CORE_ADDR lockaddr,
5423 ULONGEST orig_size,
5424 CORE_ADDR *jump_entry,
5425 CORE_ADDR *trampoline,
5426 ULONGEST *trampoline_size,
5427 unsigned char *jjump_pad_insn,
5428 ULONGEST *jjump_pad_insn_size,
5429 CORE_ADDR *adjusted_insn_addr,
5430 CORE_ADDR *adjusted_insn_addr_end,
5431 char *err)
5432 {
5433 return (*the_low_target.install_fast_tracepoint_jump_pad)
5434 (tpoint, tpaddr, collector, lockaddr, orig_size,
5435 jump_entry, trampoline, trampoline_size,
5436 jjump_pad_insn, jjump_pad_insn_size,
5437 adjusted_insn_addr, adjusted_insn_addr_end,
5438 err);
5439 }
5440
5441 static struct emit_ops *
5442 linux_emit_ops (void)
5443 {
5444 if (the_low_target.emit_ops != NULL)
5445 return (*the_low_target.emit_ops) ();
5446 else
5447 return NULL;
5448 }
5449
5450 static int
5451 linux_get_min_fast_tracepoint_insn_len (void)
5452 {
5453 return (*the_low_target.get_min_fast_tracepoint_insn_len) ();
5454 }
5455
5456 /* Extract &phdr and num_phdr in the inferior. Return 0 on success. */
5457
5458 static int
5459 get_phdr_phnum_from_proc_auxv (const int pid, const int is_elf64,
5460 CORE_ADDR *phdr_memaddr, int *num_phdr)
5461 {
5462 char filename[PATH_MAX];
5463 int fd;
5464 const int auxv_size = is_elf64
5465 ? sizeof (Elf64_auxv_t) : sizeof (Elf32_auxv_t);
5466 char buf[sizeof (Elf64_auxv_t)]; /* The larger of the two. */
5467
5468 xsnprintf (filename, sizeof filename, "/proc/%d/auxv", pid);
5469
5470 fd = open (filename, O_RDONLY);
5471 if (fd < 0)
5472 return 1;
5473
5474 *phdr_memaddr = 0;
5475 *num_phdr = 0;
5476 while (read (fd, buf, auxv_size) == auxv_size
5477 && (*phdr_memaddr == 0 || *num_phdr == 0))
5478 {
5479 if (is_elf64)
5480 {
5481 Elf64_auxv_t *const aux = (Elf64_auxv_t *) buf;
5482
5483 switch (aux->a_type)
5484 {
5485 case AT_PHDR:
5486 *phdr_memaddr = aux->a_un.a_val;
5487 break;
5488 case AT_PHNUM:
5489 *num_phdr = aux->a_un.a_val;
5490 break;
5491 }
5492 }
5493 else
5494 {
5495 Elf32_auxv_t *const aux = (Elf32_auxv_t *) buf;
5496
5497 switch (aux->a_type)
5498 {
5499 case AT_PHDR:
5500 *phdr_memaddr = aux->a_un.a_val;
5501 break;
5502 case AT_PHNUM:
5503 *num_phdr = aux->a_un.a_val;
5504 break;
5505 }
5506 }
5507 }
5508
5509 close (fd);
5510
5511 if (*phdr_memaddr == 0 || *num_phdr == 0)
5512 {
5513 warning ("Unexpected missing AT_PHDR and/or AT_PHNUM: "
5514 "phdr_memaddr = %ld, phdr_num = %d",
5515 (long) *phdr_memaddr, *num_phdr);
5516 return 2;
5517 }
5518
5519 return 0;
5520 }
5521
5522 /* Return &_DYNAMIC (via PT_DYNAMIC) in the inferior, or 0 if not present. */
5523
5524 static CORE_ADDR
5525 get_dynamic (const int pid, const int is_elf64)
5526 {
5527 CORE_ADDR phdr_memaddr, relocation;
5528 int num_phdr, i;
5529 unsigned char *phdr_buf;
5530 const int phdr_size = is_elf64 ? sizeof (Elf64_Phdr) : sizeof (Elf32_Phdr);
5531
5532 if (get_phdr_phnum_from_proc_auxv (pid, is_elf64, &phdr_memaddr, &num_phdr))
5533 return 0;
5534
5535 gdb_assert (num_phdr < 100); /* Basic sanity check. */
5536 phdr_buf = alloca (num_phdr * phdr_size);
5537
5538 if (linux_read_memory (phdr_memaddr, phdr_buf, num_phdr * phdr_size))
5539 return 0;
5540
5541 /* Compute relocation: it is expected to be 0 for "regular" executables,
5542 non-zero for PIE ones. */
5543 relocation = -1;
5544 for (i = 0; relocation == -1 && i < num_phdr; i++)
5545 if (is_elf64)
5546 {
5547 Elf64_Phdr *const p = (Elf64_Phdr *) (phdr_buf + i * phdr_size);
5548
5549 if (p->p_type == PT_PHDR)
5550 relocation = phdr_memaddr - p->p_vaddr;
5551 }
5552 else
5553 {
5554 Elf32_Phdr *const p = (Elf32_Phdr *) (phdr_buf + i * phdr_size);
5555
5556 if (p->p_type == PT_PHDR)
5557 relocation = phdr_memaddr - p->p_vaddr;
5558 }
5559
5560 if (relocation == -1)
5561 {
5562 /* PT_PHDR is optional, but necessary for PIE in general. Fortunately
5563 any real world executables, including PIE executables, have always
5564 PT_PHDR present. PT_PHDR is not present in some shared libraries or
5565 in fpc (Free Pascal 2.4) binaries but neither of those have a need for
5566 or present DT_DEBUG anyway (fpc binaries are statically linked).
5567
5568 Therefore if there exists DT_DEBUG there is always also PT_PHDR.
5569
5570 GDB could find RELOCATION also from AT_ENTRY - e_entry. */
5571
5572 return 0;
5573 }
5574
5575 for (i = 0; i < num_phdr; i++)
5576 {
5577 if (is_elf64)
5578 {
5579 Elf64_Phdr *const p = (Elf64_Phdr *) (phdr_buf + i * phdr_size);
5580
5581 if (p->p_type == PT_DYNAMIC)
5582 return p->p_vaddr + relocation;
5583 }
5584 else
5585 {
5586 Elf32_Phdr *const p = (Elf32_Phdr *) (phdr_buf + i * phdr_size);
5587
5588 if (p->p_type == PT_DYNAMIC)
5589 return p->p_vaddr + relocation;
5590 }
5591 }
5592
5593 return 0;
5594 }
5595
5596 /* Return &_r_debug in the inferior, or -1 if not present. Return value
5597 can be 0 if the inferior does not yet have the library list initialized.
5598 We look for DT_MIPS_RLD_MAP first. MIPS executables use this instead of
5599 DT_DEBUG, although they sometimes contain an unused DT_DEBUG entry too. */
5600
5601 static CORE_ADDR
5602 get_r_debug (const int pid, const int is_elf64)
5603 {
5604 CORE_ADDR dynamic_memaddr;
5605 const int dyn_size = is_elf64 ? sizeof (Elf64_Dyn) : sizeof (Elf32_Dyn);
5606 unsigned char buf[sizeof (Elf64_Dyn)]; /* The larger of the two. */
5607 CORE_ADDR map = -1;
5608
5609 dynamic_memaddr = get_dynamic (pid, is_elf64);
5610 if (dynamic_memaddr == 0)
5611 return map;
5612
5613 while (linux_read_memory (dynamic_memaddr, buf, dyn_size) == 0)
5614 {
5615 if (is_elf64)
5616 {
5617 Elf64_Dyn *const dyn = (Elf64_Dyn *) buf;
5618 #ifdef DT_MIPS_RLD_MAP
5619 union
5620 {
5621 Elf64_Xword map;
5622 unsigned char buf[sizeof (Elf64_Xword)];
5623 }
5624 rld_map;
5625
5626 if (dyn->d_tag == DT_MIPS_RLD_MAP)
5627 {
5628 if (linux_read_memory (dyn->d_un.d_val,
5629 rld_map.buf, sizeof (rld_map.buf)) == 0)
5630 return rld_map.map;
5631 else
5632 break;
5633 }
5634 #endif /* DT_MIPS_RLD_MAP */
5635
5636 if (dyn->d_tag == DT_DEBUG && map == -1)
5637 map = dyn->d_un.d_val;
5638
5639 if (dyn->d_tag == DT_NULL)
5640 break;
5641 }
5642 else
5643 {
5644 Elf32_Dyn *const dyn = (Elf32_Dyn *) buf;
5645 #ifdef DT_MIPS_RLD_MAP
5646 union
5647 {
5648 Elf32_Word map;
5649 unsigned char buf[sizeof (Elf32_Word)];
5650 }
5651 rld_map;
5652
5653 if (dyn->d_tag == DT_MIPS_RLD_MAP)
5654 {
5655 if (linux_read_memory (dyn->d_un.d_val,
5656 rld_map.buf, sizeof (rld_map.buf)) == 0)
5657 return rld_map.map;
5658 else
5659 break;
5660 }
5661 #endif /* DT_MIPS_RLD_MAP */
5662
5663 if (dyn->d_tag == DT_DEBUG && map == -1)
5664 map = dyn->d_un.d_val;
5665
5666 if (dyn->d_tag == DT_NULL)
5667 break;
5668 }
5669
5670 dynamic_memaddr += dyn_size;
5671 }
5672
5673 return map;
5674 }
5675
5676 /* Read one pointer from MEMADDR in the inferior. */
5677
5678 static int
5679 read_one_ptr (CORE_ADDR memaddr, CORE_ADDR *ptr, int ptr_size)
5680 {
5681 int ret;
5682
5683 /* Go through a union so this works on either big or little endian
5684 hosts, when the inferior's pointer size is smaller than the size
5685 of CORE_ADDR. It is assumed the inferior's endianness is the
5686 same of the superior's. */
5687 union
5688 {
5689 CORE_ADDR core_addr;
5690 unsigned int ui;
5691 unsigned char uc;
5692 } addr;
5693
5694 ret = linux_read_memory (memaddr, &addr.uc, ptr_size);
5695 if (ret == 0)
5696 {
5697 if (ptr_size == sizeof (CORE_ADDR))
5698 *ptr = addr.core_addr;
5699 else if (ptr_size == sizeof (unsigned int))
5700 *ptr = addr.ui;
5701 else
5702 gdb_assert_not_reached ("unhandled pointer size");
5703 }
5704 return ret;
5705 }
5706
5707 struct link_map_offsets
5708 {
5709 /* Offset and size of r_debug.r_version. */
5710 int r_version_offset;
5711
5712 /* Offset and size of r_debug.r_map. */
5713 int r_map_offset;
5714
5715 /* Offset to l_addr field in struct link_map. */
5716 int l_addr_offset;
5717
5718 /* Offset to l_name field in struct link_map. */
5719 int l_name_offset;
5720
5721 /* Offset to l_ld field in struct link_map. */
5722 int l_ld_offset;
5723
5724 /* Offset to l_next field in struct link_map. */
5725 int l_next_offset;
5726
5727 /* Offset to l_prev field in struct link_map. */
5728 int l_prev_offset;
5729 };
5730
5731 /* Construct qXfer:libraries-svr4:read reply. */
5732
5733 static int
5734 linux_qxfer_libraries_svr4 (const char *annex, unsigned char *readbuf,
5735 unsigned const char *writebuf,
5736 CORE_ADDR offset, int len)
5737 {
5738 char *document;
5739 unsigned document_len;
5740 struct process_info_private *const priv = current_process ()->private;
5741 char filename[PATH_MAX];
5742 int pid, is_elf64;
5743
5744 static const struct link_map_offsets lmo_32bit_offsets =
5745 {
5746 0, /* r_version offset. */
5747 4, /* r_debug.r_map offset. */
5748 0, /* l_addr offset in link_map. */
5749 4, /* l_name offset in link_map. */
5750 8, /* l_ld offset in link_map. */
5751 12, /* l_next offset in link_map. */
5752 16 /* l_prev offset in link_map. */
5753 };
5754
5755 static const struct link_map_offsets lmo_64bit_offsets =
5756 {
5757 0, /* r_version offset. */
5758 8, /* r_debug.r_map offset. */
5759 0, /* l_addr offset in link_map. */
5760 8, /* l_name offset in link_map. */
5761 16, /* l_ld offset in link_map. */
5762 24, /* l_next offset in link_map. */
5763 32 /* l_prev offset in link_map. */
5764 };
5765 const struct link_map_offsets *lmo;
5766 unsigned int machine;
5767 int ptr_size;
5768 CORE_ADDR lm_addr = 0, lm_prev = 0;
5769 int allocated = 1024;
5770 char *p;
5771 CORE_ADDR l_name, l_addr, l_ld, l_next, l_prev;
5772 int header_done = 0;
5773
5774 if (writebuf != NULL)
5775 return -2;
5776 if (readbuf == NULL)
5777 return -1;
5778
5779 pid = lwpid_of (get_thread_lwp (current_inferior));
5780 xsnprintf (filename, sizeof filename, "/proc/%d/exe", pid);
5781 is_elf64 = elf_64_file_p (filename, &machine);
5782 lmo = is_elf64 ? &lmo_64bit_offsets : &lmo_32bit_offsets;
5783 ptr_size = is_elf64 ? 8 : 4;
5784
5785 while (annex[0] != '\0')
5786 {
5787 const char *sep;
5788 CORE_ADDR *addrp;
5789 int len;
5790
5791 sep = strchr (annex, '=');
5792 if (sep == NULL)
5793 break;
5794
5795 len = sep - annex;
5796 if (len == 5 && strncmp (annex, "start", 5) == 0)
5797 addrp = &lm_addr;
5798 else if (len == 4 && strncmp (annex, "prev", 4) == 0)
5799 addrp = &lm_prev;
5800 else
5801 {
5802 annex = strchr (sep, ';');
5803 if (annex == NULL)
5804 break;
5805 annex++;
5806 continue;
5807 }
5808
5809 annex = decode_address_to_semicolon (addrp, sep + 1);
5810 }
5811
5812 if (lm_addr == 0)
5813 {
5814 int r_version = 0;
5815
5816 if (priv->r_debug == 0)
5817 priv->r_debug = get_r_debug (pid, is_elf64);
5818
5819 /* We failed to find DT_DEBUG. Such situation will not change
5820 for this inferior - do not retry it. Report it to GDB as
5821 E01, see for the reasons at the GDB solib-svr4.c side. */
5822 if (priv->r_debug == (CORE_ADDR) -1)
5823 return -1;
5824
5825 if (priv->r_debug != 0)
5826 {
5827 if (linux_read_memory (priv->r_debug + lmo->r_version_offset,
5828 (unsigned char *) &r_version,
5829 sizeof (r_version)) != 0
5830 || r_version != 1)
5831 {
5832 warning ("unexpected r_debug version %d", r_version);
5833 }
5834 else if (read_one_ptr (priv->r_debug + lmo->r_map_offset,
5835 &lm_addr, ptr_size) != 0)
5836 {
5837 warning ("unable to read r_map from 0x%lx",
5838 (long) priv->r_debug + lmo->r_map_offset);
5839 }
5840 }
5841 }
5842
5843 document = xmalloc (allocated);
5844 strcpy (document, "<library-list-svr4 version=\"1.0\"");
5845 p = document + strlen (document);
5846
5847 while (lm_addr
5848 && read_one_ptr (lm_addr + lmo->l_name_offset,
5849 &l_name, ptr_size) == 0
5850 && read_one_ptr (lm_addr + lmo->l_addr_offset,
5851 &l_addr, ptr_size) == 0
5852 && read_one_ptr (lm_addr + lmo->l_ld_offset,
5853 &l_ld, ptr_size) == 0
5854 && read_one_ptr (lm_addr + lmo->l_prev_offset,
5855 &l_prev, ptr_size) == 0
5856 && read_one_ptr (lm_addr + lmo->l_next_offset,
5857 &l_next, ptr_size) == 0)
5858 {
5859 unsigned char libname[PATH_MAX];
5860
5861 if (lm_prev != l_prev)
5862 {
5863 warning ("Corrupted shared library list: 0x%lx != 0x%lx",
5864 (long) lm_prev, (long) l_prev);
5865 break;
5866 }
5867
5868 /* Ignore the first entry even if it has valid name as the first entry
5869 corresponds to the main executable. The first entry should not be
5870 skipped if the dynamic loader was loaded late by a static executable
5871 (see solib-svr4.c parameter ignore_first). But in such case the main
5872 executable does not have PT_DYNAMIC present and this function already
5873 exited above due to failed get_r_debug. */
5874 if (lm_prev == 0)
5875 {
5876 sprintf (p, " main-lm=\"0x%lx\"", (unsigned long) lm_addr);
5877 p = p + strlen (p);
5878 }
5879 else
5880 {
5881 /* Not checking for error because reading may stop before
5882 we've got PATH_MAX worth of characters. */
5883 libname[0] = '\0';
5884 linux_read_memory (l_name, libname, sizeof (libname) - 1);
5885 libname[sizeof (libname) - 1] = '\0';
5886 if (libname[0] != '\0')
5887 {
5888 /* 6x the size for xml_escape_text below. */
5889 size_t len = 6 * strlen ((char *) libname);
5890 char *name;
5891
5892 if (!header_done)
5893 {
5894 /* Terminate `<library-list-svr4'. */
5895 *p++ = '>';
5896 header_done = 1;
5897 }
5898
5899 while (allocated < p - document + len + 200)
5900 {
5901 /* Expand to guarantee sufficient storage. */
5902 uintptr_t document_len = p - document;
5903
5904 document = xrealloc (document, 2 * allocated);
5905 allocated *= 2;
5906 p = document + document_len;
5907 }
5908
5909 name = xml_escape_text ((char *) libname);
5910 p += sprintf (p, "<library name=\"%s\" lm=\"0x%lx\" "
5911 "l_addr=\"0x%lx\" l_ld=\"0x%lx\"/>",
5912 name, (unsigned long) lm_addr,
5913 (unsigned long) l_addr, (unsigned long) l_ld);
5914 free (name);
5915 }
5916 }
5917
5918 lm_prev = lm_addr;
5919 lm_addr = l_next;
5920 }
5921
5922 if (!header_done)
5923 {
5924 /* Empty list; terminate `<library-list-svr4'. */
5925 strcpy (p, "/>");
5926 }
5927 else
5928 strcpy (p, "</library-list-svr4>");
5929
5930 document_len = strlen (document);
5931 if (offset < document_len)
5932 document_len -= offset;
5933 else
5934 document_len = 0;
5935 if (len > document_len)
5936 len = document_len;
5937
5938 memcpy (readbuf, document + offset, len);
5939 xfree (document);
5940
5941 return len;
5942 }
5943
5944 #ifdef HAVE_LINUX_BTRACE
5945
5946 /* Enable branch tracing. */
5947
5948 static struct btrace_target_info *
5949 linux_low_enable_btrace (ptid_t ptid)
5950 {
5951 struct btrace_target_info *tinfo;
5952
5953 tinfo = linux_enable_btrace (ptid);
5954
5955 if (tinfo != NULL)
5956 {
5957 struct thread_info *thread = find_thread_ptid (ptid);
5958 struct regcache *regcache = get_thread_regcache (thread, 0);
5959
5960 tinfo->ptr_bits = register_size (regcache->tdesc, 0) * 8;
5961 }
5962
5963 return tinfo;
5964 }
5965
5966 /* Read branch trace data as btrace xml document. */
5967
5968 static void
5969 linux_low_read_btrace (struct btrace_target_info *tinfo, struct buffer *buffer,
5970 int type)
5971 {
5972 VEC (btrace_block_s) *btrace;
5973 struct btrace_block *block;
5974 int i;
5975
5976 btrace = linux_read_btrace (tinfo, type);
5977
5978 buffer_grow_str (buffer, "<!DOCTYPE btrace SYSTEM \"btrace.dtd\">\n");
5979 buffer_grow_str (buffer, "<btrace version=\"1.0\">\n");
5980
5981 for (i = 0; VEC_iterate (btrace_block_s, btrace, i, block); i++)
5982 buffer_xml_printf (buffer, "<block begin=\"0x%s\" end=\"0x%s\"/>\n",
5983 paddress (block->begin), paddress (block->end));
5984
5985 buffer_grow_str (buffer, "</btrace>\n");
5986
5987 VEC_free (btrace_block_s, btrace);
5988 }
5989 #endif /* HAVE_LINUX_BTRACE */
5990
5991 static struct target_ops linux_target_ops = {
5992 linux_create_inferior,
5993 linux_attach,
5994 linux_kill,
5995 linux_detach,
5996 linux_mourn,
5997 linux_join,
5998 linux_thread_alive,
5999 linux_resume,
6000 linux_wait,
6001 linux_fetch_registers,
6002 linux_store_registers,
6003 linux_prepare_to_access_memory,
6004 linux_done_accessing_memory,
6005 linux_read_memory,
6006 linux_write_memory,
6007 linux_look_up_symbols,
6008 linux_request_interrupt,
6009 linux_read_auxv,
6010 linux_insert_point,
6011 linux_remove_point,
6012 linux_stopped_by_watchpoint,
6013 linux_stopped_data_address,
6014 #if defined(__UCLIBC__) && defined(HAS_NOMMU) \
6015 && defined(PT_TEXT_ADDR) && defined(PT_DATA_ADDR) \
6016 && defined(PT_TEXT_END_ADDR)
6017 linux_read_offsets,
6018 #else
6019 NULL,
6020 #endif
6021 #ifdef USE_THREAD_DB
6022 thread_db_get_tls_address,
6023 #else
6024 NULL,
6025 #endif
6026 linux_qxfer_spu,
6027 hostio_last_error_from_errno,
6028 linux_qxfer_osdata,
6029 linux_xfer_siginfo,
6030 linux_supports_non_stop,
6031 linux_async,
6032 linux_start_non_stop,
6033 linux_supports_multi_process,
6034 #ifdef USE_THREAD_DB
6035 thread_db_handle_monitor_command,
6036 #else
6037 NULL,
6038 #endif
6039 linux_common_core_of_thread,
6040 linux_read_loadmap,
6041 linux_process_qsupported,
6042 linux_supports_tracepoints,
6043 linux_read_pc,
6044 linux_write_pc,
6045 linux_thread_stopped,
6046 NULL,
6047 linux_pause_all,
6048 linux_unpause_all,
6049 linux_cancel_breakpoints,
6050 linux_stabilize_threads,
6051 linux_install_fast_tracepoint_jump_pad,
6052 linux_emit_ops,
6053 linux_supports_disable_randomization,
6054 linux_get_min_fast_tracepoint_insn_len,
6055 linux_qxfer_libraries_svr4,
6056 linux_supports_agent,
6057 #ifdef HAVE_LINUX_BTRACE
6058 linux_supports_btrace,
6059 linux_low_enable_btrace,
6060 linux_disable_btrace,
6061 linux_low_read_btrace,
6062 #else
6063 NULL,
6064 NULL,
6065 NULL,
6066 NULL,
6067 #endif
6068 linux_supports_range_stepping,
6069 };
6070
6071 static void
6072 linux_init_signals ()
6073 {
6074 /* FIXME drow/2002-06-09: As above, we should check with LinuxThreads
6075 to find what the cancel signal actually is. */
6076 #ifndef __ANDROID__ /* Bionic doesn't use SIGRTMIN the way glibc does. */
6077 signal (__SIGRTMIN+1, SIG_IGN);
6078 #endif
6079 }
6080
6081 #ifdef HAVE_LINUX_REGSETS
6082 void
6083 initialize_regsets_info (struct regsets_info *info)
6084 {
6085 for (info->num_regsets = 0;
6086 info->regsets[info->num_regsets].size >= 0;
6087 info->num_regsets++)
6088 ;
6089 }
6090 #endif
6091
6092 void
6093 initialize_low (void)
6094 {
6095 struct sigaction sigchld_action;
6096 memset (&sigchld_action, 0, sizeof (sigchld_action));
6097 set_target_ops (&linux_target_ops);
6098 set_breakpoint_data (the_low_target.breakpoint,
6099 the_low_target.breakpoint_len);
6100 linux_init_signals ();
6101 linux_test_for_tracefork ();
6102 linux_ptrace_init_warnings ();
6103
6104 sigchld_action.sa_handler = sigchld_handler;
6105 sigemptyset (&sigchld_action.sa_mask);
6106 sigchld_action.sa_flags = SA_RESTART;
6107 sigaction (SIGCHLD, &sigchld_action, NULL);
6108
6109 initialize_low_arch ();
6110 }