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