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