Decouple target_interrupt from all-stop/non-stop modes
[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       struct gdbarch *gdbarch = get_regcache_arch (regcache);
2462       CORE_ADDR pc;
2463       int discard = 0;
2464
2465       pc = regcache_read_pc (regcache);
2466
2467       if (pc != lp->stop_pc)
2468         {
2469           if (debug_linux_nat)
2470             fprintf_unfiltered (gdb_stdlog,
2471                                 "SC: PC of %s changed.  was=%s, now=%s\n",
2472                                 target_pid_to_str (lp->ptid),
2473                                 paddress (target_gdbarch (), lp->stop_pc),
2474                                 paddress (target_gdbarch (), pc));
2475           discard = 1;
2476         }
2477
2478 #if !USE_SIGTRAP_SIGINFO
2479       else if (!breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
2480         {
2481           if (debug_linux_nat)
2482             fprintf_unfiltered (gdb_stdlog,
2483                                 "SC: previous breakpoint of %s, at %s gone\n",
2484                                 target_pid_to_str (lp->ptid),
2485                                 paddress (target_gdbarch (), lp->stop_pc));
2486
2487           discard = 1;
2488         }
2489 #endif
2490
2491       if (discard)
2492         {
2493           if (debug_linux_nat)
2494             fprintf_unfiltered (gdb_stdlog,
2495                                 "SC: pending event of %s cancelled.\n",
2496                                 target_pid_to_str (lp->ptid));
2497
2498           lp->status = 0;
2499           linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
2500           return 0;
2501         }
2502     }
2503
2504   return 1;
2505 }
2506
2507 /* Count the LWP's that have had events.  */
2508
2509 static int
2510 count_events_callback (struct lwp_info *lp, void *data)
2511 {
2512   int *count = (int *) data;
2513
2514   gdb_assert (count != NULL);
2515
2516   /* Select only resumed LWPs that have an event pending.  */
2517   if (lp->resumed && lwp_status_pending_p (lp))
2518     (*count)++;
2519
2520   return 0;
2521 }
2522
2523 /* Select the LWP (if any) that is currently being single-stepped.  */
2524
2525 static int
2526 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
2527 {
2528   if (lp->last_resume_kind == resume_step
2529       && lp->status != 0)
2530     return 1;
2531   else
2532     return 0;
2533 }
2534
2535 /* Returns true if LP has a status pending.  */
2536
2537 static int
2538 lwp_status_pending_p (struct lwp_info *lp)
2539 {
2540   /* We check for lp->waitstatus in addition to lp->status, because we
2541      can have pending process exits recorded in lp->status and
2542      W_EXITCODE(0,0) happens to be 0.  */
2543   return lp->status != 0 || lp->waitstatus.kind != TARGET_WAITKIND_IGNORE;
2544 }
2545
2546 /* Select the Nth LWP that has had an event.  */
2547
2548 static int
2549 select_event_lwp_callback (struct lwp_info *lp, void *data)
2550 {
2551   int *selector = (int *) data;
2552
2553   gdb_assert (selector != NULL);
2554
2555   /* Select only resumed LWPs that have an event pending.  */
2556   if (lp->resumed && lwp_status_pending_p (lp))
2557     if ((*selector)-- == 0)
2558       return 1;
2559
2560   return 0;
2561 }
2562
2563 /* Called when the LWP stopped for a signal/trap.  If it stopped for a
2564    trap check what caused it (breakpoint, watchpoint, trace, etc.),
2565    and save the result in the LWP's stop_reason field.  If it stopped
2566    for a breakpoint, decrement the PC if necessary on the lwp's
2567    architecture.  */
2568
2569 static void
2570 save_stop_reason (struct lwp_info *lp)
2571 {
2572   struct regcache *regcache;
2573   struct gdbarch *gdbarch;
2574   CORE_ADDR pc;
2575   CORE_ADDR sw_bp_pc;
2576 #if USE_SIGTRAP_SIGINFO
2577   siginfo_t siginfo;
2578 #endif
2579
2580   gdb_assert (lp->stop_reason == TARGET_STOPPED_BY_NO_REASON);
2581   gdb_assert (lp->status != 0);
2582
2583   if (!linux_nat_status_is_event (lp->status))
2584     return;
2585
2586   regcache = get_thread_regcache (lp->ptid);
2587   gdbarch = get_regcache_arch (regcache);
2588
2589   pc = regcache_read_pc (regcache);
2590   sw_bp_pc = pc - gdbarch_decr_pc_after_break (gdbarch);
2591
2592 #if USE_SIGTRAP_SIGINFO
2593   if (linux_nat_get_siginfo (lp->ptid, &siginfo))
2594     {
2595       if (siginfo.si_signo == SIGTRAP)
2596         {
2597           if (GDB_ARCH_IS_TRAP_BRKPT (siginfo.si_code)
2598               && GDB_ARCH_IS_TRAP_HWBKPT (siginfo.si_code))
2599             {
2600               /* The si_code is ambiguous on this arch -- check debug
2601                  registers.  */
2602               if (!check_stopped_by_watchpoint (lp))
2603                 lp->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
2604             }
2605           else if (GDB_ARCH_IS_TRAP_BRKPT (siginfo.si_code))
2606             {
2607               /* If we determine the LWP stopped for a SW breakpoint,
2608                  trust it.  Particularly don't check watchpoint
2609                  registers, because at least on s390, we'd find
2610                  stopped-by-watchpoint as long as there's a watchpoint
2611                  set.  */
2612               lp->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
2613             }
2614           else if (GDB_ARCH_IS_TRAP_HWBKPT (siginfo.si_code))
2615             {
2616               /* This can indicate either a hardware breakpoint or
2617                  hardware watchpoint.  Check debug registers.  */
2618               if (!check_stopped_by_watchpoint (lp))
2619                 lp->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
2620             }
2621           else if (siginfo.si_code == TRAP_TRACE)
2622             {
2623               if (debug_linux_nat)
2624                 fprintf_unfiltered (gdb_stdlog,
2625                                     "CSBB: %s stopped by trace\n",
2626                                     target_pid_to_str (lp->ptid));
2627
2628               /* We may have single stepped an instruction that
2629                  triggered a watchpoint.  In that case, on some
2630                  architectures (such as x86), instead of TRAP_HWBKPT,
2631                  si_code indicates TRAP_TRACE, and we need to check
2632                  the debug registers separately.  */
2633               check_stopped_by_watchpoint (lp);
2634             }
2635         }
2636     }
2637 #else
2638   if ((!lp->step || lp->stop_pc == sw_bp_pc)
2639       && software_breakpoint_inserted_here_p (get_regcache_aspace (regcache),
2640                                               sw_bp_pc))
2641     {
2642       /* The LWP was either continued, or stepped a software
2643          breakpoint instruction.  */
2644       lp->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
2645     }
2646
2647   if (hardware_breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
2648     lp->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
2649
2650   if (lp->stop_reason == TARGET_STOPPED_BY_NO_REASON)
2651     check_stopped_by_watchpoint (lp);
2652 #endif
2653
2654   if (lp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT)
2655     {
2656       if (debug_linux_nat)
2657         fprintf_unfiltered (gdb_stdlog,
2658                             "CSBB: %s stopped by software breakpoint\n",
2659                             target_pid_to_str (lp->ptid));
2660
2661       /* Back up the PC if necessary.  */
2662       if (pc != sw_bp_pc)
2663         regcache_write_pc (regcache, sw_bp_pc);
2664
2665       /* Update this so we record the correct stop PC below.  */
2666       pc = sw_bp_pc;
2667     }
2668   else if (lp->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT)
2669     {
2670       if (debug_linux_nat)
2671         fprintf_unfiltered (gdb_stdlog,
2672                             "CSBB: %s stopped by hardware breakpoint\n",
2673                             target_pid_to_str (lp->ptid));
2674     }
2675   else if (lp->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
2676     {
2677       if (debug_linux_nat)
2678         fprintf_unfiltered (gdb_stdlog,
2679                             "CSBB: %s stopped by hardware watchpoint\n",
2680                             target_pid_to_str (lp->ptid));
2681     }
2682
2683   lp->stop_pc = pc;
2684 }
2685
2686
2687 /* Returns true if the LWP had stopped for a software breakpoint.  */
2688
2689 static int
2690 linux_nat_stopped_by_sw_breakpoint (struct target_ops *ops)
2691 {
2692   struct lwp_info *lp = find_lwp_pid (inferior_ptid);
2693
2694   gdb_assert (lp != NULL);
2695
2696   return lp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
2697 }
2698
2699 /* Implement the supports_stopped_by_sw_breakpoint method.  */
2700
2701 static int
2702 linux_nat_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
2703 {
2704   return USE_SIGTRAP_SIGINFO;
2705 }
2706
2707 /* Returns true if the LWP had stopped for a hardware
2708    breakpoint/watchpoint.  */
2709
2710 static int
2711 linux_nat_stopped_by_hw_breakpoint (struct target_ops *ops)
2712 {
2713   struct lwp_info *lp = find_lwp_pid (inferior_ptid);
2714
2715   gdb_assert (lp != NULL);
2716
2717   return lp->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
2718 }
2719
2720 /* Implement the supports_stopped_by_hw_breakpoint method.  */
2721
2722 static int
2723 linux_nat_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
2724 {
2725   return USE_SIGTRAP_SIGINFO;
2726 }
2727
2728 /* Select one LWP out of those that have events pending.  */
2729
2730 static void
2731 select_event_lwp (ptid_t filter, struct lwp_info **orig_lp, int *status)
2732 {
2733   int num_events = 0;
2734   int random_selector;
2735   struct lwp_info *event_lp = NULL;
2736
2737   /* Record the wait status for the original LWP.  */
2738   (*orig_lp)->status = *status;
2739
2740   /* In all-stop, give preference to the LWP that is being
2741      single-stepped.  There will be at most one, and it will be the
2742      LWP that the core is most interested in.  If we didn't do this,
2743      then we'd have to handle pending step SIGTRAPs somehow in case
2744      the core later continues the previously-stepped thread, as
2745      otherwise we'd report the pending SIGTRAP then, and the core, not
2746      having stepped the thread, wouldn't understand what the trap was
2747      for, and therefore would report it to the user as a random
2748      signal.  */
2749   if (!target_is_non_stop_p ())
2750     {
2751       event_lp = iterate_over_lwps (filter,
2752                                     select_singlestep_lwp_callback, NULL);
2753       if (event_lp != NULL)
2754         {
2755           if (debug_linux_nat)
2756             fprintf_unfiltered (gdb_stdlog,
2757                                 "SEL: Select single-step %s\n",
2758                                 target_pid_to_str (event_lp->ptid));
2759         }
2760     }
2761
2762   if (event_lp == NULL)
2763     {
2764       /* Pick one at random, out of those which have had events.  */
2765
2766       /* First see how many events we have.  */
2767       iterate_over_lwps (filter, count_events_callback, &num_events);
2768       gdb_assert (num_events > 0);
2769
2770       /* Now randomly pick a LWP out of those that have had
2771          events.  */
2772       random_selector = (int)
2773         ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
2774
2775       if (debug_linux_nat && num_events > 1)
2776         fprintf_unfiltered (gdb_stdlog,
2777                             "SEL: Found %d events, selecting #%d\n",
2778                             num_events, random_selector);
2779
2780       event_lp = iterate_over_lwps (filter,
2781                                     select_event_lwp_callback,
2782                                     &random_selector);
2783     }
2784
2785   if (event_lp != NULL)
2786     {
2787       /* Switch the event LWP.  */
2788       *orig_lp = event_lp;
2789       *status = event_lp->status;
2790     }
2791
2792   /* Flush the wait status for the event LWP.  */
2793   (*orig_lp)->status = 0;
2794 }
2795
2796 /* Return non-zero if LP has been resumed.  */
2797
2798 static int
2799 resumed_callback (struct lwp_info *lp, void *data)
2800 {
2801   return lp->resumed;
2802 }
2803
2804 /* Check if we should go on and pass this event to common code.
2805    Return the affected lwp if we are, or NULL otherwise.  */
2806
2807 static struct lwp_info *
2808 linux_nat_filter_event (int lwpid, int status)
2809 {
2810   struct lwp_info *lp;
2811   int event = linux_ptrace_get_extended_event (status);
2812
2813   lp = find_lwp_pid (pid_to_ptid (lwpid));
2814
2815   /* Check for stop events reported by a process we didn't already
2816      know about - anything not already in our LWP list.
2817
2818      If we're expecting to receive stopped processes after
2819      fork, vfork, and clone events, then we'll just add the
2820      new one to our list and go back to waiting for the event
2821      to be reported - the stopped process might be returned
2822      from waitpid before or after the event is.
2823
2824      But note the case of a non-leader thread exec'ing after the
2825      leader having exited, and gone from our lists.  The non-leader
2826      thread changes its tid to the tgid.  */
2827
2828   if (WIFSTOPPED (status) && lp == NULL
2829       && (WSTOPSIG (status) == SIGTRAP && event == PTRACE_EVENT_EXEC))
2830     {
2831       /* A multi-thread exec after we had seen the leader exiting.  */
2832       if (debug_linux_nat)
2833         fprintf_unfiltered (gdb_stdlog,
2834                             "LLW: Re-adding thread group leader LWP %d.\n",
2835                             lwpid);
2836
2837       lp = add_lwp (ptid_build (lwpid, lwpid, 0));
2838       lp->stopped = 1;
2839       lp->resumed = 1;
2840       add_thread (lp->ptid);
2841     }
2842
2843   if (WIFSTOPPED (status) && !lp)
2844     {
2845       if (debug_linux_nat)
2846         fprintf_unfiltered (gdb_stdlog,
2847                             "LHEW: saving LWP %ld status %s in stopped_pids list\n",
2848                             (long) lwpid, status_to_str (status));
2849       add_to_pid_list (&stopped_pids, lwpid, status);
2850       return NULL;
2851     }
2852
2853   /* Make sure we don't report an event for the exit of an LWP not in
2854      our list, i.e. not part of the current process.  This can happen
2855      if we detach from a program we originally forked and then it
2856      exits.  */
2857   if (!WIFSTOPPED (status) && !lp)
2858     return NULL;
2859
2860   /* This LWP is stopped now.  (And if dead, this prevents it from
2861      ever being continued.)  */
2862   lp->stopped = 1;
2863
2864   if (WIFSTOPPED (status) && lp->must_set_ptrace_flags)
2865     {
2866       struct inferior *inf = find_inferior_pid (ptid_get_pid (lp->ptid));
2867       int options = linux_nat_ptrace_options (inf->attach_flag);
2868
2869       linux_enable_event_reporting (ptid_get_lwp (lp->ptid), options);
2870       lp->must_set_ptrace_flags = 0;
2871     }
2872
2873   /* Handle GNU/Linux's syscall SIGTRAPs.  */
2874   if (WIFSTOPPED (status) && WSTOPSIG (status) == SYSCALL_SIGTRAP)
2875     {
2876       /* No longer need the sysgood bit.  The ptrace event ends up
2877          recorded in lp->waitstatus if we care for it.  We can carry
2878          on handling the event like a regular SIGTRAP from here
2879          on.  */
2880       status = W_STOPCODE (SIGTRAP);
2881       if (linux_handle_syscall_trap (lp, 0))
2882         return NULL;
2883     }
2884   else
2885     {
2886       /* Almost all other ptrace-stops are known to be outside of system
2887          calls, with further exceptions in linux_handle_extended_wait.  */
2888       lp->syscall_state = TARGET_WAITKIND_IGNORE;
2889     }
2890
2891   /* Handle GNU/Linux's extended waitstatus for trace events.  */
2892   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP
2893       && linux_is_extended_waitstatus (status))
2894     {
2895       if (debug_linux_nat)
2896         fprintf_unfiltered (gdb_stdlog,
2897                             "LLW: Handling extended status 0x%06x\n",
2898                             status);
2899       if (linux_handle_extended_wait (lp, status))
2900         return NULL;
2901     }
2902
2903   /* Check if the thread has exited.  */
2904   if (WIFEXITED (status) || WIFSIGNALED (status))
2905     {
2906       if (num_lwps (ptid_get_pid (lp->ptid)) > 1)
2907         {
2908           if (debug_linux_nat)
2909             fprintf_unfiltered (gdb_stdlog,
2910                                 "LLW: %s exited.\n",
2911                                 target_pid_to_str (lp->ptid));
2912
2913           /* If there is at least one more LWP, then the exit signal
2914              was not the end of the debugged application and should be
2915              ignored.  */
2916           exit_lwp (lp);
2917           return NULL;
2918         }
2919
2920       /* Note that even if the leader was ptrace-stopped, it can still
2921          exit, if e.g., some other thread brings down the whole
2922          process (calls `exit').  So don't assert that the lwp is
2923          resumed.  */
2924       if (debug_linux_nat)
2925         fprintf_unfiltered (gdb_stdlog,
2926                             "Process %ld exited (resumed=%d)\n",
2927                             ptid_get_lwp (lp->ptid), lp->resumed);
2928
2929       /* This was the last lwp in the process.  Since events are
2930          serialized to GDB core, we may not be able report this one
2931          right now, but GDB core and the other target layers will want
2932          to be notified about the exit code/signal, leave the status
2933          pending for the next time we're able to report it.  */
2934
2935       /* Dead LWP's aren't expected to reported a pending sigstop.  */
2936       lp->signalled = 0;
2937
2938       /* Store the pending event in the waitstatus, because
2939          W_EXITCODE(0,0) == 0.  */
2940       store_waitstatus (&lp->waitstatus, status);
2941       return lp;
2942     }
2943
2944   /* Make sure we don't report a SIGSTOP that we sent ourselves in
2945      an attempt to stop an LWP.  */
2946   if (lp->signalled
2947       && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2948     {
2949       lp->signalled = 0;
2950
2951       if (lp->last_resume_kind == resume_stop)
2952         {
2953           if (debug_linux_nat)
2954             fprintf_unfiltered (gdb_stdlog,
2955                                 "LLW: resume_stop SIGSTOP caught for %s.\n",
2956                                 target_pid_to_str (lp->ptid));
2957         }
2958       else
2959         {
2960           /* This is a delayed SIGSTOP.  Filter out the event.  */
2961
2962           if (debug_linux_nat)
2963             fprintf_unfiltered (gdb_stdlog,
2964                                 "LLW: %s %s, 0, 0 (discard delayed SIGSTOP)\n",
2965                                 lp->step ?
2966                                 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2967                                 target_pid_to_str (lp->ptid));
2968
2969           linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
2970           gdb_assert (lp->resumed);
2971           return NULL;
2972         }
2973     }
2974
2975   /* Make sure we don't report a SIGINT that we have already displayed
2976      for another thread.  */
2977   if (lp->ignore_sigint
2978       && WIFSTOPPED (status) && WSTOPSIG (status) == SIGINT)
2979     {
2980       if (debug_linux_nat)
2981         fprintf_unfiltered (gdb_stdlog,
2982                             "LLW: Delayed SIGINT caught for %s.\n",
2983                             target_pid_to_str (lp->ptid));
2984
2985       /* This is a delayed SIGINT.  */
2986       lp->ignore_sigint = 0;
2987
2988       linux_resume_one_lwp (lp, lp->step, GDB_SIGNAL_0);
2989       if (debug_linux_nat)
2990         fprintf_unfiltered (gdb_stdlog,
2991                             "LLW: %s %s, 0, 0 (discard SIGINT)\n",
2992                             lp->step ?
2993                             "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2994                             target_pid_to_str (lp->ptid));
2995       gdb_assert (lp->resumed);
2996
2997       /* Discard the event.  */
2998       return NULL;
2999     }
3000
3001   /* Don't report signals that GDB isn't interested in, such as
3002      signals that are neither printed nor stopped upon.  Stopping all
3003      threads can be a bit time-consuming so if we want decent
3004      performance with heavily multi-threaded programs, especially when
3005      they're using a high frequency timer, we'd better avoid it if we
3006      can.  */
3007   if (WIFSTOPPED (status))
3008     {
3009       enum gdb_signal signo = gdb_signal_from_host (WSTOPSIG (status));
3010
3011       if (!target_is_non_stop_p ())
3012         {
3013           /* Only do the below in all-stop, as we currently use SIGSTOP
3014              to implement target_stop (see linux_nat_stop) in
3015              non-stop.  */
3016           if (signo == GDB_SIGNAL_INT && signal_pass_state (signo) == 0)
3017             {
3018               /* If ^C/BREAK is typed at the tty/console, SIGINT gets
3019                  forwarded to the entire process group, that is, all LWPs
3020                  will receive it - unless they're using CLONE_THREAD to
3021                  share signals.  Since we only want to report it once, we
3022                  mark it as ignored for all LWPs except this one.  */
3023               iterate_over_lwps (pid_to_ptid (ptid_get_pid (lp->ptid)),
3024                                               set_ignore_sigint, NULL);
3025               lp->ignore_sigint = 0;
3026             }
3027           else
3028             maybe_clear_ignore_sigint (lp);
3029         }
3030
3031       /* When using hardware single-step, we need to report every signal.
3032          Otherwise, signals in pass_mask may be short-circuited
3033          except signals that might be caused by a breakpoint.  */
3034       if (!lp->step
3035           && WSTOPSIG (status) && sigismember (&pass_mask, WSTOPSIG (status))
3036           && !linux_wstatus_maybe_breakpoint (status))
3037         {
3038           linux_resume_one_lwp (lp, lp->step, signo);
3039           if (debug_linux_nat)
3040             fprintf_unfiltered (gdb_stdlog,
3041                                 "LLW: %s %s, %s (preempt 'handle')\n",
3042                                 lp->step ?
3043                                 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
3044                                 target_pid_to_str (lp->ptid),
3045                                 (signo != GDB_SIGNAL_0
3046                                  ? strsignal (gdb_signal_to_host (signo))
3047                                  : "0"));
3048           return NULL;
3049         }
3050     }
3051
3052   /* An interesting event.  */
3053   gdb_assert (lp);
3054   lp->status = status;
3055   save_stop_reason (lp);
3056   return lp;
3057 }
3058
3059 /* Detect zombie thread group leaders, and "exit" them.  We can't reap
3060    their exits until all other threads in the group have exited.  */
3061
3062 static void
3063 check_zombie_leaders (void)
3064 {
3065   struct inferior *inf;
3066
3067   ALL_INFERIORS (inf)
3068     {
3069       struct lwp_info *leader_lp;
3070
3071       if (inf->pid == 0)
3072         continue;
3073
3074       leader_lp = find_lwp_pid (pid_to_ptid (inf->pid));
3075       if (leader_lp != NULL
3076           /* Check if there are other threads in the group, as we may
3077              have raced with the inferior simply exiting.  */
3078           && num_lwps (inf->pid) > 1
3079           && linux_proc_pid_is_zombie (inf->pid))
3080         {
3081           if (debug_linux_nat)
3082             fprintf_unfiltered (gdb_stdlog,
3083                                 "CZL: Thread group leader %d zombie "
3084                                 "(it exited, or another thread execd).\n",
3085                                 inf->pid);
3086
3087           /* A leader zombie can mean one of two things:
3088
3089              - It exited, and there's an exit status pending
3090              available, or only the leader exited (not the whole
3091              program).  In the latter case, we can't waitpid the
3092              leader's exit status until all other threads are gone.
3093
3094              - There are 3 or more threads in the group, and a thread
3095              other than the leader exec'd.  See comments on exec
3096              events at the top of the file.  We could try
3097              distinguishing the exit and exec cases, by waiting once
3098              more, and seeing if something comes out, but it doesn't
3099              sound useful.  The previous leader _does_ go away, and
3100              we'll re-add the new one once we see the exec event
3101              (which is just the same as what would happen if the
3102              previous leader did exit voluntarily before some other
3103              thread execs).  */
3104
3105           if (debug_linux_nat)
3106             fprintf_unfiltered (gdb_stdlog,
3107                                 "CZL: Thread group leader %d vanished.\n",
3108                                 inf->pid);
3109           exit_lwp (leader_lp);
3110         }
3111     }
3112 }
3113
3114 static ptid_t
3115 linux_nat_wait_1 (struct target_ops *ops,
3116                   ptid_t ptid, struct target_waitstatus *ourstatus,
3117                   int target_options)
3118 {
3119   sigset_t prev_mask;
3120   enum resume_kind last_resume_kind;
3121   struct lwp_info *lp;
3122   int status;
3123
3124   if (debug_linux_nat)
3125     fprintf_unfiltered (gdb_stdlog, "LLW: enter\n");
3126
3127   /* The first time we get here after starting a new inferior, we may
3128      not have added it to the LWP list yet - this is the earliest
3129      moment at which we know its PID.  */
3130   if (ptid_is_pid (inferior_ptid))
3131     {
3132       /* Upgrade the main thread's ptid.  */
3133       thread_change_ptid (inferior_ptid,
3134                           ptid_build (ptid_get_pid (inferior_ptid),
3135                                       ptid_get_pid (inferior_ptid), 0));
3136
3137       lp = add_initial_lwp (inferior_ptid);
3138       lp->resumed = 1;
3139     }
3140
3141   /* Make sure SIGCHLD is blocked until the sigsuspend below.  */
3142   block_child_signals (&prev_mask);
3143
3144   /* First check if there is a LWP with a wait status pending.  */
3145   lp = iterate_over_lwps (ptid, status_callback, NULL);
3146   if (lp != NULL)
3147     {
3148       if (debug_linux_nat)
3149         fprintf_unfiltered (gdb_stdlog,
3150                             "LLW: Using pending wait status %s for %s.\n",
3151                             status_to_str (lp->status),
3152                             target_pid_to_str (lp->ptid));
3153     }
3154
3155   /* But if we don't find a pending event, we'll have to wait.  Always
3156      pull all events out of the kernel.  We'll randomly select an
3157      event LWP out of all that have events, to prevent starvation.  */
3158
3159   while (lp == NULL)
3160     {
3161       pid_t lwpid;
3162
3163       /* Always use -1 and WNOHANG, due to couple of a kernel/ptrace
3164          quirks:
3165
3166          - If the thread group leader exits while other threads in the
3167            thread group still exist, waitpid(TGID, ...) hangs.  That
3168            waitpid won't return an exit status until the other threads
3169            in the group are reapped.
3170
3171          - When a non-leader thread execs, that thread just vanishes
3172            without reporting an exit (so we'd hang if we waited for it
3173            explicitly in that case).  The exec event is reported to
3174            the TGID pid.  */
3175
3176       errno = 0;
3177       lwpid = my_waitpid (-1, &status,  __WALL | WNOHANG);
3178
3179       if (debug_linux_nat)
3180         fprintf_unfiltered (gdb_stdlog,
3181                             "LNW: waitpid(-1, ...) returned %d, %s\n",
3182                             lwpid, errno ? safe_strerror (errno) : "ERRNO-OK");
3183
3184       if (lwpid > 0)
3185         {
3186           if (debug_linux_nat)
3187             {
3188               fprintf_unfiltered (gdb_stdlog,
3189                                   "LLW: waitpid %ld received %s\n",
3190                                   (long) lwpid, status_to_str (status));
3191             }
3192
3193           linux_nat_filter_event (lwpid, status);
3194           /* Retry until nothing comes out of waitpid.  A single
3195              SIGCHLD can indicate more than one child stopped.  */
3196           continue;
3197         }
3198
3199       /* Now that we've pulled all events out of the kernel, resume
3200          LWPs that don't have an interesting event to report.  */
3201       iterate_over_lwps (minus_one_ptid,
3202                          resume_stopped_resumed_lwps, &minus_one_ptid);
3203
3204       /* ... and find an LWP with a status to report to the core, if
3205          any.  */
3206       lp = iterate_over_lwps (ptid, status_callback, NULL);
3207       if (lp != NULL)
3208         break;
3209
3210       /* Check for zombie thread group leaders.  Those can't be reaped
3211          until all other threads in the thread group are.  */
3212       check_zombie_leaders ();
3213
3214       /* If there are no resumed children left, bail.  We'd be stuck
3215          forever in the sigsuspend call below otherwise.  */
3216       if (iterate_over_lwps (ptid, resumed_callback, NULL) == NULL)
3217         {
3218           if (debug_linux_nat)
3219             fprintf_unfiltered (gdb_stdlog, "LLW: exit (no resumed LWP)\n");
3220
3221           ourstatus->kind = TARGET_WAITKIND_NO_RESUMED;
3222
3223           restore_child_signals_mask (&prev_mask);
3224           return minus_one_ptid;
3225         }
3226
3227       /* No interesting event to report to the core.  */
3228
3229       if (target_options & TARGET_WNOHANG)
3230         {
3231           if (debug_linux_nat)
3232             fprintf_unfiltered (gdb_stdlog, "LLW: exit (ignore)\n");
3233
3234           ourstatus->kind = TARGET_WAITKIND_IGNORE;
3235           restore_child_signals_mask (&prev_mask);
3236           return minus_one_ptid;
3237         }
3238
3239       /* We shouldn't end up here unless we want to try again.  */
3240       gdb_assert (lp == NULL);
3241
3242       /* Block until we get an event reported with SIGCHLD.  */
3243       if (debug_linux_nat)
3244         fprintf_unfiltered (gdb_stdlog, "LNW: about to sigsuspend\n");
3245       sigsuspend (&suspend_mask);
3246     }
3247
3248   gdb_assert (lp);
3249
3250   status = lp->status;
3251   lp->status = 0;
3252
3253   if (!target_is_non_stop_p ())
3254     {
3255       /* Now stop all other LWP's ...  */
3256       iterate_over_lwps (minus_one_ptid, stop_callback, NULL);
3257
3258       /* ... and wait until all of them have reported back that
3259          they're no longer running.  */
3260       iterate_over_lwps (minus_one_ptid, stop_wait_callback, NULL);
3261     }
3262
3263   /* If we're not waiting for a specific LWP, choose an event LWP from
3264      among those that have had events.  Giving equal priority to all
3265      LWPs that have had events helps prevent starvation.  */
3266   if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
3267     select_event_lwp (ptid, &lp, &status);
3268
3269   gdb_assert (lp != NULL);
3270
3271   /* Now that we've selected our final event LWP, un-adjust its PC if
3272      it was a software breakpoint, and we can't reliably support the
3273      "stopped by software breakpoint" stop reason.  */
3274   if (lp->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
3275       && !USE_SIGTRAP_SIGINFO)
3276     {
3277       struct regcache *regcache = get_thread_regcache (lp->ptid);
3278       struct gdbarch *gdbarch = get_regcache_arch (regcache);
3279       int decr_pc = gdbarch_decr_pc_after_break (gdbarch);
3280
3281       if (decr_pc != 0)
3282         {
3283           CORE_ADDR pc;
3284
3285           pc = regcache_read_pc (regcache);
3286           regcache_write_pc (regcache, pc + decr_pc);
3287         }
3288     }
3289
3290   /* We'll need this to determine whether to report a SIGSTOP as
3291      GDB_SIGNAL_0.  Need to take a copy because resume_clear_callback
3292      clears it.  */
3293   last_resume_kind = lp->last_resume_kind;
3294
3295   if (!target_is_non_stop_p ())
3296     {
3297       /* In all-stop, from the core's perspective, all LWPs are now
3298          stopped until a new resume action is sent over.  */
3299       iterate_over_lwps (minus_one_ptid, resume_clear_callback, NULL);
3300     }
3301   else
3302     {
3303       resume_clear_callback (lp, NULL);
3304     }
3305
3306   if (linux_nat_status_is_event (status))
3307     {
3308       if (debug_linux_nat)
3309         fprintf_unfiltered (gdb_stdlog,
3310                             "LLW: trap ptid is %s.\n",
3311                             target_pid_to_str (lp->ptid));
3312     }
3313
3314   if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
3315     {
3316       *ourstatus = lp->waitstatus;
3317       lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
3318     }
3319   else
3320     store_waitstatus (ourstatus, status);
3321
3322   if (debug_linux_nat)
3323     fprintf_unfiltered (gdb_stdlog, "LLW: exit\n");
3324
3325   restore_child_signals_mask (&prev_mask);
3326
3327   if (last_resume_kind == resume_stop
3328       && ourstatus->kind == TARGET_WAITKIND_STOPPED
3329       && WSTOPSIG (status) == SIGSTOP)
3330     {
3331       /* A thread that has been requested to stop by GDB with
3332          target_stop, and it stopped cleanly, so report as SIG0.  The
3333          use of SIGSTOP is an implementation detail.  */
3334       ourstatus->value.sig = GDB_SIGNAL_0;
3335     }
3336
3337   if (ourstatus->kind == TARGET_WAITKIND_EXITED
3338       || ourstatus->kind == TARGET_WAITKIND_SIGNALLED)
3339     lp->core = -1;
3340   else
3341     lp->core = linux_common_core_of_thread (lp->ptid);
3342
3343   return lp->ptid;
3344 }
3345
3346 /* Resume LWPs that are currently stopped without any pending status
3347    to report, but are resumed from the core's perspective.  */
3348
3349 static int
3350 resume_stopped_resumed_lwps (struct lwp_info *lp, void *data)
3351 {
3352   ptid_t *wait_ptid_p = (ptid_t *) data;
3353
3354   if (!lp->stopped)
3355     {
3356       if (debug_linux_nat)
3357         fprintf_unfiltered (gdb_stdlog,
3358                             "RSRL: NOT resuming LWP %s, not stopped\n",
3359                             target_pid_to_str (lp->ptid));
3360     }
3361   else if (!lp->resumed)
3362     {
3363       if (debug_linux_nat)
3364         fprintf_unfiltered (gdb_stdlog,
3365                             "RSRL: NOT resuming LWP %s, not resumed\n",
3366                             target_pid_to_str (lp->ptid));
3367     }
3368   else if (lwp_status_pending_p (lp))
3369     {
3370       if (debug_linux_nat)
3371         fprintf_unfiltered (gdb_stdlog,
3372                             "RSRL: NOT resuming LWP %s, has pending status\n",
3373                             target_pid_to_str (lp->ptid));
3374     }
3375   else
3376     {
3377       struct regcache *regcache = get_thread_regcache (lp->ptid);
3378       struct gdbarch *gdbarch = get_regcache_arch (regcache);
3379
3380       TRY
3381         {
3382           CORE_ADDR pc = regcache_read_pc (regcache);
3383           int leave_stopped = 0;
3384
3385           /* Don't bother if there's a breakpoint at PC that we'd hit
3386              immediately, and we're not waiting for this LWP.  */
3387           if (!ptid_match (lp->ptid, *wait_ptid_p))
3388             {
3389               if (breakpoint_inserted_here_p (get_regcache_aspace (regcache), pc))
3390                 leave_stopped = 1;
3391             }
3392
3393           if (!leave_stopped)
3394             {
3395               if (debug_linux_nat)
3396                 fprintf_unfiltered (gdb_stdlog,
3397                                     "RSRL: resuming stopped-resumed LWP %s at "
3398                                     "%s: step=%d\n",
3399                                     target_pid_to_str (lp->ptid),
3400                                     paddress (gdbarch, pc),
3401                                     lp->step);
3402
3403               linux_resume_one_lwp_throw (lp, lp->step, GDB_SIGNAL_0);
3404             }
3405         }
3406       CATCH (ex, RETURN_MASK_ERROR)
3407         {
3408           if (!check_ptrace_stopped_lwp_gone (lp))
3409             throw_exception (ex);
3410         }
3411       END_CATCH
3412     }
3413
3414   return 0;
3415 }
3416
3417 static ptid_t
3418 linux_nat_wait (struct target_ops *ops,
3419                 ptid_t ptid, struct target_waitstatus *ourstatus,
3420                 int target_options)
3421 {
3422   ptid_t event_ptid;
3423
3424   if (debug_linux_nat)
3425     {
3426       char *options_string;
3427
3428       options_string = target_options_to_string (target_options);
3429       fprintf_unfiltered (gdb_stdlog,
3430                           "linux_nat_wait: [%s], [%s]\n",
3431                           target_pid_to_str (ptid),
3432                           options_string);
3433       xfree (options_string);
3434     }
3435
3436   /* Flush the async file first.  */
3437   if (target_is_async_p ())
3438     async_file_flush ();
3439
3440   /* Resume LWPs that are currently stopped without any pending status
3441      to report, but are resumed from the core's perspective.  LWPs get
3442      in this state if we find them stopping at a time we're not
3443      interested in reporting the event (target_wait on a
3444      specific_process, for example, see linux_nat_wait_1), and
3445      meanwhile the event became uninteresting.  Don't bother resuming
3446      LWPs we're not going to wait for if they'd stop immediately.  */
3447   if (target_is_non_stop_p ())
3448     iterate_over_lwps (minus_one_ptid, resume_stopped_resumed_lwps, &ptid);
3449
3450   event_ptid = linux_nat_wait_1 (ops, ptid, ourstatus, target_options);
3451
3452   /* If we requested any event, and something came out, assume there
3453      may be more.  If we requested a specific lwp or process, also
3454      assume there may be more.  */
3455   if (target_is_async_p ()
3456       && ((ourstatus->kind != TARGET_WAITKIND_IGNORE
3457            && ourstatus->kind != TARGET_WAITKIND_NO_RESUMED)
3458           || !ptid_equal (ptid, minus_one_ptid)))
3459     async_file_mark ();
3460
3461   return event_ptid;
3462 }
3463
3464 /* Kill one LWP.  */
3465
3466 static void
3467 kill_one_lwp (pid_t pid)
3468 {
3469   /* PTRACE_KILL may resume the inferior.  Send SIGKILL first.  */
3470
3471   errno = 0;
3472   kill_lwp (pid, SIGKILL);
3473   if (debug_linux_nat)
3474     {
3475       int save_errno = errno;
3476
3477       fprintf_unfiltered (gdb_stdlog,
3478                           "KC:  kill (SIGKILL) %ld, 0, 0 (%s)\n", (long) pid,
3479                           save_errno ? safe_strerror (save_errno) : "OK");
3480     }
3481
3482   /* Some kernels ignore even SIGKILL for processes under ptrace.  */
3483
3484   errno = 0;
3485   ptrace (PTRACE_KILL, pid, 0, 0);
3486   if (debug_linux_nat)
3487     {
3488       int save_errno = errno;
3489
3490       fprintf_unfiltered (gdb_stdlog,
3491                           "KC:  PTRACE_KILL %ld, 0, 0 (%s)\n", (long) pid,
3492                           save_errno ? safe_strerror (save_errno) : "OK");
3493     }
3494 }
3495
3496 /* Wait for an LWP to die.  */
3497
3498 static void
3499 kill_wait_one_lwp (pid_t pid)
3500 {
3501   pid_t res;
3502
3503   /* We must make sure that there are no pending events (delayed
3504      SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
3505      program doesn't interfere with any following debugging session.  */
3506
3507   do
3508     {
3509       res = my_waitpid (pid, NULL, __WALL);
3510       if (res != (pid_t) -1)
3511         {
3512           if (debug_linux_nat)
3513             fprintf_unfiltered (gdb_stdlog,
3514                                 "KWC: wait %ld received unknown.\n",
3515                                 (long) pid);
3516           /* The Linux kernel sometimes fails to kill a thread
3517              completely after PTRACE_KILL; that goes from the stop
3518              point in do_fork out to the one in get_signal_to_deliver
3519              and waits again.  So kill it again.  */
3520           kill_one_lwp (pid);
3521         }
3522     }
3523   while (res == pid);
3524
3525   gdb_assert (res == -1 && errno == ECHILD);
3526 }
3527
3528 /* Callback for iterate_over_lwps.  */
3529
3530 static int
3531 kill_callback (struct lwp_info *lp, void *data)
3532 {
3533   kill_one_lwp (ptid_get_lwp (lp->ptid));
3534   return 0;
3535 }
3536
3537 /* Callback for iterate_over_lwps.  */
3538
3539 static int
3540 kill_wait_callback (struct lwp_info *lp, void *data)
3541 {
3542   kill_wait_one_lwp (ptid_get_lwp (lp->ptid));
3543   return 0;
3544 }
3545
3546 /* Kill the fork children of any threads of inferior INF that are
3547    stopped at a fork event.  */
3548
3549 static void
3550 kill_unfollowed_fork_children (struct inferior *inf)
3551 {
3552   struct thread_info *thread;
3553
3554   ALL_NON_EXITED_THREADS (thread)
3555     if (thread->inf == inf)
3556       {
3557         struct target_waitstatus *ws = &thread->pending_follow;
3558
3559         if (ws->kind == TARGET_WAITKIND_FORKED
3560             || ws->kind == TARGET_WAITKIND_VFORKED)
3561           {
3562             ptid_t child_ptid = ws->value.related_pid;
3563             int child_pid = ptid_get_pid (child_ptid);
3564             int child_lwp = ptid_get_lwp (child_ptid);
3565             int status;
3566
3567             kill_one_lwp (child_lwp);
3568             kill_wait_one_lwp (child_lwp);
3569
3570             /* Let the arch-specific native code know this process is
3571                gone.  */
3572             linux_nat_forget_process (child_pid);
3573           }
3574       }
3575 }
3576
3577 static void
3578 linux_nat_kill (struct target_ops *ops)
3579 {
3580   struct target_waitstatus last;
3581
3582   /* If we're stopped while forking and we haven't followed yet,
3583      kill the other task.  We need to do this first because the
3584      parent will be sleeping if this is a vfork.  */
3585   kill_unfollowed_fork_children (current_inferior ());
3586
3587   if (forks_exist_p ())
3588     linux_fork_killall ();
3589   else
3590     {
3591       ptid_t ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
3592
3593       /* Stop all threads before killing them, since ptrace requires
3594          that the thread is stopped to sucessfully PTRACE_KILL.  */
3595       iterate_over_lwps (ptid, stop_callback, NULL);
3596       /* ... and wait until all of them have reported back that
3597          they're no longer running.  */
3598       iterate_over_lwps (ptid, stop_wait_callback, NULL);
3599
3600       /* Kill all LWP's ...  */
3601       iterate_over_lwps (ptid, kill_callback, NULL);
3602
3603       /* ... and wait until we've flushed all events.  */
3604       iterate_over_lwps (ptid, kill_wait_callback, NULL);
3605     }
3606
3607   target_mourn_inferior ();
3608 }
3609
3610 static void
3611 linux_nat_mourn_inferior (struct target_ops *ops)
3612 {
3613   int pid = ptid_get_pid (inferior_ptid);
3614
3615   purge_lwp_list (pid);
3616
3617   if (! forks_exist_p ())
3618     /* Normal case, no other forks available.  */
3619     linux_ops->to_mourn_inferior (ops);
3620   else
3621     /* Multi-fork case.  The current inferior_ptid has exited, but
3622        there are other viable forks to debug.  Delete the exiting
3623        one and context-switch to the first available.  */
3624     linux_fork_mourn_inferior ();
3625
3626   /* Let the arch-specific native code know this process is gone.  */
3627   linux_nat_forget_process (pid);
3628 }
3629
3630 /* Convert a native/host siginfo object, into/from the siginfo in the
3631    layout of the inferiors' architecture.  */
3632
3633 static void
3634 siginfo_fixup (siginfo_t *siginfo, gdb_byte *inf_siginfo, int direction)
3635 {
3636   int done = 0;
3637
3638   if (linux_nat_siginfo_fixup != NULL)
3639     done = linux_nat_siginfo_fixup (siginfo, inf_siginfo, direction);
3640
3641   /* If there was no callback, or the callback didn't do anything,
3642      then just do a straight memcpy.  */
3643   if (!done)
3644     {
3645       if (direction == 1)
3646         memcpy (siginfo, inf_siginfo, sizeof (siginfo_t));
3647       else
3648         memcpy (inf_siginfo, siginfo, sizeof (siginfo_t));
3649     }
3650 }
3651
3652 static enum target_xfer_status
3653 linux_xfer_siginfo (struct target_ops *ops, enum target_object object,
3654                     const char *annex, gdb_byte *readbuf,
3655                     const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
3656                     ULONGEST *xfered_len)
3657 {
3658   int pid;
3659   siginfo_t siginfo;
3660   gdb_byte inf_siginfo[sizeof (siginfo_t)];
3661
3662   gdb_assert (object == TARGET_OBJECT_SIGNAL_INFO);
3663   gdb_assert (readbuf || writebuf);
3664
3665   pid = ptid_get_lwp (inferior_ptid);
3666   if (pid == 0)
3667     pid = ptid_get_pid (inferior_ptid);
3668
3669   if (offset > sizeof (siginfo))
3670     return TARGET_XFER_E_IO;
3671
3672   errno = 0;
3673   ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
3674   if (errno != 0)
3675     return TARGET_XFER_E_IO;
3676
3677   /* When GDB is built as a 64-bit application, ptrace writes into
3678      SIGINFO an object with 64-bit layout.  Since debugging a 32-bit
3679      inferior with a 64-bit GDB should look the same as debugging it
3680      with a 32-bit GDB, we need to convert it.  GDB core always sees
3681      the converted layout, so any read/write will have to be done
3682      post-conversion.  */
3683   siginfo_fixup (&siginfo, inf_siginfo, 0);
3684
3685   if (offset + len > sizeof (siginfo))
3686     len = sizeof (siginfo) - offset;
3687
3688   if (readbuf != NULL)
3689     memcpy (readbuf, inf_siginfo + offset, len);
3690   else
3691     {
3692       memcpy (inf_siginfo + offset, writebuf, len);
3693
3694       /* Convert back to ptrace layout before flushing it out.  */
3695       siginfo_fixup (&siginfo, inf_siginfo, 1);
3696
3697       errno = 0;
3698       ptrace (PTRACE_SETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, &siginfo);
3699       if (errno != 0)
3700         return TARGET_XFER_E_IO;
3701     }
3702
3703   *xfered_len = len;
3704   return TARGET_XFER_OK;
3705 }
3706
3707 static enum target_xfer_status
3708 linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
3709                         const char *annex, gdb_byte *readbuf,
3710                         const gdb_byte *writebuf,
3711                         ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
3712 {
3713   struct cleanup *old_chain;
3714   enum target_xfer_status xfer;
3715
3716   if (object == TARGET_OBJECT_SIGNAL_INFO)
3717     return linux_xfer_siginfo (ops, object, annex, readbuf, writebuf,
3718                                offset, len, xfered_len);
3719
3720   /* The target is connected but no live inferior is selected.  Pass
3721      this request down to a lower stratum (e.g., the executable
3722      file).  */
3723   if (object == TARGET_OBJECT_MEMORY && ptid_equal (inferior_ptid, null_ptid))
3724     return TARGET_XFER_EOF;
3725
3726   old_chain = save_inferior_ptid ();
3727
3728   if (ptid_lwp_p (inferior_ptid))
3729     inferior_ptid = pid_to_ptid (ptid_get_lwp (inferior_ptid));
3730
3731   xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
3732                                      offset, len, xfered_len);
3733
3734   do_cleanups (old_chain);
3735   return xfer;
3736 }
3737
3738 static int
3739 linux_nat_thread_alive (struct target_ops *ops, ptid_t ptid)
3740 {
3741   /* As long as a PTID is in lwp list, consider it alive.  */
3742   return find_lwp_pid (ptid) != NULL;
3743 }
3744
3745 /* Implement the to_update_thread_list target method for this
3746    target.  */
3747
3748 static void
3749 linux_nat_update_thread_list (struct target_ops *ops)
3750 {
3751   struct lwp_info *lwp;
3752
3753   /* We add/delete threads from the list as clone/exit events are
3754      processed, so just try deleting exited threads still in the
3755      thread list.  */
3756   delete_exited_threads ();
3757
3758   /* Update the processor core that each lwp/thread was last seen
3759      running on.  */
3760   ALL_LWPS (lwp)
3761     lwp->core = linux_common_core_of_thread (lwp->ptid);
3762 }
3763
3764 static char *
3765 linux_nat_pid_to_str (struct target_ops *ops, ptid_t ptid)
3766 {
3767   static char buf[64];
3768
3769   if (ptid_lwp_p (ptid)
3770       && (ptid_get_pid (ptid) != ptid_get_lwp (ptid)
3771           || num_lwps (ptid_get_pid (ptid)) > 1))
3772     {
3773       snprintf (buf, sizeof (buf), "LWP %ld", ptid_get_lwp (ptid));
3774       return buf;
3775     }
3776
3777   return normal_pid_to_str (ptid);
3778 }
3779
3780 static const char *
3781 linux_nat_thread_name (struct target_ops *self, struct thread_info *thr)
3782 {
3783   return linux_proc_tid_get_name (thr->ptid);
3784 }
3785
3786 /* Accepts an integer PID; Returns a string representing a file that
3787    can be opened to get the symbols for the child process.  */
3788
3789 static char *
3790 linux_child_pid_to_exec_file (struct target_ops *self, int pid)
3791 {
3792   return linux_proc_pid_to_exec_file (pid);
3793 }
3794
3795 /* Implement the to_xfer_partial interface for memory reads using the /proc
3796    filesystem.  Because we can use a single read() call for /proc, this
3797    can be much more efficient than banging away at PTRACE_PEEKTEXT,
3798    but it doesn't support writes.  */
3799
3800 static enum target_xfer_status
3801 linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
3802                          const char *annex, gdb_byte *readbuf,
3803                          const gdb_byte *writebuf,
3804                          ULONGEST offset, LONGEST len, ULONGEST *xfered_len)
3805 {
3806   LONGEST ret;
3807   int fd;
3808   char filename[64];
3809
3810   if (object != TARGET_OBJECT_MEMORY || !readbuf)
3811     return TARGET_XFER_EOF;
3812
3813   /* Don't bother for one word.  */
3814   if (len < 3 * sizeof (long))
3815     return TARGET_XFER_EOF;
3816
3817   /* We could keep this file open and cache it - possibly one per
3818      thread.  That requires some juggling, but is even faster.  */
3819   xsnprintf (filename, sizeof filename, "/proc/%d/mem",
3820              ptid_get_pid (inferior_ptid));
3821   fd = gdb_open_cloexec (filename, O_RDONLY | O_LARGEFILE, 0);
3822   if (fd == -1)
3823     return TARGET_XFER_EOF;
3824
3825   /* If pread64 is available, use it.  It's faster if the kernel
3826      supports it (only one syscall), and it's 64-bit safe even on
3827      32-bit platforms (for instance, SPARC debugging a SPARC64
3828      application).  */
3829 #ifdef HAVE_PREAD64
3830   if (pread64 (fd, readbuf, len, offset) != len)
3831 #else
3832   if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
3833 #endif
3834     ret = 0;
3835   else
3836     ret = len;
3837
3838   close (fd);
3839
3840   if (ret == 0)
3841     return TARGET_XFER_EOF;
3842   else
3843     {
3844       *xfered_len = ret;
3845       return TARGET_XFER_OK;
3846     }
3847 }
3848
3849
3850 /* Enumerate spufs IDs for process PID.  */
3851 static LONGEST
3852 spu_enumerate_spu_ids (int pid, gdb_byte *buf, ULONGEST offset, ULONGEST len)
3853 {
3854   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
3855   LONGEST pos = 0;
3856   LONGEST written = 0;
3857   char path[128];
3858   DIR *dir;
3859   struct dirent *entry;
3860
3861   xsnprintf (path, sizeof path, "/proc/%d/fd", pid);
3862   dir = opendir (path);
3863   if (!dir)
3864     return -1;
3865
3866   rewinddir (dir);
3867   while ((entry = readdir (dir)) != NULL)
3868     {
3869       struct stat st;
3870       struct statfs stfs;
3871       int fd;
3872
3873       fd = atoi (entry->d_name);
3874       if (!fd)
3875         continue;
3876
3877       xsnprintf (path, sizeof path, "/proc/%d/fd/%d", pid, fd);
3878       if (stat (path, &st) != 0)
3879         continue;
3880       if (!S_ISDIR (st.st_mode))
3881         continue;
3882
3883       if (statfs (path, &stfs) != 0)
3884         continue;
3885       if (stfs.f_type != SPUFS_MAGIC)
3886         continue;
3887
3888       if (pos >= offset && pos + 4 <= offset + len)
3889         {
3890           store_unsigned_integer (buf + pos - offset, 4, byte_order, fd);
3891           written += 4;
3892         }
3893       pos += 4;
3894     }
3895
3896   closedir (dir);
3897   return written;
3898 }
3899
3900 /* Implement the to_xfer_partial interface for the TARGET_OBJECT_SPU
3901    object type, using the /proc file system.  */
3902
3903 static enum target_xfer_status
3904 linux_proc_xfer_spu (struct target_ops *ops, enum target_object object,
3905                      const char *annex, gdb_byte *readbuf,
3906                      const gdb_byte *writebuf,
3907                      ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
3908 {
3909   char buf[128];
3910   int fd = 0;
3911   int ret = -1;
3912   int pid = ptid_get_pid (inferior_ptid);
3913
3914   if (!annex)
3915     {
3916       if (!readbuf)
3917         return TARGET_XFER_E_IO;
3918       else
3919         {
3920           LONGEST l = spu_enumerate_spu_ids (pid, readbuf, offset, len);
3921
3922           if (l < 0)
3923             return TARGET_XFER_E_IO;
3924           else if (l == 0)
3925             return TARGET_XFER_EOF;
3926           else
3927             {
3928               *xfered_len = (ULONGEST) l;
3929               return TARGET_XFER_OK;
3930             }
3931         }
3932     }
3933
3934   xsnprintf (buf, sizeof buf, "/proc/%d/fd/%s", pid, annex);
3935   fd = gdb_open_cloexec (buf, writebuf? O_WRONLY : O_RDONLY, 0);
3936   if (fd <= 0)
3937     return TARGET_XFER_E_IO;
3938
3939   if (offset != 0
3940       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
3941     {
3942       close (fd);
3943       return TARGET_XFER_EOF;
3944     }
3945
3946   if (writebuf)
3947     ret = write (fd, writebuf, (size_t) len);
3948   else if (readbuf)
3949     ret = read (fd, readbuf, (size_t) len);
3950
3951   close (fd);
3952
3953   if (ret < 0)
3954     return TARGET_XFER_E_IO;
3955   else if (ret == 0)
3956     return TARGET_XFER_EOF;
3957   else
3958     {
3959       *xfered_len = (ULONGEST) ret;
3960       return TARGET_XFER_OK;
3961     }
3962 }
3963
3964
3965 /* Parse LINE as a signal set and add its set bits to SIGS.  */
3966
3967 static void
3968 add_line_to_sigset (const char *line, sigset_t *sigs)
3969 {
3970   int len = strlen (line) - 1;
3971   const char *p;
3972   int signum;
3973
3974   if (line[len] != '\n')
3975     error (_("Could not parse signal set: %s"), line);
3976
3977   p = line;
3978   signum = len * 4;
3979   while (len-- > 0)
3980     {
3981       int digit;
3982
3983       if (*p >= '0' && *p <= '9')
3984         digit = *p - '0';
3985       else if (*p >= 'a' && *p <= 'f')
3986         digit = *p - 'a' + 10;
3987       else
3988         error (_("Could not parse signal set: %s"), line);
3989
3990       signum -= 4;
3991
3992       if (digit & 1)
3993         sigaddset (sigs, signum + 1);
3994       if (digit & 2)
3995         sigaddset (sigs, signum + 2);
3996       if (digit & 4)
3997         sigaddset (sigs, signum + 3);
3998       if (digit & 8)
3999         sigaddset (sigs, signum + 4);
4000
4001       p++;
4002     }
4003 }
4004
4005 /* Find process PID's pending signals from /proc/pid/status and set
4006    SIGS to match.  */
4007
4008 void
4009 linux_proc_pending_signals (int pid, sigset_t *pending,
4010                             sigset_t *blocked, sigset_t *ignored)
4011 {
4012   FILE *procfile;
4013   char buffer[PATH_MAX], fname[PATH_MAX];
4014   struct cleanup *cleanup;
4015
4016   sigemptyset (pending);
4017   sigemptyset (blocked);
4018   sigemptyset (ignored);
4019   xsnprintf (fname, sizeof fname, "/proc/%d/status", pid);
4020   procfile = gdb_fopen_cloexec (fname, "r");
4021   if (procfile == NULL)
4022     error (_("Could not open %s"), fname);
4023   cleanup = make_cleanup_fclose (procfile);
4024
4025   while (fgets (buffer, PATH_MAX, procfile) != NULL)
4026     {
4027       /* Normal queued signals are on the SigPnd line in the status
4028          file.  However, 2.6 kernels also have a "shared" pending
4029          queue for delivering signals to a thread group, so check for
4030          a ShdPnd line also.
4031
4032          Unfortunately some Red Hat kernels include the shared pending
4033          queue but not the ShdPnd status field.  */
4034
4035       if (startswith (buffer, "SigPnd:\t"))
4036         add_line_to_sigset (buffer + 8, pending);
4037       else if (startswith (buffer, "ShdPnd:\t"))
4038         add_line_to_sigset (buffer + 8, pending);
4039       else if (startswith (buffer, "SigBlk:\t"))
4040         add_line_to_sigset (buffer + 8, blocked);
4041       else if (startswith (buffer, "SigIgn:\t"))
4042         add_line_to_sigset (buffer + 8, ignored);
4043     }
4044
4045   do_cleanups (cleanup);
4046 }
4047
4048 static enum target_xfer_status
4049 linux_nat_xfer_osdata (struct target_ops *ops, enum target_object object,
4050                        const char *annex, gdb_byte *readbuf,
4051                        const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
4052                        ULONGEST *xfered_len)
4053 {
4054   gdb_assert (object == TARGET_OBJECT_OSDATA);
4055
4056   *xfered_len = linux_common_xfer_osdata (annex, readbuf, offset, len);
4057   if (*xfered_len == 0)
4058     return TARGET_XFER_EOF;
4059   else
4060     return TARGET_XFER_OK;
4061 }
4062
4063 static enum target_xfer_status
4064 linux_xfer_partial (struct target_ops *ops, enum target_object object,
4065                     const char *annex, gdb_byte *readbuf,
4066                     const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
4067                     ULONGEST *xfered_len)
4068 {
4069   enum target_xfer_status xfer;
4070
4071   if (object == TARGET_OBJECT_AUXV)
4072     return memory_xfer_auxv (ops, object, annex, readbuf, writebuf,
4073                              offset, len, xfered_len);
4074
4075   if (object == TARGET_OBJECT_OSDATA)
4076     return linux_nat_xfer_osdata (ops, object, annex, readbuf, writebuf,
4077                                   offset, len, xfered_len);
4078
4079   if (object == TARGET_OBJECT_SPU)
4080     return linux_proc_xfer_spu (ops, object, annex, readbuf, writebuf,
4081                                 offset, len, xfered_len);
4082
4083   /* GDB calculates all the addresses in possibly larget width of the address.
4084      Address width needs to be masked before its final use - either by
4085      linux_proc_xfer_partial or inf_ptrace_xfer_partial.
4086
4087      Compare ADDR_BIT first to avoid a compiler warning on shift overflow.  */
4088
4089   if (object == TARGET_OBJECT_MEMORY)
4090     {
4091       int addr_bit = gdbarch_addr_bit (target_gdbarch ());
4092
4093       if (addr_bit < (sizeof (ULONGEST) * HOST_CHAR_BIT))
4094         offset &= ((ULONGEST) 1 << addr_bit) - 1;
4095     }
4096
4097   xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
4098                                   offset, len, xfered_len);
4099   if (xfer != TARGET_XFER_EOF)
4100     return xfer;
4101
4102   return super_xfer_partial (ops, object, annex, readbuf, writebuf,
4103                              offset, len, xfered_len);
4104 }
4105
4106 static void
4107 cleanup_target_stop (void *arg)
4108 {
4109   ptid_t *ptid = (ptid_t *) arg;
4110
4111   gdb_assert (arg != NULL);
4112
4113   /* Unpause all */
4114   target_resume (*ptid, 0, GDB_SIGNAL_0);
4115 }
4116
4117 static VEC(static_tracepoint_marker_p) *
4118 linux_child_static_tracepoint_markers_by_strid (struct target_ops *self,
4119                                                 const char *strid)
4120 {
4121   char s[IPA_CMD_BUF_SIZE];
4122   struct cleanup *old_chain;
4123   int pid = ptid_get_pid (inferior_ptid);
4124   VEC(static_tracepoint_marker_p) *markers = NULL;
4125   struct static_tracepoint_marker *marker = NULL;
4126   char *p = s;
4127   ptid_t ptid = ptid_build (pid, 0, 0);
4128
4129   /* Pause all */
4130   target_stop (ptid);
4131
4132   memcpy (s, "qTfSTM", sizeof ("qTfSTM"));
4133   s[sizeof ("qTfSTM")] = 0;
4134
4135   agent_run_command (pid, s, strlen (s) + 1);
4136
4137   old_chain = make_cleanup (free_current_marker, &marker);
4138   make_cleanup (cleanup_target_stop, &ptid);
4139
4140   while (*p++ == 'm')
4141     {
4142       if (marker == NULL)
4143         marker = XCNEW (struct static_tracepoint_marker);
4144
4145       do
4146         {
4147           parse_static_tracepoint_marker_definition (p, &p, marker);
4148
4149           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
4150             {
4151               VEC_safe_push (static_tracepoint_marker_p,
4152                              markers, marker);
4153               marker = NULL;
4154             }
4155           else
4156             {
4157               release_static_tracepoint_marker (marker);
4158               memset (marker, 0, sizeof (*marker));
4159             }
4160         }
4161       while (*p++ == ',');      /* comma-separated list */
4162
4163       memcpy (s, "qTsSTM", sizeof ("qTsSTM"));
4164       s[sizeof ("qTsSTM")] = 0;
4165       agent_run_command (pid, s, strlen (s) + 1);
4166       p = s;
4167     }
4168
4169   do_cleanups (old_chain);
4170
4171   return markers;
4172 }
4173
4174 /* Create a prototype generic GNU/Linux target.  The client can override
4175    it with local methods.  */
4176
4177 static void
4178 linux_target_install_ops (struct target_ops *t)
4179 {
4180   t->to_insert_fork_catchpoint = linux_child_insert_fork_catchpoint;
4181   t->to_remove_fork_catchpoint = linux_child_remove_fork_catchpoint;
4182   t->to_insert_vfork_catchpoint = linux_child_insert_vfork_catchpoint;
4183   t->to_remove_vfork_catchpoint = linux_child_remove_vfork_catchpoint;
4184   t->to_insert_exec_catchpoint = linux_child_insert_exec_catchpoint;
4185   t->to_remove_exec_catchpoint = linux_child_remove_exec_catchpoint;
4186   t->to_set_syscall_catchpoint = linux_child_set_syscall_catchpoint;
4187   t->to_pid_to_exec_file = linux_child_pid_to_exec_file;
4188   t->to_post_startup_inferior = linux_child_post_startup_inferior;
4189   t->to_post_attach = linux_child_post_attach;
4190   t->to_follow_fork = linux_child_follow_fork;
4191
4192   super_xfer_partial = t->to_xfer_partial;
4193   t->to_xfer_partial = linux_xfer_partial;
4194
4195   t->to_static_tracepoint_markers_by_strid
4196     = linux_child_static_tracepoint_markers_by_strid;
4197 }
4198
4199 struct target_ops *
4200 linux_target (void)
4201 {
4202   struct target_ops *t;
4203
4204   t = inf_ptrace_target ();
4205   linux_target_install_ops (t);
4206
4207   return t;
4208 }
4209
4210 struct target_ops *
4211 linux_trad_target (CORE_ADDR (*register_u_offset)(struct gdbarch *, int, int))
4212 {
4213   struct target_ops *t;
4214
4215   t = inf_ptrace_trad_target (register_u_offset);
4216   linux_target_install_ops (t);
4217
4218   return t;
4219 }
4220
4221 /* target_is_async_p implementation.  */
4222
4223 static int
4224 linux_nat_is_async_p (struct target_ops *ops)
4225 {
4226   return linux_is_async_p ();
4227 }
4228
4229 /* target_can_async_p implementation.  */
4230
4231 static int
4232 linux_nat_can_async_p (struct target_ops *ops)
4233 {
4234   /* NOTE: palves 2008-03-21: We're only async when the user requests
4235      it explicitly with the "set target-async" command.
4236      Someday, linux will always be async.  */
4237   return target_async_permitted;
4238 }
4239
4240 static int
4241 linux_nat_supports_non_stop (struct target_ops *self)
4242 {
4243   return 1;
4244 }
4245
4246 /* to_always_non_stop_p implementation.  */
4247
4248 static int
4249 linux_nat_always_non_stop_p (struct target_ops *self)
4250 {
4251   return 1;
4252 }
4253
4254 /* True if we want to support multi-process.  To be removed when GDB
4255    supports multi-exec.  */
4256
4257 int linux_multi_process = 1;
4258
4259 static int
4260 linux_nat_supports_multi_process (struct target_ops *self)
4261 {
4262   return linux_multi_process;
4263 }
4264
4265 static int
4266 linux_nat_supports_disable_randomization (struct target_ops *self)
4267 {
4268 #ifdef HAVE_PERSONALITY
4269   return 1;
4270 #else
4271   return 0;
4272 #endif
4273 }
4274
4275 static int async_terminal_is_ours = 1;
4276
4277 /* target_terminal_inferior implementation.
4278
4279    This is a wrapper around child_terminal_inferior to add async support.  */
4280
4281 static void
4282 linux_nat_terminal_inferior (struct target_ops *self)
4283 {
4284   child_terminal_inferior (self);
4285
4286   /* Calls to target_terminal_*() are meant to be idempotent.  */
4287   if (!async_terminal_is_ours)
4288     return;
4289
4290   delete_file_handler (input_fd);
4291   async_terminal_is_ours = 0;
4292   set_sigint_trap ();
4293 }
4294
4295 /* target_terminal_ours implementation.
4296
4297    This is a wrapper around child_terminal_ours to add async support (and
4298    implement the target_terminal_ours vs target_terminal_ours_for_output
4299    distinction).  child_terminal_ours is currently no different than
4300    child_terminal_ours_for_output.
4301    We leave target_terminal_ours_for_output alone, leaving it to
4302    child_terminal_ours_for_output.  */
4303
4304 static void
4305 linux_nat_terminal_ours (struct target_ops *self)
4306 {
4307   /* GDB should never give the terminal to the inferior if the
4308      inferior is running in the background (run&, continue&, etc.),
4309      but claiming it sure should.  */
4310   child_terminal_ours (self);
4311
4312   if (async_terminal_is_ours)
4313     return;
4314
4315   clear_sigint_trap ();
4316   add_file_handler (input_fd, stdin_event_handler, 0);
4317   async_terminal_is_ours = 1;
4318 }
4319
4320 /* SIGCHLD handler that serves two purposes: In non-stop/async mode,
4321    so we notice when any child changes state, and notify the
4322    event-loop; it allows us to use sigsuspend in linux_nat_wait_1
4323    above to wait for the arrival of a SIGCHLD.  */
4324
4325 static void
4326 sigchld_handler (int signo)
4327 {
4328   int old_errno = errno;
4329
4330   if (debug_linux_nat)
4331     ui_file_write_async_safe (gdb_stdlog,
4332                               "sigchld\n", sizeof ("sigchld\n") - 1);
4333
4334   if (signo == SIGCHLD
4335       && linux_nat_event_pipe[0] != -1)
4336     async_file_mark (); /* Let the event loop know that there are
4337                            events to handle.  */
4338
4339   errno = old_errno;
4340 }
4341
4342 /* Callback registered with the target events file descriptor.  */
4343
4344 static void
4345 handle_target_event (int error, gdb_client_data client_data)
4346 {
4347   inferior_event_handler (INF_REG_EVENT, NULL);
4348 }
4349
4350 /* Create/destroy the target events pipe.  Returns previous state.  */
4351
4352 static int
4353 linux_async_pipe (int enable)
4354 {
4355   int previous = linux_is_async_p ();
4356
4357   if (previous != enable)
4358     {
4359       sigset_t prev_mask;
4360
4361       /* Block child signals while we create/destroy the pipe, as
4362          their handler writes to it.  */
4363       block_child_signals (&prev_mask);
4364
4365       if (enable)
4366         {
4367           if (gdb_pipe_cloexec (linux_nat_event_pipe) == -1)
4368             internal_error (__FILE__, __LINE__,
4369                             "creating event pipe failed.");
4370
4371           fcntl (linux_nat_event_pipe[0], F_SETFL, O_NONBLOCK);
4372           fcntl (linux_nat_event_pipe[1], F_SETFL, O_NONBLOCK);
4373         }
4374       else
4375         {
4376           close (linux_nat_event_pipe[0]);
4377           close (linux_nat_event_pipe[1]);
4378           linux_nat_event_pipe[0] = -1;
4379           linux_nat_event_pipe[1] = -1;
4380         }
4381
4382       restore_child_signals_mask (&prev_mask);
4383     }
4384
4385   return previous;
4386 }
4387
4388 /* target_async implementation.  */
4389
4390 static void
4391 linux_nat_async (struct target_ops *ops, int enable)
4392 {
4393   if (enable)
4394     {
4395       if (!linux_async_pipe (1))
4396         {
4397           add_file_handler (linux_nat_event_pipe[0],
4398                             handle_target_event, NULL);
4399           /* There may be pending events to handle.  Tell the event loop
4400              to poll them.  */
4401           async_file_mark ();
4402         }
4403     }
4404   else
4405     {
4406       delete_file_handler (linux_nat_event_pipe[0]);
4407       linux_async_pipe (0);
4408     }
4409   return;
4410 }
4411
4412 /* Stop an LWP, and push a GDB_SIGNAL_0 stop status if no other
4413    event came out.  */
4414
4415 static int
4416 linux_nat_stop_lwp (struct lwp_info *lwp, void *data)
4417 {
4418   if (!lwp->stopped)
4419     {
4420       if (debug_linux_nat)
4421         fprintf_unfiltered (gdb_stdlog,
4422                             "LNSL: running -> suspending %s\n",
4423                             target_pid_to_str (lwp->ptid));
4424
4425
4426       if (lwp->last_resume_kind == resume_stop)
4427         {
4428           if (debug_linux_nat)
4429             fprintf_unfiltered (gdb_stdlog,
4430                                 "linux-nat: already stopping LWP %ld at "
4431                                 "GDB's request\n",
4432                                 ptid_get_lwp (lwp->ptid));
4433           return 0;
4434         }
4435
4436       stop_callback (lwp, NULL);
4437       lwp->last_resume_kind = resume_stop;
4438     }
4439   else
4440     {
4441       /* Already known to be stopped; do nothing.  */
4442
4443       if (debug_linux_nat)
4444         {
4445           if (find_thread_ptid (lwp->ptid)->stop_requested)
4446             fprintf_unfiltered (gdb_stdlog,
4447                                 "LNSL: already stopped/stop_requested %s\n",
4448                                 target_pid_to_str (lwp->ptid));
4449           else
4450             fprintf_unfiltered (gdb_stdlog,
4451                                 "LNSL: already stopped/no "
4452                                 "stop_requested yet %s\n",
4453                                 target_pid_to_str (lwp->ptid));
4454         }
4455     }
4456   return 0;
4457 }
4458
4459 static void
4460 linux_nat_stop (struct target_ops *self, ptid_t ptid)
4461 {
4462   iterate_over_lwps (ptid, linux_nat_stop_lwp, NULL);
4463 }
4464
4465 static void
4466 linux_nat_close (struct target_ops *self)
4467 {
4468   /* Unregister from the event loop.  */
4469   if (linux_nat_is_async_p (self))
4470     linux_nat_async (self, 0);
4471
4472   if (linux_ops->to_close)
4473     linux_ops->to_close (linux_ops);
4474
4475   super_close (self);
4476 }
4477
4478 /* When requests are passed down from the linux-nat layer to the
4479    single threaded inf-ptrace layer, ptids of (lwpid,0,0) form are
4480    used.  The address space pointer is stored in the inferior object,
4481    but the common code that is passed such ptid can't tell whether
4482    lwpid is a "main" process id or not (it assumes so).  We reverse
4483    look up the "main" process id from the lwp here.  */
4484
4485 static struct address_space *
4486 linux_nat_thread_address_space (struct target_ops *t, ptid_t ptid)
4487 {
4488   struct lwp_info *lwp;
4489   struct inferior *inf;
4490   int pid;
4491
4492   if (ptid_get_lwp (ptid) == 0)
4493     {
4494       /* An (lwpid,0,0) ptid.  Look up the lwp object to get at the
4495          tgid.  */
4496       lwp = find_lwp_pid (ptid);
4497       pid = ptid_get_pid (lwp->ptid);
4498     }
4499   else
4500     {
4501       /* A (pid,lwpid,0) ptid.  */
4502       pid = ptid_get_pid (ptid);
4503     }
4504
4505   inf = find_inferior_pid (pid);
4506   gdb_assert (inf != NULL);
4507   return inf->aspace;
4508 }
4509
4510 /* Return the cached value of the processor core for thread PTID.  */
4511
4512 static int
4513 linux_nat_core_of_thread (struct target_ops *ops, ptid_t ptid)
4514 {
4515   struct lwp_info *info = find_lwp_pid (ptid);
4516
4517   if (info)
4518     return info->core;
4519   return -1;
4520 }
4521
4522 /* Implementation of to_filesystem_is_local.  */
4523
4524 static int
4525 linux_nat_filesystem_is_local (struct target_ops *ops)
4526 {
4527   struct inferior *inf = current_inferior ();
4528
4529   if (inf->fake_pid_p || inf->pid == 0)
4530     return 1;
4531
4532   return linux_ns_same (inf->pid, LINUX_NS_MNT);
4533 }
4534
4535 /* Convert the INF argument passed to a to_fileio_* method
4536    to a process ID suitable for passing to its corresponding
4537    linux_mntns_* function.  If INF is non-NULL then the
4538    caller is requesting the filesystem seen by INF.  If INF
4539    is NULL then the caller is requesting the filesystem seen
4540    by the GDB.  We fall back to GDB's filesystem in the case
4541    that INF is non-NULL but its PID is unknown.  */
4542
4543 static pid_t
4544 linux_nat_fileio_pid_of (struct inferior *inf)
4545 {
4546   if (inf == NULL || inf->fake_pid_p || inf->pid == 0)
4547     return getpid ();
4548   else
4549     return inf->pid;
4550 }
4551
4552 /* Implementation of to_fileio_open.  */
4553
4554 static int
4555 linux_nat_fileio_open (struct target_ops *self,
4556                        struct inferior *inf, const char *filename,
4557                        int flags, int mode, int warn_if_slow,
4558                        int *target_errno)
4559 {
4560   int nat_flags;
4561   mode_t nat_mode;
4562   int fd;
4563
4564   if (fileio_to_host_openflags (flags, &nat_flags) == -1
4565       || fileio_to_host_mode (mode, &nat_mode) == -1)
4566     {
4567       *target_errno = FILEIO_EINVAL;
4568       return -1;
4569     }
4570
4571   fd = linux_mntns_open_cloexec (linux_nat_fileio_pid_of (inf),
4572                                  filename, nat_flags, nat_mode);
4573   if (fd == -1)
4574     *target_errno = host_to_fileio_error (errno);
4575
4576   return fd;
4577 }
4578
4579 /* Implementation of to_fileio_readlink.  */
4580
4581 static char *
4582 linux_nat_fileio_readlink (struct target_ops *self,
4583                            struct inferior *inf, const char *filename,
4584                            int *target_errno)
4585 {
4586   char buf[PATH_MAX];
4587   int len;
4588   char *ret;
4589
4590   len = linux_mntns_readlink (linux_nat_fileio_pid_of (inf),
4591                               filename, buf, sizeof (buf));
4592   if (len < 0)
4593     {
4594       *target_errno = host_to_fileio_error (errno);
4595       return NULL;
4596     }
4597
4598   ret = (char *) xmalloc (len + 1);
4599   memcpy (ret, buf, len);
4600   ret[len] = '\0';
4601   return ret;
4602 }
4603
4604 /* Implementation of to_fileio_unlink.  */
4605
4606 static int
4607 linux_nat_fileio_unlink (struct target_ops *self,
4608                          struct inferior *inf, const char *filename,
4609                          int *target_errno)
4610 {
4611   int ret;
4612
4613   ret = linux_mntns_unlink (linux_nat_fileio_pid_of (inf),
4614                             filename);
4615   if (ret == -1)
4616     *target_errno = host_to_fileio_error (errno);
4617
4618   return ret;
4619 }
4620
4621 void
4622 linux_nat_add_target (struct target_ops *t)
4623 {
4624   /* Save the provided single-threaded target.  We save this in a separate
4625      variable because another target we've inherited from (e.g. inf-ptrace)
4626      may have saved a pointer to T; we want to use it for the final
4627      process stratum target.  */
4628   linux_ops_saved = *t;
4629   linux_ops = &linux_ops_saved;
4630
4631   /* Override some methods for multithreading.  */
4632   t->to_create_inferior = linux_nat_create_inferior;
4633   t->to_attach = linux_nat_attach;
4634   t->to_detach = linux_nat_detach;
4635   t->to_resume = linux_nat_resume;
4636   t->to_wait = linux_nat_wait;
4637   t->to_pass_signals = linux_nat_pass_signals;
4638   t->to_xfer_partial = linux_nat_xfer_partial;
4639   t->to_kill = linux_nat_kill;
4640   t->to_mourn_inferior = linux_nat_mourn_inferior;
4641   t->to_thread_alive = linux_nat_thread_alive;
4642   t->to_update_thread_list = linux_nat_update_thread_list;
4643   t->to_pid_to_str = linux_nat_pid_to_str;
4644   t->to_thread_name = linux_nat_thread_name;
4645   t->to_has_thread_control = tc_schedlock;
4646   t->to_thread_address_space = linux_nat_thread_address_space;
4647   t->to_stopped_by_watchpoint = linux_nat_stopped_by_watchpoint;
4648   t->to_stopped_data_address = linux_nat_stopped_data_address;
4649   t->to_stopped_by_sw_breakpoint = linux_nat_stopped_by_sw_breakpoint;
4650   t->to_supports_stopped_by_sw_breakpoint = linux_nat_supports_stopped_by_sw_breakpoint;
4651   t->to_stopped_by_hw_breakpoint = linux_nat_stopped_by_hw_breakpoint;
4652   t->to_supports_stopped_by_hw_breakpoint = linux_nat_supports_stopped_by_hw_breakpoint;
4653
4654   t->to_can_async_p = linux_nat_can_async_p;
4655   t->to_is_async_p = linux_nat_is_async_p;
4656   t->to_supports_non_stop = linux_nat_supports_non_stop;
4657   t->to_always_non_stop_p = linux_nat_always_non_stop_p;
4658   t->to_async = linux_nat_async;
4659   t->to_terminal_inferior = linux_nat_terminal_inferior;
4660   t->to_terminal_ours = linux_nat_terminal_ours;
4661
4662   super_close = t->to_close;
4663   t->to_close = linux_nat_close;
4664
4665   t->to_stop = linux_nat_stop;
4666
4667   t->to_supports_multi_process = linux_nat_supports_multi_process;
4668
4669   t->to_supports_disable_randomization
4670     = linux_nat_supports_disable_randomization;
4671
4672   t->to_core_of_thread = linux_nat_core_of_thread;
4673
4674   t->to_filesystem_is_local = linux_nat_filesystem_is_local;
4675   t->to_fileio_open = linux_nat_fileio_open;
4676   t->to_fileio_readlink = linux_nat_fileio_readlink;
4677   t->to_fileio_unlink = linux_nat_fileio_unlink;
4678
4679   /* We don't change the stratum; this target will sit at
4680      process_stratum and thread_db will set at thread_stratum.  This
4681      is a little strange, since this is a multi-threaded-capable
4682      target, but we want to be on the stack below thread_db, and we
4683      also want to be used for single-threaded processes.  */
4684
4685   add_target (t);
4686 }
4687
4688 /* Register a method to call whenever a new thread is attached.  */
4689 void
4690 linux_nat_set_new_thread (struct target_ops *t,
4691                           void (*new_thread) (struct lwp_info *))
4692 {
4693   /* Save the pointer.  We only support a single registered instance
4694      of the GNU/Linux native target, so we do not need to map this to
4695      T.  */
4696   linux_nat_new_thread = new_thread;
4697 }
4698
4699 /* See declaration in linux-nat.h.  */
4700
4701 void
4702 linux_nat_set_new_fork (struct target_ops *t,
4703                         linux_nat_new_fork_ftype *new_fork)
4704 {
4705   /* Save the pointer.  */
4706   linux_nat_new_fork = new_fork;
4707 }
4708
4709 /* See declaration in linux-nat.h.  */
4710
4711 void
4712 linux_nat_set_forget_process (struct target_ops *t,
4713                               linux_nat_forget_process_ftype *fn)
4714 {
4715   /* Save the pointer.  */
4716   linux_nat_forget_process_hook = fn;
4717 }
4718
4719 /* See declaration in linux-nat.h.  */
4720
4721 void
4722 linux_nat_forget_process (pid_t pid)
4723 {
4724   if (linux_nat_forget_process_hook != NULL)
4725     linux_nat_forget_process_hook (pid);
4726 }
4727
4728 /* Register a method that converts a siginfo object between the layout
4729    that ptrace returns, and the layout in the architecture of the
4730    inferior.  */
4731 void
4732 linux_nat_set_siginfo_fixup (struct target_ops *t,
4733                              int (*siginfo_fixup) (siginfo_t *,
4734                                                    gdb_byte *,
4735                                                    int))
4736 {
4737   /* Save the pointer.  */
4738   linux_nat_siginfo_fixup = siginfo_fixup;
4739 }
4740
4741 /* Register a method to call prior to resuming a thread.  */
4742
4743 void
4744 linux_nat_set_prepare_to_resume (struct target_ops *t,
4745                                  void (*prepare_to_resume) (struct lwp_info *))
4746 {
4747   /* Save the pointer.  */
4748   linux_nat_prepare_to_resume = prepare_to_resume;
4749 }
4750
4751 /* See linux-nat.h.  */
4752
4753 int
4754 linux_nat_get_siginfo (ptid_t ptid, siginfo_t *siginfo)
4755 {
4756   int pid;
4757
4758   pid = ptid_get_lwp (ptid);
4759   if (pid == 0)
4760     pid = ptid_get_pid (ptid);
4761
4762   errno = 0;
4763   ptrace (PTRACE_GETSIGINFO, pid, (PTRACE_TYPE_ARG3) 0, siginfo);
4764   if (errno != 0)
4765     {
4766       memset (siginfo, 0, sizeof (*siginfo));
4767       return 0;
4768     }
4769   return 1;
4770 }
4771
4772 /* See nat/linux-nat.h.  */
4773
4774 ptid_t
4775 current_lwp_ptid (void)
4776 {
4777   gdb_assert (ptid_lwp_p (inferior_ptid));
4778   return inferior_ptid;
4779 }
4780
4781 /* Provide a prototype to silence -Wmissing-prototypes.  */
4782 extern initialize_file_ftype _initialize_linux_nat;
4783
4784 void
4785 _initialize_linux_nat (void)
4786 {
4787   add_setshow_zuinteger_cmd ("lin-lwp", class_maintenance,
4788                              &debug_linux_nat, _("\
4789 Set debugging of GNU/Linux lwp module."), _("\
4790 Show debugging of GNU/Linux lwp module."), _("\
4791 Enables printf debugging output."),
4792                              NULL,
4793                              show_debug_linux_nat,
4794                              &setdebuglist, &showdebuglist);
4795
4796   add_setshow_boolean_cmd ("linux-namespaces", class_maintenance,
4797                            &debug_linux_namespaces, _("\
4798 Set debugging of GNU/Linux namespaces module."), _("\
4799 Show debugging of GNU/Linux namespaces module."), _("\
4800 Enables printf debugging output."),
4801                            NULL,
4802                            NULL,
4803                            &setdebuglist, &showdebuglist);
4804
4805   /* Save this mask as the default.  */
4806   sigprocmask (SIG_SETMASK, NULL, &normal_mask);
4807
4808   /* Install a SIGCHLD handler.  */
4809   sigchld_action.sa_handler = sigchld_handler;
4810   sigemptyset (&sigchld_action.sa_mask);
4811   sigchld_action.sa_flags = SA_RESTART;
4812
4813   /* Make it the default.  */
4814   sigaction (SIGCHLD, &sigchld_action, NULL);
4815
4816   /* Make sure we don't block SIGCHLD during a sigsuspend.  */
4817   sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
4818   sigdelset (&suspend_mask, SIGCHLD);
4819
4820   sigemptyset (&blocked_mask);
4821 }
4822 \f
4823
4824 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
4825    the GNU/Linux Threads library and therefore doesn't really belong
4826    here.  */
4827
4828 /* Return the set of signals used by the threads library in *SET.  */
4829
4830 void
4831 lin_thread_get_thread_signals (sigset_t *set)
4832 {
4833   sigemptyset (set);
4834
4835   /* NPTL reserves the first two RT signals, but does not provide any
4836      way for the debugger to query the signal numbers - fortunately
4837      they don't change.  */
4838   sigaddset (set, __SIGRTMIN);
4839   sigaddset (set, __SIGRTMIN + 1);
4840 }