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