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