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