Include <signal.h>.
[external/binutils.git] / gdb / linux-thread-db.c
1 /* libthread_db assisted debugging support, generic parts.
2
3    Copyright (C) 1999, 2000, 2001, 2003, 2004, 2005, 2006
4    Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor,
21    Boston, MA 02110-1301, USA.  */
22
23 #include "defs.h"
24
25 #include "gdb_assert.h"
26 #include <dlfcn.h>
27 #include "gdb_proc_service.h"
28 #include "gdb_thread_db.h"
29
30 #include "bfd.h"
31 #include "exceptions.h"
32 #include "gdbthread.h"
33 #include "inferior.h"
34 #include "symfile.h"
35 #include "objfiles.h"
36 #include "target.h"
37 #include "regcache.h"
38 #include "solib-svr4.h"
39 #include "gdbcore.h"
40 #include "linux-nat.h"
41
42 #include <signal.h>
43
44 #ifdef HAVE_GNU_LIBC_VERSION_H
45 #include <gnu/libc-version.h>
46 #endif
47
48 #ifndef LIBTHREAD_DB_SO
49 #define LIBTHREAD_DB_SO "libthread_db.so.1"
50 #endif
51
52 /* If we're running on GNU/Linux, we must explicitly attach to any new
53    threads.  */
54
55 /* FIXME: There is certainly some room for improvements:
56    - Cache LWP ids.
57    - Bypass libthread_db when fetching or storing registers for
58    threads bound to a LWP.  */
59
60 /* This module's target vector.  */
61 static struct target_ops thread_db_ops;
62
63 /* The target vector that we call for things this module can't handle.  */
64 static struct target_ops *target_beneath;
65
66 /* Pointer to the next function on the objfile event chain.  */
67 static void (*target_new_objfile_chain) (struct objfile * objfile);
68
69 /* Non-zero if we're using this module's target vector.  */
70 static int using_thread_db;
71
72 /* Non-zero if we have determined the signals used by the threads
73    library.  */
74 static int thread_signals;
75 static sigset_t thread_stop_set;
76 static sigset_t thread_print_set;
77
78 /* Structure that identifies the child process for the
79    <proc_service.h> interface.  */
80 static struct ps_prochandle proc_handle;
81
82 /* Connection to the libthread_db library.  */
83 static td_thragent_t *thread_agent;
84
85 /* Pointers to the libthread_db functions.  */
86
87 static td_err_e (*td_init_p) (void);
88
89 static td_err_e (*td_ta_new_p) (struct ps_prochandle * ps,
90                                 td_thragent_t **ta);
91 static td_err_e (*td_ta_map_id2thr_p) (const td_thragent_t *ta, thread_t pt,
92                                        td_thrhandle_t *__th);
93 static td_err_e (*td_ta_map_lwp2thr_p) (const td_thragent_t *ta,
94                                         lwpid_t lwpid, td_thrhandle_t *th);
95 static td_err_e (*td_ta_thr_iter_p) (const td_thragent_t *ta,
96                                      td_thr_iter_f *callback, void *cbdata_p,
97                                      td_thr_state_e state, int ti_pri,
98                                      sigset_t *ti_sigmask_p,
99                                      unsigned int ti_user_flags);
100 static td_err_e (*td_ta_event_addr_p) (const td_thragent_t *ta,
101                                        td_event_e event, td_notify_t *ptr);
102 static td_err_e (*td_ta_set_event_p) (const td_thragent_t *ta,
103                                       td_thr_events_t *event);
104 static td_err_e (*td_ta_event_getmsg_p) (const td_thragent_t *ta,
105                                          td_event_msg_t *msg);
106
107 static td_err_e (*td_thr_validate_p) (const td_thrhandle_t *th);
108 static td_err_e (*td_thr_get_info_p) (const td_thrhandle_t *th,
109                                       td_thrinfo_t *infop);
110 static td_err_e (*td_thr_event_enable_p) (const td_thrhandle_t *th,
111                                           int event);
112
113 static td_err_e (*td_thr_tls_get_addr_p) (const td_thrhandle_t *th,
114                                           void *map_address,
115                                           size_t offset, void **address);
116
117 /* Location of the thread creation event breakpoint.  The code at this
118    location in the child process will be called by the pthread library
119    whenever a new thread is created.  By setting a special breakpoint
120    at this location, GDB can detect when a new thread is created.  We
121    obtain this location via the td_ta_event_addr call.  */
122 static CORE_ADDR td_create_bp_addr;
123
124 /* Location of the thread death event breakpoint.  */
125 static CORE_ADDR td_death_bp_addr;
126
127 /* Prototypes for local functions.  */
128 static void thread_db_find_new_threads (void);
129 static void attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
130                            const td_thrinfo_t *ti_p, int verbose);
131 static void detach_thread (ptid_t ptid, int verbose);
132 \f
133
134 /* Building process ids.  */
135
136 #define GET_PID(ptid)           ptid_get_pid (ptid)
137 #define GET_LWP(ptid)           ptid_get_lwp (ptid)
138 #define GET_THREAD(ptid)        ptid_get_tid (ptid)
139
140 #define is_lwp(ptid)            (GET_LWP (ptid) != 0)
141 #define is_thread(ptid)         (GET_THREAD (ptid) != 0)
142
143 #define BUILD_LWP(lwp, pid)     ptid_build (pid, lwp, 0)
144 \f
145
146 /* Use "struct private_thread_info" to cache thread state.  This is
147    a substantial optimization.  */
148
149 struct private_thread_info
150 {
151   /* Flag set when we see a TD_DEATH event for this thread.  */
152   unsigned int dying:1;
153
154   /* Cached thread state.  */
155   unsigned int th_valid:1;
156   unsigned int ti_valid:1;
157
158   td_thrhandle_t th;
159   td_thrinfo_t ti;
160 };
161 \f
162
163 static char *
164 thread_db_err_str (td_err_e err)
165 {
166   static char buf[64];
167
168   switch (err)
169     {
170     case TD_OK:
171       return "generic 'call succeeded'";
172     case TD_ERR:
173       return "generic error";
174     case TD_NOTHR:
175       return "no thread to satisfy query";
176     case TD_NOSV:
177       return "no sync handle to satisfy query";
178     case TD_NOLWP:
179       return "no LWP to satisfy query";
180     case TD_BADPH:
181       return "invalid process handle";
182     case TD_BADTH:
183       return "invalid thread handle";
184     case TD_BADSH:
185       return "invalid synchronization handle";
186     case TD_BADTA:
187       return "invalid thread agent";
188     case TD_BADKEY:
189       return "invalid key";
190     case TD_NOMSG:
191       return "no event message for getmsg";
192     case TD_NOFPREGS:
193       return "FPU register set not available";
194     case TD_NOLIBTHREAD:
195       return "application not linked with libthread";
196     case TD_NOEVENT:
197       return "requested event is not supported";
198     case TD_NOCAPAB:
199       return "capability not available";
200     case TD_DBERR:
201       return "debugger service failed";
202     case TD_NOAPLIC:
203       return "operation not applicable to";
204     case TD_NOTSD:
205       return "no thread-specific data for this thread";
206     case TD_MALLOC:
207       return "malloc failed";
208     case TD_PARTIALREG:
209       return "only part of register set was written/read";
210     case TD_NOXREGS:
211       return "X register set not available for this thread";
212     default:
213       snprintf (buf, sizeof (buf), "unknown thread_db error '%d'", err);
214       return buf;
215     }
216 }
217 \f
218 /* A callback function for td_ta_thr_iter, which we use to map all
219    threads to LWPs.
220
221    THP is a handle to the current thread; if INFOP is not NULL, the
222    struct thread_info associated with this thread is returned in
223    *INFOP.
224
225    If the thread is a zombie, TD_THR_ZOMBIE is returned.  Otherwise,
226    zero is returned to indicate success.  */
227
228 static int
229 thread_get_info_callback (const td_thrhandle_t *thp, void *infop)
230 {
231   td_thrinfo_t ti;
232   td_err_e err;
233   struct thread_info *thread_info;
234   ptid_t thread_ptid;
235
236   err = td_thr_get_info_p (thp, &ti);
237   if (err != TD_OK)
238     error (_("thread_get_info_callback: cannot get thread info: %s"),
239            thread_db_err_str (err));
240
241   /* Fill the cache.  */
242   thread_ptid = ptid_build (GET_PID (inferior_ptid), ti.ti_lid, ti.ti_tid);
243   thread_info = find_thread_pid (thread_ptid);
244
245   /* In the case of a zombie thread, don't continue.  We don't want to
246      attach to it thinking it is a new thread.  */
247   if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
248     {
249       if (infop != NULL)
250         *(struct thread_info **) infop = thread_info;
251       if (thread_info != NULL)
252         {
253           memcpy (&thread_info->private->th, thp, sizeof (*thp));
254           thread_info->private->th_valid = 1;
255           memcpy (&thread_info->private->ti, &ti, sizeof (ti));
256           thread_info->private->ti_valid = 1;
257         }
258       return TD_THR_ZOMBIE;
259     }
260
261   if (thread_info == NULL)
262     {
263       /* New thread.  Attach to it now (why wait?).  */
264       attach_thread (thread_ptid, thp, &ti, 1);
265       thread_info = find_thread_pid (thread_ptid);
266       gdb_assert (thread_info != NULL);
267     }
268
269   memcpy (&thread_info->private->th, thp, sizeof (*thp));
270   thread_info->private->th_valid = 1;
271   memcpy (&thread_info->private->ti, &ti, sizeof (ti));
272   thread_info->private->ti_valid = 1;
273
274   if (infop != NULL)
275     *(struct thread_info **) infop = thread_info;
276
277   return 0;
278 }
279
280 /* Accessor functions for the thread_db information, with caching.  */
281
282 static void
283 thread_db_map_id2thr (struct thread_info *thread_info, int fatal)
284 {
285   td_err_e err;
286
287   if (thread_info->private->th_valid)
288     return;
289
290   err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (thread_info->ptid),
291                             &thread_info->private->th);
292   if (err != TD_OK)
293     {
294       if (fatal)
295         error (_("Cannot find thread %ld: %s"),
296                (long) GET_THREAD (thread_info->ptid),
297                thread_db_err_str (err));
298     }
299   else
300     thread_info->private->th_valid = 1;
301 }
302 \f
303 /* Convert between user-level thread ids and LWP ids.  */
304
305 static ptid_t
306 thread_from_lwp (ptid_t ptid)
307 {
308   td_thrhandle_t th;
309   td_err_e err;
310   struct thread_info *thread_info;
311   ptid_t thread_ptid;
312
313   if (GET_LWP (ptid) == 0)
314     ptid = BUILD_LWP (GET_PID (ptid), GET_PID (ptid));
315
316   gdb_assert (is_lwp (ptid));
317
318   err = td_ta_map_lwp2thr_p (thread_agent, GET_LWP (ptid), &th);
319   if (err != TD_OK)
320     error (_("Cannot find user-level thread for LWP %ld: %s"),
321            GET_LWP (ptid), thread_db_err_str (err));
322
323   thread_info = NULL;
324
325   /* Fetch the thread info.  If we get back TD_THR_ZOMBIE, then the
326      event thread has already died.  If another gdb interface has called
327      thread_alive() previously, the thread won't be found on the thread list
328      anymore.  In that case, we don't want to process this ptid anymore
329      to avoid the possibility of later treating it as a newly
330      discovered thread id that we should add to the list.  Thus,
331      we return a -1 ptid which is also how the thread list marks a
332      dead thread.  */
333   if (thread_get_info_callback (&th, &thread_info) == TD_THR_ZOMBIE
334       && thread_info == NULL)
335     return pid_to_ptid (-1);
336
337   gdb_assert (thread_info && thread_info->private->ti_valid);
338
339   return ptid_build (GET_PID (ptid), GET_LWP (ptid),
340                      thread_info->private->ti.ti_tid);
341 }
342
343 static ptid_t
344 lwp_from_thread (ptid_t ptid)
345 {
346   return BUILD_LWP (GET_LWP (ptid), GET_PID (ptid));
347 }
348 \f
349
350 void
351 thread_db_init (struct target_ops *target)
352 {
353   target_beneath = target;
354 }
355
356 static void *
357 verbose_dlsym (void *handle, const char *name)
358 {
359   void *sym = dlsym (handle, name);
360   if (sym == NULL)
361     warning (_("Symbol \"%s\" not found in libthread_db: %s"), name, dlerror ());
362   return sym;
363 }
364
365 static int
366 thread_db_load (void)
367 {
368   void *handle;
369   td_err_e err;
370
371   handle = dlopen (LIBTHREAD_DB_SO, RTLD_NOW);
372   if (handle == NULL)
373     {
374       fprintf_filtered (gdb_stderr, "\n\ndlopen failed on '%s' - %s\n",
375                         LIBTHREAD_DB_SO, dlerror ());
376       fprintf_filtered (gdb_stderr,
377                         "GDB will not be able to debug pthreads.\n\n");
378       return 0;
379     }
380
381   /* Initialize pointers to the dynamic library functions we will use.
382      Essential functions first.  */
383
384   td_init_p = verbose_dlsym (handle, "td_init");
385   if (td_init_p == NULL)
386     return 0;
387
388   td_ta_new_p = verbose_dlsym (handle, "td_ta_new");
389   if (td_ta_new_p == NULL)
390     return 0;
391
392   td_ta_map_id2thr_p = verbose_dlsym (handle, "td_ta_map_id2thr");
393   if (td_ta_map_id2thr_p == NULL)
394     return 0;
395
396   td_ta_map_lwp2thr_p = verbose_dlsym (handle, "td_ta_map_lwp2thr");
397   if (td_ta_map_lwp2thr_p == NULL)
398     return 0;
399
400   td_ta_thr_iter_p = verbose_dlsym (handle, "td_ta_thr_iter");
401   if (td_ta_thr_iter_p == NULL)
402     return 0;
403
404   td_thr_validate_p = verbose_dlsym (handle, "td_thr_validate");
405   if (td_thr_validate_p == NULL)
406     return 0;
407
408   td_thr_get_info_p = verbose_dlsym (handle, "td_thr_get_info");
409   if (td_thr_get_info_p == NULL)
410     return 0;
411
412   /* Initialize the library.  */
413   err = td_init_p ();
414   if (err != TD_OK)
415     {
416       warning (_("Cannot initialize libthread_db: %s"), thread_db_err_str (err));
417       return 0;
418     }
419
420   /* These are not essential.  */
421   td_ta_event_addr_p = dlsym (handle, "td_ta_event_addr");
422   td_ta_set_event_p = dlsym (handle, "td_ta_set_event");
423   td_ta_event_getmsg_p = dlsym (handle, "td_ta_event_getmsg");
424   td_thr_event_enable_p = dlsym (handle, "td_thr_event_enable");
425   td_thr_tls_get_addr_p = dlsym (handle, "td_thr_tls_get_addr");
426
427   return 1;
428 }
429
430 static td_err_e
431 enable_thread_event (td_thragent_t *thread_agent, int event, CORE_ADDR *bp)
432 {
433   td_notify_t notify;
434   td_err_e err;
435
436   /* Get the breakpoint address for thread EVENT.  */
437   err = td_ta_event_addr_p (thread_agent, event, &notify);
438   if (err != TD_OK)
439     return err;
440
441   /* Set up the breakpoint.  */
442   gdb_assert (exec_bfd);
443   (*bp) = (gdbarch_convert_from_func_ptr_addr
444            (current_gdbarch,
445             /* Do proper sign extension for the target.  */
446             (bfd_get_sign_extend_vma (exec_bfd) > 0
447              ? (CORE_ADDR) (intptr_t) notify.u.bptaddr
448              : (CORE_ADDR) (uintptr_t) notify.u.bptaddr),
449             &current_target));
450   create_thread_event_breakpoint ((*bp));
451
452   return TD_OK;
453 }
454
455 static void
456 enable_thread_event_reporting (void)
457 {
458   td_thr_events_t events;
459   td_notify_t notify;
460   td_err_e err;
461 #ifdef HAVE_GNU_LIBC_VERSION_H
462   const char *libc_version;
463   int libc_major, libc_minor;
464 #endif
465
466   /* We cannot use the thread event reporting facility if these
467      functions aren't available.  */
468   if (td_ta_event_addr_p == NULL || td_ta_set_event_p == NULL
469       || td_ta_event_getmsg_p == NULL || td_thr_event_enable_p == NULL)
470     return;
471
472   /* Set the process wide mask saying which events we're interested in.  */
473   td_event_emptyset (&events);
474   td_event_addset (&events, TD_CREATE);
475
476 #ifdef HAVE_GNU_LIBC_VERSION_H
477   /* FIXME: kettenis/2000-04-23: The event reporting facility is
478      broken for TD_DEATH events in glibc 2.1.3, so don't enable it for
479      now.  */
480   libc_version = gnu_get_libc_version ();
481   if (sscanf (libc_version, "%d.%d", &libc_major, &libc_minor) == 2
482       && (libc_major > 2 || (libc_major == 2 && libc_minor > 1)))
483 #endif
484     td_event_addset (&events, TD_DEATH);
485
486   err = td_ta_set_event_p (thread_agent, &events);
487   if (err != TD_OK)
488     {
489       warning (_("Unable to set global thread event mask: %s"),
490                thread_db_err_str (err));
491       return;
492     }
493
494   /* Delete previous thread event breakpoints, if any.  */
495   remove_thread_event_breakpoints ();
496   td_create_bp_addr = 0;
497   td_death_bp_addr = 0;
498
499   /* Set up the thread creation event.  */
500   err = enable_thread_event (thread_agent, TD_CREATE, &td_create_bp_addr);
501   if (err != TD_OK)
502     {
503       warning (_("Unable to get location for thread creation breakpoint: %s"),
504                thread_db_err_str (err));
505       return;
506     }
507
508   /* Set up the thread death event.  */
509   err = enable_thread_event (thread_agent, TD_DEATH, &td_death_bp_addr);
510   if (err != TD_OK)
511     {
512       warning (_("Unable to get location for thread death breakpoint: %s"),
513                thread_db_err_str (err));
514       return;
515     }
516 }
517
518 static void
519 disable_thread_event_reporting (void)
520 {
521   td_thr_events_t events;
522
523   /* Set the process wide mask saying we aren't interested in any
524      events anymore.  */
525   td_event_emptyset (&events);
526   td_ta_set_event_p (thread_agent, &events);
527
528   /* Delete thread event breakpoints, if any.  */
529   remove_thread_event_breakpoints ();
530   td_create_bp_addr = 0;
531   td_death_bp_addr = 0;
532 }
533
534 static void
535 check_thread_signals (void)
536 {
537 #ifdef GET_THREAD_SIGNALS
538   if (!thread_signals)
539     {
540       sigset_t mask;
541       int i;
542
543       GET_THREAD_SIGNALS (&mask);
544       sigemptyset (&thread_stop_set);
545       sigemptyset (&thread_print_set);
546
547       for (i = 1; i < NSIG; i++)
548         {
549           if (sigismember (&mask, i))
550             {
551               if (signal_stop_update (target_signal_from_host (i), 0))
552                 sigaddset (&thread_stop_set, i);
553               if (signal_print_update (target_signal_from_host (i), 0))
554                 sigaddset (&thread_print_set, i);
555               thread_signals = 1;
556             }
557         }
558     }
559 #endif
560 }
561
562 /* Check whether thread_db is usable.  This function is called when
563    an inferior is created (or otherwise acquired, e.g. attached to)
564    and when new shared libraries are loaded into a running process.  */
565
566 void
567 check_for_thread_db (void)
568 {
569   td_err_e err;
570   static int already_loaded;
571
572   /* First time through, report that libthread_db was successfuly
573      loaded.  Can't print this in in thread_db_load as, at that stage,
574      the interpreter and it's console haven't started.  */
575
576   if (!already_loaded)
577     {
578       Dl_info info;
579       const char *library = NULL;
580       if (dladdr ((*td_ta_new_p), &info) != 0)
581         library = info.dli_fname;
582
583       /* Try dlinfo?  */
584
585       if (library == NULL)
586         /* Paranoid - don't let a NULL path slip through.  */
587         library = LIBTHREAD_DB_SO;
588
589       printf_unfiltered (_("Using host libthread_db library \"%s\".\n"),
590                          library);
591       already_loaded = 1;
592     }
593
594   if (using_thread_db)
595     /* Nothing to do.  The thread library was already detected and the
596        target vector was already activated.  */
597     return;
598
599   /* Don't attempt to use thread_db on targets which can not run
600      (executables not running yet, core files) for now.  */
601   if (!target_has_execution)
602     return;
603
604   /* Don't attempt to use thread_db for remote targets.  */
605   if (!target_can_run (&current_target))
606     return;
607
608   /* Initialize the structure that identifies the child process.  */
609   proc_handle.pid = GET_PID (inferior_ptid);
610
611   /* Now attempt to open a connection to the thread library.  */
612   err = td_ta_new_p (&proc_handle, &thread_agent);
613   switch (err)
614     {
615     case TD_NOLIBTHREAD:
616       /* No thread library was detected.  */
617       break;
618
619     case TD_OK:
620       printf_unfiltered (_("[Thread debugging using libthread_db enabled]\n"));
621
622       /* The thread library was detected.  Activate the thread_db target.  */
623       push_target (&thread_db_ops);
624       using_thread_db = 1;
625
626       enable_thread_event_reporting ();
627       thread_db_find_new_threads ();
628       break;
629
630     default:
631       warning (_("Cannot initialize thread debugging library: %s"),
632                thread_db_err_str (err));
633       break;
634     }
635 }
636
637 static void
638 thread_db_new_objfile (struct objfile *objfile)
639 {
640   if (objfile != NULL)
641     check_for_thread_db ();
642
643   if (target_new_objfile_chain)
644     target_new_objfile_chain (objfile);
645 }
646
647 /* Attach to a new thread.  This function is called when we receive a
648    TD_CREATE event or when we iterate over all threads and find one
649    that wasn't already in our list.  */
650
651 static void
652 attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
653                const td_thrinfo_t *ti_p, int verbose)
654 {
655   struct thread_info *tp;
656   td_err_e err;
657
658   /* If we're being called after a TD_CREATE event, we may already
659      know about this thread.  There are two ways this can happen.  We
660      may have iterated over all threads between the thread creation
661      and the TD_CREATE event, for instance when the user has issued
662      the `info threads' command before the SIGTRAP for hitting the
663      thread creation breakpoint was reported.  Alternatively, the
664      thread may have exited and a new one been created with the same
665      thread ID.  In the first case we don't need to do anything; in
666      the second case we should discard information about the dead
667      thread and attach to the new one.  */
668   if (in_thread_list (ptid))
669     {
670       tp = find_thread_pid (ptid);
671       gdb_assert (tp != NULL);
672
673       if (!tp->private->dying)
674         return;
675
676       delete_thread (ptid);
677     }
678
679   check_thread_signals ();
680
681   /* Add the thread to GDB's thread list.  */
682   tp = add_thread (ptid);
683   tp->private = xmalloc (sizeof (struct private_thread_info));
684   memset (tp->private, 0, sizeof (struct private_thread_info));
685
686   if (verbose)
687     printf_unfiltered (_("[New %s]\n"), target_pid_to_str (ptid));
688
689   if (ti_p->ti_state == TD_THR_UNKNOWN || ti_p->ti_state == TD_THR_ZOMBIE)
690     return;                     /* A zombie thread -- do not attach.  */
691
692   /* Under GNU/Linux, we have to attach to each and every thread.  */
693 #ifdef ATTACH_LWP
694   ATTACH_LWP (BUILD_LWP (ti_p->ti_lid, GET_PID (ptid)), 0);
695 #endif
696
697   /* Enable thread event reporting for this thread.  */
698   err = td_thr_event_enable_p (th_p, 1);
699   if (err != TD_OK)
700     error (_("Cannot enable thread event reporting for %s: %s"),
701            target_pid_to_str (ptid), thread_db_err_str (err));
702 }
703
704 static void
705 thread_db_attach (char *args, int from_tty)
706 {
707   target_beneath->to_attach (args, from_tty);
708
709   /* Destroy thread info; it's no longer valid.  */
710   init_thread_list ();
711
712   /* The child process is now the actual multi-threaded
713      program.  Snatch its process ID...  */
714   proc_handle.pid = GET_PID (inferior_ptid);
715
716   /* ...and perform the remaining initialization steps.  */
717   enable_thread_event_reporting ();
718   thread_db_find_new_threads ();
719 }
720
721 static void
722 detach_thread (ptid_t ptid, int verbose)
723 {
724   struct thread_info *thread_info;
725
726   if (verbose)
727     printf_unfiltered (_("[%s exited]\n"), target_pid_to_str (ptid));
728
729   /* Don't delete the thread now, because it still reports as active
730      until it has executed a few instructions after the event
731      breakpoint - if we deleted it now, "info threads" would cause us
732      to re-attach to it.  Just mark it as having had a TD_DEATH
733      event.  This means that we won't delete it from our thread list
734      until we notice that it's dead (via prune_threads), or until
735      something re-uses its thread ID.  */
736   thread_info = find_thread_pid (ptid);
737   gdb_assert (thread_info != NULL);
738   thread_info->private->dying = 1;
739 }
740
741 static void
742 thread_db_detach (char *args, int from_tty)
743 {
744   disable_thread_event_reporting ();
745
746   /* There's no need to save & restore inferior_ptid here, since the
747      inferior is supposed to be survive this function call.  */
748   inferior_ptid = lwp_from_thread (inferior_ptid);
749
750   /* Forget about the child's process ID.  We shouldn't need it
751      anymore.  */
752   proc_handle.pid = 0;
753
754   target_beneath->to_detach (args, from_tty);
755 }
756
757 static int
758 clear_lwpid_callback (struct thread_info *thread, void *dummy)
759 {
760   /* If we know that our thread implementation is 1-to-1, we could save
761      a certain amount of information; it's not clear how much, so we
762      are always conservative.  */
763
764   thread->private->th_valid = 0;
765   thread->private->ti_valid = 0;
766
767   return 0;
768 }
769
770 static void
771 thread_db_resume (ptid_t ptid, int step, enum target_signal signo)
772 {
773   struct cleanup *old_chain = save_inferior_ptid ();
774
775   if (GET_PID (ptid) == -1)
776     inferior_ptid = lwp_from_thread (inferior_ptid);
777   else if (is_thread (ptid))
778     ptid = lwp_from_thread (ptid);
779
780   /* Clear cached data which may not be valid after the resume.  */
781   iterate_over_threads (clear_lwpid_callback, NULL);
782
783   target_beneath->to_resume (ptid, step, signo);
784
785   do_cleanups (old_chain);
786 }
787
788 /* Check if PID is currently stopped at the location of a thread event
789    breakpoint location.  If it is, read the event message and act upon
790    the event.  */
791
792 static void
793 check_event (ptid_t ptid)
794 {
795   td_event_msg_t msg;
796   td_thrinfo_t ti;
797   td_err_e err;
798   CORE_ADDR stop_pc;
799   int loop = 0;
800
801   /* Bail out early if we're not at a thread event breakpoint.  */
802   stop_pc = read_pc_pid (ptid) - DECR_PC_AFTER_BREAK;
803   if (stop_pc != td_create_bp_addr && stop_pc != td_death_bp_addr)
804     return;
805
806   /* If we are at a create breakpoint, we do not know what new lwp
807      was created and cannot specifically locate the event message for it.
808      We have to call td_ta_event_getmsg() to get
809      the latest message.  Since we have no way of correlating whether
810      the event message we get back corresponds to our breakpoint, we must
811      loop and read all event messages, processing them appropriately.
812      This guarantees we will process the correct message before continuing
813      from the breakpoint.
814
815      Currently, death events are not enabled.  If they are enabled,
816      the death event can use the td_thr_event_getmsg() interface to
817      get the message specifically for that lwp and avoid looping
818      below.  */
819
820   loop = 1;
821
822   do
823     {
824       err = td_ta_event_getmsg_p (thread_agent, &msg);
825       if (err != TD_OK)
826         {
827           if (err == TD_NOMSG)
828             return;
829
830           error (_("Cannot get thread event message: %s"),
831                  thread_db_err_str (err));
832         }
833
834       err = td_thr_get_info_p (msg.th_p, &ti);
835       if (err != TD_OK)
836         error (_("Cannot get thread info: %s"), thread_db_err_str (err));
837
838       ptid = ptid_build (GET_PID (ptid), ti.ti_lid, ti.ti_tid);
839
840       switch (msg.event)
841         {
842         case TD_CREATE:
843           /* Call attach_thread whether or not we already know about a
844              thread with this thread ID.  */
845           attach_thread (ptid, msg.th_p, &ti, 1);
846
847           break;
848
849         case TD_DEATH:
850
851           if (!in_thread_list (ptid))
852             error (_("Spurious thread death event."));
853
854           detach_thread (ptid, 1);
855
856           break;
857
858         default:
859           error (_("Spurious thread event."));
860         }
861     }
862   while (loop);
863 }
864
865 static ptid_t
866 thread_db_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
867 {
868   extern ptid_t trap_ptid;
869
870   if (GET_PID (ptid) != -1 && is_thread (ptid))
871     ptid = lwp_from_thread (ptid);
872
873   ptid = target_beneath->to_wait (ptid, ourstatus);
874
875   if (proc_handle.pid == 0)
876     /* The current child process isn't the actual multi-threaded
877        program yet, so don't try to do any special thread-specific
878        post-processing and bail out early.  */
879     return ptid;
880
881   if (ourstatus->kind == TARGET_WAITKIND_EXITED
882     || ourstatus->kind == TARGET_WAITKIND_SIGNALLED)
883     return pid_to_ptid (-1);
884
885   if (ourstatus->kind == TARGET_WAITKIND_EXECD)
886     {
887       remove_thread_event_breakpoints ();
888       unpush_target (&thread_db_ops);
889       using_thread_db = 0;
890
891       return pid_to_ptid (GET_PID (ptid));
892     }
893
894   if (ourstatus->kind == TARGET_WAITKIND_STOPPED
895       && ourstatus->value.sig == TARGET_SIGNAL_TRAP)
896     /* Check for a thread event.  */
897     check_event (ptid);
898
899   if (!ptid_equal (trap_ptid, null_ptid))
900     trap_ptid = thread_from_lwp (trap_ptid);
901
902   /* Change the ptid back into the higher level PID + TID format.
903      If the thread is dead and no longer on the thread list, we will 
904      get back a dead ptid.  This can occur if the thread death event
905      gets postponed by other simultaneous events.  In such a case, 
906      we want to just ignore the event and continue on.  */
907   ptid = thread_from_lwp (ptid);
908   if (GET_PID (ptid) == -1)
909     ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
910   
911   return ptid;
912 }
913
914 static LONGEST
915 thread_db_xfer_partial (struct target_ops *ops, enum target_object object,
916                         const char *annex, gdb_byte *readbuf,
917                         const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
918 {
919   struct cleanup *old_chain = save_inferior_ptid ();
920   LONGEST xfer;
921
922   if (is_thread (inferior_ptid))
923     {
924       /* FIXME: This seems to be necessary to make sure breakpoints
925          are removed.  */
926       if (!target_thread_alive (inferior_ptid))
927         inferior_ptid = pid_to_ptid (GET_PID (inferior_ptid));
928       else
929         inferior_ptid = lwp_from_thread (inferior_ptid);
930     }
931
932   xfer = target_beneath->to_xfer_partial (ops, object, annex,
933                                           readbuf, writebuf, offset, len);
934
935   do_cleanups (old_chain);
936   return xfer;
937 }
938
939 static void
940 thread_db_kill (void)
941 {
942   /* There's no need to save & restore inferior_ptid here, since the
943      inferior isn't supposed to survive this function call.  */
944   inferior_ptid = lwp_from_thread (inferior_ptid);
945   target_beneath->to_kill ();
946 }
947
948 static void
949 thread_db_create_inferior (char *exec_file, char *allargs, char **env,
950                            int from_tty)
951 {
952   unpush_target (&thread_db_ops);
953   using_thread_db = 0;
954   target_beneath->to_create_inferior (exec_file, allargs, env, from_tty);
955 }
956
957 static void
958 thread_db_post_startup_inferior (ptid_t ptid)
959 {
960   if (proc_handle.pid == 0)
961     {
962       /* The child process is now the actual multi-threaded
963          program.  Snatch its process ID...  */
964       proc_handle.pid = GET_PID (ptid);
965
966       /* ...and perform the remaining initialization steps.  */
967       enable_thread_event_reporting ();
968       thread_db_find_new_threads ();
969     }
970 }
971
972 static void
973 thread_db_mourn_inferior (void)
974 {
975   /* Forget about the child's process ID.  We shouldn't need it
976      anymore.  */
977   proc_handle.pid = 0;
978
979   target_beneath->to_mourn_inferior ();
980
981   /* Delete the old thread event breakpoints.  Do this after mourning
982      the inferior, so that we don't try to uninsert them.  */
983   remove_thread_event_breakpoints ();
984
985   /* Detach thread_db target ops.  */
986   unpush_target (&thread_db_ops);
987   using_thread_db = 0;
988 }
989
990 static int
991 find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
992 {
993   td_thrinfo_t ti;
994   td_err_e err;
995   ptid_t ptid;
996
997   err = td_thr_get_info_p (th_p, &ti);
998   if (err != TD_OK)
999     error (_("find_new_threads_callback: cannot get thread info: %s"),
1000            thread_db_err_str (err));
1001
1002   if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
1003     return 0;                   /* A zombie -- ignore.  */
1004
1005   ptid = ptid_build (GET_PID (inferior_ptid), ti.ti_lid, ti.ti_tid);
1006
1007   if (!in_thread_list (ptid))
1008     attach_thread (ptid, th_p, &ti, 1);
1009
1010   return 0;
1011 }
1012
1013 static void
1014 thread_db_find_new_threads (void)
1015 {
1016   td_err_e err;
1017
1018   /* Iterate over all user-space threads to discover new threads.  */
1019   err = td_ta_thr_iter_p (thread_agent, find_new_threads_callback, NULL,
1020                           TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
1021                           TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
1022   if (err != TD_OK)
1023     error (_("Cannot find new threads: %s"), thread_db_err_str (err));
1024 }
1025
1026 static char *
1027 thread_db_pid_to_str (ptid_t ptid)
1028 {
1029   if (is_thread (ptid))
1030     {
1031       static char buf[64];
1032       struct thread_info *thread_info;
1033
1034       thread_info = find_thread_pid (ptid);
1035       if (thread_info == NULL)
1036         snprintf (buf, sizeof (buf), "Thread %ld (LWP %ld) (Missing)",
1037                   GET_THREAD (ptid), GET_LWP (ptid));
1038       else
1039         snprintf (buf, sizeof (buf), "Thread %ld (LWP %ld)",
1040                   GET_THREAD (ptid), GET_LWP (ptid));
1041
1042       return buf;
1043     }
1044
1045   if (target_beneath->to_pid_to_str (ptid))
1046     return target_beneath->to_pid_to_str (ptid);
1047
1048   return normal_pid_to_str (ptid);
1049 }
1050
1051 /* Return a string describing the state of the thread specified by
1052    INFO.  */
1053
1054 static char *
1055 thread_db_extra_thread_info (struct thread_info *info)
1056 {
1057   if (info->private->dying)
1058     return "Exiting";
1059
1060   return NULL;
1061 }
1062
1063 /* Get the address of the thread local variable in load module LM which
1064    is stored at OFFSET within the thread local storage for thread PTID.  */
1065
1066 static CORE_ADDR
1067 thread_db_get_thread_local_address (ptid_t ptid,
1068                                     CORE_ADDR lm,
1069                                     CORE_ADDR offset)
1070 {
1071   if (is_thread (ptid))
1072     {
1073       td_err_e err;
1074       void *address;
1075       struct thread_info *thread_info;
1076
1077       /* glibc doesn't provide the needed interface.  */
1078       if (!td_thr_tls_get_addr_p)
1079         throw_error (TLS_NO_LIBRARY_SUPPORT_ERROR,
1080                      _("No TLS library support"));
1081
1082       /* Caller should have verified that lm != 0.  */
1083       gdb_assert (lm != 0);
1084
1085       /* Get info about the thread.  */
1086       thread_info = find_thread_pid (ptid);
1087       thread_db_map_id2thr (thread_info, 1);
1088
1089       /* Finally, get the address of the variable.  */
1090       err = td_thr_tls_get_addr_p (&thread_info->private->th,
1091                                    (void *)(size_t) lm,
1092                                    offset, &address);
1093
1094 #ifdef THREAD_DB_HAS_TD_NOTALLOC
1095       /* The memory hasn't been allocated, yet.  */
1096       if (err == TD_NOTALLOC)
1097           /* Now, if libthread_db provided the initialization image's
1098              address, we *could* try to build a non-lvalue value from
1099              the initialization image.  */
1100         throw_error (TLS_NOT_ALLOCATED_YET_ERROR,
1101                      _("TLS not allocated yet"));
1102 #endif
1103
1104       /* Something else went wrong.  */
1105       if (err != TD_OK)
1106         throw_error (TLS_GENERIC_ERROR,
1107                      (("%s")), thread_db_err_str (err));
1108
1109       /* Cast assuming host == target.  Joy.  */
1110       /* Do proper sign extension for the target.  */
1111       gdb_assert (exec_bfd);
1112       return (bfd_get_sign_extend_vma (exec_bfd) > 0
1113               ? (CORE_ADDR) (intptr_t) address
1114               : (CORE_ADDR) (uintptr_t) address);
1115     }
1116
1117   if (target_beneath->to_get_thread_local_address)
1118     return target_beneath->to_get_thread_local_address (ptid, lm, offset);
1119   else
1120     throw_error (TLS_GENERIC_ERROR,
1121                  _("TLS not supported on this target"));
1122 }
1123
1124 static void
1125 init_thread_db_ops (void)
1126 {
1127   thread_db_ops.to_shortname = "multi-thread";
1128   thread_db_ops.to_longname = "multi-threaded child process.";
1129   thread_db_ops.to_doc = "Threads and pthreads support.";
1130   thread_db_ops.to_attach = thread_db_attach;
1131   thread_db_ops.to_detach = thread_db_detach;
1132   thread_db_ops.to_resume = thread_db_resume;
1133   thread_db_ops.to_wait = thread_db_wait;
1134   thread_db_ops.to_xfer_partial = thread_db_xfer_partial;
1135   thread_db_ops.to_kill = thread_db_kill;
1136   thread_db_ops.to_create_inferior = thread_db_create_inferior;
1137   thread_db_ops.to_post_startup_inferior = thread_db_post_startup_inferior;
1138   thread_db_ops.to_mourn_inferior = thread_db_mourn_inferior;
1139   thread_db_ops.to_find_new_threads = thread_db_find_new_threads;
1140   thread_db_ops.to_pid_to_str = thread_db_pid_to_str;
1141   thread_db_ops.to_stratum = thread_stratum;
1142   thread_db_ops.to_has_thread_control = tc_schedlock;
1143   thread_db_ops.to_get_thread_local_address
1144     = thread_db_get_thread_local_address;
1145   thread_db_ops.to_extra_thread_info = thread_db_extra_thread_info;
1146   thread_db_ops.to_magic = OPS_MAGIC;
1147 }
1148
1149 void
1150 _initialize_thread_db (void)
1151 {
1152   /* Only initialize the module if we can load libthread_db.  */
1153   if (thread_db_load ())
1154     {
1155       init_thread_db_ops ();
1156       add_target (&thread_db_ops);
1157
1158       /* Add ourselves to objfile event chain.  */
1159       target_new_objfile_chain = deprecated_target_new_objfile_hook;
1160       deprecated_target_new_objfile_hook = thread_db_new_objfile;
1161     }
1162 }