PR server/16255: gdbserver cannot attach to a second inferior that is multi-threaded.
[external/binutils.git] / gdb / gdbserver / thread-db.c
1 /* Thread management interface, for the remote server for GDB.
2    Copyright (C) 2002-2014 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 #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   const char ** (*td_symbol_list_p) (void);
92 };
93
94 static char *libthread_db_search_path;
95
96 static int find_one_thread (ptid_t);
97 static int find_new_threads_callback (const td_thrhandle_t *th_p, void *data);
98
99 static const char *
100 thread_db_err_str (td_err_e err)
101 {
102   static char buf[64];
103
104   switch (err)
105     {
106     case TD_OK:
107       return "generic 'call succeeded'";
108     case TD_ERR:
109       return "generic error";
110     case TD_NOTHR:
111       return "no thread to satisfy query";
112     case TD_NOSV:
113       return "no sync handle to satisfy query";
114     case TD_NOLWP:
115       return "no LWP to satisfy query";
116     case TD_BADPH:
117       return "invalid process handle";
118     case TD_BADTH:
119       return "invalid thread handle";
120     case TD_BADSH:
121       return "invalid synchronization handle";
122     case TD_BADTA:
123       return "invalid thread agent";
124     case TD_BADKEY:
125       return "invalid key";
126     case TD_NOMSG:
127       return "no event message for getmsg";
128     case TD_NOFPREGS:
129       return "FPU register set not available";
130     case TD_NOLIBTHREAD:
131       return "application not linked with libthread";
132     case TD_NOEVENT:
133       return "requested event is not supported";
134     case TD_NOCAPAB:
135       return "capability not available";
136     case TD_DBERR:
137       return "debugger service failed";
138     case TD_NOAPLIC:
139       return "operation not applicable to";
140     case TD_NOTSD:
141       return "no thread-specific data for this thread";
142     case TD_MALLOC:
143       return "malloc failed";
144     case TD_PARTIALREG:
145       return "only part of register set was written/read";
146     case TD_NOXREGS:
147       return "X register set not available for this thread";
148 #ifdef HAVE_TD_VERSION
149     case TD_VERSION:
150       return "version mismatch between libthread_db and libpthread";
151 #endif
152     default:
153       xsnprintf (buf, sizeof (buf), "unknown thread_db error '%d'", err);
154       return buf;
155     }
156 }
157
158 #if 0
159 static char *
160 thread_db_state_str (td_thr_state_e state)
161 {
162   static char buf[64];
163
164   switch (state)
165     {
166     case TD_THR_STOPPED:
167       return "stopped by debugger";
168     case TD_THR_RUN:
169       return "runnable";
170     case TD_THR_ACTIVE:
171       return "active";
172     case TD_THR_ZOMBIE:
173       return "zombie";
174     case TD_THR_SLEEP:
175       return "sleeping";
176     case TD_THR_STOPPED_ASLEEP:
177       return "stopped by debugger AND blocked";
178     default:
179       xsnprintf (buf, sizeof (buf), "unknown thread_db state %d", state);
180       return buf;
181     }
182 }
183 #endif
184
185 static int
186 thread_db_create_event (CORE_ADDR where)
187 {
188   td_event_msg_t msg;
189   td_err_e err;
190   struct lwp_info *lwp;
191   struct thread_db *thread_db = current_process ()->private->thread_db;
192
193   if (thread_db->td_ta_event_getmsg_p == NULL)
194     fatal ("unexpected thread_db->td_ta_event_getmsg_p == NULL");
195
196   if (debug_threads)
197     debug_printf ("Thread creation event.\n");
198
199   /* FIXME: This assumes we don't get another event.
200      In the LinuxThreads implementation, this is safe,
201      because all events come from the manager thread
202      (except for its own creation, of course).  */
203   err = thread_db->td_ta_event_getmsg_p (thread_db->thread_agent, &msg);
204   if (err != TD_OK)
205     fprintf (stderr, "thread getmsg err: %s\n",
206              thread_db_err_str (err));
207
208   /* If we do not know about the main thread yet, this would be a good time to
209      find it.  We need to do this to pick up the main thread before any newly
210      created threads.  */
211   lwp = get_thread_lwp (current_inferior);
212   if (lwp->thread_known == 0)
213     find_one_thread (current_inferior->entry.id);
214
215   /* msg.event == TD_EVENT_CREATE */
216
217   find_new_threads_callback (msg.th_p, NULL);
218
219   return 0;
220 }
221
222 static int
223 thread_db_enable_reporting (void)
224 {
225   td_thr_events_t events;
226   td_notify_t notify;
227   td_err_e err;
228   struct thread_db *thread_db = current_process ()->private->thread_db;
229
230   if (thread_db->td_ta_set_event_p == NULL
231       || thread_db->td_ta_event_addr_p == NULL
232       || thread_db->td_ta_event_getmsg_p == NULL)
233     /* This libthread_db is missing required support.  */
234     return 0;
235
236   /* Set the process wide mask saying which events we're interested in.  */
237   td_event_emptyset (&events);
238   td_event_addset (&events, TD_CREATE);
239
240   err = thread_db->td_ta_set_event_p (thread_db->thread_agent, &events);
241   if (err != TD_OK)
242     {
243       warning ("Unable to set global thread event mask: %s",
244                thread_db_err_str (err));
245       return 0;
246     }
247
248   /* Get address for thread creation breakpoint.  */
249   err = thread_db->td_ta_event_addr_p (thread_db->thread_agent, TD_CREATE,
250                                        &notify);
251   if (err != TD_OK)
252     {
253       warning ("Unable to get location for thread creation breakpoint: %s",
254                thread_db_err_str (err));
255       return 0;
256     }
257   thread_db->td_create_bp
258     = set_breakpoint_at ((CORE_ADDR) (unsigned long) notify.u.bptaddr,
259                          thread_db_create_event);
260
261   return 1;
262 }
263
264 static int
265 find_one_thread (ptid_t ptid)
266 {
267   td_thrhandle_t th;
268   td_thrinfo_t ti;
269   td_err_e err;
270   struct thread_info *inferior;
271   struct lwp_info *lwp;
272   struct thread_db *thread_db = current_process ()->private->thread_db;
273   int lwpid = ptid_get_lwp (ptid);
274
275   inferior = (struct thread_info *) find_inferior_id (&all_threads, ptid);
276   lwp = get_thread_lwp (inferior);
277   if (lwp->thread_known)
278     return 1;
279
280   /* Get information about this thread.  */
281   err = thread_db->td_ta_map_lwp2thr_p (thread_db->thread_agent, lwpid, &th);
282   if (err != TD_OK)
283     error ("Cannot get thread handle for LWP %d: %s",
284            lwpid, thread_db_err_str (err));
285
286   err = thread_db->td_thr_get_info_p (&th, &ti);
287   if (err != TD_OK)
288     error ("Cannot get thread info for LWP %d: %s",
289            lwpid, thread_db_err_str (err));
290
291   if (debug_threads)
292     debug_printf ("Found thread %ld (LWP %d)\n",
293                   ti.ti_tid, ti.ti_lid);
294
295   if (lwpid != ti.ti_lid)
296     {
297       warning ("PID mismatch!  Expected %ld, got %ld",
298                (long) lwpid, (long) ti.ti_lid);
299       return 0;
300     }
301
302   if (thread_db_use_events)
303     {
304       err = thread_db->td_thr_event_enable_p (&th, 1);
305       if (err != TD_OK)
306         error ("Cannot enable thread event reporting for %d: %s",
307                ti.ti_lid, thread_db_err_str (err));
308     }
309
310   /* If the new thread ID is zero, a final thread ID will be available
311      later.  Do not enable thread debugging yet.  */
312   if (ti.ti_tid == 0)
313     return 0;
314
315   lwp->thread_known = 1;
316   lwp->th = th;
317
318   return 1;
319 }
320
321 /* Attach a thread.  Return true on success.  */
322
323 static int
324 attach_thread (const td_thrhandle_t *th_p, td_thrinfo_t *ti_p)
325 {
326   struct process_info *proc = current_process ();
327   int pid = pid_of (proc);
328   ptid_t ptid = ptid_build (pid, ti_p->ti_lid, 0);
329   struct lwp_info *lwp;
330   int err;
331
332   if (debug_threads)
333     debug_printf ("Attaching to thread %ld (LWP %d)\n",
334                   ti_p->ti_tid, ti_p->ti_lid);
335   err = linux_attach_lwp (ptid);
336   if (err != 0)
337     {
338       warning ("Could not attach to thread %ld (LWP %d): %s\n",
339                ti_p->ti_tid, ti_p->ti_lid,
340                linux_attach_fail_reason_string (ptid, err));
341       return 0;
342     }
343
344   lwp = find_lwp_pid (ptid);
345   gdb_assert (lwp != NULL);
346   lwp->thread_known = 1;
347   lwp->th = *th_p;
348
349   if (thread_db_use_events)
350     {
351       td_err_e err;
352       struct thread_db *thread_db = proc->private->thread_db;
353
354       err = thread_db->td_thr_event_enable_p (th_p, 1);
355       if (err != TD_OK)
356         error ("Cannot enable thread event reporting for %d: %s",
357                ti_p->ti_lid, thread_db_err_str (err));
358     }
359
360   return 1;
361 }
362
363 /* Attach thread if we haven't seen it yet.
364    Increment *COUNTER if we have attached a new thread.
365    Return false on failure.  */
366
367 static int
368 maybe_attach_thread (const td_thrhandle_t *th_p, td_thrinfo_t *ti_p,
369                      int *counter)
370 {
371   struct lwp_info *lwp;
372
373   lwp = find_lwp_pid (pid_to_ptid (ti_p->ti_lid));
374   if (lwp != NULL)
375     return 1;
376
377   if (!attach_thread (th_p, ti_p))
378     return 0;
379
380   if (counter != NULL)
381     *counter += 1;
382
383   return 1;
384 }
385
386 static int
387 find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
388 {
389   td_thrinfo_t ti;
390   td_err_e err;
391   struct thread_db *thread_db = current_process ()->private->thread_db;
392
393   err = thread_db->td_thr_get_info_p (th_p, &ti);
394   if (err != TD_OK)
395     error ("Cannot get thread info: %s", thread_db_err_str (err));
396
397   /* Check for zombies.  */
398   if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
399     return 0;
400
401   if (!maybe_attach_thread (th_p, &ti, (int *) data))
402     {
403       /* Terminate iteration early: we might be looking at stale data in
404          the inferior.  The thread_db_find_new_threads will retry.  */
405       return 1;
406     }
407
408   return 0;
409 }
410
411 static void
412 thread_db_find_new_threads (void)
413 {
414   td_err_e err;
415   ptid_t ptid = current_ptid;
416   struct thread_db *thread_db = current_process ()->private->thread_db;
417   int loop, iteration;
418
419   /* This function is only called when we first initialize thread_db.
420      First locate the initial thread.  If it is not ready for
421      debugging yet, then stop.  */
422   if (find_one_thread (ptid) == 0)
423     return;
424
425   /* Require 4 successive iterations which do not find any new threads.
426      The 4 is a heuristic: there is an inherent race here, and I have
427      seen that 2 iterations in a row are not always sufficient to
428      "capture" all threads.  */
429   for (loop = 0, iteration = 0; loop < 4; ++loop, ++iteration)
430     {
431       int new_thread_count = 0;
432
433       /* Iterate over all user-space threads to discover new threads.  */
434       err = thread_db->td_ta_thr_iter_p (thread_db->thread_agent,
435                                          find_new_threads_callback,
436                                          &new_thread_count,
437                                          TD_THR_ANY_STATE,
438                                          TD_THR_LOWEST_PRIORITY,
439                                          TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
440       if (debug_threads)
441         debug_printf ("Found %d threads in iteration %d.\n",
442                       new_thread_count, iteration);
443
444       if (new_thread_count != 0)
445         {
446           /* Found new threads.  Restart iteration from beginning.  */
447           loop = -1;
448         }
449     }
450   if (err != TD_OK)
451     error ("Cannot find new threads: %s", thread_db_err_str (err));
452 }
453
454 /* Cache all future symbols that thread_db might request.  We can not
455    request symbols at arbitrary states in the remote protocol, only
456    when the client tells us that new symbols are available.  So when
457    we load the thread library, make sure to check the entire list.  */
458
459 static void
460 thread_db_look_up_symbols (void)
461 {
462   struct thread_db *thread_db = current_process ()->private->thread_db;
463   const char **sym_list;
464   CORE_ADDR unused;
465
466   for (sym_list = thread_db->td_symbol_list_p (); *sym_list; sym_list++)
467     look_up_one_symbol (*sym_list, &unused, 1);
468
469   /* We're not interested in any other libraries loaded after this
470      point, only in symbols in libpthread.so.  */
471   thread_db->all_symbols_looked_up = 1;
472 }
473
474 int
475 thread_db_look_up_one_symbol (const char *name, CORE_ADDR *addrp)
476 {
477   struct thread_db *thread_db = current_process ()->private->thread_db;
478   int may_ask_gdb = !thread_db->all_symbols_looked_up;
479
480   /* If we've passed the call to thread_db_look_up_symbols, then
481      anything not in the cache must not exist; we're not interested
482      in any libraries loaded after that point, only in symbols in
483      libpthread.so.  It might not be an appropriate time to look
484      up a symbol, e.g. while we're trying to fetch registers.  */
485   return look_up_one_symbol (name, addrp, may_ask_gdb);
486 }
487
488 int
489 thread_db_get_tls_address (struct thread_info *thread, CORE_ADDR offset,
490                            CORE_ADDR load_module, CORE_ADDR *address)
491 {
492   psaddr_t addr;
493   td_err_e err;
494   struct lwp_info *lwp;
495   struct thread_info *saved_inferior;
496   struct process_info *proc;
497   struct thread_db *thread_db;
498
499   proc = get_thread_process (thread);
500   thread_db = proc->private->thread_db;
501
502   /* If the thread layer is not (yet) initialized, fail.  */
503   if (thread_db == NULL || !thread_db->all_symbols_looked_up)
504     return TD_ERR;
505
506   if (thread_db->td_thr_tls_get_addr_p == NULL)
507     return -1;
508
509   lwp = get_thread_lwp (thread);
510   if (!lwp->thread_known)
511     find_one_thread (thread->entry.id);
512   if (!lwp->thread_known)
513     return TD_NOTHR;
514
515   saved_inferior = current_inferior;
516   current_inferior = thread;
517   /* Note the cast through uintptr_t: this interface only works if
518      a target address fits in a psaddr_t, which is a host pointer.
519      So a 32-bit debugger can not access 64-bit TLS through this.  */
520   err = thread_db->td_thr_tls_get_addr_p (&lwp->th,
521                                           (psaddr_t) (uintptr_t) load_module,
522                                           offset, &addr);
523   current_inferior = saved_inferior;
524   if (err == TD_OK)
525     {
526       *address = (CORE_ADDR) (uintptr_t) addr;
527       return 0;
528     }
529   else
530     return err;
531 }
532
533 #ifdef USE_LIBTHREAD_DB_DIRECTLY
534
535 static int
536 thread_db_load_search (void)
537 {
538   td_err_e err;
539   struct thread_db *tdb;
540   struct process_info *proc = current_process ();
541
542   if (proc->private->thread_db != NULL)
543     fatal ("unexpected: proc->private->thread_db != NULL");
544
545   tdb = xcalloc (1, sizeof (*tdb));
546   proc->private->thread_db = tdb;
547
548   tdb->td_ta_new_p = &td_ta_new;
549
550   /* Attempt to open a connection to the thread library.  */
551   err = tdb->td_ta_new_p (&tdb->proc_handle, &tdb->thread_agent);
552   if (err != TD_OK)
553     {
554       if (debug_threads)
555         debug_printf ("td_ta_new(): %s\n", thread_db_err_str (err));
556       free (tdb);
557       proc->private->thread_db = NULL;
558       return 0;
559     }
560
561   tdb->td_ta_map_lwp2thr_p = &td_ta_map_lwp2thr;
562   tdb->td_thr_get_info_p = &td_thr_get_info;
563   tdb->td_ta_thr_iter_p = &td_ta_thr_iter;
564   tdb->td_symbol_list_p = &td_symbol_list;
565
566   /* This is required only when thread_db_use_events is on.  */
567   tdb->td_thr_event_enable_p = &td_thr_event_enable;
568
569   /* These are not essential.  */
570   tdb->td_ta_event_addr_p = &td_ta_event_addr;
571   tdb->td_ta_set_event_p = &td_ta_set_event;
572   tdb->td_ta_event_getmsg_p = &td_ta_event_getmsg;
573   tdb->td_thr_tls_get_addr_p = &td_thr_tls_get_addr;
574
575   return 1;
576 }
577
578 #else
579
580 static int
581 try_thread_db_load_1 (void *handle)
582 {
583   td_err_e err;
584   struct thread_db *tdb;
585   struct process_info *proc = current_process ();
586
587   if (proc->private->thread_db != NULL)
588     fatal ("unexpected: proc->private->thread_db != NULL");
589
590   tdb = xcalloc (1, sizeof (*tdb));
591   proc->private->thread_db = tdb;
592
593   tdb->handle = handle;
594
595   /* Initialize pointers to the dynamic library functions we will use.
596      Essential functions first.  */
597
598 #define CHK(required, a)                                        \
599   do                                                            \
600     {                                                           \
601       if ((a) == NULL)                                          \
602         {                                                       \
603           if (debug_threads)                                    \
604             debug_printf ("dlsym: %s\n", dlerror ());           \
605           if (required)                                         \
606             {                                                   \
607               free (tdb);                                       \
608               proc->private->thread_db = NULL;                  \
609               return 0;                                         \
610             }                                                   \
611         }                                                       \
612     }                                                           \
613   while (0)
614
615   CHK (1, tdb->td_ta_new_p = dlsym (handle, "td_ta_new"));
616
617   /* Attempt to open a connection to the thread library.  */
618   err = tdb->td_ta_new_p (&tdb->proc_handle, &tdb->thread_agent);
619   if (err != TD_OK)
620     {
621       if (debug_threads)
622         debug_printf ("td_ta_new(): %s\n", thread_db_err_str (err));
623       free (tdb);
624       proc->private->thread_db = NULL;
625       return 0;
626     }
627
628   CHK (1, tdb->td_ta_map_lwp2thr_p = dlsym (handle, "td_ta_map_lwp2thr"));
629   CHK (1, tdb->td_thr_get_info_p = dlsym (handle, "td_thr_get_info"));
630   CHK (1, tdb->td_ta_thr_iter_p = dlsym (handle, "td_ta_thr_iter"));
631   CHK (1, tdb->td_symbol_list_p = dlsym (handle, "td_symbol_list"));
632
633   /* This is required only when thread_db_use_events is on.  */
634   CHK (thread_db_use_events,
635        tdb->td_thr_event_enable_p = dlsym (handle, "td_thr_event_enable"));
636
637   /* These are not essential.  */
638   CHK (0, tdb->td_ta_event_addr_p = dlsym (handle, "td_ta_event_addr"));
639   CHK (0, tdb->td_ta_set_event_p = dlsym (handle, "td_ta_set_event"));
640   CHK (0, tdb->td_ta_event_getmsg_p = dlsym (handle, "td_ta_event_getmsg"));
641   CHK (0, tdb->td_thr_tls_get_addr_p = dlsym (handle, "td_thr_tls_get_addr"));
642
643 #undef CHK
644
645   return 1;
646 }
647
648 #ifdef HAVE_DLADDR
649
650 /* Lookup a library in which given symbol resides.
651    Note: this is looking in the GDBSERVER process, not in the inferior.
652    Returns library name, or NULL.  */
653
654 static const char *
655 dladdr_to_soname (const void *addr)
656 {
657   Dl_info info;
658
659   if (dladdr (addr, &info) != 0)
660     return info.dli_fname;
661   return NULL;
662 }
663
664 #endif
665
666 static int
667 try_thread_db_load (const char *library)
668 {
669   void *handle;
670
671   if (debug_threads)
672     debug_printf ("Trying host libthread_db library: %s.\n",
673                   library);
674   handle = dlopen (library, RTLD_NOW);
675   if (handle == NULL)
676     {
677       if (debug_threads)
678         debug_printf ("dlopen failed: %s.\n", dlerror ());
679       return 0;
680     }
681
682 #ifdef HAVE_DLADDR
683   if (debug_threads && strchr (library, '/') == NULL)
684     {
685       void *td_init;
686
687       td_init = dlsym (handle, "td_init");
688       if (td_init != NULL)
689         {
690           const char *const libpath = dladdr_to_soname (td_init);
691
692           if (libpath != NULL)
693             fprintf (stderr, "Host %s resolved to: %s.\n",
694                      library, libpath);
695         }
696     }
697 #endif
698
699   if (try_thread_db_load_1 (handle))
700     return 1;
701
702   /* This library "refused" to work on current inferior.  */
703   dlclose (handle);
704   return 0;
705 }
706
707 /* Handle $sdir in libthread-db-search-path.
708    Look for libthread_db in the system dirs, or wherever a plain
709    dlopen(file_without_path) will look.
710    The result is true for success.  */
711
712 static int
713 try_thread_db_load_from_sdir (void)
714 {
715   return try_thread_db_load (LIBTHREAD_DB_SO);
716 }
717
718 /* Try to load libthread_db from directory DIR of length DIR_LEN.
719    The result is true for success.  */
720
721 static int
722 try_thread_db_load_from_dir (const char *dir, size_t dir_len)
723 {
724   char path[PATH_MAX];
725
726   if (dir_len + 1 + strlen (LIBTHREAD_DB_SO) + 1 > sizeof (path))
727     {
728       char *cp = xmalloc (dir_len + 1);
729
730       memcpy (cp, dir, dir_len);
731       cp[dir_len] = '\0';
732       warning (_("libthread-db-search-path component too long,"
733                  " ignored: %s."), cp);
734       free (cp);
735       return 0;
736     }
737
738   memcpy (path, dir, dir_len);
739   path[dir_len] = '/';
740   strcpy (path + dir_len + 1, LIBTHREAD_DB_SO);
741   return try_thread_db_load (path);
742 }
743
744 /* Search libthread_db_search_path for libthread_db which "agrees"
745    to work on current inferior.
746    The result is true for success.  */
747
748 static int
749 thread_db_load_search (void)
750 {
751   VEC (char_ptr) *dir_vec;
752   char *this_dir;
753   int i, rc = 0;
754
755   if (libthread_db_search_path == NULL)
756     libthread_db_search_path = xstrdup (LIBTHREAD_DB_SEARCH_PATH);
757
758   dir_vec = dirnames_to_char_ptr_vec (libthread_db_search_path);
759
760   for (i = 0; VEC_iterate (char_ptr, dir_vec, i, this_dir); ++i)
761     {
762       const int pdir_len = sizeof ("$pdir") - 1;
763       size_t this_dir_len;
764
765       this_dir_len = strlen (this_dir);
766
767       if (strncmp (this_dir, "$pdir", pdir_len) == 0
768           && (this_dir[pdir_len] == '\0'
769               || this_dir[pdir_len] == '/'))
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 (strcmp (this_dir, "$sdir") == 0)
776         {
777           if (try_thread_db_load_from_sdir ())
778             {
779               rc = 1;
780               break;
781             }
782         }
783       else
784         {
785           if (try_thread_db_load_from_dir (this_dir, this_dir_len))
786             {
787               rc = 1;
788               break;
789             }
790         }
791     }
792
793   free_char_ptr_vec (dir_vec);
794   if (debug_threads)
795     debug_printf ("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 }