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