2009-05-15 Paul Pluzhnikov <ppluzhnikov@google.com>
[binutils-gdb.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, 2007, 2008, 2009
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 3 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, see <http://www.gnu.org/licenses/>. */
20
21 #include "defs.h"
22
23 #include "gdb_assert.h"
24 #include <dlfcn.h>
25 #include "gdb_proc_service.h"
26 #include "gdb_thread_db.h"
27
28 #include "bfd.h"
29 #include "command.h"
30 #include "exceptions.h"
31 #include "gdbcmd.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.h"
39 #include "solib-svr4.h"
40 #include "gdbcore.h"
41 #include "observer.h"
42 #include "linux-nat.h"
43
44 #include <signal.h>
45
46 #ifdef HAVE_GNU_LIBC_VERSION_H
47 #include <gnu/libc-version.h>
48 #endif
49
50 /* GNU/Linux libthread_db support.
51
52 libthread_db is a library, provided along with libpthread.so, which
53 exposes the internals of the thread library to a debugger. It
54 allows GDB to find existing threads, new threads as they are
55 created, thread IDs (usually, the result of pthread_self), and
56 thread-local variables.
57
58 The libthread_db interface originates on Solaris, where it is
59 both more powerful and more complicated. This implementation
60 only works for LinuxThreads and NPTL, the two glibc threading
61 libraries. It assumes that each thread is permanently assigned
62 to a single light-weight process (LWP).
63
64 libthread_db-specific information is stored in the "private" field
65 of struct thread_info. When the field is NULL we do not yet have
66 information about the new thread; this could be temporary (created,
67 but the thread library's data structures do not reflect it yet)
68 or permanent (created using clone instead of pthread_create).
69
70 Process IDs managed by linux-thread-db.c match those used by
71 linux-nat.c: a common PID for all processes, an LWP ID for each
72 thread, and no TID. We save the TID in private. Keeping it out
73 of the ptid_t prevents thread IDs changing when libpthread is
74 loaded or unloaded. */
75
76 static char *libthread_db_search_path;
77
78 /* If we're running on GNU/Linux, we must explicitly attach to any new
79 threads. */
80
81 /* This module's target vector. */
82 static struct target_ops thread_db_ops;
83
84 /* Handle from dlopen for libthread_db.so. Not NULL if we're using this
85 module's target vector. */
86 static void *thread_db_handle;
87
88 /* Non-zero if we have determined the signals used by the threads
89 library. */
90 static int thread_signals;
91 static sigset_t thread_stop_set;
92 static sigset_t thread_print_set;
93
94 /* Structure that identifies the child process for the
95 <proc_service.h> interface. */
96 static struct ps_prochandle proc_handle;
97
98 /* Connection to the libthread_db library. */
99 static td_thragent_t *thread_agent;
100
101 /* Pointers to the libthread_db functions. */
102
103 static td_err_e (*td_init_p) (void);
104
105 static td_err_e (*td_ta_new_p) (struct ps_prochandle * ps,
106 td_thragent_t **ta);
107 static td_err_e (*td_ta_map_id2thr_p) (const td_thragent_t *ta, thread_t pt,
108 td_thrhandle_t *__th);
109 static td_err_e (*td_ta_map_lwp2thr_p) (const td_thragent_t *ta,
110 lwpid_t lwpid, td_thrhandle_t *th);
111 static td_err_e (*td_ta_thr_iter_p) (const td_thragent_t *ta,
112 td_thr_iter_f *callback, void *cbdata_p,
113 td_thr_state_e state, int ti_pri,
114 sigset_t *ti_sigmask_p,
115 unsigned int ti_user_flags);
116 static td_err_e (*td_ta_event_addr_p) (const td_thragent_t *ta,
117 td_event_e event, td_notify_t *ptr);
118 static td_err_e (*td_ta_set_event_p) (const td_thragent_t *ta,
119 td_thr_events_t *event);
120 static td_err_e (*td_ta_event_getmsg_p) (const td_thragent_t *ta,
121 td_event_msg_t *msg);
122
123 static td_err_e (*td_thr_validate_p) (const td_thrhandle_t *th);
124 static td_err_e (*td_thr_get_info_p) (const td_thrhandle_t *th,
125 td_thrinfo_t *infop);
126 static td_err_e (*td_thr_event_enable_p) (const td_thrhandle_t *th,
127 int event);
128
129 static td_err_e (*td_thr_tls_get_addr_p) (const td_thrhandle_t *th,
130 void *map_address,
131 size_t offset, void **address);
132
133 /* Location of the thread creation event breakpoint. The code at this
134 location in the child process will be called by the pthread library
135 whenever a new thread is created. By setting a special breakpoint
136 at this location, GDB can detect when a new thread is created. We
137 obtain this location via the td_ta_event_addr call. */
138 static CORE_ADDR td_create_bp_addr;
139
140 /* Location of the thread death event breakpoint. */
141 static CORE_ADDR td_death_bp_addr;
142
143 /* Prototypes for local functions. */
144 static void thread_db_find_new_threads_1 (void);
145 static void attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
146 const td_thrinfo_t *ti_p);
147 static void detach_thread (ptid_t ptid);
148 \f
149
150 /* Use "struct private_thread_info" to cache thread state. This is
151 a substantial optimization. */
152
153 struct private_thread_info
154 {
155 /* Flag set when we see a TD_DEATH event for this thread. */
156 unsigned int dying:1;
157
158 /* Cached thread state. */
159 td_thrhandle_t th;
160 thread_t tid;
161 };
162 \f
163
164 static char *
165 thread_db_err_str (td_err_e err)
166 {
167 static char buf[64];
168
169 switch (err)
170 {
171 case TD_OK:
172 return "generic 'call succeeded'";
173 case TD_ERR:
174 return "generic error";
175 case TD_NOTHR:
176 return "no thread to satisfy query";
177 case TD_NOSV:
178 return "no sync handle to satisfy query";
179 case TD_NOLWP:
180 return "no LWP to satisfy query";
181 case TD_BADPH:
182 return "invalid process handle";
183 case TD_BADTH:
184 return "invalid thread handle";
185 case TD_BADSH:
186 return "invalid synchronization handle";
187 case TD_BADTA:
188 return "invalid thread agent";
189 case TD_BADKEY:
190 return "invalid key";
191 case TD_NOMSG:
192 return "no event message for getmsg";
193 case TD_NOFPREGS:
194 return "FPU register set not available";
195 case TD_NOLIBTHREAD:
196 return "application not linked with libthread";
197 case TD_NOEVENT:
198 return "requested event is not supported";
199 case TD_NOCAPAB:
200 return "capability not available";
201 case TD_DBERR:
202 return "debugger service failed";
203 case TD_NOAPLIC:
204 return "operation not applicable to";
205 case TD_NOTSD:
206 return "no thread-specific data for this thread";
207 case TD_MALLOC:
208 return "malloc failed";
209 case TD_PARTIALREG:
210 return "only part of register set was written/read";
211 case TD_NOXREGS:
212 return "X register set not available for this thread";
213 #ifdef THREAD_DB_HAS_TD_NOTALLOC
214 case TD_NOTALLOC:
215 return "thread has not yet allocated TLS for given module";
216 #endif
217 #ifdef THREAD_DB_HAS_TD_VERSION
218 case TD_VERSION:
219 return "versions of libpthread and libthread_db do not match";
220 #endif
221 #ifdef THREAD_DB_HAS_TD_NOTLS
222 case TD_NOTLS:
223 return "there is no TLS segment in the given module";
224 #endif
225 default:
226 snprintf (buf, sizeof (buf), "unknown thread_db error '%d'", err);
227 return buf;
228 }
229 }
230 \f
231 /* Return 1 if any threads have been registered. There may be none if
232 the threading library is not fully initialized yet. */
233
234 static int
235 have_threads_callback (struct thread_info *thread, void *dummy)
236 {
237 return thread->private != NULL;
238 }
239
240 static int
241 have_threads (void)
242 {
243 return iterate_over_threads (have_threads_callback, NULL) != NULL;
244 }
245
246 /* A callback function for td_ta_thr_iter, which we use to map all
247 threads to LWPs.
248
249 THP is a handle to the current thread; if INFOP is not NULL, the
250 struct thread_info associated with this thread is returned in
251 *INFOP.
252
253 If the thread is a zombie, TD_THR_ZOMBIE is returned. Otherwise,
254 zero is returned to indicate success. */
255
256 static int
257 thread_get_info_callback (const td_thrhandle_t *thp, void *infop)
258 {
259 td_thrinfo_t ti;
260 td_err_e err;
261 struct thread_info *thread_info;
262 ptid_t thread_ptid;
263
264 err = td_thr_get_info_p (thp, &ti);
265 if (err != TD_OK)
266 error (_("thread_get_info_callback: cannot get thread info: %s"),
267 thread_db_err_str (err));
268
269 /* Fill the cache. */
270 thread_ptid = ptid_build (GET_PID (proc_handle.ptid), ti.ti_lid, 0);
271 thread_info = find_thread_pid (thread_ptid);
272
273 /* In the case of a zombie thread, don't continue. We don't want to
274 attach to it thinking it is a new thread. */
275 if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
276 {
277 if (infop != NULL)
278 *(struct thread_info **) infop = thread_info;
279 return TD_THR_ZOMBIE;
280 }
281
282 if (thread_info == NULL)
283 {
284 /* New thread. Attach to it now (why wait?). */
285 if (!have_threads ())
286 thread_db_find_new_threads_1 ();
287 else
288 attach_thread (thread_ptid, thp, &ti);
289 thread_info = find_thread_pid (thread_ptid);
290 gdb_assert (thread_info != NULL);
291 }
292
293 if (infop != NULL)
294 *(struct thread_info **) infop = thread_info;
295
296 return 0;
297 }
298 \f
299 /* Convert between user-level thread ids and LWP ids. */
300
301 static ptid_t
302 thread_from_lwp (ptid_t ptid)
303 {
304 td_thrhandle_t th;
305 td_err_e err;
306 struct thread_info *thread_info;
307 ptid_t thread_ptid;
308
309 /* This ptid comes from linux-nat.c, which should always fill in the
310 LWP. */
311 gdb_assert (GET_LWP (ptid) != 0);
312
313 /* Access an lwp we know is stopped. */
314 proc_handle.ptid = ptid;
315 err = td_ta_map_lwp2thr_p (thread_agent, GET_LWP (ptid), &th);
316 if (err != TD_OK)
317 error (_("Cannot find user-level thread for LWP %ld: %s"),
318 GET_LWP (ptid), thread_db_err_str (err));
319
320 thread_info = NULL;
321
322 /* Fetch the thread info. If we get back TD_THR_ZOMBIE, then the
323 event thread has already died. If another gdb interface has called
324 thread_alive() previously, the thread won't be found on the thread list
325 anymore. In that case, we don't want to process this ptid anymore
326 to avoid the possibility of later treating it as a newly
327 discovered thread id that we should add to the list. Thus,
328 we return a -1 ptid which is also how the thread list marks a
329 dead thread. */
330 if (thread_get_info_callback (&th, &thread_info) == TD_THR_ZOMBIE
331 && thread_info == NULL)
332 return pid_to_ptid (-1);
333
334 gdb_assert (ptid_get_tid (ptid) == 0);
335 return ptid;
336 }
337 \f
338
339 /* Attach to lwp PTID, doing whatever else is required to have this
340 LWP under the debugger's control --- e.g., enabling event
341 reporting. Returns true on success. */
342 int
343 thread_db_attach_lwp (ptid_t ptid)
344 {
345 td_thrhandle_t th;
346 td_thrinfo_t ti;
347 td_err_e err;
348
349 if (thread_db_handle == NULL)
350 return 0;
351
352 /* This ptid comes from linux-nat.c, which should always fill in the
353 LWP. */
354 gdb_assert (GET_LWP (ptid) != 0);
355
356 /* Access an lwp we know is stopped. */
357 proc_handle.ptid = ptid;
358
359 /* If we have only looked at the first thread before libpthread was
360 initialized, we may not know its thread ID yet. Make sure we do
361 before we add another thread to the list. */
362 if (!have_threads ())
363 thread_db_find_new_threads_1 ();
364
365 err = td_ta_map_lwp2thr_p (thread_agent, GET_LWP (ptid), &th);
366 if (err != TD_OK)
367 /* Cannot find user-level thread. */
368 return 0;
369
370 err = td_thr_get_info_p (&th, &ti);
371 if (err != TD_OK)
372 {
373 warning (_("Cannot get thread info: %s"), thread_db_err_str (err));
374 return 0;
375 }
376
377 attach_thread (ptid, &th, &ti);
378 return 1;
379 }
380
381 static void *
382 verbose_dlsym (void *handle, const char *name)
383 {
384 void *sym = dlsym (handle, name);
385 if (sym == NULL)
386 warning (_("Symbol \"%s\" not found in libthread_db: %s"), name, dlerror ());
387 return sym;
388 }
389
390 static td_err_e
391 enable_thread_event (td_thragent_t *thread_agent, int event, CORE_ADDR *bp)
392 {
393 td_notify_t notify;
394 td_err_e err;
395
396 /* Access an lwp we know is stopped. */
397 proc_handle.ptid = inferior_ptid;
398
399 /* Get the breakpoint address for thread EVENT. */
400 err = td_ta_event_addr_p (thread_agent, event, &notify);
401 if (err != TD_OK)
402 return err;
403
404 /* Set up the breakpoint. */
405 gdb_assert (exec_bfd);
406 (*bp) = (gdbarch_convert_from_func_ptr_addr
407 (current_gdbarch,
408 /* Do proper sign extension for the target. */
409 (bfd_get_sign_extend_vma (exec_bfd) > 0
410 ? (CORE_ADDR) (intptr_t) notify.u.bptaddr
411 : (CORE_ADDR) (uintptr_t) notify.u.bptaddr),
412 &current_target));
413 create_thread_event_breakpoint ((*bp));
414
415 return TD_OK;
416 }
417
418 static void
419 enable_thread_event_reporting (void)
420 {
421 td_thr_events_t events;
422 td_notify_t notify;
423 td_err_e err;
424 #ifdef HAVE_GNU_LIBC_VERSION_H
425 const char *libc_version;
426 int libc_major, libc_minor;
427 #endif
428
429 /* We cannot use the thread event reporting facility if these
430 functions aren't available. */
431 if (td_ta_event_addr_p == NULL || td_ta_set_event_p == NULL
432 || td_ta_event_getmsg_p == NULL || td_thr_event_enable_p == NULL)
433 return;
434
435 /* Set the process wide mask saying which events we're interested in. */
436 td_event_emptyset (&events);
437 td_event_addset (&events, TD_CREATE);
438
439 #ifdef HAVE_GNU_LIBC_VERSION_H
440 /* The event reporting facility is broken for TD_DEATH events in
441 glibc 2.1.3, so don't enable it if we have glibc but a lower
442 version. */
443 libc_version = gnu_get_libc_version ();
444 if (sscanf (libc_version, "%d.%d", &libc_major, &libc_minor) == 2
445 && (libc_major > 2 || (libc_major == 2 && libc_minor > 1)))
446 #endif
447 td_event_addset (&events, TD_DEATH);
448
449 err = td_ta_set_event_p (thread_agent, &events);
450 if (err != TD_OK)
451 {
452 warning (_("Unable to set global thread event mask: %s"),
453 thread_db_err_str (err));
454 return;
455 }
456
457 /* Delete previous thread event breakpoints, if any. */
458 remove_thread_event_breakpoints ();
459 td_create_bp_addr = 0;
460 td_death_bp_addr = 0;
461
462 /* Set up the thread creation event. */
463 err = enable_thread_event (thread_agent, TD_CREATE, &td_create_bp_addr);
464 if (err != TD_OK)
465 {
466 warning (_("Unable to get location for thread creation breakpoint: %s"),
467 thread_db_err_str (err));
468 return;
469 }
470
471 /* Set up the thread death event. */
472 err = enable_thread_event (thread_agent, TD_DEATH, &td_death_bp_addr);
473 if (err != TD_OK)
474 {
475 warning (_("Unable to get location for thread death breakpoint: %s"),
476 thread_db_err_str (err));
477 return;
478 }
479 }
480
481 /* Attempt to initialize dlopen()ed libthread_db, described by HANDLE.
482 Return 1 on success.
483 Failure could happen if libthread_db does not have symbols we expect,
484 or when it refuses to work with the current inferior (e.g. due to
485 version mismatch between libthread_db and libpthread). */
486
487 static int
488 try_thread_db_load_1 (void *handle)
489 {
490 td_err_e err;
491
492 /* Initialize pointers to the dynamic library functions we will use.
493 Essential functions first. */
494
495 td_init_p = verbose_dlsym (handle, "td_init");
496 if (td_init_p == NULL)
497 return 0;
498
499 err = td_init_p ();
500 if (err != TD_OK)
501 {
502 warning (_("Cannot initialize libthread_db: %s"), thread_db_err_str (err));
503 return 0;
504 }
505
506 td_ta_new_p = verbose_dlsym (handle, "td_ta_new");
507 if (td_ta_new_p == NULL)
508 return 0;
509
510 /* Initialize the structure that identifies the child process. */
511 proc_handle.ptid = inferior_ptid;
512
513 /* Now attempt to open a connection to the thread library. */
514 err = td_ta_new_p (&proc_handle, &thread_agent);
515 if (err != TD_OK)
516 {
517 td_ta_new_p = NULL;
518 if (info_verbose)
519 printf_unfiltered (_("td_ta_new failed: %s\n"),
520 thread_db_err_str (err));
521 else
522 switch (err)
523 {
524 case TD_NOLIBTHREAD:
525 #ifdef THREAD_DB_HAS_TD_VERSION
526 case TD_VERSION:
527 #endif
528 /* The errors above are not unexpected and silently ignored:
529 they just mean we haven't found correct version of
530 libthread_db yet. */
531 break;
532 default:
533 warning (_("td_ta_new failed: %s"), thread_db_err_str (err));
534 }
535 return 0;
536 }
537
538 td_ta_map_id2thr_p = verbose_dlsym (handle, "td_ta_map_id2thr");
539 if (td_ta_map_id2thr_p == NULL)
540 return 0;
541
542 td_ta_map_lwp2thr_p = verbose_dlsym (handle, "td_ta_map_lwp2thr");
543 if (td_ta_map_lwp2thr_p == NULL)
544 return 0;
545
546 td_ta_thr_iter_p = verbose_dlsym (handle, "td_ta_thr_iter");
547 if (td_ta_thr_iter_p == NULL)
548 return 0;
549
550 td_thr_validate_p = verbose_dlsym (handle, "td_thr_validate");
551 if (td_thr_validate_p == NULL)
552 return 0;
553
554 td_thr_get_info_p = verbose_dlsym (handle, "td_thr_get_info");
555 if (td_thr_get_info_p == NULL)
556 return 0;
557
558 /* These are not essential. */
559 td_ta_event_addr_p = dlsym (handle, "td_ta_event_addr");
560 td_ta_set_event_p = dlsym (handle, "td_ta_set_event");
561 td_ta_event_getmsg_p = dlsym (handle, "td_ta_event_getmsg");
562 td_thr_event_enable_p = dlsym (handle, "td_thr_event_enable");
563 td_thr_tls_get_addr_p = dlsym (handle, "td_thr_tls_get_addr");
564
565 printf_unfiltered (_("[Thread debugging using libthread_db enabled]\n"));
566
567 /* The thread library was detected. Activate the thread_db target. */
568 push_target (&thread_db_ops);
569 thread_db_handle = handle;
570
571 enable_thread_event_reporting ();
572 thread_db_find_new_threads_1 ();
573 return 1;
574 }
575
576 /* Lookup a library in which given symbol resides.
577 Note: this is looking in GDB process, not in the inferior.
578 Returns library name, or NULL. */
579
580 static const char *
581 dladdr_to_soname (const void *addr)
582 {
583 Dl_info info;
584
585 if (dladdr (addr, &info) != 0)
586 return info.dli_fname;
587 return NULL;
588 }
589
590 /* Attempt to use LIBRARY as libthread_db. LIBRARY could be absolute,
591 relative, or just LIBTHREAD_DB. */
592
593 static int
594 try_thread_db_load (const char *library)
595 {
596 void *handle;
597
598 if (info_verbose)
599 printf_unfiltered (_("Trying host libthread_db library: %s.\n"),
600 library);
601 handle = dlopen (library, RTLD_NOW);
602 if (handle == NULL)
603 {
604 if (info_verbose)
605 printf_unfiltered (_("dlopen failed: %s.\n"), dlerror ());
606 return 0;
607 }
608
609 if (info_verbose && strchr (library, '/') == NULL)
610 {
611 void *td_init;
612
613 td_init = dlsym (handle, "td_init");
614 if (td_init != NULL)
615 {
616 const char *const libpath = dladdr_to_soname (td_init);
617
618 if (libpath != NULL)
619 printf_unfiltered (_("Host %s resolved to: %s.\n"),
620 library, libpath);
621 }
622 }
623
624 if (try_thread_db_load_1 (handle))
625 return 1;
626
627 /* This library "refused" to work on current inferior. */
628 dlclose (handle);
629 return 0;
630 }
631
632
633 /* Search libthread_db_search_path for libthread_db which "agrees"
634 to work on current inferior. */
635
636 static int
637 thread_db_load_search (void)
638 {
639 char path[PATH_MAX];
640 const char *search_path = libthread_db_search_path;
641 int rc = 0;
642
643 while (*search_path)
644 {
645 const char *end = strchr (search_path, ':');
646 if (end)
647 {
648 size_t len = end - search_path;
649 if (len + 1 + strlen (LIBTHREAD_DB_SO) + 1 > sizeof (path))
650 {
651 char *cp = xmalloc (len + 1);
652 memcpy (cp, search_path, len);
653 cp[len] = '\0';
654 warning (_("libthread_db_search_path component too long,"
655 " ignored: %s."), cp);
656 xfree (cp);
657 search_path += len + 1;
658 continue;
659 }
660 memcpy (path, search_path, len);
661 path[len] = '\0';
662 search_path += len + 1;
663 }
664 else
665 {
666 size_t len = strlen (search_path);
667
668 if (len + 1 + strlen (LIBTHREAD_DB_SO) + 1 > sizeof (path))
669 {
670 warning (_("libthread_db_search_path component too long,"
671 " ignored: %s."), search_path);
672 break;
673 }
674 memcpy (path, search_path, len + 1);
675 search_path += len;
676 }
677 strcat (path, "/");
678 strcat (path, LIBTHREAD_DB_SO);
679 if (try_thread_db_load (path))
680 {
681 rc = 1;
682 break;
683 }
684 }
685 if (rc == 0)
686 rc = try_thread_db_load (LIBTHREAD_DB_SO);
687 return rc;
688 }
689
690 /* Attempt to load and initialize libthread_db.
691 Return 1 on success.
692 */
693
694 static int
695 thread_db_load (void)
696 {
697 struct objfile *obj;
698
699 if (thread_db_handle != NULL)
700 return 1;
701
702 /* Don't attempt to use thread_db on targets which can not run
703 (executables not running yet, core files) for now. */
704 if (!target_has_execution)
705 return 0;
706
707 /* Don't attempt to use thread_db for remote targets. */
708 if (!target_can_run (&current_target))
709 return 0;
710
711 if (thread_db_load_search ())
712 return 1;
713
714 /* None of the libthread_db's on our search path, not the system default
715 ones worked. If the executable is dynamically linked against
716 libpthread, try loading libthread_db from the same directory. */
717
718 ALL_OBJFILES (obj)
719 if (libpthread_name_p (obj->name))
720 {
721 char path[PATH_MAX], *cp;
722
723 gdb_assert (strlen (obj->name) < sizeof (path));
724 strcpy (path, obj->name);
725 cp = strrchr (path, '/');
726
727 if (cp == NULL)
728 {
729 warning (_("Expected absolute pathname for libpthread in the"
730 " inferior, but got %s."), path);
731 }
732 else if (cp + 1 + strlen (LIBTHREAD_DB_SO) + 1 > path + sizeof (path))
733 {
734 warning (_("Unexpected: path to libpthread in the inferior is"
735 " too long: %s"), path);
736 }
737 else
738 {
739 strcpy (cp + 1, LIBTHREAD_DB_SO);
740 if (try_thread_db_load (path))
741 return 1;
742 }
743 warning (_("Unable to find libthread_db matching inferior's thread"
744 " library, thread debugging will not be available."));
745 return 0;
746 }
747 /* Either this executable isn't using libpthread at all, or it is
748 statically linked. Since we can't easily distinguish these two cases,
749 no warning is issued. */
750 return 0;
751 }
752
753 static void
754 disable_thread_event_reporting (void)
755 {
756 td_thr_events_t events;
757
758 /* Set the process wide mask saying we aren't interested in any
759 events anymore. */
760 td_event_emptyset (&events);
761 td_ta_set_event_p (thread_agent, &events);
762
763 /* Delete thread event breakpoints, if any. */
764 remove_thread_event_breakpoints ();
765 td_create_bp_addr = 0;
766 td_death_bp_addr = 0;
767 }
768
769 static void
770 check_thread_signals (void)
771 {
772 #ifdef GET_THREAD_SIGNALS
773 if (!thread_signals)
774 {
775 sigset_t mask;
776 int i;
777
778 GET_THREAD_SIGNALS (&mask);
779 sigemptyset (&thread_stop_set);
780 sigemptyset (&thread_print_set);
781
782 for (i = 1; i < NSIG; i++)
783 {
784 if (sigismember (&mask, i))
785 {
786 if (signal_stop_update (target_signal_from_host (i), 0))
787 sigaddset (&thread_stop_set, i);
788 if (signal_print_update (target_signal_from_host (i), 0))
789 sigaddset (&thread_print_set, i);
790 thread_signals = 1;
791 }
792 }
793 }
794 #endif
795 }
796
797 /* Check whether thread_db is usable. This function is called when
798 an inferior is created (or otherwise acquired, e.g. attached to)
799 and when new shared libraries are loaded into a running process. */
800
801 void
802 check_for_thread_db (void)
803 {
804 td_err_e err;
805 static void *last_loaded;
806
807 /* Do nothing if we couldn't load libthread_db.so.1. */
808 if (!thread_db_load ())
809 return;
810
811 /* First time through, report that libthread_db was successfuly
812 loaded. Can't print this in in thread_db_load as, at that stage,
813 the interpreter and it's console haven't started.
814 We track td_ta_new_p because the user may switch executables,
815 and as a result we may decide to use a different version of
816 libthread_db. */
817
818 if (last_loaded != td_ta_new_p)
819 {
820 last_loaded = td_ta_new_p;
821
822 if (info_verbose || *libthread_db_search_path)
823 {
824 const char *library;
825
826 library = dladdr_to_soname (*td_ta_new_p);
827 if (library == NULL)
828 library = LIBTHREAD_DB_SO;
829
830 printf_unfiltered (_("Using host libthread_db library \"%s\".\n"),
831 library);
832 }
833 }
834 }
835
836 static void
837 thread_db_new_objfile (struct objfile *objfile)
838 {
839 if (objfile != NULL)
840 check_for_thread_db ();
841 }
842
843 /* Attach to a new thread. This function is called when we receive a
844 TD_CREATE event or when we iterate over all threads and find one
845 that wasn't already in our list. */
846
847 static void
848 attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
849 const td_thrinfo_t *ti_p)
850 {
851 struct private_thread_info *private;
852 struct thread_info *tp = NULL;
853 td_err_e err;
854
855 /* If we're being called after a TD_CREATE event, we may already
856 know about this thread. There are two ways this can happen. We
857 may have iterated over all threads between the thread creation
858 and the TD_CREATE event, for instance when the user has issued
859 the `info threads' command before the SIGTRAP for hitting the
860 thread creation breakpoint was reported. Alternatively, the
861 thread may have exited and a new one been created with the same
862 thread ID. In the first case we don't need to do anything; in
863 the second case we should discard information about the dead
864 thread and attach to the new one. */
865 if (in_thread_list (ptid))
866 {
867 tp = find_thread_pid (ptid);
868 gdb_assert (tp != NULL);
869
870 /* If tp->private is NULL, then GDB is already attached to this
871 thread, but we do not know anything about it. We can learn
872 about it here. This can only happen if we have some other
873 way besides libthread_db to notice new threads (i.e.
874 PTRACE_EVENT_CLONE); assume the same mechanism notices thread
875 exit, so this can not be a stale thread recreated with the
876 same ID. */
877 if (tp->private != NULL)
878 {
879 if (!tp->private->dying)
880 return;
881
882 delete_thread (ptid);
883 tp = NULL;
884 }
885 }
886
887 check_thread_signals ();
888
889 if (ti_p->ti_state == TD_THR_UNKNOWN || ti_p->ti_state == TD_THR_ZOMBIE)
890 return; /* A zombie thread -- do not attach. */
891
892 /* Under GNU/Linux, we have to attach to each and every thread. */
893 if (tp == NULL
894 && lin_lwp_attach_lwp (BUILD_LWP (ti_p->ti_lid, GET_PID (ptid))) < 0)
895 return;
896
897 /* Construct the thread's private data. */
898 private = xmalloc (sizeof (struct private_thread_info));
899 memset (private, 0, sizeof (struct private_thread_info));
900
901 /* A thread ID of zero may mean the thread library has not initialized
902 yet. But we shouldn't even get here if that's the case. FIXME:
903 if we change GDB to always have at least one thread in the thread
904 list this will have to go somewhere else; maybe private == NULL
905 until the thread_db target claims it. */
906 gdb_assert (ti_p->ti_tid != 0);
907 private->th = *th_p;
908 private->tid = ti_p->ti_tid;
909
910 /* Add the thread to GDB's thread list. */
911 if (tp == NULL)
912 tp = add_thread_with_info (ptid, private);
913 else
914 tp->private = private;
915
916 /* Enable thread event reporting for this thread. */
917 err = td_thr_event_enable_p (th_p, 1);
918 if (err != TD_OK)
919 error (_("Cannot enable thread event reporting for %s: %s"),
920 target_pid_to_str (ptid), thread_db_err_str (err));
921 }
922
923 static void
924 detach_thread (ptid_t ptid)
925 {
926 struct thread_info *thread_info;
927
928 /* Don't delete the thread now, because it still reports as active
929 until it has executed a few instructions after the event
930 breakpoint - if we deleted it now, "info threads" would cause us
931 to re-attach to it. Just mark it as having had a TD_DEATH
932 event. This means that we won't delete it from our thread list
933 until we notice that it's dead (via prune_threads), or until
934 something re-uses its thread ID. We'll report the thread exit
935 when the underlying LWP dies. */
936 thread_info = find_thread_pid (ptid);
937 gdb_assert (thread_info != NULL && thread_info->private != NULL);
938 thread_info->private->dying = 1;
939 }
940
941 static void
942 thread_db_detach (struct target_ops *ops, char *args, int from_tty)
943 {
944 struct target_ops *target_beneath = find_target_beneath (ops);
945
946 disable_thread_event_reporting ();
947
948 /* Forget about the child's process ID. We shouldn't need it
949 anymore. */
950 proc_handle.ptid = null_ptid;
951
952 /* Detach thread_db target ops. */
953 unpush_target (&thread_db_ops);
954 if (thread_db_handle)
955 dlclose (thread_db_handle);
956 thread_db_handle = NULL;
957
958 target_beneath->to_detach (target_beneath, args, from_tty);
959 }
960
961 /* Check if PID is currently stopped at the location of a thread event
962 breakpoint location. If it is, read the event message and act upon
963 the event. */
964
965 static void
966 check_event (ptid_t ptid)
967 {
968 struct regcache *regcache = get_thread_regcache (ptid);
969 struct gdbarch *gdbarch = get_regcache_arch (regcache);
970 td_event_msg_t msg;
971 td_thrinfo_t ti;
972 td_err_e err;
973 CORE_ADDR stop_pc;
974 int loop = 0;
975
976 /* Bail out early if we're not at a thread event breakpoint. */
977 stop_pc = regcache_read_pc (regcache)
978 - gdbarch_decr_pc_after_break (gdbarch);
979 if (stop_pc != td_create_bp_addr && stop_pc != td_death_bp_addr)
980 return;
981
982 /* Access an lwp we know is stopped. */
983 proc_handle.ptid = ptid;
984
985 /* If we have only looked at the first thread before libpthread was
986 initialized, we may not know its thread ID yet. Make sure we do
987 before we add another thread to the list. */
988 if (!have_threads ())
989 thread_db_find_new_threads_1 ();
990
991 /* If we are at a create breakpoint, we do not know what new lwp
992 was created and cannot specifically locate the event message for it.
993 We have to call td_ta_event_getmsg() to get
994 the latest message. Since we have no way of correlating whether
995 the event message we get back corresponds to our breakpoint, we must
996 loop and read all event messages, processing them appropriately.
997 This guarantees we will process the correct message before continuing
998 from the breakpoint.
999
1000 Currently, death events are not enabled. If they are enabled,
1001 the death event can use the td_thr_event_getmsg() interface to
1002 get the message specifically for that lwp and avoid looping
1003 below. */
1004
1005 loop = 1;
1006
1007 do
1008 {
1009 err = td_ta_event_getmsg_p (thread_agent, &msg);
1010 if (err != TD_OK)
1011 {
1012 if (err == TD_NOMSG)
1013 return;
1014
1015 error (_("Cannot get thread event message: %s"),
1016 thread_db_err_str (err));
1017 }
1018
1019 err = td_thr_get_info_p (msg.th_p, &ti);
1020 if (err != TD_OK)
1021 error (_("Cannot get thread info: %s"), thread_db_err_str (err));
1022
1023 ptid = ptid_build (GET_PID (ptid), ti.ti_lid, 0);
1024
1025 switch (msg.event)
1026 {
1027 case TD_CREATE:
1028 /* Call attach_thread whether or not we already know about a
1029 thread with this thread ID. */
1030 attach_thread (ptid, msg.th_p, &ti);
1031
1032 break;
1033
1034 case TD_DEATH:
1035
1036 if (!in_thread_list (ptid))
1037 error (_("Spurious thread death event."));
1038
1039 detach_thread (ptid);
1040
1041 break;
1042
1043 default:
1044 error (_("Spurious thread event."));
1045 }
1046 }
1047 while (loop);
1048 }
1049
1050 static ptid_t
1051 thread_db_wait (struct target_ops *ops,
1052 ptid_t ptid, struct target_waitstatus *ourstatus)
1053 {
1054 struct target_ops *beneath = find_target_beneath (ops);
1055
1056 ptid = beneath->to_wait (beneath, ptid, ourstatus);
1057
1058 if (ourstatus->kind == TARGET_WAITKIND_IGNORE)
1059 return ptid;
1060
1061 if (ourstatus->kind == TARGET_WAITKIND_EXITED
1062 || ourstatus->kind == TARGET_WAITKIND_SIGNALLED)
1063 return ptid;
1064
1065 if (ourstatus->kind == TARGET_WAITKIND_EXECD)
1066 {
1067 remove_thread_event_breakpoints ();
1068 unpush_target (&thread_db_ops);
1069 if (thread_db_handle)
1070 dlclose (thread_db_handle);
1071 thread_db_handle = NULL;
1072
1073 return ptid;
1074 }
1075
1076 /* If we do not know about the main thread yet, this would be a good time to
1077 find it. */
1078 if (ourstatus->kind == TARGET_WAITKIND_STOPPED && !have_threads ())
1079 thread_db_find_new_threads_1 ();
1080
1081 if (ourstatus->kind == TARGET_WAITKIND_STOPPED
1082 && ourstatus->value.sig == TARGET_SIGNAL_TRAP)
1083 /* Check for a thread event. */
1084 check_event (ptid);
1085
1086 if (have_threads ())
1087 {
1088 /* Change ptids back into the higher level PID + TID format. If
1089 the thread is dead and no longer on the thread list, we will
1090 get back a dead ptid. This can occur if the thread death
1091 event gets postponed by other simultaneous events. In such a
1092 case, we want to just ignore the event and continue on. */
1093
1094 ptid = thread_from_lwp (ptid);
1095 if (GET_PID (ptid) == -1)
1096 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1097 }
1098
1099 return ptid;
1100 }
1101
1102 static void
1103 thread_db_mourn_inferior (struct target_ops *ops)
1104 {
1105 struct target_ops *target_beneath = find_target_beneath (ops);
1106
1107 /* Forget about the child's process ID. We shouldn't need it
1108 anymore. */
1109 proc_handle.ptid = null_ptid;
1110
1111 target_beneath->to_mourn_inferior (target_beneath);
1112
1113 /* Delete the old thread event breakpoints. Do this after mourning
1114 the inferior, so that we don't try to uninsert them. */
1115 remove_thread_event_breakpoints ();
1116
1117 /* Detach thread_db target ops. */
1118 unpush_target (ops);
1119 if (thread_db_handle)
1120 dlclose (thread_db_handle);
1121 thread_db_handle = NULL;
1122 }
1123
1124 static int
1125 find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
1126 {
1127 td_thrinfo_t ti;
1128 td_err_e err;
1129 ptid_t ptid;
1130 struct thread_info *tp;
1131
1132 err = td_thr_get_info_p (th_p, &ti);
1133 if (err != TD_OK)
1134 error (_("find_new_threads_callback: cannot get thread info: %s"),
1135 thread_db_err_str (err));
1136
1137 if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
1138 return 0; /* A zombie -- ignore. */
1139
1140 ptid = ptid_build (GET_PID (proc_handle.ptid), ti.ti_lid, 0);
1141
1142 if (ti.ti_tid == 0)
1143 {
1144 /* A thread ID of zero means that this is the main thread, but
1145 glibc has not yet initialized thread-local storage and the
1146 pthread library. We do not know what the thread's TID will
1147 be yet. Just enable event reporting and otherwise ignore
1148 it. */
1149
1150 err = td_thr_event_enable_p (th_p, 1);
1151 if (err != TD_OK)
1152 error (_("Cannot enable thread event reporting for %s: %s"),
1153 target_pid_to_str (ptid), thread_db_err_str (err));
1154
1155 return 0;
1156 }
1157
1158 tp = find_thread_pid (ptid);
1159 if (tp == NULL || tp->private == NULL)
1160 attach_thread (ptid, th_p, &ti);
1161
1162 return 0;
1163 }
1164
1165 /* Search for new threads, accessing memory through stopped thread
1166 PTID. */
1167
1168 static void
1169 thread_db_find_new_threads_1 (void)
1170 {
1171 td_err_e err;
1172 struct lwp_info *lp;
1173 ptid_t ptid;
1174
1175 /* In linux, we can only read memory through a stopped lwp. */
1176 ALL_LWPS (lp, ptid)
1177 if (lp->stopped)
1178 break;
1179
1180 if (!lp)
1181 /* There is no stopped thread. Bail out. */
1182 return;
1183
1184 /* Access an lwp we know is stopped. */
1185 proc_handle.ptid = ptid;
1186 /* Iterate over all user-space threads to discover new threads. */
1187 err = td_ta_thr_iter_p (thread_agent, find_new_threads_callback, NULL,
1188 TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
1189 TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
1190 if (err != TD_OK)
1191 error (_("Cannot find new threads: %s"), thread_db_err_str (err));
1192 }
1193
1194 static void
1195 thread_db_find_new_threads (struct target_ops *ops)
1196 {
1197 thread_db_find_new_threads_1 ();
1198 }
1199
1200 static char *
1201 thread_db_pid_to_str (struct target_ops *ops, ptid_t ptid)
1202 {
1203 struct thread_info *thread_info = find_thread_pid (ptid);
1204 struct target_ops *beneath;
1205
1206 if (thread_info != NULL && thread_info->private != NULL)
1207 {
1208 static char buf[64];
1209 thread_t tid;
1210
1211 tid = thread_info->private->tid;
1212 snprintf (buf, sizeof (buf), "Thread 0x%lx (LWP %ld)",
1213 tid, GET_LWP (ptid));
1214
1215 return buf;
1216 }
1217
1218 beneath = find_target_beneath (ops);
1219 if (beneath->to_pid_to_str (beneath, ptid))
1220 return beneath->to_pid_to_str (beneath, ptid);
1221
1222 return normal_pid_to_str (ptid);
1223 }
1224
1225 /* Return a string describing the state of the thread specified by
1226 INFO. */
1227
1228 static char *
1229 thread_db_extra_thread_info (struct thread_info *info)
1230 {
1231 if (info->private == NULL)
1232 return NULL;
1233
1234 if (info->private->dying)
1235 return "Exiting";
1236
1237 return NULL;
1238 }
1239
1240 /* Get the address of the thread local variable in load module LM which
1241 is stored at OFFSET within the thread local storage for thread PTID. */
1242
1243 static CORE_ADDR
1244 thread_db_get_thread_local_address (struct target_ops *ops,
1245 ptid_t ptid,
1246 CORE_ADDR lm,
1247 CORE_ADDR offset)
1248 {
1249 struct thread_info *thread_info;
1250 struct target_ops *beneath;
1251
1252 /* If we have not discovered any threads yet, check now. */
1253 if (!have_threads ())
1254 thread_db_find_new_threads_1 ();
1255
1256 /* Find the matching thread. */
1257 thread_info = find_thread_pid (ptid);
1258
1259 if (thread_info != NULL && thread_info->private != NULL)
1260 {
1261 td_err_e err;
1262 void *address;
1263
1264 /* glibc doesn't provide the needed interface. */
1265 if (!td_thr_tls_get_addr_p)
1266 throw_error (TLS_NO_LIBRARY_SUPPORT_ERROR,
1267 _("No TLS library support"));
1268
1269 /* Caller should have verified that lm != 0. */
1270 gdb_assert (lm != 0);
1271
1272 /* Finally, get the address of the variable. */
1273 err = td_thr_tls_get_addr_p (&thread_info->private->th,
1274 (void *)(size_t) lm,
1275 offset, &address);
1276
1277 #ifdef THREAD_DB_HAS_TD_NOTALLOC
1278 /* The memory hasn't been allocated, yet. */
1279 if (err == TD_NOTALLOC)
1280 /* Now, if libthread_db provided the initialization image's
1281 address, we *could* try to build a non-lvalue value from
1282 the initialization image. */
1283 throw_error (TLS_NOT_ALLOCATED_YET_ERROR,
1284 _("TLS not allocated yet"));
1285 #endif
1286
1287 /* Something else went wrong. */
1288 if (err != TD_OK)
1289 throw_error (TLS_GENERIC_ERROR,
1290 (("%s")), thread_db_err_str (err));
1291
1292 /* Cast assuming host == target. Joy. */
1293 /* Do proper sign extension for the target. */
1294 gdb_assert (exec_bfd);
1295 return (bfd_get_sign_extend_vma (exec_bfd) > 0
1296 ? (CORE_ADDR) (intptr_t) address
1297 : (CORE_ADDR) (uintptr_t) address);
1298 }
1299
1300 beneath = find_target_beneath (ops);
1301 if (beneath->to_get_thread_local_address)
1302 return beneath->to_get_thread_local_address (beneath, ptid, lm, offset);
1303 else
1304 throw_error (TLS_GENERIC_ERROR,
1305 _("TLS not supported on this target"));
1306 }
1307
1308 /* Callback routine used to find a thread based on the TID part of
1309 its PTID. */
1310
1311 static int
1312 thread_db_find_thread_from_tid (struct thread_info *thread, void *data)
1313 {
1314 long *tid = (long *) data;
1315
1316 if (thread->private->tid == *tid)
1317 return 1;
1318
1319 return 0;
1320 }
1321
1322 /* Implement the to_get_ada_task_ptid target method for this target. */
1323
1324 static ptid_t
1325 thread_db_get_ada_task_ptid (long lwp, long thread)
1326 {
1327 struct thread_info *thread_info;
1328
1329 thread_db_find_new_threads_1 ();
1330 thread_info = iterate_over_threads (thread_db_find_thread_from_tid, &thread);
1331
1332 gdb_assert (thread_info != NULL);
1333
1334 return (thread_info->ptid);
1335 }
1336
1337 static void
1338 init_thread_db_ops (void)
1339 {
1340 thread_db_ops.to_shortname = "multi-thread";
1341 thread_db_ops.to_longname = "multi-threaded child process.";
1342 thread_db_ops.to_doc = "Threads and pthreads support.";
1343 thread_db_ops.to_detach = thread_db_detach;
1344 thread_db_ops.to_wait = thread_db_wait;
1345 thread_db_ops.to_mourn_inferior = thread_db_mourn_inferior;
1346 thread_db_ops.to_find_new_threads = thread_db_find_new_threads;
1347 thread_db_ops.to_pid_to_str = thread_db_pid_to_str;
1348 thread_db_ops.to_stratum = thread_stratum;
1349 thread_db_ops.to_has_thread_control = tc_schedlock;
1350 thread_db_ops.to_get_thread_local_address
1351 = thread_db_get_thread_local_address;
1352 thread_db_ops.to_extra_thread_info = thread_db_extra_thread_info;
1353 thread_db_ops.to_get_ada_task_ptid = thread_db_get_ada_task_ptid;
1354 thread_db_ops.to_magic = OPS_MAGIC;
1355 }
1356
1357 /* Provide a prototype to silence -Wmissing-prototypes. */
1358 extern initialize_file_ftype _initialize_thread_db;
1359
1360 void
1361 _initialize_thread_db (void)
1362 {
1363 init_thread_db_ops ();
1364 add_target (&thread_db_ops);
1365
1366 /* Defer loading of libthread_db.so until inferior is running.
1367 This allows gdb to load correct libthread_db for a given
1368 executable -- there could be mutiple versions of glibc,
1369 compiled with LinuxThreads or NPTL, and until there is
1370 a running inferior, we can't tell which libthread_db is
1371 the correct one to load. */
1372
1373 libthread_db_search_path = xstrdup (LIBTHREAD_DB_SEARCH_PATH);
1374
1375 add_setshow_optional_filename_cmd ("libthread-db-search-path",
1376 class_support,
1377 &libthread_db_search_path, _("\
1378 Set search path for libthread_db."), _("\
1379 Show the current search path or libthread_db."), _("\
1380 This path is used to search for libthread_db to be loaded into \
1381 gdb itself."),
1382 NULL,
1383 NULL,
1384 &setlist, &showlist);
1385 /* Add ourselves to objfile event chain. */
1386 observer_attach_new_objfile (thread_db_new_objfile);
1387 }