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