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