* Makefile.in (i386-linux-nat.o): Update dependencies.
[external/binutils.git] / gdb / lin-lwp.c
1 /* Multi-threaded debugging support for GNU/Linux (LWP layer).
2    Copyright 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include "defs.h"
22
23 #include "gdb_assert.h"
24 #include "gdb_string.h"
25 #include <errno.h>
26 #include <signal.h>
27 #ifdef HAVE_TKILL_SYSCALL
28 #include <unistd.h>
29 #include <sys/syscall.h>
30 #endif
31 #include <sys/ptrace.h>
32 #include "gdb_wait.h"
33
34 #include "gdbthread.h"
35 #include "inferior.h"
36 #include "target.h"
37 #include "regcache.h"
38 #include "gdbcmd.h"
39
40 static int debug_lin_lwp;
41 extern char *strsignal (int sig);
42
43 #include "linux-nat.h"
44
45 /* On GNU/Linux there are no real LWP's.  The closest thing to LWP's
46    are processes sharing the same VM space.  A multi-threaded process
47    is basically a group of such processes.  However, such a grouping
48    is almost entirely a user-space issue; the kernel doesn't enforce
49    such a grouping at all (this might change in the future).  In
50    general, we'll rely on the threads library (i.e. the GNU/Linux
51    Threads library) to provide such a grouping.
52
53    It is perfectly well possible to write a multi-threaded application
54    without the assistance of a threads library, by using the clone
55    system call directly.  This module should be able to give some
56    rudimentary support for debugging such applications if developers
57    specify the CLONE_PTRACE flag in the clone system call, and are
58    using the Linux kernel 2.4 or above.
59
60    Note that there are some peculiarities in GNU/Linux that affect
61    this code:
62
63    - In general one should specify the __WCLONE flag to waitpid in
64      order to make it report events for any of the cloned processes
65      (and leave it out for the initial process).  However, if a cloned
66      process has exited the exit status is only reported if the
67      __WCLONE flag is absent.  Linux kernel 2.4 has a __WALL flag, but
68      we cannot use it since GDB must work on older systems too.
69
70    - When a traced, cloned process exits and is waited for by the
71      debugger, the kernel reassigns it to the original parent and
72      keeps it around as a "zombie".  Somehow, the GNU/Linux Threads
73      library doesn't notice this, which leads to the "zombie problem":
74      When debugged a multi-threaded process that spawns a lot of
75      threads will run out of processes, even if the threads exit,
76      because the "zombies" stay around.  */
77
78 /* List of known LWPs.  */
79 static struct lwp_info *lwp_list;
80
81 /* Number of LWPs in the list.  */
82 static int num_lwps;
83
84 /* Non-zero if we're running in "threaded" mode.  */
85 static int threaded;
86 \f
87
88 #define GET_LWP(ptid)           ptid_get_lwp (ptid)
89 #define GET_PID(ptid)           ptid_get_pid (ptid)
90 #define is_lwp(ptid)            (GET_LWP (ptid) != 0)
91 #define BUILD_LWP(lwp, pid)     ptid_build (pid, lwp, 0)
92
93 /* If the last reported event was a SIGTRAP, this variable is set to
94    the process id of the LWP/thread that got it.  */
95 ptid_t trap_ptid;
96 \f
97
98 /* This module's target-specific operations.  */
99 static struct target_ops lin_lwp_ops;
100
101 /* The standard child operations.  */
102 extern struct target_ops child_ops;
103
104 /* Since we cannot wait (in lin_lwp_wait) for the initial process and
105    any cloned processes with a single call to waitpid, we have to use
106    the WNOHANG flag and call waitpid in a loop.  To optimize
107    things a bit we use `sigsuspend' to wake us up when a process has
108    something to report (it will send us a SIGCHLD if it has).  To make
109    this work we have to juggle with the signal mask.  We save the
110    original signal mask such that we can restore it before creating a
111    new process in order to avoid blocking certain signals in the
112    inferior.  We then block SIGCHLD during the waitpid/sigsuspend
113    loop.  */
114
115 /* Original signal mask.  */
116 static sigset_t normal_mask;
117
118 /* Signal mask for use with sigsuspend in lin_lwp_wait, initialized in
119    _initialize_lin_lwp.  */
120 static sigset_t suspend_mask;
121
122 /* Signals to block to make that sigsuspend work.  */
123 static sigset_t blocked_mask;
124 \f
125
126 /* Prototypes for local functions.  */
127 static int stop_wait_callback (struct lwp_info *lp, void *data);
128 static int lin_lwp_thread_alive (ptid_t ptid);
129 \f
130 /* Convert wait status STATUS to a string.  Used for printing debug
131    messages only.  */
132
133 static char *
134 status_to_str (int status)
135 {
136   static char buf[64];
137
138   if (WIFSTOPPED (status))
139     snprintf (buf, sizeof (buf), "%s (stopped)",
140               strsignal (WSTOPSIG (status)));
141   else if (WIFSIGNALED (status))
142     snprintf (buf, sizeof (buf), "%s (terminated)",
143               strsignal (WSTOPSIG (status)));
144   else
145     snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
146
147   return buf;
148 }
149 \f
150 /* Initialize the list of LWPs.  Note that this module, contrary to
151    what GDB's generic threads layer does for its thread list,
152    re-initializes the LWP lists whenever we mourn or detach (which
153    doesn't involve mourning) the inferior.  */
154
155 static void
156 init_lwp_list (void)
157 {
158   struct lwp_info *lp, *lpnext;
159
160   for (lp = lwp_list; lp; lp = lpnext)
161     {
162       lpnext = lp->next;
163       xfree (lp);
164     }
165
166   lwp_list = NULL;
167   num_lwps = 0;
168   threaded = 0;
169 }
170
171 /* Add the LWP specified by PID to the list.  If this causes the
172    number of LWPs to become larger than one, go into "threaded" mode.
173    Return a pointer to the structure describing the new LWP.  */
174
175 static struct lwp_info *
176 add_lwp (ptid_t ptid)
177 {
178   struct lwp_info *lp;
179
180   gdb_assert (is_lwp (ptid));
181
182   lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
183
184   memset (lp, 0, sizeof (struct lwp_info));
185
186   lp->ptid = ptid;
187
188   lp->next = lwp_list;
189   lwp_list = lp;
190   if (++num_lwps > 1)
191     threaded = 1;
192
193   return lp;
194 }
195
196 /* Remove the LWP specified by PID from the list.  */
197
198 static void
199 delete_lwp (ptid_t ptid)
200 {
201   struct lwp_info *lp, *lpprev;
202
203   lpprev = NULL;
204
205   for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
206     if (ptid_equal (lp->ptid, ptid))
207       break;
208
209   if (!lp)
210     return;
211
212   /* We don't go back to "non-threaded" mode if the number of threads
213      becomes less than two.  */
214   num_lwps--;
215
216   if (lpprev)
217     lpprev->next = lp->next;
218   else
219     lwp_list = lp->next;
220
221   xfree (lp);
222 }
223
224 /* Return a pointer to the structure describing the LWP corresponding
225    to PID.  If no corresponding LWP could be found, return NULL.  */
226
227 static struct lwp_info *
228 find_lwp_pid (ptid_t ptid)
229 {
230   struct lwp_info *lp;
231   int lwp;
232
233   if (is_lwp (ptid))
234     lwp = GET_LWP (ptid);
235   else
236     lwp = GET_PID (ptid);
237
238   for (lp = lwp_list; lp; lp = lp->next)
239     if (lwp == GET_LWP (lp->ptid))
240       return lp;
241
242   return NULL;
243 }
244
245 /* Call CALLBACK with its second argument set to DATA for every LWP in
246    the list.  If CALLBACK returns 1 for a particular LWP, return a
247    pointer to the structure describing that LWP immediately.
248    Otherwise return NULL.  */
249
250 struct lwp_info *
251 iterate_over_lwps (int (*callback) (struct lwp_info *, void *), void *data)
252 {
253   struct lwp_info *lp, *lpnext;
254
255   for (lp = lwp_list; lp; lp = lpnext)
256     {
257       lpnext = lp->next;
258       if ((*callback) (lp, data))
259         return lp;
260     }
261
262   return NULL;
263 }
264 \f
265
266 #if 0
267 static void
268 lin_lwp_open (char *args, int from_tty)
269 {
270   push_target (&lin_lwp_ops);
271 }
272 #endif
273
274 /* Attach to the LWP specified by PID.  If VERBOSE is non-zero, print
275    a message telling the user that a new LWP has been added to the
276    process.  */
277
278 void
279 lin_lwp_attach_lwp (ptid_t ptid, int verbose)
280 {
281   struct lwp_info *lp;
282
283   gdb_assert (is_lwp (ptid));
284
285   /* Make sure SIGCHLD is blocked.  We don't want SIGCHLD events
286      to interrupt either the ptrace() or waitpid() calls below.  */
287   if (!sigismember (&blocked_mask, SIGCHLD))
288     {
289       sigaddset (&blocked_mask, SIGCHLD);
290       sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
291     }
292
293   if (verbose)
294     printf_filtered ("[New %s]\n", target_pid_to_str (ptid));
295
296   lp = find_lwp_pid (ptid);
297   if (lp == NULL)
298     lp = add_lwp (ptid);
299
300   /* We assume that we're already attached to any LWP that has an
301      id equal to the overall process id.  */
302   if (GET_LWP (ptid) != GET_PID (ptid))
303     {
304       pid_t pid;
305       int status;
306
307       if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
308         error ("Can't attach %s: %s", target_pid_to_str (ptid),
309                safe_strerror (errno));
310
311       if (debug_lin_lwp)
312         fprintf_unfiltered (gdb_stdlog,
313                             "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
314                             target_pid_to_str (ptid));
315
316       pid = waitpid (GET_LWP (ptid), &status, 0);
317       if (pid == -1 && errno == ECHILD)
318         {
319           /* Try again with __WCLONE to check cloned processes.  */
320           pid = waitpid (GET_LWP (ptid), &status, __WCLONE);
321           lp->cloned = 1;
322         }
323
324       gdb_assert (pid == GET_LWP (ptid)
325                   && WIFSTOPPED (status) && WSTOPSIG (status));
326
327       child_post_attach (pid);
328
329       lp->stopped = 1;
330
331       if (debug_lin_lwp)
332         {
333           fprintf_unfiltered (gdb_stdlog,
334                               "LLAL: waitpid %s received %s\n",
335                               target_pid_to_str (ptid),
336                               status_to_str (status));
337         }
338     }
339   else
340     {
341       /* We assume that the LWP representing the original process
342          is already stopped.  Mark it as stopped in the data structure
343          that the lin-lwp layer uses to keep track of threads.  Note
344          that this won't have already been done since the main thread
345          will have, we assume, been stopped by an attach from a
346          different layer.  */
347       lp->stopped = 1;
348     }
349 }
350
351 static void
352 lin_lwp_attach (char *args, int from_tty)
353 {
354   struct lwp_info *lp;
355   pid_t pid;
356   int status;
357
358   /* FIXME: We should probably accept a list of process id's, and
359      attach all of them.  */
360   child_ops.to_attach (args, from_tty);
361
362   /* Add the initial process as the first LWP to the list.  */
363   lp = add_lwp (BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid)));
364
365   /* Make sure the initial process is stopped.  The user-level threads
366      layer might want to poke around in the inferior, and that won't
367      work if things haven't stabilized yet.  */
368   pid = waitpid (GET_PID (inferior_ptid), &status, 0);
369   if (pid == -1 && errno == ECHILD)
370     {
371       warning ("%s is a cloned process", target_pid_to_str (inferior_ptid));
372
373       /* Try again with __WCLONE to check cloned processes.  */
374       pid = waitpid (GET_PID (inferior_ptid), &status, __WCLONE);
375       lp->cloned = 1;
376     }
377
378   gdb_assert (pid == GET_PID (inferior_ptid)
379               && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP);
380
381   lp->stopped = 1;
382
383   /* Fake the SIGSTOP that core GDB expects.  */
384   lp->status = W_STOPCODE (SIGSTOP);
385   lp->resumed = 1;
386   if (debug_lin_lwp)
387     {
388       fprintf_unfiltered (gdb_stdlog,
389                           "LLA: waitpid %ld, faking SIGSTOP\n", (long) pid);
390     }
391 }
392
393 static int
394 detach_callback (struct lwp_info *lp, void *data)
395 {
396   gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
397
398   if (debug_lin_lwp && lp->status)
399     fprintf_unfiltered (gdb_stdlog, "DC:  Pending %s for %s on detach.\n",
400                         strsignal (WSTOPSIG (lp->status)),
401                         target_pid_to_str (lp->ptid));
402
403   while (lp->signalled && lp->stopped)
404     {
405       errno = 0;
406       if (ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0,
407                   WSTOPSIG (lp->status)) < 0)
408         error ("Can't continue %s: %s", target_pid_to_str (lp->ptid),
409                safe_strerror (errno));
410
411       if (debug_lin_lwp)
412         fprintf_unfiltered (gdb_stdlog,
413                             "DC:  PTRACE_CONTINUE (%s, 0, %s) (OK)\n",
414                             target_pid_to_str (lp->ptid),
415                             status_to_str (lp->status));
416
417       lp->stopped = 0;
418       lp->signalled = 0;
419       lp->status = 0;
420       stop_wait_callback (lp, NULL);
421
422       gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
423     }
424
425   /* We don't actually detach from the LWP that has an id equal to the
426      overall process id just yet.  */
427   if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
428     {
429       errno = 0;
430       if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
431                   WSTOPSIG (lp->status)) < 0)
432         error ("Can't detach %s: %s", target_pid_to_str (lp->ptid),
433                safe_strerror (errno));
434
435       if (debug_lin_lwp)
436         fprintf_unfiltered (gdb_stdlog,
437                             "PTRACE_DETACH (%s, %s, 0) (OK)\n",
438                             target_pid_to_str (lp->ptid),
439                             strsignal (WSTOPSIG (lp->status)));
440
441       delete_lwp (lp->ptid);
442     }
443
444   return 0;
445 }
446
447 static void
448 lin_lwp_detach (char *args, int from_tty)
449 {
450   iterate_over_lwps (detach_callback, NULL);
451
452   /* Only the initial process should be left right now.  */
453   gdb_assert (num_lwps == 1);
454
455   trap_ptid = null_ptid;
456
457   /* Destroy LWP info; it's no longer valid.  */
458   init_lwp_list ();
459
460   /* Restore the original signal mask.  */
461   sigprocmask (SIG_SETMASK, &normal_mask, NULL);
462   sigemptyset (&blocked_mask);
463
464   inferior_ptid = pid_to_ptid (GET_PID (inferior_ptid));
465   child_ops.to_detach (args, from_tty);
466 }
467 \f
468
469 /* Resume LP.  */
470
471 static int
472 resume_callback (struct lwp_info *lp, void *data)
473 {
474   if (lp->stopped && lp->status == 0)
475     {
476       struct thread_info *tp;
477
478       child_resume (pid_to_ptid (GET_LWP (lp->ptid)), 0, TARGET_SIGNAL_0);
479       if (debug_lin_lwp)
480         fprintf_unfiltered (gdb_stdlog,
481                             "RC:  PTRACE_CONT %s, 0, 0 (resume sibling)\n",
482                             target_pid_to_str (lp->ptid));
483       lp->stopped = 0;
484       lp->step = 0;
485     }
486
487   return 0;
488 }
489
490 static int
491 resume_clear_callback (struct lwp_info *lp, void *data)
492 {
493   lp->resumed = 0;
494   return 0;
495 }
496
497 static int
498 resume_set_callback (struct lwp_info *lp, void *data)
499 {
500   lp->resumed = 1;
501   return 0;
502 }
503
504 static void
505 lin_lwp_resume (ptid_t ptid, int step, enum target_signal signo)
506 {
507   struct lwp_info *lp;
508   int resume_all;
509
510   /* A specific PTID means `step only this process id'.  */
511   resume_all = (PIDGET (ptid) == -1);
512
513   if (resume_all)
514     iterate_over_lwps (resume_set_callback, NULL);
515   else
516     iterate_over_lwps (resume_clear_callback, NULL);
517
518   /* If PID is -1, it's the current inferior that should be
519      handled specially.  */
520   if (PIDGET (ptid) == -1)
521     ptid = inferior_ptid;
522
523   lp = find_lwp_pid (ptid);
524   if (lp)
525     {
526       ptid = pid_to_ptid (GET_LWP (lp->ptid));
527
528       /* Remember if we're stepping.  */
529       lp->step = step;
530
531       /* Mark this LWP as resumed.  */
532       lp->resumed = 1;
533
534       /* If we have a pending wait status for this thread, there is no
535          point in resuming the process.  */
536       if (lp->status)
537         {
538           /* FIXME: What should we do if we are supposed to continue
539              this thread with a signal?  */
540           gdb_assert (signo == TARGET_SIGNAL_0);
541           return;
542         }
543
544       /* Mark LWP as not stopped to prevent it from being continued by
545          resume_callback.  */
546       lp->stopped = 0;
547     }
548
549   if (resume_all)
550     iterate_over_lwps (resume_callback, NULL);
551
552   child_resume (ptid, step, signo);
553   if (debug_lin_lwp)
554     fprintf_unfiltered (gdb_stdlog,
555                         "LLR: %s %s, %s (resume event thread)\n",
556                         step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
557                         target_pid_to_str (ptid),
558                         signo ? strsignal (signo) : "0");
559 }
560 \f
561
562 /* Issue kill to specified lwp.  */
563
564 static int tkill_failed;
565
566 static int
567 kill_lwp (int lwpid, int signo)
568 {
569   errno = 0;
570
571 /* Use tkill, if possible, in case we are using nptl threads.  If tkill
572    fails, then we are not using nptl threads and we should be using kill.  */
573
574 #ifdef HAVE_TKILL_SYSCALL
575   if (!tkill_failed)
576     {
577       int ret = syscall (__NR_tkill, lwpid, signo);
578       if (errno != ENOSYS)
579         return ret;
580       errno = 0;
581       tkill_failed = 1;
582     }
583 #endif
584
585   return kill (lwpid, signo);
586 }
587
588 /* Send a SIGSTOP to LP.  */
589
590 static int
591 stop_callback (struct lwp_info *lp, void *data)
592 {
593   if (!lp->stopped && !lp->signalled)
594     {
595       int ret;
596
597       if (debug_lin_lwp)
598         {
599           fprintf_unfiltered (gdb_stdlog,
600                               "SC:  kill %s **<SIGSTOP>**\n",
601                               target_pid_to_str (lp->ptid));
602         }
603       errno = 0;
604       ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
605       if (debug_lin_lwp)
606         {
607           fprintf_unfiltered (gdb_stdlog,
608                               "SC:  lwp kill %d %s\n",
609                               ret,
610                               errno ? safe_strerror (errno) : "ERRNO-OK");
611         }
612
613       lp->signalled = 1;
614       gdb_assert (lp->status == 0);
615     }
616
617   return 0;
618 }
619
620 /* Wait until LP is stopped.  If DATA is non-null it is interpreted as
621    a pointer to a set of signals to be flushed immediately.  */
622
623 static int
624 stop_wait_callback (struct lwp_info *lp, void *data)
625 {
626   sigset_t *flush_mask = data;
627
628   if (!lp->stopped && lp->signalled)
629     {
630       pid_t pid;
631       int status;
632
633       gdb_assert (lp->status == 0);
634
635       pid = waitpid (GET_LWP (lp->ptid), &status, 0);
636       if (pid == -1 && errno == ECHILD)
637         {
638           pid = waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
639           if (pid == -1 && errno == ECHILD)
640             {
641               /* The thread has previously exited.  We need to delete it now
642                  because in the case of nptl threads, there won't be an
643                  exit event unless it is the main thread.  */
644               if (debug_lin_lwp)
645                 fprintf_unfiltered (gdb_stdlog,
646                                     "SWC: %s exited.\n",
647                                     target_pid_to_str (lp->ptid));
648               delete_lwp (lp->ptid);
649               return 0;
650             }
651         }
652
653       gdb_assert (pid == GET_LWP (lp->ptid));
654
655       if (debug_lin_lwp)
656         {
657           fprintf_unfiltered (gdb_stdlog,
658                               "SWC: waitpid %s received %s\n",
659                               target_pid_to_str (lp->ptid),
660                               status_to_str (status));
661         }
662
663       /* Check if the thread has exited.  */
664       if (WIFEXITED (status) || WIFSIGNALED (status))
665         {
666           gdb_assert (num_lwps > 1);
667
668           if (in_thread_list (lp->ptid))
669             {
670               /* Core GDB cannot deal with us deleting the current
671                  thread.  */
672               if (!ptid_equal (lp->ptid, inferior_ptid))
673                 delete_thread (lp->ptid);
674               printf_unfiltered ("[%s exited]\n",
675                                  target_pid_to_str (lp->ptid));
676             }
677           if (debug_lin_lwp)
678             fprintf_unfiltered (gdb_stdlog,
679                                 "SWC: %s exited.\n",
680                                 target_pid_to_str (lp->ptid));
681
682           delete_lwp (lp->ptid);
683           return 0;
684         }
685
686       /* Check if the current LWP has previously exited.  For nptl threads,
687          there is no exit signal issued for LWPs that are not the
688          main thread so we should check whenever the thread is stopped.  */
689       if (!lin_lwp_thread_alive (lp->ptid))
690         {
691           if (in_thread_list (lp->ptid))
692             {
693               /* Core GDB cannot deal with us deleting the current
694                  thread.  */
695               if (!ptid_equal (lp->ptid, inferior_ptid))
696                 delete_thread (lp->ptid);
697               printf_unfiltered ("[%s exited]\n",
698                                  target_pid_to_str (lp->ptid));
699             }
700           if (debug_lin_lwp)
701             fprintf_unfiltered (gdb_stdlog,
702                                 "SWC: %s already exited.\n",
703                                 target_pid_to_str (lp->ptid));
704
705           delete_lwp (lp->ptid);
706           return 0;
707         }
708
709       gdb_assert (WIFSTOPPED (status));
710
711       /* Ignore any signals in FLUSH_MASK.  */
712       if (flush_mask && sigismember (flush_mask, WSTOPSIG (status)))
713         {
714           errno = 0;
715           ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
716           if (debug_lin_lwp)
717             fprintf_unfiltered (gdb_stdlog,
718                                 "PTRACE_CONT %s, 0, 0 (%s)\n",
719                                 target_pid_to_str (lp->ptid),
720                                 errno ? safe_strerror (errno) : "OK");
721
722           return stop_wait_callback (lp, flush_mask);
723         }
724
725       if (WSTOPSIG (status) != SIGSTOP)
726         {
727           if (WSTOPSIG (status) == SIGTRAP)
728             {
729               /* If a LWP other than the LWP that we're reporting an
730                  event for has hit a GDB breakpoint (as opposed to
731                  some random trap signal), then just arrange for it to
732                  hit it again later.  We don't keep the SIGTRAP status
733                  and don't forward the SIGTRAP signal to the LWP.  We
734                  will handle the current event, eventually we will
735                  resume all LWPs, and this one will get its breakpoint
736                  trap again.
737
738                  If we do not do this, then we run the risk that the
739                  user will delete or disable the breakpoint, but the
740                  thread will have already tripped on it.  */
741
742               /* Now resume this LWP and get the SIGSTOP event. */
743               errno = 0;
744               ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
745               if (debug_lin_lwp)
746                 {
747                   fprintf_unfiltered (gdb_stdlog,
748                                       "PTRACE_CONT %s, 0, 0 (%s)\n",
749                                       target_pid_to_str (lp->ptid),
750                                       errno ? safe_strerror (errno) : "OK");
751
752                   fprintf_unfiltered (gdb_stdlog,
753                                       "SWC: Candidate SIGTRAP event in %s\n",
754                                       target_pid_to_str (lp->ptid));
755                 }
756               /* Hold the SIGTRAP for handling by lin_lwp_wait. */
757               stop_wait_callback (lp, data);
758               /* If there's another event, throw it back into the queue. */
759               if (lp->status)
760                 {
761                   if (debug_lin_lwp)
762                     {
763                       fprintf_unfiltered (gdb_stdlog,
764                                           "SWC: kill %s, %s\n",
765                                           target_pid_to_str (lp->ptid),
766                                           status_to_str ((int) status));
767                     }
768                   kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
769                 }
770               /* Save the sigtrap event. */
771               lp->status = status;
772               return 0;
773             }
774           else
775             {
776               /* The thread was stopped with a signal other than
777                  SIGSTOP, and didn't accidentally trip a breakpoint. */
778
779               if (debug_lin_lwp)
780                 {
781                   fprintf_unfiltered (gdb_stdlog,
782                                       "SWC: Pending event %s in %s\n",
783                                       status_to_str ((int) status),
784                                       target_pid_to_str (lp->ptid));
785                 }
786               /* Now resume this LWP and get the SIGSTOP event. */
787               errno = 0;
788               ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
789               if (debug_lin_lwp)
790                 fprintf_unfiltered (gdb_stdlog,
791                                     "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
792                                     target_pid_to_str (lp->ptid),
793                                     errno ? safe_strerror (errno) : "OK");
794
795               /* Hold this event/waitstatus while we check to see if
796                  there are any more (we still want to get that SIGSTOP). */
797               stop_wait_callback (lp, data);
798               /* If the lp->status field is still empty, use it to hold
799                  this event.  If not, then this event must be returned
800                  to the event queue of the LWP.  */
801               if (lp->status == 0)
802                 lp->status = status;
803               else
804                 {
805                   if (debug_lin_lwp)
806                     {
807                       fprintf_unfiltered (gdb_stdlog,
808                                           "SWC: kill %s, %s\n",
809                                           target_pid_to_str (lp->ptid),
810                                           status_to_str ((int) status));
811                     }
812                   kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
813                 }
814               return 0;
815             }
816         }
817       else
818         {
819           /* We caught the SIGSTOP that we intended to catch, so
820              there's no SIGSTOP pending.  */
821           lp->stopped = 1;
822           lp->signalled = 0;
823         }
824     }
825
826   return 0;
827 }
828
829 /* Return non-zero if LP has a wait status pending.  */
830
831 static int
832 status_callback (struct lwp_info *lp, void *data)
833 {
834   /* Only report a pending wait status if we pretend that this has
835      indeed been resumed.  */
836   return (lp->status != 0 && lp->resumed);
837 }
838
839 /* Return non-zero if LP isn't stopped.  */
840
841 static int
842 running_callback (struct lwp_info *lp, void *data)
843 {
844   return (lp->stopped == 0);
845 }
846
847 /* Count the LWP's that have had events.  */
848
849 static int
850 count_events_callback (struct lwp_info *lp, void *data)
851 {
852   int *count = data;
853
854   gdb_assert (count != NULL);
855
856   /* Count only LWPs that have a SIGTRAP event pending.  */
857   if (lp->status != 0
858       && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
859     (*count)++;
860
861   return 0;
862 }
863
864 /* Select the LWP (if any) that is currently being single-stepped.  */
865
866 static int
867 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
868 {
869   if (lp->step && lp->status != 0)
870     return 1;
871   else
872     return 0;
873 }
874
875 /* Select the Nth LWP that has had a SIGTRAP event.  */
876
877 static int
878 select_event_lwp_callback (struct lwp_info *lp, void *data)
879 {
880   int *selector = data;
881
882   gdb_assert (selector != NULL);
883
884   /* Select only LWPs that have a SIGTRAP event pending. */
885   if (lp->status != 0
886       && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
887     if ((*selector)-- == 0)
888       return 1;
889
890   return 0;
891 }
892
893 static int
894 cancel_breakpoints_callback (struct lwp_info *lp, void *data)
895 {
896   struct lwp_info *event_lp = data;
897
898   /* Leave the LWP that has been elected to receive a SIGTRAP alone.  */
899   if (lp == event_lp)
900     return 0;
901
902   /* If a LWP other than the LWP that we're reporting an event for has
903      hit a GDB breakpoint (as opposed to some random trap signal),
904      then just arrange for it to hit it again later.  We don't keep
905      the SIGTRAP status and don't forward the SIGTRAP signal to the
906      LWP.  We will handle the current event, eventually we will resume
907      all LWPs, and this one will get its breakpoint trap again.
908
909      If we do not do this, then we run the risk that the user will
910      delete or disable the breakpoint, but the LWP will have already
911      tripped on it.  */
912
913   if (lp->status != 0
914       && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
915       && breakpoint_inserted_here_p (read_pc_pid (lp->ptid) -
916                                      DECR_PC_AFTER_BREAK))
917     {
918       if (debug_lin_lwp)
919         fprintf_unfiltered (gdb_stdlog,
920                             "CBC: Push back breakpoint for %s\n",
921                             target_pid_to_str (lp->ptid));
922
923       /* Back up the PC if necessary.  */
924       if (DECR_PC_AFTER_BREAK)
925         write_pc_pid (read_pc_pid (lp->ptid) - DECR_PC_AFTER_BREAK, lp->ptid);
926
927       /* Throw away the SIGTRAP.  */
928       lp->status = 0;
929     }
930
931   return 0;
932 }
933
934 /* Select one LWP out of those that have events pending.  */
935
936 static void
937 select_event_lwp (struct lwp_info **orig_lp, int *status)
938 {
939   int num_events = 0;
940   int random_selector;
941   struct lwp_info *event_lp;
942
943   /* Record the wait status for the origional LWP.  */
944   (*orig_lp)->status = *status;
945
946   /* Give preference to any LWP that is being single-stepped.  */
947   event_lp = iterate_over_lwps (select_singlestep_lwp_callback, NULL);
948   if (event_lp != NULL)
949     {
950       if (debug_lin_lwp)
951         fprintf_unfiltered (gdb_stdlog,
952                             "SEL: Select single-step %s\n",
953                             target_pid_to_str (event_lp->ptid));
954     }
955   else
956     {
957       /* No single-stepping LWP.  Select one at random, out of those
958          which have had SIGTRAP events.  */
959
960       /* First see how many SIGTRAP events we have.  */
961       iterate_over_lwps (count_events_callback, &num_events);
962
963       /* Now randomly pick a LWP out of those that have had a SIGTRAP.  */
964       random_selector = (int)
965         ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
966
967       if (debug_lin_lwp && num_events > 1)
968         fprintf_unfiltered (gdb_stdlog,
969                             "SEL: Found %d SIGTRAP events, selecting #%d\n",
970                             num_events, random_selector);
971
972       event_lp = iterate_over_lwps (select_event_lwp_callback,
973                                     &random_selector);
974     }
975
976   if (event_lp != NULL)
977     {
978       /* Switch the event LWP.  */
979       *orig_lp = event_lp;
980       *status = event_lp->status;
981     }
982
983   /* Flush the wait status for the event LWP.  */
984   (*orig_lp)->status = 0;
985 }
986
987 /* Return non-zero if LP has been resumed.  */
988
989 static int
990 resumed_callback (struct lwp_info *lp, void *data)
991 {
992   return lp->resumed;
993 }
994
995 #ifdef CHILD_WAIT
996
997 /* We need to override child_wait to support attaching to cloned
998    processes, since a normal wait (as done by the default version)
999    ignores those processes.  */
1000
1001 /* Wait for child PTID to do something.  Return id of the child,
1002    minus_one_ptid in case of error; store status into *OURSTATUS.  */
1003
1004 ptid_t
1005 child_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
1006 {
1007   int save_errno;
1008   int status;
1009   pid_t pid;
1010
1011   do
1012     {
1013       set_sigint_trap ();       /* Causes SIGINT to be passed on to the
1014                                    attached process.  */
1015       set_sigio_trap ();
1016
1017       pid = waitpid (GET_PID (ptid), &status, 0);
1018       if (pid == -1 && errno == ECHILD)
1019         /* Try again with __WCLONE to check cloned processes.  */
1020         pid = waitpid (GET_PID (ptid), &status, __WCLONE);
1021
1022       if (debug_lin_lwp)
1023         {
1024           fprintf_unfiltered (gdb_stdlog,
1025                               "CW:  waitpid %ld received %s\n",
1026                               (long) pid, status_to_str (status));
1027         }
1028
1029       save_errno = errno;
1030
1031       /* Make sure we don't report an event for the exit of the
1032          original program, if we've detached from it.  */
1033       if (pid != -1 && !WIFSTOPPED (status) && pid != GET_PID (inferior_ptid))
1034         {
1035           pid = -1;
1036           save_errno = EINTR;
1037         }
1038
1039       /* Check for stop events reported by a process we didn't already
1040          know about - in this case, anything other than inferior_ptid.
1041
1042          If we're expecting to receive stopped processes after fork,
1043          vfork, and clone events, then we'll just add the new one to
1044          our list and go back to waiting for the event to be reported
1045          - the stopped process might be returned from waitpid before
1046          or after the event is.  If we want to handle debugging of
1047          CLONE_PTRACE processes we need to do more here, i.e. switch
1048          to multi-threaded mode.  */
1049       if (pid != -1 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP
1050           && pid != GET_PID (inferior_ptid))
1051         {
1052           pid = -1;
1053           save_errno = EINTR;
1054         }
1055
1056       clear_sigio_trap ();
1057       clear_sigint_trap ();
1058     }
1059   while (pid == -1 && save_errno == EINTR);
1060
1061   if (pid == -1)
1062     {
1063       warning ("Child process unexpectedly missing: %s",
1064                safe_strerror (errno));
1065
1066       /* Claim it exited with unknown signal.  */
1067       ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
1068       ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1069       return minus_one_ptid;
1070     }
1071
1072   /* Handle GNU/Linux's extended waitstatus for trace events.  */
1073   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1074     return linux_handle_extended_wait (pid, status, ourstatus);
1075
1076   store_waitstatus (ourstatus, status);
1077   return pid_to_ptid (pid);
1078 }
1079
1080 #endif
1081
1082 /* Stop an active thread, verify it still exists, then resume it.  */
1083
1084 static int
1085 stop_and_resume_callback (struct lwp_info *lp, void *data)
1086 {
1087   struct lwp_info *ptr;
1088
1089   if (!lp->stopped && !lp->signalled)
1090     {
1091       stop_callback (lp, NULL);
1092       stop_wait_callback (lp, NULL);
1093       /* Resume if the lwp still exists.  */
1094       for (ptr = lwp_list; ptr; ptr = ptr->next)
1095         if (lp == ptr)
1096           resume_callback (lp, NULL);
1097     }
1098   return 0;
1099 }
1100
1101 static ptid_t
1102 lin_lwp_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
1103 {
1104   struct lwp_info *lp = NULL;
1105   int options = 0;
1106   int status = 0;
1107   pid_t pid = PIDGET (ptid);
1108   sigset_t flush_mask;
1109
1110   sigemptyset (&flush_mask);
1111
1112   /* Make sure SIGCHLD is blocked.  */
1113   if (!sigismember (&blocked_mask, SIGCHLD))
1114     {
1115       sigaddset (&blocked_mask, SIGCHLD);
1116       sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
1117     }
1118
1119 retry:
1120
1121   /* Make sure there is at least one LWP that has been resumed, at
1122      least if there are any LWPs at all.  */
1123   gdb_assert (num_lwps == 0 || iterate_over_lwps (resumed_callback, NULL));
1124
1125   /* First check if there is a LWP with a wait status pending.  */
1126   if (pid == -1)
1127     {
1128       /* Any LWP that's been resumed will do.  */
1129       lp = iterate_over_lwps (status_callback, NULL);
1130       if (lp)
1131         {
1132           status = lp->status;
1133           lp->status = 0;
1134
1135           if (debug_lin_lwp && status)
1136             fprintf_unfiltered (gdb_stdlog,
1137                                 "LLW: Using pending wait status %s for %s.\n",
1138                                 status_to_str (status),
1139                                 target_pid_to_str (lp->ptid));
1140         }
1141
1142       /* But if we don't fine one, we'll have to wait, and check both
1143          cloned and uncloned processes.  We start with the cloned
1144          processes.  */
1145       options = __WCLONE | WNOHANG;
1146     }
1147   else if (is_lwp (ptid))
1148     {
1149       if (debug_lin_lwp)
1150         fprintf_unfiltered (gdb_stdlog,
1151                             "LLW: Waiting for specific LWP %s.\n",
1152                             target_pid_to_str (ptid));
1153
1154       /* We have a specific LWP to check.  */
1155       lp = find_lwp_pid (ptid);
1156       gdb_assert (lp);
1157       status = lp->status;
1158       lp->status = 0;
1159
1160       if (debug_lin_lwp && status)
1161         fprintf_unfiltered (gdb_stdlog,
1162                             "LLW: Using pending wait status %s for %s.\n",
1163                             status_to_str (status),
1164                             target_pid_to_str (lp->ptid));
1165
1166       /* If we have to wait, take into account whether PID is a cloned
1167          process or not.  And we have to convert it to something that
1168          the layer beneath us can understand.  */
1169       options = lp->cloned ? __WCLONE : 0;
1170       pid = GET_LWP (ptid);
1171     }
1172
1173   if (status && lp->signalled)
1174     {
1175       /* A pending SIGSTOP may interfere with the normal stream of
1176          events.  In a typical case where interference is a problem,
1177          we have a SIGSTOP signal pending for LWP A while
1178          single-stepping it, encounter an event in LWP B, and take the
1179          pending SIGSTOP while trying to stop LWP A.  After processing
1180          the event in LWP B, LWP A is continued, and we'll never see
1181          the SIGTRAP associated with the last time we were
1182          single-stepping LWP A.  */
1183
1184       /* Resume the thread.  It should halt immediately returning the
1185          pending SIGSTOP.  */
1186       registers_changed ();
1187       child_resume (pid_to_ptid (GET_LWP (lp->ptid)), lp->step,
1188                     TARGET_SIGNAL_0);
1189       if (debug_lin_lwp)
1190         fprintf_unfiltered (gdb_stdlog,
1191                             "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
1192                             lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1193                             target_pid_to_str (lp->ptid));
1194       lp->stopped = 0;
1195       gdb_assert (lp->resumed);
1196
1197       /* This should catch the pending SIGSTOP.  */
1198       stop_wait_callback (lp, NULL);
1199     }
1200
1201   set_sigint_trap ();           /* Causes SIGINT to be passed on to the
1202                                    attached process. */
1203   set_sigio_trap ();
1204
1205   while (status == 0)
1206     {
1207       pid_t lwpid;
1208
1209       lwpid = waitpid (pid, &status, options);
1210       if (lwpid > 0)
1211         {
1212           gdb_assert (pid == -1 || lwpid == pid);
1213
1214           if (debug_lin_lwp)
1215             {
1216               fprintf_unfiltered (gdb_stdlog,
1217                                   "LLW: waitpid %ld received %s\n",
1218                                   (long) lwpid, status_to_str (status));
1219             }
1220
1221           lp = find_lwp_pid (pid_to_ptid (lwpid));
1222
1223           /* Check for stop events reported by a process we didn't
1224              already know about - anything not already in our LWP
1225              list.
1226
1227              If we're expecting to receive stopped processes after
1228              fork, vfork, and clone events, then we'll just add the
1229              new one to our list and go back to waiting for the event
1230              to be reported - the stopped process might be returned
1231              from waitpid before or after the event is.  */
1232           if (WIFSTOPPED (status) && !lp)
1233             {
1234               linux_record_stopped_pid (lwpid);
1235               status = 0;
1236               continue;
1237             }
1238
1239           /* Make sure we don't report an event for the exit of an LWP not in
1240              our list, i.e.  not part of the current process.  This can happen
1241              if we detach from a program we original forked and then it
1242              exits.  */
1243           if (!WIFSTOPPED (status) && !lp)
1244             {
1245               status = 0;
1246               continue;
1247             }
1248
1249           /* NOTE drow/2003-06-17: This code seems to be meant for debugging
1250              CLONE_PTRACE processes which do not use the thread library -
1251              otherwise we wouldn't find the new LWP this way.  That doesn't
1252              currently work, and the following code is currently unreachable
1253              due to the two blocks above.  If it's fixed some day, this code
1254              should be broken out into a function so that we can also pick up
1255              LWPs from the new interface.  */
1256           if (!lp)
1257             {
1258               lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
1259               if (options & __WCLONE)
1260                 lp->cloned = 1;
1261
1262               if (threaded)
1263                 {
1264                   gdb_assert (WIFSTOPPED (status)
1265                               && WSTOPSIG (status) == SIGSTOP);
1266                   lp->signalled = 1;
1267
1268                   if (!in_thread_list (inferior_ptid))
1269                     {
1270                       inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
1271                                                  GET_PID (inferior_ptid));
1272                       add_thread (inferior_ptid);
1273                     }
1274
1275                   add_thread (lp->ptid);
1276                   printf_unfiltered ("[New %s]\n",
1277                                      target_pid_to_str (lp->ptid));
1278                 }
1279             }
1280
1281           /* Check if the thread has exited.  */
1282           if ((WIFEXITED (status) || WIFSIGNALED (status)) && num_lwps > 1)
1283             {
1284               if (in_thread_list (lp->ptid))
1285                 {
1286                   /* Core GDB cannot deal with us deleting the current
1287                      thread.  */
1288                   if (!ptid_equal (lp->ptid, inferior_ptid))
1289                     delete_thread (lp->ptid);
1290                   printf_unfiltered ("[%s exited]\n",
1291                                      target_pid_to_str (lp->ptid));
1292                 }
1293
1294               /* If this is the main thread, we must stop all threads and
1295                  verify if they are still alive.  This is because in the nptl
1296                  thread model, there is no signal issued for exiting LWPs
1297                  other than the main thread.  We only get the main thread
1298                  exit signal once all child threads have already exited.
1299                  If we stop all the threads and use the stop_wait_callback
1300                  to check if they have exited we can determine whether this
1301                  signal should be ignored or whether it means the end of the
1302                  debugged application, regardless of which threading model
1303                  is being used.  */
1304               if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
1305                 {
1306                   lp->stopped = 1;
1307                   iterate_over_lwps (stop_and_resume_callback, NULL);
1308                 }
1309
1310               if (debug_lin_lwp)
1311                 fprintf_unfiltered (gdb_stdlog,
1312                                     "LLW: %s exited.\n",
1313                                     target_pid_to_str (lp->ptid));
1314
1315               delete_lwp (lp->ptid);
1316
1317               /* If there is at least one more LWP, then the exit signal
1318                  was not the end of the debugged application and should be
1319                  ignored.  */
1320               if (num_lwps > 0)
1321                 {
1322                   /* Make sure there is at least one thread running.  */
1323                   gdb_assert (iterate_over_lwps (running_callback, NULL));
1324
1325                   /* Discard the event.  */
1326                   status = 0;
1327                   continue;
1328                 }
1329             }
1330
1331           /* Check if the current LWP has previously exited.  In the nptl
1332              thread model, LWPs other than the main thread do not issue
1333              signals when they exit so we must check whenever the thread
1334              has stopped.  A similar check is made in stop_wait_callback().  */
1335           if (num_lwps > 1 && !lin_lwp_thread_alive (lp->ptid))
1336             {
1337               if (in_thread_list (lp->ptid))
1338                 {
1339                   /* Core GDB cannot deal with us deleting the current
1340                      thread.  */
1341                   if (!ptid_equal (lp->ptid, inferior_ptid))
1342                     delete_thread (lp->ptid);
1343                   printf_unfiltered ("[%s exited]\n",
1344                                      target_pid_to_str (lp->ptid));
1345                 }
1346               if (debug_lin_lwp)
1347                 fprintf_unfiltered (gdb_stdlog,
1348                                     "LLW: %s exited.\n",
1349                                     target_pid_to_str (lp->ptid));
1350
1351               delete_lwp (lp->ptid);
1352
1353               /* Make sure there is at least one thread running.  */
1354               gdb_assert (iterate_over_lwps (running_callback, NULL));
1355
1356               /* Discard the event.  */
1357               status = 0;
1358               continue;
1359             }
1360
1361           /* Make sure we don't report a SIGSTOP that we sent
1362              ourselves in an attempt to stop an LWP.  */
1363           if (lp->signalled
1364               && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
1365             {
1366               if (debug_lin_lwp)
1367                 fprintf_unfiltered (gdb_stdlog,
1368                                     "LLW: Delayed SIGSTOP caught for %s.\n",
1369                                     target_pid_to_str (lp->ptid));
1370
1371               /* This is a delayed SIGSTOP.  */
1372               lp->signalled = 0;
1373
1374               registers_changed ();
1375               child_resume (pid_to_ptid (GET_LWP (lp->ptid)), lp->step,
1376                             TARGET_SIGNAL_0);
1377               if (debug_lin_lwp)
1378                 fprintf_unfiltered (gdb_stdlog,
1379                                     "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
1380                                     lp->step ?
1381                                     "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1382                                     target_pid_to_str (lp->ptid));
1383
1384               lp->stopped = 0;
1385               gdb_assert (lp->resumed);
1386
1387               /* Discard the event.  */
1388               status = 0;
1389               continue;
1390             }
1391
1392           break;
1393         }
1394
1395       if (pid == -1)
1396         {
1397           /* Alternate between checking cloned and uncloned processes.  */
1398           options ^= __WCLONE;
1399
1400           /* And suspend every time we have checked both.  */
1401           if (options & __WCLONE)
1402             sigsuspend (&suspend_mask);
1403         }
1404
1405       /* We shouldn't end up here unless we want to try again.  */
1406       gdb_assert (status == 0);
1407     }
1408
1409   clear_sigio_trap ();
1410   clear_sigint_trap ();
1411
1412   gdb_assert (lp);
1413
1414   /* Don't report signals that GDB isn't interested in, such as
1415      signals that are neither printed nor stopped upon.  Stopping all
1416      threads can be a bit time-consuming so if we want decent
1417      performance with heavily multi-threaded programs, especially when
1418      they're using a high frequency timer, we'd better avoid it if we
1419      can.  */
1420
1421   if (WIFSTOPPED (status))
1422     {
1423       int signo = target_signal_from_host (WSTOPSIG (status));
1424
1425       if (signal_stop_state (signo) == 0
1426           && signal_print_state (signo) == 0
1427           && signal_pass_state (signo) == 1)
1428         {
1429           /* FIMXE: kettenis/2001-06-06: Should we resume all threads
1430              here?  It is not clear we should.  GDB may not expect
1431              other threads to run.  On the other hand, not resuming
1432              newly attached threads may cause an unwanted delay in
1433              getting them running.  */
1434           registers_changed ();
1435           child_resume (pid_to_ptid (GET_LWP (lp->ptid)), lp->step, signo);
1436           if (debug_lin_lwp)
1437             fprintf_unfiltered (gdb_stdlog,
1438                                 "LLW: %s %s, %s (preempt 'handle')\n",
1439                                 lp->step ?
1440                                 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1441                                 target_pid_to_str (lp->ptid),
1442                                 signo ? strsignal (signo) : "0");
1443           lp->stopped = 0;
1444           status = 0;
1445           goto retry;
1446         }
1447
1448       if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
1449         {
1450           /* If ^C/BREAK is typed at the tty/console, SIGINT gets
1451              forwarded to the entire process group, that is, all LWP's
1452              will receive it.  Since we only want to report it once,
1453              we try to flush it from all LWPs except this one.  */
1454           sigaddset (&flush_mask, SIGINT);
1455         }
1456     }
1457
1458   /* This LWP is stopped now.  */
1459   lp->stopped = 1;
1460
1461   if (debug_lin_lwp)
1462     fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
1463                         status_to_str (status), target_pid_to_str (lp->ptid));
1464
1465   /* Now stop all other LWP's ...  */
1466   iterate_over_lwps (stop_callback, NULL);
1467
1468   /* ... and wait until all of them have reported back that they're no
1469      longer running.  */
1470   iterate_over_lwps (stop_wait_callback, &flush_mask);
1471
1472   /* If we're not waiting for a specific LWP, choose an event LWP from
1473      among those that have had events.  Giving equal priority to all
1474      LWPs that have had events helps prevent starvation.  */
1475   if (pid == -1)
1476     select_event_lwp (&lp, &status);
1477
1478   /* Now that we've selected our final event LWP, cancel any
1479      breakpoints in other LWPs that have hit a GDB breakpoint.  See
1480      the comment in cancel_breakpoints_callback to find out why.  */
1481   iterate_over_lwps (cancel_breakpoints_callback, lp);
1482
1483   /* If we're not running in "threaded" mode, we'll report the bare
1484      process id.  */
1485
1486   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
1487     {
1488       trap_ptid = (threaded ? lp->ptid : pid_to_ptid (GET_LWP (lp->ptid)));
1489       if (debug_lin_lwp)
1490         fprintf_unfiltered (gdb_stdlog,
1491                             "LLW: trap_ptid is %s.\n",
1492                             target_pid_to_str (trap_ptid));
1493     }
1494   else
1495     trap_ptid = null_ptid;
1496
1497   /* Handle GNU/Linux's extended waitstatus for trace events.  */
1498   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1499     {
1500       linux_handle_extended_wait (ptid_get_pid (trap_ptid),
1501                                   status, ourstatus);
1502       return trap_ptid;
1503     }
1504
1505   store_waitstatus (ourstatus, status);
1506   return (threaded ? lp->ptid : pid_to_ptid (GET_LWP (lp->ptid)));
1507 }
1508
1509 static int
1510 kill_callback (struct lwp_info *lp, void *data)
1511 {
1512   errno = 0;
1513   ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
1514   if (debug_lin_lwp)
1515     fprintf_unfiltered (gdb_stdlog,
1516                         "KC:  PTRACE_KILL %s, 0, 0 (%s)\n",
1517                         target_pid_to_str (lp->ptid),
1518                         errno ? safe_strerror (errno) : "OK");
1519
1520   return 0;
1521 }
1522
1523 static int
1524 kill_wait_callback (struct lwp_info *lp, void *data)
1525 {
1526   pid_t pid;
1527
1528   /* We must make sure that there are no pending events (delayed
1529      SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
1530      program doesn't interfere with any following debugging session.  */
1531
1532   /* For cloned processes we must check both with __WCLONE and
1533      without, since the exit status of a cloned process isn't reported
1534      with __WCLONE.  */
1535   if (lp->cloned)
1536     {
1537       do
1538         {
1539           pid = waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
1540           if (pid != (pid_t) -1 && debug_lin_lwp)
1541             {
1542               fprintf_unfiltered (gdb_stdlog,
1543                                   "KWC: wait %s received unknown.\n",
1544                                   target_pid_to_str (lp->ptid));
1545             }
1546         }
1547       while (pid == GET_LWP (lp->ptid));
1548
1549       gdb_assert (pid == -1 && errno == ECHILD);
1550     }
1551
1552   do
1553     {
1554       pid = waitpid (GET_LWP (lp->ptid), NULL, 0);
1555       if (pid != (pid_t) -1 && debug_lin_lwp)
1556         {
1557           fprintf_unfiltered (gdb_stdlog,
1558                               "KWC: wait %s received unk.\n",
1559                               target_pid_to_str (lp->ptid));
1560         }
1561     }
1562   while (pid == GET_LWP (lp->ptid));
1563
1564   gdb_assert (pid == -1 && errno == ECHILD);
1565   return 0;
1566 }
1567
1568 static void
1569 lin_lwp_kill (void)
1570 {
1571   /* Kill all LWP's ...  */
1572   iterate_over_lwps (kill_callback, NULL);
1573
1574   /* ... and wait until we've flushed all events.  */
1575   iterate_over_lwps (kill_wait_callback, NULL);
1576
1577   target_mourn_inferior ();
1578 }
1579
1580 static void
1581 lin_lwp_create_inferior (char *exec_file, char *allargs, char **env)
1582 {
1583   child_ops.to_create_inferior (exec_file, allargs, env);
1584 }
1585
1586 static void
1587 lin_lwp_mourn_inferior (void)
1588 {
1589   trap_ptid = null_ptid;
1590
1591   /* Destroy LWP info; it's no longer valid.  */
1592   init_lwp_list ();
1593
1594   /* Restore the original signal mask.  */
1595   sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1596   sigemptyset (&blocked_mask);
1597
1598   child_ops.to_mourn_inferior ();
1599 }
1600
1601 static int
1602 lin_lwp_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len, int write,
1603                      struct mem_attrib *attrib, struct target_ops *target)
1604 {
1605   struct cleanup *old_chain = save_inferior_ptid ();
1606   int xfer;
1607
1608   if (is_lwp (inferior_ptid))
1609     inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
1610
1611   xfer = linux_proc_xfer_memory (memaddr, myaddr, len, write, attrib, target);
1612   if (xfer == 0)
1613     xfer = child_xfer_memory (memaddr, myaddr, len, write, attrib, target);
1614
1615   do_cleanups (old_chain);
1616   return xfer;
1617 }
1618
1619 static int
1620 lin_lwp_thread_alive (ptid_t ptid)
1621 {
1622   gdb_assert (is_lwp (ptid));
1623
1624   errno = 0;
1625   ptrace (PTRACE_PEEKUSER, GET_LWP (ptid), 0, 0);
1626   if (debug_lin_lwp)
1627     fprintf_unfiltered (gdb_stdlog,
1628                         "LLTA: PTRACE_PEEKUSER %s, 0, 0 (%s)\n",
1629                         target_pid_to_str (ptid),
1630                         errno ? safe_strerror (errno) : "OK");
1631   if (errno)
1632     return 0;
1633
1634   return 1;
1635 }
1636
1637 static char *
1638 lin_lwp_pid_to_str (ptid_t ptid)
1639 {
1640   static char buf[64];
1641
1642   if (is_lwp (ptid))
1643     {
1644       snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
1645       return buf;
1646     }
1647
1648   return normal_pid_to_str (ptid);
1649 }
1650
1651 static void
1652 init_lin_lwp_ops (void)
1653 {
1654 #if 0
1655   lin_lwp_ops.to_open = lin_lwp_open;
1656 #endif
1657   lin_lwp_ops.to_shortname = "lwp-layer";
1658   lin_lwp_ops.to_longname = "lwp-layer";
1659   lin_lwp_ops.to_doc = "Low level threads support (LWP layer)";
1660   lin_lwp_ops.to_attach = lin_lwp_attach;
1661   lin_lwp_ops.to_detach = lin_lwp_detach;
1662   lin_lwp_ops.to_resume = lin_lwp_resume;
1663   lin_lwp_ops.to_wait = lin_lwp_wait;
1664   /* fetch_inferior_registers and store_inferior_registers will
1665      honor the LWP id, so we can use them directly.  */
1666   lin_lwp_ops.to_fetch_registers = fetch_inferior_registers;
1667   lin_lwp_ops.to_store_registers = store_inferior_registers;
1668   lin_lwp_ops.to_xfer_memory = lin_lwp_xfer_memory;
1669   lin_lwp_ops.to_kill = lin_lwp_kill;
1670   lin_lwp_ops.to_create_inferior = lin_lwp_create_inferior;
1671   lin_lwp_ops.to_mourn_inferior = lin_lwp_mourn_inferior;
1672   lin_lwp_ops.to_thread_alive = lin_lwp_thread_alive;
1673   lin_lwp_ops.to_pid_to_str = lin_lwp_pid_to_str;
1674   lin_lwp_ops.to_post_startup_inferior = child_post_startup_inferior;
1675   lin_lwp_ops.to_post_attach = child_post_attach;
1676   lin_lwp_ops.to_insert_fork_catchpoint = child_insert_fork_catchpoint;
1677   lin_lwp_ops.to_insert_vfork_catchpoint = child_insert_vfork_catchpoint;
1678   lin_lwp_ops.to_insert_exec_catchpoint = child_insert_exec_catchpoint;
1679
1680   lin_lwp_ops.to_stratum = thread_stratum;
1681   lin_lwp_ops.to_has_thread_control = tc_schedlock;
1682   lin_lwp_ops.to_magic = OPS_MAGIC;
1683 }
1684
1685 static void
1686 sigchld_handler (int signo)
1687 {
1688   /* Do nothing.  The only reason for this handler is that it allows
1689      us to use sigsuspend in lin_lwp_wait above to wait for the
1690      arrival of a SIGCHLD.  */
1691 }
1692
1693 void
1694 _initialize_lin_lwp (void)
1695 {
1696   struct sigaction action;
1697
1698   extern void thread_db_init (struct target_ops *);
1699
1700   init_lin_lwp_ops ();
1701   add_target (&lin_lwp_ops);
1702   thread_db_init (&lin_lwp_ops);
1703
1704   /* Save the original signal mask.  */
1705   sigprocmask (SIG_SETMASK, NULL, &normal_mask);
1706
1707   action.sa_handler = sigchld_handler;
1708   sigemptyset (&action.sa_mask);
1709   action.sa_flags = 0;
1710   sigaction (SIGCHLD, &action, NULL);
1711
1712   /* Make sure we don't block SIGCHLD during a sigsuspend.  */
1713   sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
1714   sigdelset (&suspend_mask, SIGCHLD);
1715
1716   sigemptyset (&blocked_mask);
1717
1718   add_show_from_set (add_set_cmd ("lin-lwp", no_class, var_zinteger,
1719                                   (char *) &debug_lin_lwp,
1720                                   "Set debugging of GNU/Linux lwp module.\n\
1721 Enables printf debugging output.\n", &setdebuglist), &showdebuglist);
1722 }
1723 \f
1724
1725 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
1726    the GNU/Linux Threads library and therefore doesn't really belong
1727    here.  */
1728
1729 /* Read variable NAME in the target and return its value if found.
1730    Otherwise return zero.  It is assumed that the type of the variable
1731    is `int'.  */
1732
1733 static int
1734 get_signo (const char *name)
1735 {
1736   struct minimal_symbol *ms;
1737   int signo;
1738
1739   ms = lookup_minimal_symbol (name, NULL, NULL);
1740   if (ms == NULL)
1741     return 0;
1742
1743   if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (char *) &signo,
1744                           sizeof (signo)) != 0)
1745     return 0;
1746
1747   return signo;
1748 }
1749
1750 /* Return the set of signals used by the threads library in *SET.  */
1751
1752 void
1753 lin_thread_get_thread_signals (sigset_t *set)
1754 {
1755   struct sigaction action;
1756   int restart, cancel;
1757
1758   sigemptyset (set);
1759
1760   restart = get_signo ("__pthread_sig_restart");
1761   if (restart == 0)
1762     return;
1763
1764   cancel = get_signo ("__pthread_sig_cancel");
1765   if (cancel == 0)
1766     return;
1767
1768   sigaddset (set, restart);
1769   sigaddset (set, cancel);
1770
1771   /* The GNU/Linux Threads library makes terminating threads send a
1772      special "cancel" signal instead of SIGCHLD.  Make sure we catch
1773      those (to prevent them from terminating GDB itself, which is
1774      likely to be their default action) and treat them the same way as
1775      SIGCHLD.  */
1776
1777   action.sa_handler = sigchld_handler;
1778   sigemptyset (&action.sa_mask);
1779   action.sa_flags = 0;
1780   sigaction (cancel, &action, NULL);
1781
1782   /* We block the "cancel" signal throughout this code ...  */
1783   sigaddset (&blocked_mask, cancel);
1784   sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
1785
1786   /* ... except during a sigsuspend.  */
1787   sigdelset (&suspend_mask, cancel);
1788 }