Fix date of last commit.
[external/binutils.git] / gdb / linux-thread.c
1 /* Low level interface for debugging GNU/Linux threads for GDB,
2    the GNU debugger.
3    Copyright 1998, 1999 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 2 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, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21 /* This module implements the debugging interface of the linuxthreads package
22    of the glibc. This package implements a simple clone()-based implementation
23    of Posix threads for Linux. To use this module, be sure that you have at
24    least the version of the linuxthreads package that holds the support of
25    GDB (currently 0.8 included in the glibc-2.0.7).
26
27    Right now, the linuxthreads package does not care of priority scheduling,
28    so, neither this module does; In particular, the threads are resumed
29    in any order, which could lead to different scheduling than the one
30    happening when GDB does not control the execution.
31
32    The latest point is that ptrace(PT_ATTACH, ...) is intrusive in Linux:
33    When a process is attached, then the attaching process becomes the current
34    parent of the attached process, and the old parent has lost this child.
35    If the old parent does a wait[...](), then this child is no longer
36    considered by the kernel as a child of the old parent, thus leading to
37    results of the call different when the child is attached and when it's not.
38
39    A fix has been submitted to the Linux community to solve this problem,
40    which consequences are not visible to the application itself, but on the
41    process which may wait() for the completion of the application (mostly,
42    it may consider that the application no longer exists (errno == ECHILD),
43    although it does, and thus being unable to get the exit status and resource
44    usage of the child. If by chance, it is able to wait() for the application
45    after it has died (by receiving first a SIGCHILD, and then doing a wait(),
46    then the exit status and resource usage may be wrong, because the
47    linuxthreads package heavily relies on wait() synchronization to keep
48    them correct.  */
49
50 #include "defs.h"
51 #include <sys/types.h> /* for pid_t */
52 #include <sys/ptrace.h> /* for PT_* flags */
53 #include "gdb_wait.h" /* for WUNTRACED and __WCLONE flags */
54 #include <signal.h> /* for struct sigaction and NSIG */
55 #include <sys/utsname.h>
56
57 #include "target.h"
58 #include "inferior.h"
59 #include "gdbcore.h"
60 #include "gdbthread.h"
61 #include "gdbcmd.h"
62 #include "breakpoint.h"
63
64 #ifndef PT_ATTACH
65 #define PT_ATTACH       PTRACE_ATTACH
66 #endif
67 #ifndef PT_KILL
68 #define PT_KILL         PTRACE_KILL
69 #endif
70 #ifndef PT_READ_U
71 #define PT_READ_U       PTRACE_PEEKUSR
72 #endif
73
74 #ifdef NSIG
75 #define LINUXTHREAD_NSIG NSIG
76 #else
77 #ifdef _NSIG
78 #define LINUXTHREAD_NSIG _NSIG
79 #endif
80 #endif
81
82 extern int child_suppress_run;          /* make inftarg.c non-runnable */
83 struct target_ops linuxthreads_ops;     /* Forward declaration */
84 extern struct target_ops child_ops;     /* target vector for inftarg.c */
85
86 static CORE_ADDR linuxthreads_handles;  /* array of linuxthreads handles */
87 static CORE_ADDR linuxthreads_manager;  /* pid of linuxthreads manager thread */
88 static CORE_ADDR linuxthreads_initial;  /* pid of linuxthreads initial thread */
89 static CORE_ADDR linuxthreads_debug;    /* linuxthreads internal debug flag */
90 static CORE_ADDR linuxthreads_num;      /* number of valid handle entries */
91
92 static int linuxthreads_max;            /* Maximum number of linuxthreads.
93                                            Zero if this executable doesn't use
94                                            threads, or wasn't linked with a
95                                            debugger-friendly version of the
96                                            linuxthreads library.  */
97
98 static int linuxthreads_sizeof_handle;  /* size of a linuxthreads handle */
99 static int linuxthreads_offset_descr;   /* h_descr offset of the linuxthreads
100                                            handle */
101 static int linuxthreads_offset_pid;     /* p_pid offset of the linuxthreads
102                                            descr */
103
104 static int linuxthreads_manager_pid;    /* manager pid */
105 static int linuxthreads_initial_pid;    /* initial pid */
106
107 /* These variables form a bag of threads with interesting status.  If
108    wait_thread (PID) finds that PID stopped for some interesting
109    reason (i.e. anything other than stopped with SIGSTOP), then it
110    records its status in this queue.  linuxthreads_wait and
111    linuxthreads_find_trap extract processes from here.  */
112 static int *linuxthreads_wait_pid;      /* wait array of pid */
113 static int *linuxthreads_wait_status;   /* wait array of status */
114 static int linuxthreads_wait_last;      /* index of last valid elt in
115                                            linuxthreads_wait_{pid,status} */
116
117 static sigset_t linuxthreads_block_mask;  /* sigset without SIGCHLD */
118
119 static int linuxthreads_step_pid;       /* current stepped pid */
120 static int linuxthreads_step_signo;     /* current stepped target signal */
121 static int linuxthreads_exit_status;    /* exit status of initial thread */
122
123 static int linuxthreads_inferior_pid;   /* temporary internal inferior pid */
124 static int linuxthreads_breakpoint_pid; /* last pid that hit a breakpoint */
125 static int linuxthreads_attach_pending; /* attach command without wait */
126
127 static int linuxthreads_breakpoints_inserted;   /* any breakpoints inserted */
128
129 /* LinuxThreads uses certain signals for communication between
130    processes; we need to tell GDB to pass them through silently to the
131    inferior.  The LinuxThreads library has global variables we can
132    read containing the relevant signal numbers, but since the signal
133    numbers are chosen at run-time, those variables aren't initialized
134    until the shared library's constructors have had a chance to run.  */
135
136 struct linuxthreads_signal {
137
138   /* The name of the LinuxThreads library variable that contains
139      the signal number.  */
140   char *var;
141
142   /* True if this variable must exist for us to debug properly.  */
143   int required;
144   
145   /* The variable's address in the inferior, or zero if the
146      LinuxThreads library hasn't been loaded into this inferior yet.  */
147   CORE_ADDR addr;
148
149   /* The signal number, or zero if we don't know yet (either because
150      we haven't found the variable, or it hasn't been initialized).
151      This is an actual target signal number that you could pass to
152      `kill', not a GDB signal number.  */
153   int signal;
154
155   /* GDB's original settings for `stop' and `print' for this signal.
156      We restore them when the user selects a different executable.
157      Invariant: if sig->signal != 0, then sig->{stop,print} contain
158      the original settings.  */
159   int stop, print;
160 };
161
162 struct linuxthreads_signal linuxthreads_sig_restart = {
163   "__pthread_sig_restart", 1, 0, 0, 0, 0
164 };
165 struct linuxthreads_signal linuxthreads_sig_cancel = {
166   "__pthread_sig_cancel", 1, 0, 0, 0, 0
167 };
168 struct linuxthreads_signal linuxthreads_sig_debug = {
169   "__pthread_sig_debug", 0, 0, 0, 0, 0
170 };
171
172 /* Set by thread_db module when it takes over the thread_stratum. 
173    In that case we must:
174    a) refrain from turning on the debug signal, and
175    b) refrain from calling add_thread.  */
176
177 int using_thread_db = 0;
178
179 /* A table of breakpoint locations, one per PID.  */
180 static struct linuxthreads_breakpoint {
181   CORE_ADDR     pc;     /* PC of breakpoint */
182   int           pid;    /* pid of breakpoint */
183   int           step;   /* whether the pc has been reached after sstep */
184 } *linuxthreads_breakpoint_zombie;              /* Zombie breakpoints array */
185 static int linuxthreads_breakpoint_last;        /* Last zombie breakpoint */
186
187 /* linuxthreads_{insert,remove}_breakpoint pass the breakpoint address
188    to {insert,remove}_breakpoint via this variable, since
189    iterate_active_threads doesn't provide any way to pass values
190    through to the worker function.  */
191 static CORE_ADDR linuxthreads_breakpoint_addr;
192
193 #define REMOVE_BREAKPOINT_ZOMBIE(_i) \
194 { \
195   if ((_i) < linuxthreads_breakpoint_last) \
196     linuxthreads_breakpoint_zombie[(_i)] = \
197       linuxthreads_breakpoint_zombie[linuxthreads_breakpoint_last]; \
198   linuxthreads_breakpoint_last--; \
199 }
200
201
202 \f
203 #ifndef PTRACE_XFER_TYPE
204 #define PTRACE_XFER_TYPE int
205 #endif
206 /* Check to see if the given thread is alive.  */
207 static int
208 linuxthreads_thread_alive (int pid)
209 {
210   errno = 0;
211   return ptrace (PT_READ_U, pid, (PTRACE_ARG3_TYPE)0, 0) >= 0 || errno == 0;
212 }
213
214 /* On detach(), find a SIGTRAP status.  If stop is non-zero, find a
215    SIGSTOP one, too.
216
217    Make sure PID is ready to run, and free of interference from our
218    efforts to debug it (e.g., pending SIGSTOP or SIGTRAP signals).  If
219    STOP is zero, just look for a SIGTRAP.  If STOP is non-zero, look
220    for a SIGSTOP, too.  Return non-zero if PID is alive and ready to
221    run; return zero if PID is dead.
222
223    PID may or may not be stopped at the moment, and we may or may not
224    have waited for it already.  We check the linuxthreads_wait bag in
225    case we've already got a status for it.  We may possibly wait for
226    it ourselves.
227
228    PID may have signals waiting to be delivered.  If they're caused by
229    our efforts to debug it, accept them with wait, but don't pass them
230    through to PID.  Do pass all other signals through.  */   
231 static int
232 linuxthreads_find_trap (int pid, int stop)
233 {
234   int i;
235   int rpid;
236   int status;
237   int found_stop = 0;
238   int found_trap = 0;
239
240   /* PID may have any number of signals pending.  The kernel will
241      report each of them to us via wait, and then it's up to us to
242      pass them along to the process via ptrace, if we so choose.
243
244      We need to paw through the whole set until we've found a SIGTRAP
245      (or a SIGSTOP, if `stop' is set).  We don't pass the SIGTRAP (or
246      SIGSTOP) through, but we do re-send all the others, so PID will
247      receive them when we resume it.  */
248   int *wstatus = alloca (LINUXTHREAD_NSIG * sizeof (int));
249   int last = 0;
250
251   /* Look at the pending status */
252   for (i = linuxthreads_wait_last; i >= 0; i--)
253     if (linuxthreads_wait_pid[i] == pid)
254       {
255         status = linuxthreads_wait_status[i];
256
257         /* Delete the i'th member of the table.  Since the table is
258            unordered, we can do this simply by copying the table's
259            last element to the i'th position, and shrinking the table
260            by one element.  */
261         if (i < linuxthreads_wait_last)
262           {
263             linuxthreads_wait_status[i] =
264               linuxthreads_wait_status[linuxthreads_wait_last];
265             linuxthreads_wait_pid[i] =
266               linuxthreads_wait_pid[linuxthreads_wait_last];
267           }
268         linuxthreads_wait_last--;
269
270         if (!WIFSTOPPED(status)) /* Thread has died */
271           return 0;
272
273         if (WSTOPSIG(status) == SIGTRAP)
274           {
275             if (stop)
276               found_trap = 1;
277             else
278               return 1;
279           }
280         else if (WSTOPSIG(status) == SIGSTOP)
281           {
282             if (stop)
283               found_stop = 1;
284           }
285         else
286           {
287             wstatus[0] = status;
288             last = 1;
289           }
290
291         break;
292       }
293
294   if (stop)
295     {
296       /* Make sure that we'll find what we're looking for.  */
297       if (!found_trap)
298         {
299           kill (pid, SIGTRAP);
300         }
301       if (!found_stop)
302         {
303           kill (pid, SIGSTOP);
304         }
305     }
306                       
307   /* Catch all status until SIGTRAP and optionally SIGSTOP show up.  */
308   for (;;)
309     {
310       /* resume the child every time... */
311       child_resume (pid, 1, TARGET_SIGNAL_0);
312
313       /* loop as long as errno == EINTR:
314          waitpid syscall may be aborted due to GDB receiving a signal. 
315          FIXME: EINTR handling should no longer be necessary here, since
316          we now block SIGCHLD except in an explicit sigsuspend call.  */
317       
318       for (;;)
319         {
320           rpid = waitpid (pid, &status, __WCLONE);
321           if (rpid > 0)
322             {
323               break;
324             }
325           if (errno == EINTR)
326             {
327               continue;
328             }
329
330           /* There are a few reasons the wait call above may have
331              failed.  If the thread manager dies, its children get
332              reparented, and this interferes with GDB waiting for
333              them, in some cases.  Another possibility is that the
334              initial thread was not cloned, so calling wait with
335              __WCLONE won't find it.  I think neither of these should
336              occur in modern Linux kernels --- they don't seem to in
337              2.0.36.  */
338           rpid = waitpid (pid, &status, 0);
339           if (rpid > 0)
340             {
341               break;
342             }
343           if (errno != EINTR)
344             perror_with_name ("find_trap/waitpid");
345         }
346
347       if (!WIFSTOPPED(status)) /* Thread has died */
348         return 0;
349
350       if (WSTOPSIG(status) == SIGTRAP)
351         if (!stop || found_stop)
352           break;
353         else
354           found_trap = 1;
355       else if (WSTOPSIG(status) != SIGSTOP)
356         wstatus[last++] = status;
357       else if (stop)
358         {
359           if (found_trap)
360             break;
361           else
362             found_stop = 1;
363         }
364     }
365
366   /* Resend any other signals we noticed to the thread, to be received
367      when we continue it.  */
368   while (--last >= 0)
369     {
370       kill (pid, WSTOPSIG(wstatus[last]));
371     }
372
373   return 1;
374 }
375
376 /* Cleanup stub for save_inferior_pid.  */
377 static void
378 restore_inferior_pid (void *arg)
379 {
380   int *saved_pid_ptr = arg;
381   inferior_pid = *saved_pid_ptr;
382   xfree (arg);
383 }
384
385 /* Register a cleanup to restore the value of inferior_pid.  */
386 static struct cleanup *
387 save_inferior_pid (void)
388 {
389   int *saved_pid_ptr;
390   
391   saved_pid_ptr = xmalloc (sizeof (int));
392   *saved_pid_ptr = inferior_pid;
393   return make_cleanup (restore_inferior_pid, saved_pid_ptr);
394 }
395
396 static void
397 sigchld_handler (int signo)
398 {
399   /* This handler is used to get an EINTR while doing waitpid()
400      when an event is received */
401 }
402
403 /* Have we already collected a wait status for PID in the
404    linuxthreads_wait bag?  */
405 static int
406 linuxthreads_pending_status (int pid)
407 {
408   int i;
409   for (i = linuxthreads_wait_last; i >= 0; i--)
410     if (linuxthreads_wait_pid[i] == pid)
411       return 1;
412   return 0;
413 }
414
415 \f
416 /* Internal linuxthreads signal management */
417
418 /* Check in OBJFILE for the variable that holds the number for signal SIG.
419    We assume that we've already found other LinuxThreads-ish variables
420    in OBJFILE, so we complain if it's required, but not there.
421    Return true iff things are okay.  */
422 static int
423 find_signal_var (struct linuxthreads_signal *sig, struct objfile *objfile)
424 {
425   struct minimal_symbol *ms = lookup_minimal_symbol (sig->var, NULL, objfile);
426
427   if (! ms)
428     {
429       if (sig->required)
430         {
431           fprintf_unfiltered (gdb_stderr,
432                               "Unable to find linuxthreads symbol \"%s\"\n",
433                               sig->var);
434           return 0;
435         }
436       else
437         {
438           sig->addr = 0;
439           return 1;
440         }
441     }
442
443   sig->addr = SYMBOL_VALUE_ADDRESS (ms);
444
445   return 1;
446 }
447
448 static int
449 find_all_signal_vars (struct objfile *objfile)
450 {
451   return (   find_signal_var (&linuxthreads_sig_restart, objfile)
452           && find_signal_var (&linuxthreads_sig_cancel,  objfile)
453           && find_signal_var (&linuxthreads_sig_debug,   objfile));
454 }
455
456 /* A struct complaint isn't appropriate here.  */
457 static int complained_cannot_determine_thread_signal_number = 0;
458
459 /* Check to see if the variable holding the signal number for SIG has
460    been initialized yet.  If it has, tell GDB to pass that signal
461    through to the inferior silently.  */
462 static void
463 check_signal_number (struct linuxthreads_signal *sig)
464 {
465   int num;
466
467   if (sig->signal)
468     /* We already know this signal number.  */
469     return;
470
471   if (! sig->addr)
472     /* We don't know the variable's address yet.  */
473     return;
474
475   if (target_read_memory (sig->addr, (char *)&num, sizeof (num))
476       != 0)
477     {
478       /* If this happens once, it'll probably happen for all the
479          signals, so only complain once.  */
480       if (! complained_cannot_determine_thread_signal_number)
481         warning ("Cannot determine thread signal number; "
482                  "GDB may report spurious signals.");
483       complained_cannot_determine_thread_signal_number = 1;
484       return;
485     }
486   
487   if (num == 0)
488     /* It hasn't been initialized yet.  */
489     return;
490
491   /* We know sig->signal was zero, and is becoming non-zero, so it's
492      okay to sample GDB's original settings.  */
493   sig->signal = num;
494   sig->stop  = signal_stop_update  (target_signal_from_host (num), 0);
495   sig->print = signal_print_update (target_signal_from_host (num), 0);
496 }
497
498 void
499 check_all_signal_numbers (void)
500 {
501   /* If this isn't a LinuxThreads program, quit early.  */
502   if (! linuxthreads_max)
503     return;
504
505   check_signal_number (&linuxthreads_sig_restart);
506   check_signal_number (&linuxthreads_sig_cancel);
507   check_signal_number (&linuxthreads_sig_debug);
508
509   /* handle linuxthread exit */
510   if (linuxthreads_sig_debug.signal
511       || linuxthreads_sig_restart.signal)
512     {
513       struct sigaction sact;
514
515       sact.sa_handler = sigchld_handler;
516       sigemptyset(&sact.sa_mask);
517       sact.sa_flags = 0;
518
519       if (linuxthreads_sig_debug.signal > 0)
520         sigaction(linuxthreads_sig_cancel.signal, &sact, NULL);
521       else
522         sigaction(linuxthreads_sig_restart.signal, &sact, NULL);
523     }
524 }
525
526
527 /* Restore GDB's original settings for SIG.
528    This should only be called when we're no longer sure if we're
529    talking to an executable that uses LinuxThreads, so we clear the
530    signal number and variable address too.  */
531 static void
532 restore_signal (struct linuxthreads_signal *sig)
533 {
534   if (! sig->signal)
535     return;
536
537   /* We know sig->signal was non-zero, and is becoming zero, so it's
538      okay to restore GDB's original settings.  */
539   signal_stop_update  (target_signal_from_host (sig->signal), sig->stop);
540   signal_print_update (target_signal_from_host (sig->signal), sig->print);
541
542   sig->signal = 0;
543   sig->addr = 0;
544 }
545
546
547 /* Restore GDB's original settings for all LinuxThreads signals.
548    This should only be called when we're no longer sure if we're
549    talking to an executable that uses LinuxThreads, so we clear the
550    signal number and variable address too.  */
551 static void
552 restore_all_signals (void)
553 {
554   restore_signal (&linuxthreads_sig_restart);
555   restore_signal (&linuxthreads_sig_cancel);
556   restore_signal (&linuxthreads_sig_debug);
557
558   /* If it happens again, we should complain again.  */
559   complained_cannot_determine_thread_signal_number = 0;
560 }
561
562
563 \f
564
565 /* Apply FUNC to the pid of each active thread.  This consults the
566    inferior's handle table to find active threads.
567
568    If ALL is non-zero, process all threads.
569    If ALL is zero, skip threads with pending status.  */
570 static void
571 iterate_active_threads (void (*func) (int), int all)
572 {
573   CORE_ADDR descr;
574   int pid;
575   int i;
576   int num;
577
578   read_memory (linuxthreads_num, (char *)&num, sizeof (int));
579
580   for (i = 0; i < linuxthreads_max && num > 0; i++)
581     {
582       read_memory (linuxthreads_handles +
583                    linuxthreads_sizeof_handle * i + linuxthreads_offset_descr,
584                    (char *)&descr, sizeof (void *));
585       if (descr)
586         {
587           num--;
588           read_memory (descr + linuxthreads_offset_pid,
589                        (char *)&pid, sizeof (pid_t));
590           if (pid > 0 && pid != linuxthreads_manager_pid
591               && (all || (!linuxthreads_pending_status (pid))))
592             (*func)(pid);
593         }
594     }
595 }
596
597 /* Insert a thread breakpoint at linuxthreads_breakpoint_addr.
598    This is the worker function for linuxthreads_insert_breakpoint,
599    which passes it to iterate_active_threads.  */
600 static void
601 insert_breakpoint (int pid)
602 {
603   int j;
604
605   /* Remove (if any) the positive zombie breakpoint.  */
606   for (j = linuxthreads_breakpoint_last; j >= 0; j--)
607     if (linuxthreads_breakpoint_zombie[j].pid == pid)
608       {
609         if ((linuxthreads_breakpoint_zombie[j].pc - DECR_PC_AFTER_BREAK
610              == linuxthreads_breakpoint_addr)
611             && !linuxthreads_breakpoint_zombie[j].step)
612           REMOVE_BREAKPOINT_ZOMBIE(j);
613         break;
614       }
615 }
616
617 /* Note that we're about to remove a thread breakpoint at
618    linuxthreads_breakpoint_addr.
619
620    This is the worker function for linuxthreads_remove_breakpoint,
621    which passes it to iterate_active_threads.  The actual work of
622    overwriting the breakpoint instruction is done by
623    child_ops.to_remove_breakpoint; here, we simply create a zombie
624    breakpoint if the thread's PC is pointing at the breakpoint being
625    removed.  */
626 static void
627 remove_breakpoint (int pid)
628 {
629   int j;
630
631   /* Insert a positive zombie breakpoint (if needed).  */
632   for (j = 0; j <= linuxthreads_breakpoint_last; j++)
633     if (linuxthreads_breakpoint_zombie[j].pid == pid)
634       break;
635
636   if (in_thread_list (pid) && linuxthreads_thread_alive (pid))
637     {
638       CORE_ADDR pc = read_pc_pid (pid);
639       if (linuxthreads_breakpoint_addr == pc - DECR_PC_AFTER_BREAK
640           && j > linuxthreads_breakpoint_last)
641         {
642           linuxthreads_breakpoint_zombie[j].pid = pid;
643           linuxthreads_breakpoint_zombie[j].pc = pc;
644           linuxthreads_breakpoint_zombie[j].step = 0;
645           linuxthreads_breakpoint_last++;
646         }
647     }
648 }
649
650 /* Kill a thread */
651 static void
652 kill_thread (int pid)
653 {
654   if (in_thread_list (pid))
655     {
656       ptrace (PT_KILL, pid, (PTRACE_ARG3_TYPE) 0, 0);
657     }
658   else
659     {
660       kill (pid, SIGKILL);
661     }
662 }
663
664 /* Resume a thread */
665 static void
666 resume_thread (int pid)
667 {
668   if (pid != inferior_pid
669       && in_thread_list (pid)
670       && linuxthreads_thread_alive (pid))
671     {
672       if (pid == linuxthreads_step_pid)
673         {
674           child_resume (pid, 1, linuxthreads_step_signo);
675         }
676       else
677         {
678           child_resume (pid, 0, TARGET_SIGNAL_0);
679         }
680     }
681 }
682
683 /* Detach a thread */
684 static void
685 detach_thread (int pid)
686 {
687   if (in_thread_list (pid) && linuxthreads_thread_alive (pid))
688     {
689       /* Remove pending SIGTRAP and SIGSTOP */
690       linuxthreads_find_trap (pid, 1);
691
692       inferior_pid = pid;
693       detach (TARGET_SIGNAL_0);
694       inferior_pid = linuxthreads_manager_pid;
695     }
696 }
697
698 /* Attach a thread */
699 void
700 attach_thread (int pid)
701 {
702   if (ptrace (PT_ATTACH, pid, (PTRACE_ARG3_TYPE) 0, 0) != 0)
703     perror_with_name ("attach_thread");
704 }
705
706 /* Stop a thread */
707 static void
708 stop_thread (int pid)
709 {
710   if (pid != inferior_pid)
711     {
712       if (in_thread_list (pid))
713         {
714           kill (pid, SIGSTOP);
715         }
716       else if (ptrace (PT_ATTACH, pid, (PTRACE_ARG3_TYPE) 0, 0) == 0)
717         {
718           if (!linuxthreads_attach_pending)
719             printf_filtered ("[New %s]\n", target_pid_to_str (pid));
720           add_thread (pid);
721           if (linuxthreads_sig_debug.signal)
722             {
723               /* After a new thread in glibc 2.1 signals gdb its existence,
724                  it suspends itself and wait for linuxthreads_sig_restart,
725                  now we can wake it up. */
726               kill (pid, linuxthreads_sig_restart.signal);
727             }
728         }
729       else
730         perror_with_name ("ptrace in stop_thread");
731     }
732 }
733
734 /* Wait for a thread */
735 static void
736 wait_thread (int pid)
737 {
738   int status;
739   int rpid;
740
741   if (pid != inferior_pid && in_thread_list (pid))
742     {
743       /* loop as long as errno == EINTR:
744          waitpid syscall may be aborted if GDB receives a signal. 
745          FIXME: EINTR handling should no longer be necessary here, since
746          we now block SIGCHLD except during an explicit sigsuspend call. */
747       for (;;)
748         {
749           /* Get first pid status.  */
750           rpid = waitpid(pid, &status, __WCLONE);
751           if (rpid > 0)
752             {
753               break;
754             }
755           if (errno == EINTR)
756             {
757               continue;
758             }
759
760           /* There are two reasons this might have failed:
761
762              1) PID is the initial thread, which wasn't cloned, so
763              passing the __WCLONE flag to waitpid prevented us from
764              finding it.
765
766              2) The manager thread is the parent of all but the
767              initial thread; if it dies, the children will all be
768              reparented to init, which will wait for them.  This means
769              our call to waitpid won't find them.
770
771              Actually, based on a casual look at the 2.0.36 kernel
772              code, I don't think either of these cases happen.  But I
773              don't have things set up for remotely debugging the
774              kernel, so I'm not sure.  And perhaps older kernels
775              didn't work.  */
776           rpid = waitpid(pid, &status, 0);
777           if (rpid > 0)
778             {
779               break;
780             }
781           if (errno != EINTR && linuxthreads_thread_alive (pid))
782             perror_with_name ("wait_thread/waitpid");
783
784           /* the thread is dead.  */
785           return;
786         }
787       if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP)
788         {
789           linuxthreads_wait_pid[++linuxthreads_wait_last] = pid;
790           linuxthreads_wait_status[linuxthreads_wait_last] = status;
791         }
792     }
793 }
794
795 /* Walk through the linuxthreads handles in order to detect all
796    threads and stop them */
797 static void
798 update_stop_threads (int test_pid)
799 {
800   struct cleanup *old_chain = NULL;
801
802   check_all_signal_numbers ();
803
804   if (linuxthreads_manager_pid == 0)
805     {
806       if (linuxthreads_manager)
807         {
808           if (test_pid > 0 && test_pid != inferior_pid)
809             {
810               old_chain = save_inferior_pid ();
811               inferior_pid = test_pid;
812             }
813           read_memory (linuxthreads_manager,
814                        (char *)&linuxthreads_manager_pid, sizeof (pid_t));
815         }
816       if (linuxthreads_initial)
817         {
818           if (test_pid > 0 && test_pid != inferior_pid)
819             {
820               old_chain = save_inferior_pid ();
821               inferior_pid = test_pid;
822             }
823           read_memory(linuxthreads_initial,
824                       (char *)&linuxthreads_initial_pid, sizeof (pid_t));
825         }
826     }
827
828   if (linuxthreads_manager_pid != 0)
829     {
830       if (old_chain == NULL && test_pid > 0 &&
831           test_pid != inferior_pid && linuxthreads_thread_alive (test_pid))
832         {
833           old_chain = save_inferior_pid ();
834           inferior_pid = test_pid;
835         }
836
837       if (linuxthreads_thread_alive (inferior_pid))
838         {
839           if (test_pid > 0)
840             {
841               if (test_pid != linuxthreads_manager_pid
842                   && !linuxthreads_pending_status (linuxthreads_manager_pid))
843                 {
844                   stop_thread (linuxthreads_manager_pid);
845                   wait_thread (linuxthreads_manager_pid);
846                 }
847               if (!in_thread_list (test_pid))
848                 {
849                   if (!linuxthreads_attach_pending)
850                     printf_filtered ("[New %s]\n",
851                                      target_pid_to_str (test_pid));
852                   add_thread (test_pid);
853                   if (linuxthreads_sig_debug.signal
854                       && inferior_pid == test_pid)
855                     {
856                       /* After a new thread in glibc 2.1 signals gdb its
857                          existence, it suspends itself and wait for
858                          linuxthreads_sig_restart, now we can wake it up. */
859                       kill (test_pid, linuxthreads_sig_restart.signal);
860                     }
861                 }
862             }
863           iterate_active_threads (stop_thread, 0);
864           iterate_active_threads (wait_thread, 0);
865         }
866     }
867
868   if (old_chain != NULL)
869     do_cleanups (old_chain);
870 }
871
872 /* This routine is called whenever a new symbol table is read in, or
873    when all symbol tables are removed.  linux-thread event handling
874    can only be initialized when we find the right variables in
875    libpthread.so.  Since it's a shared library, those variables don't
876    show up until the library gets mapped and the symbol table is read
877    in.  */
878
879 /* This new_objfile event is now managed by a chained function pointer. 
880  * It is the callee's responsability to call the next client on the chain.
881  */
882
883 /* Saved pointer to previous owner of the new_objfile event. */
884 static void (*target_new_objfile_chain) (struct objfile *);
885
886 void
887 linuxthreads_new_objfile (struct objfile *objfile)
888 {
889   struct minimal_symbol *ms;
890
891   /* Call predecessor on chain, if any.
892      Calling the new module first allows it to dominate, 
893      if it finds its compatible libraries.  */
894
895   if (target_new_objfile_chain)
896     target_new_objfile_chain (objfile);
897
898   if (!objfile)
899     {
900       /* We're starting an entirely new executable, so we can no
901          longer be sure that it uses LinuxThreads.  Restore the signal
902          flags to their original states.  */
903       restore_all_signals ();
904
905       /* Indicate that we don't know anything's address any more.  */
906       linuxthreads_max = 0;
907
908       goto quit;
909     }
910
911   /* If we've already found our variables in another objfile, don't
912      bother looking for them again.  */
913   if (linuxthreads_max)
914     goto quit;
915
916   if (! lookup_minimal_symbol ("__pthread_initial_thread", NULL, objfile))
917     /* This object file isn't the pthreads library.  */
918     goto quit;
919
920   if ((ms = lookup_minimal_symbol ("__pthread_threads_debug",
921                                    NULL, objfile)) == NULL)
922     {
923       /* The debugging-aware libpthreads is not present in this objfile */
924       warning ("\
925 This program seems to use POSIX threads, but the thread library used\n\
926 does not support debugging.  This may make using GDB difficult.  Don't\n\
927 set breakpoints or single-step through code that might be executed by\n\
928 any thread other than the main thread.");
929       goto quit;
930     }
931   linuxthreads_debug = SYMBOL_VALUE_ADDRESS (ms);
932
933   /* Read internal structures configuration */
934   if ((ms = lookup_minimal_symbol ("__pthread_sizeof_handle",
935                                    NULL, objfile)) == NULL
936       || target_read_memory (SYMBOL_VALUE_ADDRESS (ms),
937                              (char *)&linuxthreads_sizeof_handle,
938                              sizeof (linuxthreads_sizeof_handle)) != 0)
939     {
940       fprintf_unfiltered (gdb_stderr,
941                           "Unable to find linuxthreads symbol \"%s\"\n",
942                           "__pthread_sizeof_handle");
943       goto quit;
944     }
945
946   if ((ms = lookup_minimal_symbol ("__pthread_offsetof_descr",
947                                    NULL, objfile)) == NULL
948       || target_read_memory (SYMBOL_VALUE_ADDRESS (ms),
949                              (char *)&linuxthreads_offset_descr,
950                              sizeof (linuxthreads_offset_descr)) != 0)
951     {
952       fprintf_unfiltered (gdb_stderr,
953                           "Unable to find linuxthreads symbol \"%s\"\n",
954                           "__pthread_offsetof_descr");
955       goto quit;
956     }
957          
958   if ((ms = lookup_minimal_symbol ("__pthread_offsetof_pid",
959                                    NULL, objfile)) == NULL
960       || target_read_memory (SYMBOL_VALUE_ADDRESS (ms),
961                              (char *)&linuxthreads_offset_pid,
962                              sizeof (linuxthreads_offset_pid)) != 0)
963     {
964       fprintf_unfiltered (gdb_stderr,
965                           "Unable to find linuxthreads symbol \"%s\"\n",
966                           "__pthread_offsetof_pid");
967       goto quit;
968     }
969
970   if (! find_all_signal_vars (objfile))
971     goto quit;
972
973   /* Read adresses of internal structures to access */
974   if ((ms = lookup_minimal_symbol ("__pthread_handles",
975                                    NULL, objfile)) == NULL)
976     {
977       fprintf_unfiltered (gdb_stderr,
978                           "Unable to find linuxthreads symbol \"%s\"\n",
979                           "__pthread_handles");
980       goto quit;
981     }
982   linuxthreads_handles = SYMBOL_VALUE_ADDRESS (ms);
983
984   if ((ms = lookup_minimal_symbol ("__pthread_handles_num",
985                                    NULL, objfile)) == NULL)
986     {
987       fprintf_unfiltered (gdb_stderr,
988                           "Unable to find linuxthreads symbol \"%s\"\n",
989                           "__pthread_handles_num");
990       goto quit;
991     }
992   linuxthreads_num = SYMBOL_VALUE_ADDRESS (ms);
993
994   if ((ms = lookup_minimal_symbol ("__pthread_manager_thread",
995                                    NULL, objfile)) == NULL)
996     {
997       fprintf_unfiltered (gdb_stderr,
998                           "Unable to find linuxthreads symbol \"%s\"\n",
999                           "__pthread_manager_thread");
1000       goto quit;
1001     }
1002   linuxthreads_manager = SYMBOL_VALUE_ADDRESS (ms) + linuxthreads_offset_pid;
1003
1004   if ((ms = lookup_minimal_symbol ("__pthread_initial_thread",
1005                                    NULL, objfile)) == NULL)
1006     {
1007       fprintf_unfiltered (gdb_stderr,
1008                           "Unable to find linuxthreads symbol \"%s\"\n",
1009                           "__pthread_initial_thread");
1010       goto quit;
1011     }
1012   linuxthreads_initial = SYMBOL_VALUE_ADDRESS (ms) + linuxthreads_offset_pid;
1013
1014   /* Search for this last, so it won't be set to a non-zero value unless
1015      we successfully found all the symbols above.  */
1016   if ((ms = lookup_minimal_symbol ("__pthread_threads_max",
1017                                    NULL, objfile)) == NULL
1018       || target_read_memory (SYMBOL_VALUE_ADDRESS (ms),
1019                              (char *)&linuxthreads_max,
1020                              sizeof (linuxthreads_max)) != 0)
1021     {
1022       fprintf_unfiltered (gdb_stderr,
1023                           "Unable to find linuxthreads symbol \"%s\"\n",
1024                           "__pthread_threads_max");
1025       goto quit;
1026     }
1027
1028   /* Allocate gdb internal structures */
1029   linuxthreads_wait_pid = 
1030     (int *) xmalloc (sizeof (int) * (linuxthreads_max + 1));
1031   linuxthreads_wait_status =
1032     (int *) xmalloc (sizeof (int) * (linuxthreads_max + 1));
1033   linuxthreads_breakpoint_zombie = (struct linuxthreads_breakpoint *)
1034     xmalloc (sizeof (struct linuxthreads_breakpoint) * (linuxthreads_max + 1));
1035
1036   if (inferior_pid && 
1037       !linuxthreads_attach_pending && 
1038       !using_thread_db)         /* suppressed by thread_db module */
1039     {
1040       int on = 1;
1041
1042       target_write_memory (linuxthreads_debug, (char *)&on, sizeof (on));
1043       linuxthreads_attach_pending = 1;
1044       update_stop_threads (inferior_pid);
1045       linuxthreads_attach_pending = 0;
1046     }
1047
1048   check_all_signal_numbers ();
1049
1050 quit:
1051 }
1052
1053 /* If we have switched threads from a one that stopped at breakpoint,
1054    return 1 otherwise 0.  */
1055
1056 int
1057 linuxthreads_prepare_to_proceed (int step)
1058 {
1059   if (!linuxthreads_max
1060       || !linuxthreads_manager_pid
1061       || !linuxthreads_breakpoint_pid
1062       || !breakpoint_here_p (read_pc_pid (linuxthreads_breakpoint_pid)))
1063     return 0;
1064
1065   if (step)
1066     {
1067       /* Mark the current inferior as single stepping process.  */
1068       linuxthreads_step_pid = inferior_pid;
1069     }
1070
1071   linuxthreads_inferior_pid = linuxthreads_breakpoint_pid;
1072   return linuxthreads_breakpoint_pid;
1073 }
1074
1075 /* Convert a pid to printable form. */
1076
1077 char *
1078 linuxthreads_pid_to_str (int pid)
1079 {
1080   static char buf[100];
1081
1082   sprintf (buf, "%s %d%s", linuxthreads_max ? "Thread" : "Pid", pid,
1083            (pid == linuxthreads_manager_pid) ? " (manager thread)"
1084            : (pid == linuxthreads_initial_pid) ? " (initial thread)"
1085            : "");
1086
1087   return buf;
1088 }
1089
1090 /* Attach to process PID, then initialize for debugging it
1091    and wait for the trace-trap that results from attaching.  */
1092
1093 static void
1094 linuxthreads_attach (char *args, int from_tty)
1095 {
1096   if (!args)
1097     error_no_arg ("process-id to attach");
1098
1099   push_target (&linuxthreads_ops);
1100   linuxthreads_breakpoints_inserted = 1;
1101   linuxthreads_breakpoint_last = -1;
1102   linuxthreads_wait_last = -1;
1103   WSETSTOP (linuxthreads_exit_status, 0);
1104
1105   child_ops.to_attach (args, from_tty);
1106
1107   if (linuxthreads_max)
1108     linuxthreads_attach_pending = 1;
1109 }
1110
1111 /* Take a program previously attached to and detaches it.
1112    The program resumes execution and will no longer stop
1113    on signals, etc.  We'd better not have left any breakpoints
1114    in the program or it'll die when it hits one.  For this
1115    to work, it may be necessary for the process to have been
1116    previously attached.  It *might* work if the program was
1117    started via the normal ptrace (PTRACE_TRACEME).  */
1118
1119 static void
1120 linuxthreads_detach (char *args, int from_tty)
1121 {
1122   if (linuxthreads_max)
1123     {
1124       int i;
1125       int pid;
1126       int off = 0;
1127       target_write_memory (linuxthreads_debug, (char *)&off, sizeof (off));
1128
1129       /* Walk through linuxthreads array in order to detach known threads.  */
1130       if (linuxthreads_manager_pid != 0)
1131         {
1132           /* Get rid of all positive zombie breakpoints.  */
1133           for (i = 0; i <= linuxthreads_breakpoint_last; i++)
1134             {
1135               if (linuxthreads_breakpoint_zombie[i].step)
1136                 continue;
1137
1138               pid = linuxthreads_breakpoint_zombie[i].pid;
1139               if (!linuxthreads_thread_alive (pid))
1140                 continue;
1141
1142               if (linuxthreads_breakpoint_zombie[i].pc != read_pc_pid (pid))
1143                 continue;
1144
1145               /* Continue in STEP mode until the thread pc has moved or
1146                  until SIGTRAP is found on the same PC.  */
1147               if (linuxthreads_find_trap (pid, 0)
1148                   && linuxthreads_breakpoint_zombie[i].pc == read_pc_pid (pid))
1149                 write_pc_pid (linuxthreads_breakpoint_zombie[i].pc
1150                               - DECR_PC_AFTER_BREAK, pid);
1151             }
1152
1153           /* Detach thread after thread.  */
1154           inferior_pid = linuxthreads_manager_pid;
1155           iterate_active_threads (detach_thread, 1);
1156
1157           /* Remove pending SIGTRAP and SIGSTOP */
1158           linuxthreads_find_trap (inferior_pid, 1);
1159
1160           linuxthreads_wait_last = -1;
1161           WSETSTOP (linuxthreads_exit_status, 0);
1162         }
1163
1164       linuxthreads_inferior_pid = 0;
1165       linuxthreads_breakpoint_pid = 0;
1166       linuxthreads_step_pid = 0;
1167       linuxthreads_step_signo = TARGET_SIGNAL_0;
1168       linuxthreads_manager_pid = 0;
1169       linuxthreads_initial_pid = 0;
1170       linuxthreads_attach_pending = 0;
1171       init_thread_list ();           /* Destroy thread info */
1172     }
1173
1174   child_ops.to_detach (args, from_tty);
1175
1176   unpush_target (&linuxthreads_ops);
1177 }
1178
1179 /* Resume execution of process PID.  If STEP is nozero, then
1180    just single step it.  If SIGNAL is nonzero, restart it with that
1181    signal activated.  */
1182
1183 static void
1184 linuxthreads_resume (int pid, int step, enum target_signal signo)
1185 {
1186   if (!linuxthreads_max || stop_soon_quietly || linuxthreads_manager_pid == 0)
1187     {
1188       child_ops.to_resume (pid, step, signo);
1189     }
1190   else
1191     {
1192       int rpid;
1193       if (linuxthreads_inferior_pid)
1194         {
1195           /* Prepare resume of the last thread that hit a breakpoint */
1196           linuxthreads_breakpoints_inserted = 0;
1197           rpid = linuxthreads_inferior_pid;
1198           linuxthreads_step_signo = signo;
1199         }
1200       else
1201         {
1202           struct cleanup *old_chain = NULL;
1203           int i;
1204
1205           if (pid < 0)
1206             {
1207               linuxthreads_step_pid = step ? inferior_pid : 0;
1208               linuxthreads_step_signo = signo;
1209               rpid = inferior_pid;
1210             }
1211           else
1212             rpid = pid;
1213
1214           if (pid < 0 || !step)
1215             {
1216               linuxthreads_breakpoints_inserted = 1;
1217
1218               /* Walk through linuxthreads array in order to resume threads */
1219               if (pid >= 0 && inferior_pid != pid)
1220                 {
1221                   old_chain = save_inferior_pid ();
1222                   inferior_pid = pid;
1223                 }
1224
1225               iterate_active_threads (resume_thread, 0);
1226               if (linuxthreads_manager_pid != inferior_pid
1227                   && !linuxthreads_pending_status (linuxthreads_manager_pid))
1228                 resume_thread (linuxthreads_manager_pid);
1229             }
1230           else
1231             linuxthreads_breakpoints_inserted = 0;
1232
1233           /* Deal with zombie breakpoint */
1234           for (i = 0; i <= linuxthreads_breakpoint_last; i++)
1235             if (linuxthreads_breakpoint_zombie[i].pid == rpid)
1236               {
1237                 if (linuxthreads_breakpoint_zombie[i].pc != read_pc_pid (rpid))
1238                   {
1239                     /* The current pc is out of zombie breakpoint.  */
1240                     REMOVE_BREAKPOINT_ZOMBIE(i);
1241                   }
1242                 break;
1243               }
1244
1245           if (old_chain != NULL)
1246             do_cleanups (old_chain);
1247         }
1248
1249       /* Resume initial thread. */
1250       /* [unles it has a wait event pending] */
1251       if (!linuxthreads_pending_status (rpid))
1252         {
1253           child_ops.to_resume (rpid, step, signo);
1254         }
1255     }
1256 }
1257
1258 /* Abstract out the child_wait functionality.  */
1259 int
1260 linux_child_wait (int pid, int *rpid, int *status)
1261 {
1262   int save_errno;
1263
1264   /* Note: inftarg has these inside the loop. */
1265   set_sigint_trap ();   /* Causes SIGINT to be passed on to the
1266                            attached process. */
1267   set_sigio_trap  ();
1268
1269   errno = save_errno = 0;
1270   for (;;)
1271     {
1272       errno = 0;
1273       *rpid = waitpid (pid, status, __WCLONE | WNOHANG);
1274       save_errno = errno;
1275
1276       if (*rpid > 0)
1277         {
1278           /* Got an event -- break out */
1279           break;
1280         }
1281       if (errno == EINTR)       /* interrupted by signal, try again */
1282         {
1283           continue;
1284         }
1285
1286       errno = 0;
1287       *rpid = waitpid (pid, status, WNOHANG);
1288       if (*rpid > 0)
1289         {
1290           /* Got an event -- break out */
1291           break;
1292         }
1293       if (errno == EINTR)
1294         {
1295           continue;
1296         }
1297       if (errno != 0 && save_errno != 0)
1298         {
1299           break;
1300         }
1301       sigsuspend(&linuxthreads_block_mask);
1302     }
1303   clear_sigio_trap  ();
1304   clear_sigint_trap ();
1305
1306   return errno ? errno : save_errno;
1307 }
1308
1309
1310 /* Wait for any threads to stop.  We may have to convert PID from a thread id
1311    to a LWP id, and vice versa on the way out.  */
1312
1313 static int
1314 linuxthreads_wait (int pid, struct target_waitstatus *ourstatus)
1315 {
1316   int status;
1317   int rpid;
1318   int i;
1319   int last;
1320   int *wstatus;
1321
1322   if (linuxthreads_max && !linuxthreads_breakpoints_inserted)
1323     wstatus = alloca (LINUXTHREAD_NSIG * sizeof (int));
1324
1325   /* See if the inferior has chosen values for its signals yet.  By
1326      checking for them here, we can be sure we've updated GDB's signal
1327      handling table before the inferior ever gets one of them.  (Well,
1328      before we notice, anyway.)  */
1329   check_all_signal_numbers ();
1330
1331   for (;;)
1332     {
1333       if (!linuxthreads_max)
1334           rpid = 0;
1335       else if (!linuxthreads_breakpoints_inserted)
1336         {
1337           if (linuxthreads_inferior_pid)
1338             pid = linuxthreads_inferior_pid;
1339           else if (pid < 0)
1340             pid = inferior_pid;
1341           last = rpid = 0;
1342         }
1343       else if (pid < 0 && linuxthreads_wait_last >= 0)
1344         {
1345           status = linuxthreads_wait_status[linuxthreads_wait_last];
1346           rpid = linuxthreads_wait_pid[linuxthreads_wait_last--];
1347         }
1348       else if (pid > 0 && linuxthreads_pending_status (pid))
1349         {
1350           for (i = linuxthreads_wait_last; i >= 0; i--)
1351             if (linuxthreads_wait_pid[i] == pid)
1352                 break;
1353           if (i < 0)
1354             rpid = 0;
1355           else
1356             {
1357               status = linuxthreads_wait_status[i];
1358               rpid = pid;
1359               if (i < linuxthreads_wait_last)
1360                 {
1361                   linuxthreads_wait_status[i] =
1362                     linuxthreads_wait_status[linuxthreads_wait_last];
1363                   linuxthreads_wait_pid[i] =
1364                     linuxthreads_wait_pid[linuxthreads_wait_last];
1365                 }
1366               linuxthreads_wait_last--;
1367             }
1368         }
1369       else
1370           rpid = 0;
1371
1372       if (rpid == 0)
1373         {
1374           int save_errno;
1375
1376           save_errno = linux_child_wait (pid, &rpid, &status);
1377
1378           if (rpid == -1)
1379             {
1380               if (WIFEXITED(linuxthreads_exit_status))
1381                 {
1382                   store_waitstatus (ourstatus, linuxthreads_exit_status);
1383                   return inferior_pid;
1384                 }
1385               else
1386                 {
1387                   fprintf_unfiltered
1388                       (gdb_stderr, "Child process unexpectedly missing: %s.\n",
1389                        safe_strerror (save_errno));
1390                   /* Claim it exited with unknown signal.  */
1391                   ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
1392                   ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1393                   return -1;
1394                 }
1395             }
1396
1397           /* We have now gotten a new event from waitpid above. */
1398
1399           /* Signals arrive in any order.  So get all signals until
1400              SIGTRAP and resend previous ones to be held after.  */
1401           if (linuxthreads_max
1402               && !linuxthreads_breakpoints_inserted
1403               && WIFSTOPPED(status))
1404             if (WSTOPSIG(status) == SIGTRAP)
1405               {
1406                 while (--last >= 0)
1407                   {
1408                     kill (rpid, WSTOPSIG(wstatus[last]));
1409                   }
1410
1411                 /* insert negative zombie breakpoint */
1412                 for (i = 0; i <= linuxthreads_breakpoint_last; i++)
1413                   if (linuxthreads_breakpoint_zombie[i].pid == rpid)
1414                       break;
1415                 if (i > linuxthreads_breakpoint_last)
1416                   {
1417                     linuxthreads_breakpoint_zombie[i].pid = rpid;
1418                     linuxthreads_breakpoint_last++;
1419                   }
1420                 linuxthreads_breakpoint_zombie[i].pc = read_pc_pid (rpid);
1421                 linuxthreads_breakpoint_zombie[i].step = 1;
1422               }
1423             else
1424               {
1425                 if (WSTOPSIG(status) != SIGSTOP)
1426                   {
1427                     for (i = 0; i < last; i++)
1428                       if (wstatus[i] == status)
1429                         break;
1430                     if (i >= last)
1431                       {
1432                         wstatus[last++] = status;
1433                       }
1434                   }
1435                 child_resume (rpid, 1, TARGET_SIGNAL_0);
1436                 continue;
1437               }
1438           if (linuxthreads_inferior_pid)
1439             linuxthreads_inferior_pid = 0;
1440         }
1441
1442       if (linuxthreads_max && !stop_soon_quietly)
1443         {
1444           if (linuxthreads_max
1445               && WIFSTOPPED(status)
1446               && WSTOPSIG(status) == SIGSTOP)
1447             {
1448               /* Skip SIGSTOP signals.  */
1449               if (!linuxthreads_pending_status (rpid))
1450                 {
1451                   if (linuxthreads_step_pid == rpid)
1452                     {
1453                       child_resume (rpid, 1, linuxthreads_step_signo);
1454                     }
1455                   else
1456                     {
1457                       child_resume (rpid, 0, TARGET_SIGNAL_0);
1458                     }
1459                 }
1460               continue;
1461             }
1462
1463           /* Do no report exit status of cloned threads.  */
1464           if (WIFEXITED(status))
1465             {
1466               if (rpid == linuxthreads_initial_pid)
1467                 linuxthreads_exit_status = status;
1468
1469               /* Remove any zombie breakpoint.  */
1470               for (i = 0; i <= linuxthreads_breakpoint_last; i++)
1471                 if (linuxthreads_breakpoint_zombie[i].pid == rpid)
1472                   {
1473                     REMOVE_BREAKPOINT_ZOMBIE(i);
1474                     break;
1475                   }
1476               if (pid > 0)
1477                 pid = -1;
1478               continue;
1479             }
1480
1481           /* Deal with zombie breakpoint */
1482           for (i = 0; i <= linuxthreads_breakpoint_last; i++)
1483             if (linuxthreads_breakpoint_zombie[i].pid == rpid)
1484               break;
1485
1486           if (i <= linuxthreads_breakpoint_last)
1487             {
1488               /* There is a potential zombie breakpoint */
1489               if (WIFEXITED(status)
1490                   || linuxthreads_breakpoint_zombie[i].pc != read_pc_pid (rpid))
1491                 {
1492                   /* The current pc is out of zombie breakpoint.  */
1493                   REMOVE_BREAKPOINT_ZOMBIE(i);
1494                 }
1495               else if (!linuxthreads_breakpoint_zombie[i].step
1496                        && WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)
1497                 {
1498                   /* This is a real one ==> decrement PC and restart.  */
1499                   write_pc_pid (linuxthreads_breakpoint_zombie[i].pc
1500                                 - DECR_PC_AFTER_BREAK, rpid);
1501                   if (linuxthreads_step_pid == rpid)
1502                     {
1503                       child_resume (rpid, 1, linuxthreads_step_signo);
1504                     }
1505                   else
1506                     {
1507                       child_resume (rpid, 0, TARGET_SIGNAL_0);
1508                     }
1509                   continue;
1510                 }
1511             }
1512
1513           /* Walk through linuxthreads array in order to stop them */
1514           if (linuxthreads_breakpoints_inserted)
1515             update_stop_threads (rpid);
1516
1517         }
1518       else if (rpid != inferior_pid)
1519         continue;
1520
1521       store_waitstatus (ourstatus, status);
1522
1523       if (linuxthreads_attach_pending && !stop_soon_quietly)
1524         {
1525           int on = 1;
1526           if (!using_thread_db)
1527             {
1528               target_write_memory (linuxthreads_debug, 
1529                                    (char *) &on, sizeof (on));
1530               update_stop_threads (rpid);
1531             }
1532           linuxthreads_attach_pending = 0;
1533         }
1534
1535       if (linuxthreads_breakpoints_inserted
1536           && WIFSTOPPED(status)
1537           && WSTOPSIG(status) == SIGTRAP)
1538         linuxthreads_breakpoint_pid = rpid;
1539       else if (linuxthreads_breakpoint_pid)
1540         linuxthreads_breakpoint_pid = 0;
1541
1542       return rpid;
1543     }
1544 }
1545
1546 /* Fork an inferior process, and start debugging it with ptrace.  */
1547
1548 static void
1549 linuxthreads_create_inferior (char *exec_file, char *allargs, char **env)
1550 {
1551   if (!exec_file && !exec_bfd)
1552     {
1553       error ("No executable file specified.\n\
1554 Use the \"file\" or \"exec-file\" command.");
1555       return;
1556     }
1557
1558   push_target (&linuxthreads_ops);
1559   linuxthreads_breakpoints_inserted = 1;
1560   linuxthreads_breakpoint_last = -1;
1561   linuxthreads_wait_last = -1;
1562   WSETSTOP (linuxthreads_exit_status, 0);
1563   
1564   if (linuxthreads_max)
1565     linuxthreads_attach_pending = 1;
1566
1567   child_ops.to_create_inferior (exec_file, allargs, env);
1568 }
1569
1570 void
1571 linuxthreads_discard_global_state (void)
1572 {
1573   linuxthreads_inferior_pid = 0;
1574   linuxthreads_breakpoint_pid = 0;
1575   linuxthreads_step_pid = 0;
1576   linuxthreads_step_signo = TARGET_SIGNAL_0;
1577   linuxthreads_manager_pid = 0;
1578   linuxthreads_initial_pid = 0;
1579   linuxthreads_attach_pending = 0;
1580   linuxthreads_max = 0;
1581 }
1582
1583 /* Clean up after the inferior dies.  */
1584
1585 static void
1586 linuxthreads_mourn_inferior (void)
1587 {
1588   if (linuxthreads_max)
1589     {
1590       int off = 0;
1591       target_write_memory (linuxthreads_debug, (char *)&off, sizeof (off));
1592
1593       linuxthreads_discard_global_state ();
1594       init_thread_list();           /* Destroy thread info */
1595     }
1596
1597   child_ops.to_mourn_inferior ();
1598
1599   unpush_target (&linuxthreads_ops);
1600 }
1601
1602 /* Kill the inferior process */
1603
1604 static void
1605 linuxthreads_kill (void)
1606 {
1607   int rpid;
1608   int status;
1609
1610   if (inferior_pid == 0)
1611     return;
1612
1613   if (linuxthreads_max && linuxthreads_manager_pid != 0)
1614     {
1615       /* Remove all threads status.  */
1616       inferior_pid = linuxthreads_manager_pid;
1617       iterate_active_threads (kill_thread, 1);
1618     }
1619
1620   kill_thread (inferior_pid);
1621
1622 #if 0
1623   /* doing_quit_force solves a real problem, but I think a properly
1624      placed call to catch_errors would do the trick much more cleanly.  */
1625   if (doing_quit_force >= 0)
1626     {
1627       if (linuxthreads_max && linuxthreads_manager_pid != 0)
1628         {
1629           /* Wait for thread to complete */
1630           while ((rpid = waitpid (-1, &status, __WCLONE)) > 0)
1631             if (!WIFEXITED(status))
1632               kill_thread (rpid);
1633
1634           while ((rpid = waitpid (-1, &status, 0)) > 0)
1635             if (!WIFEXITED(status))
1636               kill_thread (rpid);
1637         }
1638       else
1639         while ((rpid = waitpid (inferior_pid, &status, 0)) > 0)
1640           if (!WIFEXITED(status))
1641             ptrace (PT_KILL, inferior_pid, (PTRACE_ARG3_TYPE) 0, 0);
1642     }
1643 #endif
1644
1645   /* Wait for all threads. */
1646   do
1647     {
1648       rpid = waitpid (-1, &status, __WCLONE | WNOHANG);
1649     }
1650   while (rpid > 0 || errno == EINTR);
1651   /* FIXME: should no longer need to handle EINTR here. */
1652
1653   do
1654     {
1655       rpid = waitpid (-1, &status, WNOHANG);
1656     }
1657   while (rpid > 0 || errno == EINTR);
1658   /* FIXME: should no longer need to handle EINTR here. */
1659
1660   linuxthreads_mourn_inferior ();
1661 }
1662
1663 /* Insert a breakpoint */
1664
1665 static int
1666 linuxthreads_insert_breakpoint (CORE_ADDR addr, char *contents_cache)
1667 {
1668   if (linuxthreads_max && linuxthreads_manager_pid != 0)
1669     {
1670       linuxthreads_breakpoint_addr = addr;
1671       iterate_active_threads (insert_breakpoint, 1);
1672       insert_breakpoint (linuxthreads_manager_pid);
1673     }
1674
1675   return child_ops.to_insert_breakpoint (addr, contents_cache);
1676 }
1677
1678 /* Remove a breakpoint */
1679
1680 static int
1681 linuxthreads_remove_breakpoint (CORE_ADDR addr, char *contents_cache)
1682 {
1683   if (linuxthreads_max && linuxthreads_manager_pid != 0)
1684     {
1685       linuxthreads_breakpoint_addr = addr;
1686       iterate_active_threads (remove_breakpoint, 1);
1687       remove_breakpoint (linuxthreads_manager_pid);
1688     }
1689
1690   return child_ops.to_remove_breakpoint (addr, contents_cache);
1691 }
1692
1693 /* Mark our target-struct as eligible for stray "run" and "attach" commands.  */
1694
1695 static int
1696 linuxthreads_can_run (void)
1697 {
1698   return child_suppress_run;
1699 }
1700
1701 \f
1702 static void
1703 init_linuxthreads_ops (void)
1704 {
1705   linuxthreads_ops.to_shortname = "linuxthreads";
1706   linuxthreads_ops.to_longname  = "LINUX threads and pthread.";
1707   linuxthreads_ops.to_doc       = "LINUX threads and pthread support.";
1708   linuxthreads_ops.to_attach    = linuxthreads_attach;
1709   linuxthreads_ops.to_detach    = linuxthreads_detach;
1710   linuxthreads_ops.to_resume    = linuxthreads_resume;
1711   linuxthreads_ops.to_wait      = linuxthreads_wait;
1712   linuxthreads_ops.to_kill      = linuxthreads_kill;
1713   linuxthreads_ops.to_can_run   = linuxthreads_can_run;
1714   linuxthreads_ops.to_stratum   = thread_stratum;
1715   linuxthreads_ops.to_insert_breakpoint = linuxthreads_insert_breakpoint;
1716   linuxthreads_ops.to_remove_breakpoint = linuxthreads_remove_breakpoint;
1717   linuxthreads_ops.to_create_inferior   = linuxthreads_create_inferior;
1718   linuxthreads_ops.to_mourn_inferior    = linuxthreads_mourn_inferior;
1719   linuxthreads_ops.to_thread_alive      = linuxthreads_thread_alive;
1720   linuxthreads_ops.to_pid_to_str        = linuxthreads_pid_to_str;
1721   linuxthreads_ops.to_magic             = OPS_MAGIC;
1722 }
1723
1724 void
1725 _initialize_linuxthreads (void)
1726 {
1727   struct sigaction sact;
1728   sigset_t linuxthreads_wait_mask;        /* sigset with SIGCHLD */
1729
1730   init_linuxthreads_ops ();
1731   add_target (&linuxthreads_ops);
1732   child_suppress_run = 1;
1733
1734   /* Hook onto the "new_objfile" event.
1735    * If someone else is already hooked onto the event, 
1736    * then make sure he will be called after we are.
1737    */
1738   target_new_objfile_chain = target_new_objfile_hook;
1739   target_new_objfile_hook  = linuxthreads_new_objfile;
1740
1741   /* Attach SIGCHLD handler */
1742   sact.sa_handler = sigchld_handler;
1743   sigemptyset (&sact.sa_mask);
1744   sact.sa_flags = 0;
1745   sigaction (SIGCHLD, &sact, NULL);
1746
1747   /* initialize SIGCHLD mask */
1748   sigemptyset (&linuxthreads_wait_mask);
1749   sigaddset (&linuxthreads_wait_mask, SIGCHLD);
1750
1751   /* Use SIG_BLOCK to block receipt of SIGCHLD.
1752      The block_mask will allow us to wait for this signal explicitly.  */
1753   sigprocmask(SIG_BLOCK, 
1754               &linuxthreads_wait_mask, 
1755               &linuxthreads_block_mask);
1756   /* Make sure that linuxthreads_block_mask is not blocking SIGCHLD */
1757   sigdelset (&linuxthreads_block_mask, SIGCHLD);
1758 }