* hppa-tdep.h (hppa_regnum): Add HPPA_R31_REGNUM.
[platform/upstream/binutils.git] / gdb / thread-db.c
1 /* libthread_db assisted debugging support, generic parts.
2
3    Copyright 1999, 2000, 2001, 2003, 2004 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,
20    Boston, MA 02111-1307, USA.  */
21
22 #include "defs.h"
23
24 #include "gdb_assert.h"
25 #include <dlfcn.h>
26 #include "gdb_proc_service.h"
27 #include "gdb_thread_db.h"
28
29 #include "bfd.h"
30 #include "gdbthread.h"
31 #include "inferior.h"
32 #include "symfile.h"
33 #include "objfiles.h"
34 #include "target.h"
35 #include "regcache.h"
36 #include "solib-svr4.h"
37
38 #ifdef HAVE_GNU_LIBC_VERSION_H
39 #include <gnu/libc-version.h>
40 #endif
41
42 #ifndef LIBTHREAD_DB_SO
43 #define LIBTHREAD_DB_SO "libthread_db.so.1"
44 #endif
45
46 /* If we're running on GNU/Linux, we must explicitly attach to any new
47    threads.  */
48
49 /* FIXME: There is certainly some room for improvements:
50    - Cache LWP ids.
51    - Bypass libthread_db when fetching or storing registers for
52    threads bound to a LWP.  */
53
54 /* This module's target vector.  */
55 static struct target_ops thread_db_ops;
56
57 /* The target vector that we call for things this module can't handle.  */
58 static struct target_ops *target_beneath;
59
60 /* Pointer to the next function on the objfile event chain.  */
61 static void (*target_new_objfile_chain) (struct objfile * objfile);
62
63 /* Non-zero if we're using this module's target vector.  */
64 static int using_thread_db;
65
66 /* Non-zero if we have to keep this module's target vector active
67    across re-runs.  */
68 static int keep_thread_db;
69
70 /* Non-zero if we have determined the signals used by the threads
71    library.  */
72 static int thread_signals;
73 static sigset_t thread_stop_set;
74 static sigset_t thread_print_set;
75
76 /* Structure that identifies the child process for the
77    <proc_service.h> interface.  */
78 static struct ps_prochandle proc_handle;
79
80 /* Connection to the libthread_db library.  */
81 static td_thragent_t *thread_agent;
82
83 /* Pointers to the libthread_db functions.  */
84
85 static td_err_e (*td_init_p) (void);
86
87 static td_err_e (*td_ta_new_p) (struct ps_prochandle * ps,
88                                 td_thragent_t **ta);
89 static td_err_e (*td_ta_map_id2thr_p) (const td_thragent_t *ta, thread_t pt,
90                                        td_thrhandle_t *__th);
91 static td_err_e (*td_ta_map_lwp2thr_p) (const td_thragent_t *ta,
92                                         lwpid_t lwpid, td_thrhandle_t *th);
93 static td_err_e (*td_ta_thr_iter_p) (const td_thragent_t *ta,
94                                      td_thr_iter_f *callback, void *cbdata_p,
95                                      td_thr_state_e state, int ti_pri,
96                                      sigset_t *ti_sigmask_p,
97                                      unsigned int ti_user_flags);
98 static td_err_e (*td_ta_event_addr_p) (const td_thragent_t *ta,
99                                        td_event_e event, td_notify_t *ptr);
100 static td_err_e (*td_ta_set_event_p) (const td_thragent_t *ta,
101                                       td_thr_events_t *event);
102 static td_err_e (*td_ta_event_getmsg_p) (const td_thragent_t *ta,
103                                          td_event_msg_t *msg);
104
105 static td_err_e (*td_thr_validate_p) (const td_thrhandle_t *th);
106 static td_err_e (*td_thr_get_info_p) (const td_thrhandle_t *th,
107                                       td_thrinfo_t *infop);
108 static td_err_e (*td_thr_getfpregs_p) (const td_thrhandle_t *th,
109                                        gdb_prfpregset_t *regset);
110 static td_err_e (*td_thr_getgregs_p) (const td_thrhandle_t *th,
111                                       prgregset_t gregs);
112 static td_err_e (*td_thr_setfpregs_p) (const td_thrhandle_t *th,
113                                        const gdb_prfpregset_t *fpregs);
114 static td_err_e (*td_thr_setgregs_p) (const td_thrhandle_t *th,
115                                       prgregset_t gregs);
116 static td_err_e (*td_thr_event_enable_p) (const td_thrhandle_t *th,
117                                           int event);
118
119 static td_err_e (*td_thr_tls_get_addr_p) (const td_thrhandle_t *th,
120                                           void *map_address,
121                                           size_t offset, void **address);
122
123 /* Location of the thread creation event breakpoint.  The code at this
124    location in the child process will be called by the pthread library
125    whenever a new thread is created.  By setting a special breakpoint
126    at this location, GDB can detect when a new thread is created.  We
127    obtain this location via the td_ta_event_addr call.  */
128 static CORE_ADDR td_create_bp_addr;
129
130 /* Location of the thread death event breakpoint.  */
131 static CORE_ADDR td_death_bp_addr;
132
133 /* Prototypes for local functions.  */
134 static void thread_db_find_new_threads (void);
135 static void attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
136                            const td_thrinfo_t *ti_p, int verbose);
137 static void detach_thread (ptid_t ptid, int verbose);
138 \f
139
140 /* Building process ids.  */
141
142 #define GET_PID(ptid)           ptid_get_pid (ptid)
143 #define GET_LWP(ptid)           ptid_get_lwp (ptid)
144 #define GET_THREAD(ptid)        ptid_get_tid (ptid)
145
146 #define is_lwp(ptid)            (GET_LWP (ptid) != 0)
147 #define is_thread(ptid)         (GET_THREAD (ptid) != 0)
148
149 #define BUILD_LWP(lwp, pid)     ptid_build (pid, lwp, 0)
150 #define BUILD_THREAD(tid, pid)  ptid_build (pid, 0, tid)
151 \f
152
153 /* Use "struct private_thread_info" to cache thread state.  This is
154    a substantial optimization.  */
155
156 struct private_thread_info
157 {
158   /* Flag set when we see a TD_DEATH event for this thread.  */
159   unsigned int dying:1;
160
161   /* Cached thread state.  */
162   unsigned int th_valid:1;
163   unsigned int ti_valid:1;
164
165   td_thrhandle_t th;
166   td_thrinfo_t ti;
167 };
168 \f
169
170 static char *
171 thread_db_err_str (td_err_e err)
172 {
173   static char buf[64];
174
175   switch (err)
176     {
177     case TD_OK:
178       return "generic 'call succeeded'";
179     case TD_ERR:
180       return "generic error";
181     case TD_NOTHR:
182       return "no thread to satisfy query";
183     case TD_NOSV:
184       return "no sync handle to satisfy query";
185     case TD_NOLWP:
186       return "no LWP to satisfy query";
187     case TD_BADPH:
188       return "invalid process handle";
189     case TD_BADTH:
190       return "invalid thread handle";
191     case TD_BADSH:
192       return "invalid synchronization handle";
193     case TD_BADTA:
194       return "invalid thread agent";
195     case TD_BADKEY:
196       return "invalid key";
197     case TD_NOMSG:
198       return "no event message for getmsg";
199     case TD_NOFPREGS:
200       return "FPU register set not available";
201     case TD_NOLIBTHREAD:
202       return "application not linked with libthread";
203     case TD_NOEVENT:
204       return "requested event is not supported";
205     case TD_NOCAPAB:
206       return "capability not available";
207     case TD_DBERR:
208       return "debugger service failed";
209     case TD_NOAPLIC:
210       return "operation not applicable to";
211     case TD_NOTSD:
212       return "no thread-specific data for this thread";
213     case TD_MALLOC:
214       return "malloc failed";
215     case TD_PARTIALREG:
216       return "only part of register set was written/read";
217     case TD_NOXREGS:
218       return "X register set not available for this thread";
219     default:
220       snprintf (buf, sizeof (buf), "unknown thread_db error '%d'", err);
221       return buf;
222     }
223 }
224
225 static char *
226 thread_db_state_str (td_thr_state_e state)
227 {
228   static char buf[64];
229
230   switch (state)
231     {
232     case TD_THR_STOPPED:
233       return "stopped by debugger";
234     case TD_THR_RUN:
235       return "runnable";
236     case TD_THR_ACTIVE:
237       return "active";
238     case TD_THR_ZOMBIE:
239       return "zombie";
240     case TD_THR_SLEEP:
241       return "sleeping";
242     case TD_THR_STOPPED_ASLEEP:
243       return "stopped by debugger AND blocked";
244     default:
245       snprintf (buf, sizeof (buf), "unknown thread_db state %d", state);
246       return buf;
247     }
248 }
249 \f
250 /* A callback function for td_ta_thr_iter, which we use to map all
251    threads to LWPs.
252
253    THP is a handle to the current thread; if INFOP is not NULL, the
254    struct thread_info associated with this thread is returned in
255    *INFOP.  */
256
257 static int
258 thread_get_info_callback (const td_thrhandle_t *thp, void *infop)
259 {
260   td_thrinfo_t ti;
261   td_err_e err;
262   struct thread_info *thread_info;
263   ptid_t thread_ptid;
264
265   err = td_thr_get_info_p (thp, &ti);
266   if (err != TD_OK)
267     error ("thread_get_info_callback: cannot get thread info: %s",
268            thread_db_err_str (err));
269
270   /* Fill the cache.  */
271   thread_ptid = BUILD_THREAD (ti.ti_tid, GET_PID (inferior_ptid));
272   thread_info = find_thread_pid (thread_ptid);
273
274   if (thread_info == NULL)
275     {
276       /* New thread.  Attach to it now (why wait?).  */
277       attach_thread (thread_ptid, thp, &ti, 1);
278       thread_info = find_thread_pid (thread_ptid);
279       gdb_assert (thread_info != NULL);
280     }
281
282   memcpy (&thread_info->private->th, thp, sizeof (*thp));
283   thread_info->private->th_valid = 1;
284   memcpy (&thread_info->private->ti, &ti, sizeof (ti));
285   thread_info->private->ti_valid = 1;
286
287   if (infop != NULL)
288     *(struct thread_info **) infop = thread_info;
289
290   return 0;
291 }
292
293 /* Accessor functions for the thread_db information, with caching.  */
294
295 static void
296 thread_db_map_id2thr (struct thread_info *thread_info, int fatal)
297 {
298   td_err_e err;
299
300   if (thread_info->private->th_valid)
301     return;
302
303   err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (thread_info->ptid),
304                             &thread_info->private->th);
305   if (err != TD_OK)
306     {
307       if (fatal)
308         error ("Cannot find thread %ld: %s",
309                (long) GET_THREAD (thread_info->ptid),
310                thread_db_err_str (err));
311     }
312   else
313     thread_info->private->th_valid = 1;
314 }
315
316 static td_thrinfo_t *
317 thread_db_get_info (struct thread_info *thread_info)
318 {
319   td_err_e err;
320
321   if (thread_info->private->ti_valid)
322     return &thread_info->private->ti;
323
324   if (!thread_info->private->th_valid)
325     thread_db_map_id2thr (thread_info, 1);
326
327   err =
328     td_thr_get_info_p (&thread_info->private->th, &thread_info->private->ti);
329   if (err != TD_OK)
330     error ("thread_db_get_info: cannot get thread info: %s",
331            thread_db_err_str (err));
332
333   thread_info->private->ti_valid = 1;
334   return &thread_info->private->ti;
335 }
336 \f
337 /* Convert between user-level thread ids and LWP ids.  */
338
339 static ptid_t
340 thread_from_lwp (ptid_t ptid)
341 {
342   td_thrhandle_t th;
343   td_err_e err;
344   struct thread_info *thread_info;
345   ptid_t thread_ptid;
346
347   if (GET_LWP (ptid) == 0)
348     ptid = BUILD_LWP (GET_PID (ptid), GET_PID (ptid));
349
350   gdb_assert (is_lwp (ptid));
351
352   err = td_ta_map_lwp2thr_p (thread_agent, GET_LWP (ptid), &th);
353   if (err != TD_OK)
354     error ("Cannot find user-level thread for LWP %ld: %s",
355            GET_LWP (ptid), thread_db_err_str (err));
356
357   thread_info = NULL;
358   thread_get_info_callback (&th, &thread_info);
359   gdb_assert (thread_info && thread_info->private->ti_valid);
360
361   return BUILD_THREAD (thread_info->private->ti.ti_tid, GET_PID (ptid));
362 }
363
364 static ptid_t
365 lwp_from_thread (ptid_t ptid)
366 {
367   struct thread_info *thread_info;
368   ptid_t thread_ptid;
369
370   if (!is_thread (ptid))
371     return ptid;
372
373   thread_info = find_thread_pid (ptid);
374   thread_db_get_info (thread_info);
375
376   return BUILD_LWP (thread_info->private->ti.ti_lid, GET_PID (ptid));
377 }
378 \f
379
380 void
381 thread_db_init (struct target_ops *target)
382 {
383   target_beneath = target;
384 }
385
386 static void *
387 verbose_dlsym (void *handle, const char *name)
388 {
389   void *sym = dlsym (handle, name);
390   if (sym == NULL)
391     warning ("Symbol \"%s\" not found in libthread_db: %s", name, dlerror ());
392   return sym;
393 }
394
395 static int
396 thread_db_load (void)
397 {
398   void *handle;
399   td_err_e err;
400
401   handle = dlopen (LIBTHREAD_DB_SO, RTLD_NOW);
402   if (handle == NULL)
403     {
404       fprintf_filtered (gdb_stderr, "\n\ndlopen failed on '%s' - %s\n",
405                         LIBTHREAD_DB_SO, dlerror ());
406       fprintf_filtered (gdb_stderr,
407                         "GDB will not be able to debug pthreads.\n\n");
408       return 0;
409     }
410
411   /* Initialize pointers to the dynamic library functions we will use.
412      Essential functions first.  */
413
414   td_init_p = verbose_dlsym (handle, "td_init");
415   if (td_init_p == NULL)
416     return 0;
417
418   td_ta_new_p = verbose_dlsym (handle, "td_ta_new");
419   if (td_ta_new_p == NULL)
420     return 0;
421
422   td_ta_map_id2thr_p = verbose_dlsym (handle, "td_ta_map_id2thr");
423   if (td_ta_map_id2thr_p == NULL)
424     return 0;
425
426   td_ta_map_lwp2thr_p = verbose_dlsym (handle, "td_ta_map_lwp2thr");
427   if (td_ta_map_lwp2thr_p == NULL)
428     return 0;
429
430   td_ta_thr_iter_p = verbose_dlsym (handle, "td_ta_thr_iter");
431   if (td_ta_thr_iter_p == NULL)
432     return 0;
433
434   td_thr_validate_p = verbose_dlsym (handle, "td_thr_validate");
435   if (td_thr_validate_p == NULL)
436     return 0;
437
438   td_thr_get_info_p = verbose_dlsym (handle, "td_thr_get_info");
439   if (td_thr_get_info_p == NULL)
440     return 0;
441
442   td_thr_getfpregs_p = verbose_dlsym (handle, "td_thr_getfpregs");
443   if (td_thr_getfpregs_p == NULL)
444     return 0;
445
446   td_thr_getgregs_p = verbose_dlsym (handle, "td_thr_getgregs");
447   if (td_thr_getgregs_p == NULL)
448     return 0;
449
450   td_thr_setfpregs_p = verbose_dlsym (handle, "td_thr_setfpregs");
451   if (td_thr_setfpregs_p == NULL)
452     return 0;
453
454   td_thr_setgregs_p = verbose_dlsym (handle, "td_thr_setgregs");
455   if (td_thr_setgregs_p == NULL)
456     return 0;
457
458   /* Initialize the library.  */
459   err = td_init_p ();
460   if (err != TD_OK)
461     {
462       warning ("Cannot initialize libthread_db: %s", thread_db_err_str (err));
463       return 0;
464     }
465
466   /* These are not essential.  */
467   td_ta_event_addr_p = dlsym (handle, "td_ta_event_addr");
468   td_ta_set_event_p = dlsym (handle, "td_ta_set_event");
469   td_ta_event_getmsg_p = dlsym (handle, "td_ta_event_getmsg");
470   td_thr_event_enable_p = dlsym (handle, "td_thr_event_enable");
471   td_thr_tls_get_addr_p = dlsym (handle, "td_thr_tls_get_addr");
472
473   return 1;
474 }
475
476 static td_err_e
477 enable_thread_event (td_thragent_t *thread_agent, int event, CORE_ADDR *bp)
478 {
479   td_notify_t notify;
480   td_err_e err;
481
482   /* Get the breakpoint address for thread EVENT.  */
483   err = td_ta_event_addr_p (thread_agent, event, &notify);
484   if (err != TD_OK)
485     return err;
486
487   /* Set up the breakpoint.  */
488   (*bp) = gdbarch_convert_from_func_ptr_addr (current_gdbarch,
489                                               (CORE_ADDR) notify.u.bptaddr,
490                                               &current_target);
491   create_thread_event_breakpoint ((*bp));
492
493   return TD_OK;
494 }
495
496 static void
497 enable_thread_event_reporting (void)
498 {
499   td_thr_events_t events;
500   td_notify_t notify;
501   td_err_e err;
502 #ifdef HAVE_GNU_LIBC_VERSION_H
503   const char *libc_version;
504   int libc_major, libc_minor;
505 #endif
506
507   /* We cannot use the thread event reporting facility if these
508      functions aren't available.  */
509   if (td_ta_event_addr_p == NULL || td_ta_set_event_p == NULL
510       || td_ta_event_getmsg_p == NULL || td_thr_event_enable_p == NULL)
511     return;
512
513   /* Set the process wide mask saying which events we're interested in.  */
514   td_event_emptyset (&events);
515   td_event_addset (&events, TD_CREATE);
516
517 #ifdef HAVE_GNU_LIBC_VERSION_H
518   /* FIXME: kettenis/2000-04-23: The event reporting facility is
519      broken for TD_DEATH events in glibc 2.1.3, so don't enable it for
520      now.  */
521   libc_version = gnu_get_libc_version ();
522   if (sscanf (libc_version, "%d.%d", &libc_major, &libc_minor) == 2
523       && (libc_major > 2 || (libc_major == 2 && libc_minor > 1)))
524 #endif
525     td_event_addset (&events, TD_DEATH);
526
527   err = td_ta_set_event_p (thread_agent, &events);
528   if (err != TD_OK)
529     {
530       warning ("Unable to set global thread event mask: %s",
531                thread_db_err_str (err));
532       return;
533     }
534
535   /* Delete previous thread event breakpoints, if any.  */
536   remove_thread_event_breakpoints ();
537   td_create_bp_addr = 0;
538   td_death_bp_addr = 0;
539
540   /* Set up the thread creation event.  */
541   err = enable_thread_event (thread_agent, TD_CREATE, &td_create_bp_addr);
542   if (err != TD_OK)
543     {
544       warning ("Unable to get location for thread creation breakpoint: %s",
545                thread_db_err_str (err));
546       return;
547     }
548
549   /* Set up the thread death event.  */
550   err = enable_thread_event (thread_agent, TD_DEATH, &td_death_bp_addr);
551   if (err != TD_OK)
552     {
553       warning ("Unable to get location for thread death breakpoint: %s",
554                thread_db_err_str (err));
555       return;
556     }
557 }
558
559 static void
560 disable_thread_event_reporting (void)
561 {
562   td_thr_events_t events;
563
564   /* Set the process wide mask saying we aren't interested in any
565      events anymore.  */
566   td_event_emptyset (&events);
567   td_ta_set_event_p (thread_agent, &events);
568
569   /* Delete thread event breakpoints, if any.  */
570   remove_thread_event_breakpoints ();
571   td_create_bp_addr = 0;
572   td_death_bp_addr = 0;
573 }
574
575 static void
576 check_thread_signals (void)
577 {
578 #ifdef GET_THREAD_SIGNALS
579   if (!thread_signals)
580     {
581       sigset_t mask;
582       int i;
583
584       GET_THREAD_SIGNALS (&mask);
585       sigemptyset (&thread_stop_set);
586       sigemptyset (&thread_print_set);
587
588       for (i = 1; i < NSIG; i++)
589         {
590           if (sigismember (&mask, i))
591             {
592               if (signal_stop_update (target_signal_from_host (i), 0))
593                 sigaddset (&thread_stop_set, i);
594               if (signal_print_update (target_signal_from_host (i), 0))
595                 sigaddset (&thread_print_set, i);
596               thread_signals = 1;
597             }
598         }
599     }
600 #endif
601 }
602
603 static void
604 thread_db_new_objfile (struct objfile *objfile)
605 {
606   td_err_e err;
607
608   /* First time through, report that libthread_db was successfuly
609      loaded.  Can't print this in in thread_db_load as, at that stage,
610      the interpreter and it's console haven't started.  The real
611      problem here is that libthread_db is loaded too early - it should
612      only be loaded when there is a program to debug.  */
613   {
614     static int dejavu;
615     if (!dejavu)
616       {
617         Dl_info info;
618         const char *library = NULL;
619         /* Try dladdr.  */
620         if (dladdr ((*td_ta_new_p), &info) != 0)
621           library = info.dli_fname;
622         /* Try dlinfo?  */
623         if (library == NULL)
624           /* Paranoid - don't let a NULL path slip through.  */
625           library = LIBTHREAD_DB_SO;
626         printf_unfiltered ("Using host libthread_db library \"%s\".\n",
627                            library);
628         dejavu = 1;
629       }
630   }
631
632   /* Don't attempt to use thread_db on targets which can not run
633      (core files).  */
634   if (objfile == NULL || !target_has_execution)
635     {
636       /* All symbols have been discarded.  If the thread_db target is
637          active, deactivate it now.  */
638       if (using_thread_db)
639         {
640           gdb_assert (proc_handle.pid == 0);
641           unpush_target (&thread_db_ops);
642           using_thread_db = 0;
643         }
644
645       keep_thread_db = 0;
646
647       goto quit;
648     }
649
650   if (using_thread_db)
651     /* Nothing to do.  The thread library was already detected and the
652        target vector was already activated.  */
653     goto quit;
654
655   /* Initialize the structure that identifies the child process.  Note
656      that at this point there is no guarantee that we actually have a
657      child process.  */
658   proc_handle.pid = GET_PID (inferior_ptid);
659
660   /* Now attempt to open a connection to the thread library.  */
661   err = td_ta_new_p (&proc_handle, &thread_agent);
662   switch (err)
663     {
664     case TD_NOLIBTHREAD:
665       /* No thread library was detected.  */
666       break;
667
668     case TD_OK:
669       printf_unfiltered ("[Thread debugging using libthread_db enabled]\n");
670
671       /* The thread library was detected.  Activate the thread_db target.  */
672       push_target (&thread_db_ops);
673       using_thread_db = 1;
674
675       /* If the thread library was detected in the main symbol file
676          itself, we assume that the program was statically linked
677          against the thread library and well have to keep this
678          module's target vector activated until forever...  Well, at
679          least until all symbols have been discarded anyway (see
680          above).  */
681       if (objfile == symfile_objfile)
682         {
683           gdb_assert (proc_handle.pid == 0);
684           keep_thread_db = 1;
685         }
686
687       /* We can only poke around if there actually is a child process.
688          If there is no child process alive, postpone the steps below
689          until one has been created.  */
690       if (proc_handle.pid != 0)
691         {
692           enable_thread_event_reporting ();
693           thread_db_find_new_threads ();
694         }
695       break;
696
697     default:
698       warning ("Cannot initialize thread debugging library: %s",
699                thread_db_err_str (err));
700       break;
701     }
702
703 quit:
704   if (target_new_objfile_chain)
705     target_new_objfile_chain (objfile);
706 }
707
708 /* Attach to a new thread.  This function is called when we receive a
709    TD_CREATE event or when we iterate over all threads and find one
710    that wasn't already in our list.  */
711
712 static void
713 attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
714                const td_thrinfo_t *ti_p, int verbose)
715 {
716   struct thread_info *tp;
717   td_err_e err;
718
719   /* If we're being called after a TD_CREATE event, we may already
720      know about this thread.  There are two ways this can happen.  We
721      may have iterated over all threads between the thread creation
722      and the TD_CREATE event, for instance when the user has issued
723      the `info threads' command before the SIGTRAP for hitting the
724      thread creation breakpoint was reported.  Alternatively, the
725      thread may have exited and a new one been created with the same
726      thread ID.  In the first case we don't need to do anything; in
727      the second case we should discard information about the dead
728      thread and attach to the new one.  */
729   if (in_thread_list (ptid))
730     {
731       tp = find_thread_pid (ptid);
732       gdb_assert (tp != NULL);
733
734       if (!tp->private->dying)
735         return;
736
737       delete_thread (ptid);
738     }
739
740   check_thread_signals ();
741
742   /* Add the thread to GDB's thread list.  */
743   tp = add_thread (ptid);
744   tp->private = xmalloc (sizeof (struct private_thread_info));
745   memset (tp->private, 0, sizeof (struct private_thread_info));
746
747   if (verbose)
748     printf_unfiltered ("[New %s]\n", target_pid_to_str (ptid));
749
750   if (ti_p->ti_state == TD_THR_UNKNOWN || ti_p->ti_state == TD_THR_ZOMBIE)
751     return;                     /* A zombie thread -- do not attach.  */
752
753   /* Under GNU/Linux, we have to attach to each and every thread.  */
754 #ifdef ATTACH_LWP
755   ATTACH_LWP (BUILD_LWP (ti_p->ti_lid, GET_PID (ptid)), 0);
756 #endif
757
758   /* Enable thread event reporting for this thread.  */
759   err = td_thr_event_enable_p (th_p, 1);
760   if (err != TD_OK)
761     error ("Cannot enable thread event reporting for %s: %s",
762            target_pid_to_str (ptid), thread_db_err_str (err));
763 }
764
765 static void
766 thread_db_attach (char *args, int from_tty)
767 {
768   target_beneath->to_attach (args, from_tty);
769
770   /* Destroy thread info; it's no longer valid.  */
771   init_thread_list ();
772
773   /* The child process is now the actual multi-threaded
774      program.  Snatch its process ID...  */
775   proc_handle.pid = GET_PID (inferior_ptid);
776
777   /* ...and perform the remaining initialization steps.  */
778   enable_thread_event_reporting ();
779   thread_db_find_new_threads ();
780 }
781
782 static void
783 detach_thread (ptid_t ptid, int verbose)
784 {
785   struct thread_info *thread_info;
786
787   if (verbose)
788     printf_unfiltered ("[%s exited]\n", target_pid_to_str (ptid));
789
790   /* Don't delete the thread now, because it still reports as active
791      until it has executed a few instructions after the event
792      breakpoint - if we deleted it now, "info threads" would cause us
793      to re-attach to it.  Just mark it as having had a TD_DEATH
794      event.  This means that we won't delete it from our thread list
795      until we notice that it's dead (via prune_threads), or until
796      something re-uses its thread ID.  */
797   thread_info = find_thread_pid (ptid);
798   gdb_assert (thread_info != NULL);
799   thread_info->private->dying = 1;
800 }
801
802 static void
803 thread_db_detach (char *args, int from_tty)
804 {
805   disable_thread_event_reporting ();
806
807   /* There's no need to save & restore inferior_ptid here, since the
808      inferior is supposed to be survive this function call.  */
809   inferior_ptid = lwp_from_thread (inferior_ptid);
810
811   /* Forget about the child's process ID.  We shouldn't need it
812      anymore.  */
813   proc_handle.pid = 0;
814
815   target_beneath->to_detach (args, from_tty);
816 }
817
818 static int
819 clear_lwpid_callback (struct thread_info *thread, void *dummy)
820 {
821   /* If we know that our thread implementation is 1-to-1, we could save
822      a certain amount of information; it's not clear how much, so we
823      are always conservative.  */
824
825   thread->private->th_valid = 0;
826   thread->private->ti_valid = 0;
827
828   return 0;
829 }
830
831 static void
832 thread_db_resume (ptid_t ptid, int step, enum target_signal signo)
833 {
834   struct cleanup *old_chain = save_inferior_ptid ();
835
836   if (GET_PID (ptid) == -1)
837     inferior_ptid = lwp_from_thread (inferior_ptid);
838   else if (is_thread (ptid))
839     ptid = lwp_from_thread (ptid);
840
841   /* Clear cached data which may not be valid after the resume.  */
842   iterate_over_threads (clear_lwpid_callback, NULL);
843
844   target_beneath->to_resume (ptid, step, signo);
845
846   do_cleanups (old_chain);
847 }
848
849 /* Check if PID is currently stopped at the location of a thread event
850    breakpoint location.  If it is, read the event message and act upon
851    the event.  */
852
853 static void
854 check_event (ptid_t ptid)
855 {
856   td_event_msg_t msg;
857   td_thrinfo_t ti;
858   td_err_e err;
859   CORE_ADDR stop_pc;
860   int loop = 0;
861
862   /* Bail out early if we're not at a thread event breakpoint.  */
863   stop_pc = read_pc_pid (ptid) - DECR_PC_AFTER_BREAK;
864   if (stop_pc != td_create_bp_addr && stop_pc != td_death_bp_addr)
865     return;
866
867   /* If we are at a create breakpoint, we do not know what new lwp
868      was created and cannot specifically locate the event message for it.
869      We have to call td_ta_event_getmsg() to get
870      the latest message.  Since we have no way of correlating whether
871      the event message we get back corresponds to our breakpoint, we must
872      loop and read all event messages, processing them appropriately.
873      This guarantees we will process the correct message before continuing
874      from the breakpoint.
875
876      Currently, death events are not enabled.  If they are enabled,
877      the death event can use the td_thr_event_getmsg() interface to
878      get the message specifically for that lwp and avoid looping
879      below.  */
880
881   loop = 1;
882
883   do
884     {
885       err = td_ta_event_getmsg_p (thread_agent, &msg);
886       if (err != TD_OK)
887         {
888           if (err == TD_NOMSG)
889             return;
890
891           error ("Cannot get thread event message: %s",
892                  thread_db_err_str (err));
893         }
894
895       err = td_thr_get_info_p (msg.th_p, &ti);
896       if (err != TD_OK)
897         error ("Cannot get thread info: %s", thread_db_err_str (err));
898
899       ptid = BUILD_THREAD (ti.ti_tid, GET_PID (ptid));
900
901       switch (msg.event)
902         {
903         case TD_CREATE:
904           /* Call attach_thread whether or not we already know about a
905              thread with this thread ID.  */
906           attach_thread (ptid, msg.th_p, &ti, 1);
907
908           break;
909
910         case TD_DEATH:
911
912           if (!in_thread_list (ptid))
913             error ("Spurious thread death event.");
914
915           detach_thread (ptid, 1);
916
917           break;
918
919         default:
920           error ("Spurious thread event.");
921         }
922     }
923   while (loop);
924 }
925
926 static ptid_t
927 thread_db_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
928 {
929   extern ptid_t trap_ptid;
930
931   if (GET_PID (ptid) != -1 && is_thread (ptid))
932     ptid = lwp_from_thread (ptid);
933
934   ptid = target_beneath->to_wait (ptid, ourstatus);
935
936   if (proc_handle.pid == 0)
937     /* The current child process isn't the actual multi-threaded
938        program yet, so don't try to do any special thread-specific
939        post-processing and bail out early.  */
940     return ptid;
941
942   if (ourstatus->kind == TARGET_WAITKIND_EXITED)
943     return pid_to_ptid (-1);
944
945   if (ourstatus->kind == TARGET_WAITKIND_STOPPED
946       && ourstatus->value.sig == TARGET_SIGNAL_TRAP)
947     /* Check for a thread event.  */
948     check_event (ptid);
949
950   if (!ptid_equal (trap_ptid, null_ptid))
951     trap_ptid = thread_from_lwp (trap_ptid);
952
953   return thread_from_lwp (ptid);
954 }
955
956 static int
957 thread_db_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len, int write,
958                        struct mem_attrib *attrib, struct target_ops *target)
959 {
960   struct cleanup *old_chain = save_inferior_ptid ();
961   int xfer;
962
963   if (is_thread (inferior_ptid))
964     {
965       /* FIXME: This seems to be necessary to make sure breakpoints
966          are removed.  */
967       if (!target_thread_alive (inferior_ptid))
968         inferior_ptid = pid_to_ptid (GET_PID (inferior_ptid));
969       else
970         inferior_ptid = lwp_from_thread (inferior_ptid);
971     }
972
973   xfer =
974     target_beneath->to_xfer_memory (memaddr, myaddr, len, write, attrib,
975                                     target);
976
977   do_cleanups (old_chain);
978   return xfer;
979 }
980
981 static void
982 thread_db_fetch_registers (int regno)
983 {
984   struct thread_info *thread_info;
985   prgregset_t gregset;
986   gdb_prfpregset_t fpregset;
987   td_err_e err;
988
989   if (!is_thread (inferior_ptid))
990     {
991       /* Pass the request to the target beneath us.  */
992       target_beneath->to_fetch_registers (regno);
993       return;
994     }
995
996   thread_info = find_thread_pid (inferior_ptid);
997   thread_db_map_id2thr (thread_info, 1);
998
999   err = td_thr_getgregs_p (&thread_info->private->th, gregset);
1000   if (err != TD_OK)
1001     error ("Cannot fetch general-purpose registers for thread %ld: %s",
1002            (long) GET_THREAD (inferior_ptid), thread_db_err_str (err));
1003
1004   err = td_thr_getfpregs_p (&thread_info->private->th, &fpregset);
1005   if (err != TD_OK)
1006     error ("Cannot get floating-point registers for thread %ld: %s",
1007            (long) GET_THREAD (inferior_ptid), thread_db_err_str (err));
1008
1009   /* Note that we must call supply_gregset after calling the thread_db
1010      routines because the thread_db routines call ps_lgetgregs and
1011      friends which clobber GDB's register cache.  */
1012   supply_gregset ((gdb_gregset_t *) gregset);
1013   supply_fpregset (&fpregset);
1014 }
1015
1016 static void
1017 thread_db_store_registers (int regno)
1018 {
1019   prgregset_t gregset;
1020   gdb_prfpregset_t fpregset;
1021   td_err_e err;
1022   struct thread_info *thread_info;
1023
1024   if (!is_thread (inferior_ptid))
1025     {
1026       /* Pass the request to the target beneath us.  */
1027       target_beneath->to_store_registers (regno);
1028       return;
1029     }
1030
1031   thread_info = find_thread_pid (inferior_ptid);
1032   thread_db_map_id2thr (thread_info, 1);
1033
1034   if (regno != -1)
1035     {
1036       char raw[MAX_REGISTER_SIZE];
1037
1038       deprecated_read_register_gen (regno, raw);
1039       thread_db_fetch_registers (-1);
1040       supply_register (regno, raw);
1041     }
1042
1043   fill_gregset ((gdb_gregset_t *) gregset, -1);
1044   fill_fpregset (&fpregset, -1);
1045
1046   err = td_thr_setgregs_p (&thread_info->private->th, gregset);
1047   if (err != TD_OK)
1048     error ("Cannot store general-purpose registers for thread %ld: %s",
1049            (long) GET_THREAD (inferior_ptid), thread_db_err_str (err));
1050   err = td_thr_setfpregs_p (&thread_info->private->th, &fpregset);
1051   if (err != TD_OK)
1052     error ("Cannot store floating-point registers  for thread %ld: %s",
1053            (long) GET_THREAD (inferior_ptid), thread_db_err_str (err));
1054 }
1055
1056 static void
1057 thread_db_kill (void)
1058 {
1059   /* There's no need to save & restore inferior_ptid here, since the
1060      inferior isn't supposed to survive this function call.  */
1061   inferior_ptid = lwp_from_thread (inferior_ptid);
1062   target_beneath->to_kill ();
1063 }
1064
1065 static void
1066 thread_db_create_inferior (char *exec_file, char *allargs, char **env,
1067                            int from_tty)
1068 {
1069   if (!keep_thread_db)
1070     {
1071       unpush_target (&thread_db_ops);
1072       using_thread_db = 0;
1073     }
1074
1075   target_beneath->to_create_inferior (exec_file, allargs, env, from_tty);
1076 }
1077
1078 static void
1079 thread_db_post_startup_inferior (ptid_t ptid)
1080 {
1081   if (proc_handle.pid == 0)
1082     {
1083       /* The child process is now the actual multi-threaded
1084          program.  Snatch its process ID...  */
1085       proc_handle.pid = GET_PID (ptid);
1086
1087       /* ...and perform the remaining initialization steps.  */
1088       enable_thread_event_reporting ();
1089       thread_db_find_new_threads ();
1090     }
1091 }
1092
1093 static void
1094 thread_db_mourn_inferior (void)
1095 {
1096   remove_thread_event_breakpoints ();
1097
1098   /* Forget about the child's process ID.  We shouldn't need it
1099      anymore.  */
1100   proc_handle.pid = 0;
1101
1102   target_beneath->to_mourn_inferior ();
1103
1104   /* Detach thread_db target ops if not dealing with a statically
1105      linked threaded program.  This allows a corefile to be debugged
1106      after finishing debugging of a threaded program.  At present,
1107      debugging a statically-linked threaded program is broken, but
1108      the check is added below in the event that it is fixed in the
1109      future.  */
1110   if (!keep_thread_db)
1111     {
1112       unpush_target (&thread_db_ops);
1113       using_thread_db = 0;
1114     }
1115 }
1116
1117 static int
1118 thread_db_thread_alive (ptid_t ptid)
1119 {
1120   td_thrhandle_t th;
1121   td_err_e err;
1122
1123   if (is_thread (ptid))
1124     {
1125       struct thread_info *thread_info;
1126       thread_info = find_thread_pid (ptid);
1127
1128       thread_db_map_id2thr (thread_info, 0);
1129       if (!thread_info->private->th_valid)
1130         return 0;
1131
1132       err = td_thr_validate_p (&thread_info->private->th);
1133       if (err != TD_OK)
1134         return 0;
1135
1136       if (!thread_info->private->ti_valid)
1137         {
1138           err =
1139             td_thr_get_info_p (&thread_info->private->th,
1140                                &thread_info->private->ti);
1141           if (err != TD_OK)
1142             return 0;
1143           thread_info->private->ti_valid = 1;
1144         }
1145
1146       if (thread_info->private->ti.ti_state == TD_THR_UNKNOWN
1147           || thread_info->private->ti.ti_state == TD_THR_ZOMBIE)
1148         return 0;               /* A zombie thread.  */
1149
1150       return 1;
1151     }
1152
1153   if (target_beneath->to_thread_alive)
1154     return target_beneath->to_thread_alive (ptid);
1155
1156   return 0;
1157 }
1158
1159 static int
1160 find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
1161 {
1162   td_thrinfo_t ti;
1163   td_err_e err;
1164   ptid_t ptid;
1165
1166   err = td_thr_get_info_p (th_p, &ti);
1167   if (err != TD_OK)
1168     error ("find_new_threads_callback: cannot get thread info: %s",
1169            thread_db_err_str (err));
1170
1171   if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
1172     return 0;                   /* A zombie -- ignore.  */
1173
1174   ptid = BUILD_THREAD (ti.ti_tid, GET_PID (inferior_ptid));
1175
1176   if (!in_thread_list (ptid))
1177     attach_thread (ptid, th_p, &ti, 1);
1178
1179   return 0;
1180 }
1181
1182 static void
1183 thread_db_find_new_threads (void)
1184 {
1185   td_err_e err;
1186
1187   /* Iterate over all user-space threads to discover new threads.  */
1188   err = td_ta_thr_iter_p (thread_agent, find_new_threads_callback, NULL,
1189                           TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
1190                           TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
1191   if (err != TD_OK)
1192     error ("Cannot find new threads: %s", thread_db_err_str (err));
1193 }
1194
1195 static char *
1196 thread_db_pid_to_str (ptid_t ptid)
1197 {
1198   if (is_thread (ptid))
1199     {
1200       static char buf[64];
1201       td_thrinfo_t *ti_p;
1202       td_err_e err;
1203       struct thread_info *thread_info;
1204
1205       thread_info = find_thread_pid (ptid);
1206       thread_db_map_id2thr (thread_info, 0);
1207       if (!thread_info->private->th_valid)
1208         {
1209           snprintf (buf, sizeof (buf), "Thread %ld (Missing)",
1210                     GET_THREAD (ptid));
1211           return buf;
1212         }
1213
1214       ti_p = thread_db_get_info (thread_info);
1215
1216       if (ti_p->ti_state == TD_THR_ACTIVE && ti_p->ti_lid != 0)
1217         {
1218           snprintf (buf, sizeof (buf), "Thread %ld (LWP %d)",
1219                     (long) ti_p->ti_tid, ti_p->ti_lid);
1220         }
1221       else
1222         {
1223           snprintf (buf, sizeof (buf), "Thread %ld (%s)",
1224                     (long) ti_p->ti_tid,
1225                     thread_db_state_str (ti_p->ti_state));
1226         }
1227
1228       return buf;
1229     }
1230
1231   if (target_beneath->to_pid_to_str (ptid))
1232     return target_beneath->to_pid_to_str (ptid);
1233
1234   return normal_pid_to_str (ptid);
1235 }
1236
1237 /* Get the address of the thread local variable in OBJFILE which is
1238    stored at OFFSET within the thread local storage for thread PTID.  */
1239
1240 static CORE_ADDR
1241 thread_db_get_thread_local_address (ptid_t ptid, struct objfile *objfile,
1242                                     CORE_ADDR offset)
1243 {
1244   if (is_thread (ptid))
1245     {
1246       int objfile_is_library = (objfile->flags & OBJF_SHARED);
1247       td_err_e err;
1248       void *address;
1249       CORE_ADDR lm;
1250       struct thread_info *thread_info;
1251
1252       /* glibc doesn't provide the needed interface.  */
1253       if (!td_thr_tls_get_addr_p)
1254         error ("Cannot find thread-local variables in this thread library.");
1255
1256       /* Get the address of the link map for this objfile.  */
1257       lm = svr4_fetch_objfile_link_map (objfile);
1258
1259       /* Whoops, we couldn't find one. Bail out.  */
1260       if (!lm)
1261         {
1262           if (objfile_is_library)
1263             error ("Cannot find shared library `%s' link_map in dynamic"
1264                    " linker's module list", objfile->name);
1265           else
1266             error ("Cannot find executable file `%s' link_map in dynamic"
1267                    " linker's module list", objfile->name);
1268         }
1269
1270       /* Get info about the thread.  */
1271       thread_info = find_thread_pid (ptid);
1272       thread_db_map_id2thr (thread_info, 1);
1273
1274       /* Finally, get the address of the variable.  */
1275       err = td_thr_tls_get_addr_p (&thread_info->private->th, (void *) lm,
1276                                    offset, &address);
1277
1278 #ifdef THREAD_DB_HAS_TD_NOTALLOC
1279       /* The memory hasn't been allocated, yet.  */
1280       if (err == TD_NOTALLOC)
1281         {
1282           /* Now, if libthread_db provided the initialization image's
1283              address, we *could* try to build a non-lvalue value from
1284              the initialization image.  */
1285           if (objfile_is_library)
1286             error ("The inferior has not yet allocated storage for"
1287                    " thread-local variables in\n"
1288                    "the shared library `%s'\n"
1289                    "for the thread %ld",
1290                    objfile->name, (long) GET_THREAD (ptid));
1291           else
1292             error ("The inferior has not yet allocated storage for"
1293                    " thread-local variables in\n"
1294                    "the executable `%s'\n"
1295                    "for the thread %ld",
1296                    objfile->name, (long) GET_THREAD (ptid));
1297         }
1298 #endif
1299
1300       /* Something else went wrong.  */
1301       if (err != TD_OK)
1302         {
1303           if (objfile_is_library)
1304             error ("Cannot find thread-local storage for thread %ld, "
1305                    "shared library %s:\n%s",
1306                    (long) GET_THREAD (ptid),
1307                    objfile->name, thread_db_err_str (err));
1308           else
1309             error ("Cannot find thread-local storage for thread %ld, "
1310                    "executable file %s:\n%s",
1311                    (long) GET_THREAD (ptid),
1312                    objfile->name, thread_db_err_str (err));
1313         }
1314
1315       /* Cast assuming host == target.  Joy.  */
1316       return (CORE_ADDR) address;
1317     }
1318
1319   if (target_beneath->to_get_thread_local_address)
1320     return target_beneath->to_get_thread_local_address (ptid, objfile,
1321                                                         offset);
1322
1323   error ("Cannot find thread-local values on this target.");
1324 }
1325
1326 static void
1327 init_thread_db_ops (void)
1328 {
1329   thread_db_ops.to_shortname = "multi-thread";
1330   thread_db_ops.to_longname = "multi-threaded child process.";
1331   thread_db_ops.to_doc = "Threads and pthreads support.";
1332   thread_db_ops.to_attach = thread_db_attach;
1333   thread_db_ops.to_detach = thread_db_detach;
1334   thread_db_ops.to_resume = thread_db_resume;
1335   thread_db_ops.to_wait = thread_db_wait;
1336   thread_db_ops.to_fetch_registers = thread_db_fetch_registers;
1337   thread_db_ops.to_store_registers = thread_db_store_registers;
1338   thread_db_ops.to_xfer_memory = thread_db_xfer_memory;
1339   thread_db_ops.to_kill = thread_db_kill;
1340   thread_db_ops.to_create_inferior = thread_db_create_inferior;
1341   thread_db_ops.to_post_startup_inferior = thread_db_post_startup_inferior;
1342   thread_db_ops.to_mourn_inferior = thread_db_mourn_inferior;
1343   thread_db_ops.to_thread_alive = thread_db_thread_alive;
1344   thread_db_ops.to_find_new_threads = thread_db_find_new_threads;
1345   thread_db_ops.to_pid_to_str = thread_db_pid_to_str;
1346   thread_db_ops.to_stratum = thread_stratum;
1347   thread_db_ops.to_has_thread_control = tc_schedlock;
1348   thread_db_ops.to_get_thread_local_address
1349     = thread_db_get_thread_local_address;
1350   thread_db_ops.to_magic = OPS_MAGIC;
1351 }
1352
1353 void
1354 _initialize_thread_db (void)
1355 {
1356   /* Only initialize the module if we can load libthread_db.  */
1357   if (thread_db_load ())
1358     {
1359       init_thread_db_ops ();
1360       add_target (&thread_db_ops);
1361
1362       /* Add ourselves to objfile event chain.  */
1363       target_new_objfile_chain = deprecated_target_new_objfile_hook;
1364       deprecated_target_new_objfile_hook = thread_db_new_objfile;
1365     }
1366 }