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