Imported Upstream version 7.9
[platform/upstream/gdb.git] / gdb / gdbserver / thread-db.c
1 /* Thread management interface, for the remote server for GDB.
2    Copyright (C) 2002-2015 Free Software Foundation, Inc.
3
4    Contributed by MontaVista Software.
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 "server.h"
22
23 #include "linux-low.h"
24
25 extern int debug_threads;
26
27 static int thread_db_use_events;
28
29 #include "gdb_proc_service.h"
30 #include "nat/gdb_thread_db.h"
31 #include "gdb_vecs.h"
32
33 #ifndef USE_LIBTHREAD_DB_DIRECTLY
34 #include <dlfcn.h>
35 #endif
36
37 #include <stdint.h>
38 #include <limits.h>
39 #include <ctype.h>
40
41 struct thread_db
42 {
43   /* Structure that identifies the child process for the
44      <proc_service.h> interface.  */
45   struct ps_prochandle proc_handle;
46
47   /* Connection to the libthread_db library.  */
48   td_thragent_t *thread_agent;
49
50   /* If this flag has been set, we've already asked GDB for all
51      symbols we might need; assume symbol cache misses are
52      failures.  */
53   int all_symbols_looked_up;
54
55 #ifndef USE_LIBTHREAD_DB_DIRECTLY
56   /* Handle of the libthread_db from dlopen.  */
57   void *handle;
58 #endif
59
60   /* Thread creation event breakpoint.  The code at this location in
61      the child process will be called by the pthread library whenever
62      a new thread is created.  By setting a special breakpoint at this
63      location, GDB can detect when a new thread is created.  We obtain
64      this location via the td_ta_event_addr call.  Note that if the
65      running kernel supports tracing clones, then we don't need to use
66      (and in fact don't use) this magic thread event breakpoint to
67      learn about threads.  */
68   struct breakpoint *td_create_bp;
69
70   /* Addresses of libthread_db functions.  */
71   td_err_e (*td_ta_new_p) (struct ps_prochandle * ps, td_thragent_t **ta);
72   td_err_e (*td_ta_event_getmsg_p) (const td_thragent_t *ta,
73                                     td_event_msg_t *msg);
74   td_err_e (*td_ta_set_event_p) (const td_thragent_t *ta,
75                                  td_thr_events_t *event);
76   td_err_e (*td_ta_event_addr_p) (const td_thragent_t *ta,
77                                   td_event_e event, td_notify_t *ptr);
78   td_err_e (*td_ta_map_lwp2thr_p) (const td_thragent_t *ta, lwpid_t lwpid,
79                                    td_thrhandle_t *th);
80   td_err_e (*td_thr_get_info_p) (const td_thrhandle_t *th,
81                                  td_thrinfo_t *infop);
82   td_err_e (*td_thr_event_enable_p) (const td_thrhandle_t *th, int event);
83   td_err_e (*td_ta_thr_iter_p) (const td_thragent_t *ta,
84                                 td_thr_iter_f *callback, void *cbdata_p,
85                                 td_thr_state_e state, int ti_pri,
86                                 sigset_t *ti_sigmask_p,
87                                 unsigned int ti_user_flags);
88   td_err_e (*td_thr_tls_get_addr_p) (const td_thrhandle_t *th,
89                                      psaddr_t map_address,
90                                      size_t offset, psaddr_t *address);
91   td_err_e (*td_thr_tlsbase_p) (const td_thrhandle_t *th,
92                                 unsigned long int modid,
93                                 psaddr_t *base);
94   const char ** (*td_symbol_list_p) (void);
95 };
96
97 static char *libthread_db_search_path;
98
99 static int find_one_thread (ptid_t);
100 static int find_new_threads_callback (const td_thrhandle_t *th_p, void *data);
101
102 static const char *
103 thread_db_err_str (td_err_e err)
104 {
105   static char buf[64];
106
107   switch (err)
108     {
109     case TD_OK:
110       return "generic 'call succeeded'";
111     case TD_ERR:
112       return "generic error";
113     case TD_NOTHR:
114       return "no thread to satisfy query";
115     case TD_NOSV:
116       return "no sync handle to satisfy query";
117     case TD_NOLWP:
118       return "no LWP to satisfy query";
119     case TD_BADPH:
120       return "invalid process handle";
121     case TD_BADTH:
122       return "invalid thread handle";
123     case TD_BADSH:
124       return "invalid synchronization handle";
125     case TD_BADTA:
126       return "invalid thread agent";
127     case TD_BADKEY:
128       return "invalid key";
129     case TD_NOMSG:
130       return "no event message for getmsg";
131     case TD_NOFPREGS:
132       return "FPU register set not available";
133     case TD_NOLIBTHREAD:
134       return "application not linked with libthread";
135     case TD_NOEVENT:
136       return "requested event is not supported";
137     case TD_NOCAPAB:
138       return "capability not available";
139     case TD_DBERR:
140       return "debugger service failed";
141     case TD_NOAPLIC:
142       return "operation not applicable to";
143     case TD_NOTSD:
144       return "no thread-specific data for this thread";
145     case TD_MALLOC:
146       return "malloc failed";
147     case TD_PARTIALREG:
148       return "only part of register set was written/read";
149     case TD_NOXREGS:
150       return "X register set not available for this thread";
151 #ifdef HAVE_TD_VERSION
152     case TD_VERSION:
153       return "version mismatch between libthread_db and libpthread";
154 #endif
155     default:
156       xsnprintf (buf, sizeof (buf), "unknown thread_db error '%d'", err);
157       return buf;
158     }
159 }
160
161 #if 0
162 static char *
163 thread_db_state_str (td_thr_state_e state)
164 {
165   static char buf[64];
166
167   switch (state)
168     {
169     case TD_THR_STOPPED:
170       return "stopped by debugger";
171     case TD_THR_RUN:
172       return "runnable";
173     case TD_THR_ACTIVE:
174       return "active";
175     case TD_THR_ZOMBIE:
176       return "zombie";
177     case TD_THR_SLEEP:
178       return "sleeping";
179     case TD_THR_STOPPED_ASLEEP:
180       return "stopped by debugger AND blocked";
181     default:
182       xsnprintf (buf, sizeof (buf), "unknown thread_db state %d", state);
183       return buf;
184     }
185 }
186 #endif
187
188 static int
189 thread_db_create_event (CORE_ADDR where)
190 {
191   td_event_msg_t msg;
192   td_err_e err;
193   struct lwp_info *lwp;
194   struct thread_db *thread_db = current_process ()->private->thread_db;
195
196   gdb_assert (thread_db->td_ta_event_getmsg_p != NULL);
197
198   if (debug_threads)
199     debug_printf ("Thread creation event.\n");
200
201   /* FIXME: This assumes we don't get another event.
202      In the LinuxThreads implementation, this is safe,
203      because all events come from the manager thread
204      (except for its own creation, of course).  */
205   err = thread_db->td_ta_event_getmsg_p (thread_db->thread_agent, &msg);
206   if (err != TD_OK)
207     fprintf (stderr, "thread getmsg err: %s\n",
208              thread_db_err_str (err));
209
210   /* If we do not know about the main thread yet, this would be a good time to
211      find it.  We need to do this to pick up the main thread before any newly
212      created threads.  */
213   lwp = get_thread_lwp (current_thread);
214   if (lwp->thread_known == 0)
215     find_one_thread (current_thread->entry.id);
216
217   /* msg.event == TD_EVENT_CREATE */
218
219   find_new_threads_callback (msg.th_p, NULL);
220
221   return 0;
222 }
223
224 static int
225 thread_db_enable_reporting (void)
226 {
227   td_thr_events_t events;
228   td_notify_t notify;
229   td_err_e err;
230   struct thread_db *thread_db = current_process ()->private->thread_db;
231
232   if (thread_db->td_ta_set_event_p == NULL
233       || thread_db->td_ta_event_addr_p == NULL
234       || thread_db->td_ta_event_getmsg_p == NULL)
235     /* This libthread_db is missing required support.  */
236     return 0;
237
238   /* Set the process wide mask saying which events we're interested in.  */
239   td_event_emptyset (&events);
240   td_event_addset (&events, TD_CREATE);
241
242   err = thread_db->td_ta_set_event_p (thread_db->thread_agent, &events);
243   if (err != TD_OK)
244     {
245       warning ("Unable to set global thread event mask: %s",
246                thread_db_err_str (err));
247       return 0;
248     }
249
250   /* Get address for thread creation breakpoint.  */
251   err = thread_db->td_ta_event_addr_p (thread_db->thread_agent, TD_CREATE,
252                                        &notify);
253   if (err != TD_OK)
254     {
255       warning ("Unable to get location for thread creation breakpoint: %s",
256                thread_db_err_str (err));
257       return 0;
258     }
259   thread_db->td_create_bp
260     = set_breakpoint_at ((CORE_ADDR) (unsigned long) notify.u.bptaddr,
261                          thread_db_create_event);
262
263   return 1;
264 }
265
266 static int
267 find_one_thread (ptid_t ptid)
268 {
269   td_thrhandle_t th;
270   td_thrinfo_t ti;
271   td_err_e err;
272   struct thread_info *inferior;
273   struct lwp_info *lwp;
274   struct thread_db *thread_db = current_process ()->private->thread_db;
275   int lwpid = ptid_get_lwp (ptid);
276
277   inferior = (struct thread_info *) find_inferior_id (&all_threads, ptid);
278   lwp = get_thread_lwp (inferior);
279   if (lwp->thread_known)
280     return 1;
281
282   /* Get information about this thread.  */
283   err = thread_db->td_ta_map_lwp2thr_p (thread_db->thread_agent, lwpid, &th);
284   if (err != TD_OK)
285     error ("Cannot get thread handle for LWP %d: %s",
286            lwpid, thread_db_err_str (err));
287
288   err = thread_db->td_thr_get_info_p (&th, &ti);
289   if (err != TD_OK)
290     error ("Cannot get thread info for LWP %d: %s",
291            lwpid, thread_db_err_str (err));
292
293   if (debug_threads)
294     debug_printf ("Found thread %ld (LWP %d)\n",
295                   ti.ti_tid, ti.ti_lid);
296
297   if (lwpid != ti.ti_lid)
298     {
299       warning ("PID mismatch!  Expected %ld, got %ld",
300                (long) lwpid, (long) ti.ti_lid);
301       return 0;
302     }
303
304   if (thread_db_use_events)
305     {
306       err = thread_db->td_thr_event_enable_p (&th, 1);
307       if (err != TD_OK)
308         error ("Cannot enable thread event reporting for %d: %s",
309                ti.ti_lid, thread_db_err_str (err));
310     }
311
312   /* If the new thread ID is zero, a final thread ID will be available
313      later.  Do not enable thread debugging yet.  */
314   if (ti.ti_tid == 0)
315     return 0;
316
317   lwp->thread_known = 1;
318   lwp->th = th;
319
320   return 1;
321 }
322
323 /* Attach a thread.  Return true on success.  */
324
325 static int
326 attach_thread (const td_thrhandle_t *th_p, td_thrinfo_t *ti_p)
327 {
328   struct process_info *proc = current_process ();
329   int pid = pid_of (proc);
330   ptid_t ptid = ptid_build (pid, ti_p->ti_lid, 0);
331   struct lwp_info *lwp;
332   int err;
333
334   if (debug_threads)
335     debug_printf ("Attaching to thread %ld (LWP %d)\n",
336                   ti_p->ti_tid, ti_p->ti_lid);
337   err = linux_attach_lwp (ptid);
338   if (err != 0)
339     {
340       warning ("Could not attach to thread %ld (LWP %d): %s\n",
341                ti_p->ti_tid, ti_p->ti_lid,
342                linux_ptrace_attach_fail_reason_string (ptid, err));
343       return 0;
344     }
345
346   lwp = find_lwp_pid (ptid);
347   gdb_assert (lwp != NULL);
348   lwp->thread_known = 1;
349   lwp->th = *th_p;
350
351   if (thread_db_use_events)
352     {
353       td_err_e err;
354       struct thread_db *thread_db = proc->private->thread_db;
355
356       err = thread_db->td_thr_event_enable_p (th_p, 1);
357       if (err != TD_OK)
358         error ("Cannot enable thread event reporting for %d: %s",
359                ti_p->ti_lid, thread_db_err_str (err));
360     }
361
362   return 1;
363 }
364
365 /* Attach thread if we haven't seen it yet.
366    Increment *COUNTER if we have attached a new thread.
367    Return false on failure.  */
368
369 static int
370 maybe_attach_thread (const td_thrhandle_t *th_p, td_thrinfo_t *ti_p,
371                      int *counter)
372 {
373   struct lwp_info *lwp;
374
375   lwp = find_lwp_pid (pid_to_ptid (ti_p->ti_lid));
376   if (lwp != NULL)
377     return 1;
378
379   if (!attach_thread (th_p, ti_p))
380     return 0;
381
382   if (counter != NULL)
383     *counter += 1;
384
385   return 1;
386 }
387
388 static int
389 find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
390 {
391   td_thrinfo_t ti;
392   td_err_e err;
393   struct thread_db *thread_db = current_process ()->private->thread_db;
394
395   err = thread_db->td_thr_get_info_p (th_p, &ti);
396   if (err != TD_OK)
397     error ("Cannot get thread info: %s", thread_db_err_str (err));
398
399   if (ti.ti_lid == -1)
400     {
401       /* A thread with kernel thread ID -1 is either a thread that
402          exited and was joined, or a thread that is being created but
403          hasn't started yet, and that is reusing the tcb/stack of a
404          thread that previously exited and was joined.  (glibc marks
405          terminated and joined threads with kernel thread ID -1.  See
406          glibc PR17707.  */
407       return 0;
408     }
409
410   /* Check for zombies.  */
411   if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
412     return 0;
413
414   if (!maybe_attach_thread (th_p, &ti, (int *) data))
415     {
416       /* Terminate iteration early: we might be looking at stale data in
417          the inferior.  The thread_db_find_new_threads will retry.  */
418       return 1;
419     }
420
421   return 0;
422 }
423
424 static void
425 thread_db_find_new_threads (void)
426 {
427   td_err_e err;
428   ptid_t ptid = current_ptid;
429   struct thread_db *thread_db = current_process ()->private->thread_db;
430   int loop, iteration;
431
432   /* This function is only called when we first initialize thread_db.
433      First locate the initial thread.  If it is not ready for
434      debugging yet, then stop.  */
435   if (find_one_thread (ptid) == 0)
436     return;
437
438   /* Require 4 successive iterations which do not find any new threads.
439      The 4 is a heuristic: there is an inherent race here, and I have
440      seen that 2 iterations in a row are not always sufficient to
441      "capture" all threads.  */
442   for (loop = 0, iteration = 0; loop < 4; ++loop, ++iteration)
443     {
444       int new_thread_count = 0;
445
446       /* Iterate over all user-space threads to discover new threads.  */
447       err = thread_db->td_ta_thr_iter_p (thread_db->thread_agent,
448                                          find_new_threads_callback,
449                                          &new_thread_count,
450                                          TD_THR_ANY_STATE,
451                                          TD_THR_LOWEST_PRIORITY,
452                                          TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
453       if (debug_threads)
454         debug_printf ("Found %d threads in iteration %d.\n",
455                       new_thread_count, iteration);
456
457       if (new_thread_count != 0)
458         {
459           /* Found new threads.  Restart iteration from beginning.  */
460           loop = -1;
461         }
462     }
463   if (err != TD_OK)
464     error ("Cannot find new threads: %s", thread_db_err_str (err));
465 }
466
467 /* Cache all future symbols that thread_db might request.  We can not
468    request symbols at arbitrary states in the remote protocol, only
469    when the client tells us that new symbols are available.  So when
470    we load the thread library, make sure to check the entire list.  */
471
472 static void
473 thread_db_look_up_symbols (void)
474 {
475   struct thread_db *thread_db = current_process ()->private->thread_db;
476   const char **sym_list;
477   CORE_ADDR unused;
478
479   for (sym_list = thread_db->td_symbol_list_p (); *sym_list; sym_list++)
480     look_up_one_symbol (*sym_list, &unused, 1);
481
482   /* We're not interested in any other libraries loaded after this
483      point, only in symbols in libpthread.so.  */
484   thread_db->all_symbols_looked_up = 1;
485 }
486
487 int
488 thread_db_look_up_one_symbol (const char *name, CORE_ADDR *addrp)
489 {
490   struct thread_db *thread_db = current_process ()->private->thread_db;
491   int may_ask_gdb = !thread_db->all_symbols_looked_up;
492
493   /* If we've passed the call to thread_db_look_up_symbols, then
494      anything not in the cache must not exist; we're not interested
495      in any libraries loaded after that point, only in symbols in
496      libpthread.so.  It might not be an appropriate time to look
497      up a symbol, e.g. while we're trying to fetch registers.  */
498   return look_up_one_symbol (name, addrp, may_ask_gdb);
499 }
500
501 int
502 thread_db_get_tls_address (struct thread_info *thread, CORE_ADDR offset,
503                            CORE_ADDR load_module, CORE_ADDR *address)
504 {
505   psaddr_t addr;
506   td_err_e err;
507   struct lwp_info *lwp;
508   struct thread_info *saved_thread;
509   struct process_info *proc;
510   struct thread_db *thread_db;
511
512   proc = get_thread_process (thread);
513   thread_db = proc->private->thread_db;
514
515   /* If the thread layer is not (yet) initialized, fail.  */
516   if (thread_db == NULL || !thread_db->all_symbols_looked_up)
517     return TD_ERR;
518
519   /* If td_thr_tls_get_addr is missing rather do not expect td_thr_tlsbase
520      could work.  */
521   if (thread_db->td_thr_tls_get_addr_p == NULL
522       || (load_module == 0 && thread_db->td_thr_tlsbase_p == NULL))
523     return -1;
524
525   lwp = get_thread_lwp (thread);
526   if (!lwp->thread_known)
527     find_one_thread (thread->entry.id);
528   if (!lwp->thread_known)
529     return TD_NOTHR;
530
531   saved_thread = current_thread;
532   current_thread = thread;
533
534   if (load_module != 0)
535     {
536       /* Note the cast through uintptr_t: this interface only works if
537          a target address fits in a psaddr_t, which is a host pointer.
538          So a 32-bit debugger can not access 64-bit TLS through this.  */
539       err = thread_db->td_thr_tls_get_addr_p (&lwp->th,
540                                              (psaddr_t) (uintptr_t) load_module,
541                                               offset, &addr);
542     }
543   else
544     {
545       /* This code path handles the case of -static -pthread executables:
546          https://sourceware.org/ml/libc-help/2014-03/msg00024.html
547          For older GNU libc r_debug.r_map is NULL.  For GNU libc after
548          PR libc/16831 due to GDB PR threads/16954 LOAD_MODULE is also NULL.
549          The constant number 1 depends on GNU __libc_setup_tls
550          initialization of l_tls_modid to 1.  */
551       err = thread_db->td_thr_tlsbase_p (&lwp->th, 1, &addr);
552       addr = (char *) addr + offset;
553     }
554
555   current_thread = saved_thread;
556   if (err == TD_OK)
557     {
558       *address = (CORE_ADDR) (uintptr_t) addr;
559       return 0;
560     }
561   else
562     return err;
563 }
564
565 #ifdef USE_LIBTHREAD_DB_DIRECTLY
566
567 static int
568 thread_db_load_search (void)
569 {
570   td_err_e err;
571   struct thread_db *tdb;
572   struct process_info *proc = current_process ();
573
574   gdb_assert (proc->private->thread_db == NULL);
575
576   tdb = xcalloc (1, sizeof (*tdb));
577   proc->private->thread_db = tdb;
578
579   tdb->td_ta_new_p = &td_ta_new;
580
581   /* Attempt to open a connection to the thread library.  */
582   err = tdb->td_ta_new_p (&tdb->proc_handle, &tdb->thread_agent);
583   if (err != TD_OK)
584     {
585       if (debug_threads)
586         debug_printf ("td_ta_new(): %s\n", thread_db_err_str (err));
587       free (tdb);
588       proc->private->thread_db = NULL;
589       return 0;
590     }
591
592   tdb->td_ta_map_lwp2thr_p = &td_ta_map_lwp2thr;
593   tdb->td_thr_get_info_p = &td_thr_get_info;
594   tdb->td_ta_thr_iter_p = &td_ta_thr_iter;
595   tdb->td_symbol_list_p = &td_symbol_list;
596
597   /* This is required only when thread_db_use_events is on.  */
598   tdb->td_thr_event_enable_p = &td_thr_event_enable;
599
600   /* These are not essential.  */
601   tdb->td_ta_event_addr_p = &td_ta_event_addr;
602   tdb->td_ta_set_event_p = &td_ta_set_event;
603   tdb->td_ta_event_getmsg_p = &td_ta_event_getmsg;
604   tdb->td_thr_tls_get_addr_p = &td_thr_tls_get_addr;
605   tdb->td_thr_tlsbase_p = &td_thr_tlsbase;
606
607   return 1;
608 }
609
610 #else
611
612 static int
613 try_thread_db_load_1 (void *handle)
614 {
615   td_err_e err;
616   struct thread_db *tdb;
617   struct process_info *proc = current_process ();
618
619   gdb_assert (proc->private->thread_db == NULL);
620
621   tdb = xcalloc (1, sizeof (*tdb));
622   proc->private->thread_db = tdb;
623
624   tdb->handle = handle;
625
626   /* Initialize pointers to the dynamic library functions we will use.
627      Essential functions first.  */
628
629 #define CHK(required, a)                                        \
630   do                                                            \
631     {                                                           \
632       if ((a) == NULL)                                          \
633         {                                                       \
634           if (debug_threads)                                    \
635             debug_printf ("dlsym: %s\n", dlerror ());           \
636           if (required)                                         \
637             {                                                   \
638               free (tdb);                                       \
639               proc->private->thread_db = NULL;                  \
640               return 0;                                         \
641             }                                                   \
642         }                                                       \
643     }                                                           \
644   while (0)
645
646   CHK (1, tdb->td_ta_new_p = dlsym (handle, "td_ta_new"));
647
648   /* Attempt to open a connection to the thread library.  */
649   err = tdb->td_ta_new_p (&tdb->proc_handle, &tdb->thread_agent);
650   if (err != TD_OK)
651     {
652       if (debug_threads)
653         debug_printf ("td_ta_new(): %s\n", thread_db_err_str (err));
654       free (tdb);
655       proc->private->thread_db = NULL;
656       return 0;
657     }
658
659   CHK (1, tdb->td_ta_map_lwp2thr_p = dlsym (handle, "td_ta_map_lwp2thr"));
660   CHK (1, tdb->td_thr_get_info_p = dlsym (handle, "td_thr_get_info"));
661   CHK (1, tdb->td_ta_thr_iter_p = dlsym (handle, "td_ta_thr_iter"));
662   CHK (1, tdb->td_symbol_list_p = dlsym (handle, "td_symbol_list"));
663
664   /* This is required only when thread_db_use_events is on.  */
665   CHK (thread_db_use_events,
666        tdb->td_thr_event_enable_p = dlsym (handle, "td_thr_event_enable"));
667
668   /* These are not essential.  */
669   CHK (0, tdb->td_ta_event_addr_p = dlsym (handle, "td_ta_event_addr"));
670   CHK (0, tdb->td_ta_set_event_p = dlsym (handle, "td_ta_set_event"));
671   CHK (0, tdb->td_ta_event_getmsg_p = dlsym (handle, "td_ta_event_getmsg"));
672   CHK (0, tdb->td_thr_tls_get_addr_p = dlsym (handle, "td_thr_tls_get_addr"));
673   CHK (0, tdb->td_thr_tlsbase_p = dlsym (handle, "td_thr_tlsbase"));
674
675 #undef CHK
676
677   return 1;
678 }
679
680 #ifdef HAVE_DLADDR
681
682 /* Lookup a library in which given symbol resides.
683    Note: this is looking in the GDBSERVER process, not in the inferior.
684    Returns library name, or NULL.  */
685
686 static const char *
687 dladdr_to_soname (const void *addr)
688 {
689   Dl_info info;
690
691   if (dladdr (addr, &info) != 0)
692     return info.dli_fname;
693   return NULL;
694 }
695
696 #endif
697
698 static int
699 try_thread_db_load (const char *library)
700 {
701   void *handle;
702
703   if (debug_threads)
704     debug_printf ("Trying host libthread_db library: %s.\n",
705                   library);
706   handle = dlopen (library, RTLD_NOW);
707   if (handle == NULL)
708     {
709       if (debug_threads)
710         debug_printf ("dlopen failed: %s.\n", dlerror ());
711       return 0;
712     }
713
714 #ifdef HAVE_DLADDR
715   if (debug_threads && strchr (library, '/') == NULL)
716     {
717       void *td_init;
718
719       td_init = dlsym (handle, "td_init");
720       if (td_init != NULL)
721         {
722           const char *const libpath = dladdr_to_soname (td_init);
723
724           if (libpath != NULL)
725             fprintf (stderr, "Host %s resolved to: %s.\n",
726                      library, libpath);
727         }
728     }
729 #endif
730
731   if (try_thread_db_load_1 (handle))
732     return 1;
733
734   /* This library "refused" to work on current inferior.  */
735   dlclose (handle);
736   return 0;
737 }
738
739 /* Handle $sdir in libthread-db-search-path.
740    Look for libthread_db in the system dirs, or wherever a plain
741    dlopen(file_without_path) will look.
742    The result is true for success.  */
743
744 static int
745 try_thread_db_load_from_sdir (void)
746 {
747   return try_thread_db_load (LIBTHREAD_DB_SO);
748 }
749
750 /* Try to load libthread_db from directory DIR of length DIR_LEN.
751    The result is true for success.  */
752
753 static int
754 try_thread_db_load_from_dir (const char *dir, size_t dir_len)
755 {
756   char path[PATH_MAX];
757
758   if (dir_len + 1 + strlen (LIBTHREAD_DB_SO) + 1 > sizeof (path))
759     {
760       char *cp = xmalloc (dir_len + 1);
761
762       memcpy (cp, dir, dir_len);
763       cp[dir_len] = '\0';
764       warning (_("libthread-db-search-path component too long,"
765                  " ignored: %s."), cp);
766       free (cp);
767       return 0;
768     }
769
770   memcpy (path, dir, dir_len);
771   path[dir_len] = '/';
772   strcpy (path + dir_len + 1, LIBTHREAD_DB_SO);
773   return try_thread_db_load (path);
774 }
775
776 /* Search libthread_db_search_path for libthread_db which "agrees"
777    to work on current inferior.
778    The result is true for success.  */
779
780 static int
781 thread_db_load_search (void)
782 {
783   VEC (char_ptr) *dir_vec;
784   char *this_dir;
785   int i, rc = 0;
786
787   if (libthread_db_search_path == NULL)
788     libthread_db_search_path = xstrdup (LIBTHREAD_DB_SEARCH_PATH);
789
790   dir_vec = dirnames_to_char_ptr_vec (libthread_db_search_path);
791
792   for (i = 0; VEC_iterate (char_ptr, dir_vec, i, this_dir); ++i)
793     {
794       const int pdir_len = sizeof ("$pdir") - 1;
795       size_t this_dir_len;
796
797       this_dir_len = strlen (this_dir);
798
799       if (strncmp (this_dir, "$pdir", pdir_len) == 0
800           && (this_dir[pdir_len] == '\0'
801               || this_dir[pdir_len] == '/'))
802         {
803           /* We don't maintain a list of loaded libraries so we don't know
804              where libpthread lives.  We *could* fetch the info, but we don't
805              do that yet.  Ignore it.  */
806         }
807       else if (strcmp (this_dir, "$sdir") == 0)
808         {
809           if (try_thread_db_load_from_sdir ())
810             {
811               rc = 1;
812               break;
813             }
814         }
815       else
816         {
817           if (try_thread_db_load_from_dir (this_dir, this_dir_len))
818             {
819               rc = 1;
820               break;
821             }
822         }
823     }
824
825   free_char_ptr_vec (dir_vec);
826   if (debug_threads)
827     debug_printf ("thread_db_load_search returning %d\n", rc);
828   return rc;
829 }
830
831 #endif  /* USE_LIBTHREAD_DB_DIRECTLY */
832
833 int
834 thread_db_init (int use_events)
835 {
836   struct process_info *proc = current_process ();
837
838   /* FIXME drow/2004-10-16: This is the "overall process ID", which
839      GNU/Linux calls tgid, "thread group ID".  When we support
840      attaching to threads, the original thread may not be the correct
841      thread.  We would have to get the process ID from /proc for NPTL.
842      For LinuxThreads we could do something similar: follow the chain
843      of parent processes until we find the highest one we're attached
844      to, and use its tgid.
845
846      This isn't the only place in gdbserver that assumes that the first
847      process in the list is the thread group leader.  */
848
849   thread_db_use_events = use_events;
850
851   if (thread_db_load_search ())
852     {
853       if (use_events && thread_db_enable_reporting () == 0)
854         {
855           /* Keep trying; maybe event reporting will work later.  */
856           thread_db_mourn (proc);
857           return 0;
858         }
859       thread_db_find_new_threads ();
860       thread_db_look_up_symbols ();
861       return 1;
862     }
863
864   return 0;
865 }
866
867 static int
868 any_thread_of (struct inferior_list_entry *entry, void *args)
869 {
870   int *pid_p = args;
871
872   if (ptid_get_pid (entry->id) == *pid_p)
873     return 1;
874
875   return 0;
876 }
877
878 static void
879 switch_to_process (struct process_info *proc)
880 {
881   int pid = pid_of (proc);
882
883   current_thread =
884     (struct thread_info *) find_inferior (&all_threads,
885                                           any_thread_of, &pid);
886 }
887
888 /* Disconnect from libthread_db and free resources.  */
889
890 static void
891 disable_thread_event_reporting (struct process_info *proc)
892 {
893   struct thread_db *thread_db = proc->private->thread_db;
894   if (thread_db)
895     {
896       td_err_e (*td_ta_clear_event_p) (const td_thragent_t *ta,
897                                        td_thr_events_t *event);
898
899 #ifndef USE_LIBTHREAD_DB_DIRECTLY
900       td_ta_clear_event_p = dlsym (thread_db->handle, "td_ta_clear_event");
901 #else
902       td_ta_clear_event_p = &td_ta_clear_event;
903 #endif
904
905       if (td_ta_clear_event_p != NULL)
906         {
907           struct thread_info *saved_thread = current_thread;
908           td_thr_events_t events;
909
910           switch_to_process (proc);
911
912           /* Set the process wide mask saying we aren't interested
913              in any events anymore.  */
914           td_event_fillset (&events);
915           (*td_ta_clear_event_p) (thread_db->thread_agent, &events);
916
917           current_thread = saved_thread;
918         }
919     }
920 }
921
922 static void
923 remove_thread_event_breakpoints (struct process_info *proc)
924 {
925   struct thread_db *thread_db = proc->private->thread_db;
926
927   if (thread_db->td_create_bp != NULL)
928     {
929       struct thread_info *saved_thread = current_thread;
930
931       switch_to_process (proc);
932
933       delete_breakpoint (thread_db->td_create_bp);
934       thread_db->td_create_bp = NULL;
935
936       current_thread = saved_thread;
937     }
938 }
939
940 void
941 thread_db_detach (struct process_info *proc)
942 {
943   struct thread_db *thread_db = proc->private->thread_db;
944
945   if (thread_db)
946     {
947       disable_thread_event_reporting (proc);
948       remove_thread_event_breakpoints (proc);
949     }
950 }
951
952 /* Disconnect from libthread_db and free resources.  */
953
954 void
955 thread_db_mourn (struct process_info *proc)
956 {
957   struct thread_db *thread_db = proc->private->thread_db;
958   if (thread_db)
959     {
960       td_err_e (*td_ta_delete_p) (td_thragent_t *);
961
962 #ifndef USE_LIBTHREAD_DB_DIRECTLY
963       td_ta_delete_p = dlsym (thread_db->handle, "td_ta_delete");
964 #else
965       td_ta_delete_p = &td_ta_delete;
966 #endif
967
968       if (td_ta_delete_p != NULL)
969         (*td_ta_delete_p) (thread_db->thread_agent);
970
971 #ifndef USE_LIBTHREAD_DB_DIRECTLY
972       dlclose (thread_db->handle);
973 #endif  /* USE_LIBTHREAD_DB_DIRECTLY  */
974
975       free (thread_db);
976       proc->private->thread_db = NULL;
977     }
978 }
979
980 /* Handle "set libthread-db-search-path" monitor command and return 1.
981    For any other command, return 0.  */
982
983 int
984 thread_db_handle_monitor_command (char *mon)
985 {
986   const char *cmd = "set libthread-db-search-path";
987   size_t cmd_len = strlen (cmd);
988
989   if (strncmp (mon, cmd, cmd_len) == 0
990       && (mon[cmd_len] == '\0'
991           || mon[cmd_len] == ' '))
992     {
993       const char *cp = mon + cmd_len;
994
995       if (libthread_db_search_path != NULL)
996         free (libthread_db_search_path);
997
998       /* Skip leading space (if any).  */
999       while (isspace (*cp))
1000         ++cp;
1001
1002       if (*cp == '\0')
1003         cp = LIBTHREAD_DB_SEARCH_PATH;
1004       libthread_db_search_path = xstrdup (cp);
1005
1006       monitor_output ("libthread-db-search-path set to `");
1007       monitor_output (libthread_db_search_path);
1008       monitor_output ("'\n");
1009       return 1;
1010     }
1011
1012   /* Tell server.c to perform default processing.  */
1013   return 0;
1014 }