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