gdb/gdbserver/thread-db.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Thread management interface, for the remote server for GDB.
  2.    Copyright (C) 2002-2015 Free Software Foundation, Inc.

  3.    Contributed by MontaVista Software.

  4.    This file is part of GDB.

  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 3 of the License, or
  8.    (at your option) any later version.

  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.

  13.    You should have received a copy of the GNU General Public License
  14.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  15. #include "server.h"

  16. #include "linux-low.h"

  17. extern int debug_threads;

  18. static int thread_db_use_events;

  19. #include "gdb_proc_service.h"
  20. #include "nat/gdb_thread_db.h"
  21. #include "gdb_vecs.h"

  22. #ifndef USE_LIBTHREAD_DB_DIRECTLY
  23. #include <dlfcn.h>
  24. #endif

  25. #include <stdint.h>
  26. #include <limits.h>
  27. #include <ctype.h>

  28. struct thread_db
  29. {
  30.   /* Structure that identifies the child process for the
  31.      <proc_service.h> interface.  */
  32.   struct ps_prochandle proc_handle;

  33.   /* Connection to the libthread_db library.  */
  34.   td_thragent_t *thread_agent;

  35.   /* If this flag has been set, we've already asked GDB for all
  36.      symbols we might need; assume symbol cache misses are
  37.      failures.  */
  38.   int all_symbols_looked_up;

  39. #ifndef USE_LIBTHREAD_DB_DIRECTLY
  40.   /* Handle of the libthread_db from dlopen.  */
  41.   void *handle;
  42. #endif

  43.   /* Thread creation event breakpoint.  The code at this location in
  44.      the child process will be called by the pthread library whenever
  45.      a new thread is created.  By setting a special breakpoint at this
  46.      location, GDB can detect when a new thread is created.  We obtain
  47.      this location via the td_ta_event_addr call.  Note that if the
  48.      running kernel supports tracing clones, then we don't need to use
  49.      (and in fact don't use) this magic thread event breakpoint to
  50.      learn about threads.  */
  51.   struct breakpoint *td_create_bp;

  52.   /* Addresses of libthread_db functions.  */
  53.   td_err_e (*td_ta_new_p) (struct ps_prochandle * ps, td_thragent_t **ta);
  54.   td_err_e (*td_ta_event_getmsg_p) (const td_thragent_t *ta,
  55.                                     td_event_msg_t *msg);
  56.   td_err_e (*td_ta_set_event_p) (const td_thragent_t *ta,
  57.                                  td_thr_events_t *event);
  58.   td_err_e (*td_ta_event_addr_p) (const td_thragent_t *ta,
  59.                                   td_event_e event, td_notify_t *ptr);
  60.   td_err_e (*td_ta_map_lwp2thr_p) (const td_thragent_t *ta, lwpid_t lwpid,
  61.                                    td_thrhandle_t *th);
  62.   td_err_e (*td_thr_get_info_p) (const td_thrhandle_t *th,
  63.                                  td_thrinfo_t *infop);
  64.   td_err_e (*td_thr_event_enable_p) (const td_thrhandle_t *th, int event);
  65.   td_err_e (*td_ta_thr_iter_p) (const td_thragent_t *ta,
  66.                                 td_thr_iter_f *callback, void *cbdata_p,
  67.                                 td_thr_state_e state, int ti_pri,
  68.                                 sigset_t *ti_sigmask_p,
  69.                                 unsigned int ti_user_flags);
  70.   td_err_e (*td_thr_tls_get_addr_p) (const td_thrhandle_t *th,
  71.                                      psaddr_t map_address,
  72.                                      size_t offset, psaddr_t *address);
  73.   td_err_e (*td_thr_tlsbase_p) (const td_thrhandle_t *th,
  74.                                 unsigned long int modid,
  75.                                 psaddr_t *base);
  76.   const char ** (*td_symbol_list_p) (void);
  77. };

  78. static char *libthread_db_search_path;

  79. static int find_one_thread (ptid_t);
  80. static int find_new_threads_callback (const td_thrhandle_t *th_p, void *data);

  81. static const char *
  82. thread_db_err_str (td_err_e err)
  83. {
  84.   static char buf[64];

  85.   switch (err)
  86.     {
  87.     case TD_OK:
  88.       return "generic 'call succeeded'";
  89.     case TD_ERR:
  90.       return "generic error";
  91.     case TD_NOTHR:
  92.       return "no thread to satisfy query";
  93.     case TD_NOSV:
  94.       return "no sync handle to satisfy query";
  95.     case TD_NOLWP:
  96.       return "no LWP to satisfy query";
  97.     case TD_BADPH:
  98.       return "invalid process handle";
  99.     case TD_BADTH:
  100.       return "invalid thread handle";
  101.     case TD_BADSH:
  102.       return "invalid synchronization handle";
  103.     case TD_BADTA:
  104.       return "invalid thread agent";
  105.     case TD_BADKEY:
  106.       return "invalid key";
  107.     case TD_NOMSG:
  108.       return "no event message for getmsg";
  109.     case TD_NOFPREGS:
  110.       return "FPU register set not available";
  111.     case TD_NOLIBTHREAD:
  112.       return "application not linked with libthread";
  113.     case TD_NOEVENT:
  114.       return "requested event is not supported";
  115.     case TD_NOCAPAB:
  116.       return "capability not available";
  117.     case TD_DBERR:
  118.       return "debugger service failed";
  119.     case TD_NOAPLIC:
  120.       return "operation not applicable to";
  121.     case TD_NOTSD:
  122.       return "no thread-specific data for this thread";
  123.     case TD_MALLOC:
  124.       return "malloc failed";
  125.     case TD_PARTIALREG:
  126.       return "only part of register set was written/read";
  127.     case TD_NOXREGS:
  128.       return "X register set not available for this thread";
  129. #ifdef HAVE_TD_VERSION
  130.     case TD_VERSION:
  131.       return "version mismatch between libthread_db and libpthread";
  132. #endif
  133.     default:
  134.       xsnprintf (buf, sizeof (buf), "unknown thread_db error '%d'", err);
  135.       return buf;
  136.     }
  137. }

  138. #if 0
  139. static char *
  140. thread_db_state_str (td_thr_state_e state)
  141. {
  142.   static char buf[64];

  143.   switch (state)
  144.     {
  145.     case TD_THR_STOPPED:
  146.       return "stopped by debugger";
  147.     case TD_THR_RUN:
  148.       return "runnable";
  149.     case TD_THR_ACTIVE:
  150.       return "active";
  151.     case TD_THR_ZOMBIE:
  152.       return "zombie";
  153.     case TD_THR_SLEEP:
  154.       return "sleeping";
  155.     case TD_THR_STOPPED_ASLEEP:
  156.       return "stopped by debugger AND blocked";
  157.     default:
  158.       xsnprintf (buf, sizeof (buf), "unknown thread_db state %d", state);
  159.       return buf;
  160.     }
  161. }
  162. #endif

  163. static int
  164. thread_db_create_event (CORE_ADDR where)
  165. {
  166.   td_event_msg_t msg;
  167.   td_err_e err;
  168.   struct lwp_info *lwp;
  169.   struct thread_db *thread_db = current_process ()->private->thread_db;

  170.   gdb_assert (thread_db->td_ta_event_getmsg_p != NULL);

  171.   if (debug_threads)
  172.     debug_printf ("Thread creation event.\n");

  173.   /* FIXME: This assumes we don't get another event.
  174.      In the LinuxThreads implementation, this is safe,
  175.      because all events come from the manager thread
  176.      (except for its own creation, of course).  */
  177.   err = thread_db->td_ta_event_getmsg_p (thread_db->thread_agent, &msg);
  178.   if (err != TD_OK)
  179.     fprintf (stderr, "thread getmsg err: %s\n",
  180.              thread_db_err_str (err));

  181.   /* If we do not know about the main thread yet, this would be a good time to
  182.      find it.  We need to do this to pick up the main thread before any newly
  183.      created threads.  */
  184.   lwp = get_thread_lwp (current_thread);
  185.   if (lwp->thread_known == 0)
  186.     find_one_thread (current_thread->entry.id);

  187.   /* msg.event == TD_EVENT_CREATE */

  188.   find_new_threads_callback (msg.th_p, NULL);

  189.   return 0;
  190. }

  191. static int
  192. thread_db_enable_reporting (void)
  193. {
  194.   td_thr_events_t events;
  195.   td_notify_t notify;
  196.   td_err_e err;
  197.   struct thread_db *thread_db = current_process ()->private->thread_db;

  198.   if (thread_db->td_ta_set_event_p == NULL
  199.       || thread_db->td_ta_event_addr_p == NULL
  200.       || thread_db->td_ta_event_getmsg_p == NULL)
  201.     /* This libthread_db is missing required support.  */
  202.     return 0;

  203.   /* Set the process wide mask saying which events we're interested in.  */
  204.   td_event_emptyset (&events);
  205.   td_event_addset (&events, TD_CREATE);

  206.   err = thread_db->td_ta_set_event_p (thread_db->thread_agent, &events);
  207.   if (err != TD_OK)
  208.     {
  209.       warning ("Unable to set global thread event mask: %s",
  210.                thread_db_err_str (err));
  211.       return 0;
  212.     }

  213.   /* Get address for thread creation breakpoint.  */
  214.   err = thread_db->td_ta_event_addr_p (thread_db->thread_agent, TD_CREATE,
  215.                                        &notify);
  216.   if (err != TD_OK)
  217.     {
  218.       warning ("Unable to get location for thread creation breakpoint: %s",
  219.                thread_db_err_str (err));
  220.       return 0;
  221.     }
  222.   thread_db->td_create_bp
  223.     = set_breakpoint_at ((CORE_ADDR) (unsigned long) notify.u.bptaddr,
  224.                          thread_db_create_event);

  225.   return 1;
  226. }

  227. static int
  228. find_one_thread (ptid_t ptid)
  229. {
  230.   td_thrhandle_t th;
  231.   td_thrinfo_t ti;
  232.   td_err_e err;
  233.   struct thread_info *inferior;
  234.   struct lwp_info *lwp;
  235.   struct thread_db *thread_db = current_process ()->private->thread_db;
  236.   int lwpid = ptid_get_lwp (ptid);

  237.   inferior = (struct thread_info *) find_inferior_id (&all_threads, ptid);
  238.   lwp = get_thread_lwp (inferior);
  239.   if (lwp->thread_known)
  240.     return 1;

  241.   /* Get information about this thread.  */
  242.   err = thread_db->td_ta_map_lwp2thr_p (thread_db->thread_agent, lwpid, &th);
  243.   if (err != TD_OK)
  244.     error ("Cannot get thread handle for LWP %d: %s",
  245.            lwpid, thread_db_err_str (err));

  246.   err = thread_db->td_thr_get_info_p (&th, &ti);
  247.   if (err != TD_OK)
  248.     error ("Cannot get thread info for LWP %d: %s",
  249.            lwpid, thread_db_err_str (err));

  250.   if (debug_threads)
  251.     debug_printf ("Found thread %ld (LWP %d)\n",
  252.                   ti.ti_tid, ti.ti_lid);

  253.   if (lwpid != ti.ti_lid)
  254.     {
  255.       warning ("PID mismatch!  Expected %ld, got %ld",
  256.                (long) lwpid, (long) ti.ti_lid);
  257.       return 0;
  258.     }

  259.   if (thread_db_use_events)
  260.     {
  261.       err = thread_db->td_thr_event_enable_p (&th, 1);
  262.       if (err != TD_OK)
  263.         error ("Cannot enable thread event reporting for %d: %s",
  264.                ti.ti_lid, thread_db_err_str (err));
  265.     }

  266.   /* If the new thread ID is zero, a final thread ID will be available
  267.      later.  Do not enable thread debugging yet.  */
  268.   if (ti.ti_tid == 0)
  269.     return 0;

  270.   lwp->thread_known = 1;
  271.   lwp->th = th;

  272.   return 1;
  273. }

  274. /* Attach a thread.  Return true on success.  */

  275. static int
  276. attach_thread (const td_thrhandle_t *th_p, td_thrinfo_t *ti_p)
  277. {
  278.   struct process_info *proc = current_process ();
  279.   int pid = pid_of (proc);
  280.   ptid_t ptid = ptid_build (pid, ti_p->ti_lid, 0);
  281.   struct lwp_info *lwp;
  282.   int err;

  283.   if (debug_threads)
  284.     debug_printf ("Attaching to thread %ld (LWP %d)\n",
  285.                   ti_p->ti_tid, ti_p->ti_lid);
  286.   err = linux_attach_lwp (ptid);
  287.   if (err != 0)
  288.     {
  289.       warning ("Could not attach to thread %ld (LWP %d): %s\n",
  290.                ti_p->ti_tid, ti_p->ti_lid,
  291.                linux_ptrace_attach_fail_reason_string (ptid, err));
  292.       return 0;
  293.     }

  294.   lwp = find_lwp_pid (ptid);
  295.   gdb_assert (lwp != NULL);
  296.   lwp->thread_known = 1;
  297.   lwp->th = *th_p;

  298.   if (thread_db_use_events)
  299.     {
  300.       td_err_e err;
  301.       struct thread_db *thread_db = proc->private->thread_db;

  302.       err = thread_db->td_thr_event_enable_p (th_p, 1);
  303.       if (err != TD_OK)
  304.         error ("Cannot enable thread event reporting for %d: %s",
  305.                ti_p->ti_lid, thread_db_err_str (err));
  306.     }

  307.   return 1;
  308. }

  309. /* Attach thread if we haven't seen it yet.
  310.    Increment *COUNTER if we have attached a new thread.
  311.    Return false on failure.  */

  312. static int
  313. maybe_attach_thread (const td_thrhandle_t *th_p, td_thrinfo_t *ti_p,
  314.                      int *counter)
  315. {
  316.   struct lwp_info *lwp;

  317.   lwp = find_lwp_pid (pid_to_ptid (ti_p->ti_lid));
  318.   if (lwp != NULL)
  319.     return 1;

  320.   if (!attach_thread (th_p, ti_p))
  321.     return 0;

  322.   if (counter != NULL)
  323.     *counter += 1;

  324.   return 1;
  325. }

  326. static int
  327. find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
  328. {
  329.   td_thrinfo_t ti;
  330.   td_err_e err;
  331.   struct thread_db *thread_db = current_process ()->private->thread_db;

  332.   err = thread_db->td_thr_get_info_p (th_p, &ti);
  333.   if (err != TD_OK)
  334.     error ("Cannot get thread info: %s", thread_db_err_str (err));

  335.   if (ti.ti_lid == -1)
  336.     {
  337.       /* A thread with kernel thread ID -1 is either a thread that
  338.          exited and was joined, or a thread that is being created but
  339.          hasn't started yet, and that is reusing the tcb/stack of a
  340.          thread that previously exited and was joined.  (glibc marks
  341.          terminated and joined threads with kernel thread ID -1.  See
  342.          glibc PR17707.  */
  343.       return 0;
  344.     }

  345.   /* Check for zombies.  */
  346.   if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
  347.     return 0;

  348.   if (!maybe_attach_thread (th_p, &ti, (int *) data))
  349.     {
  350.       /* Terminate iteration early: we might be looking at stale data in
  351.          the inferior.  The thread_db_find_new_threads will retry.  */
  352.       return 1;
  353.     }

  354.   return 0;
  355. }

  356. static void
  357. thread_db_find_new_threads (void)
  358. {
  359.   td_err_e err;
  360.   ptid_t ptid = current_ptid;
  361.   struct thread_db *thread_db = current_process ()->private->thread_db;
  362.   int loop, iteration;

  363.   /* This function is only called when we first initialize thread_db.
  364.      First locate the initial thread.  If it is not ready for
  365.      debugging yet, then stop.  */
  366.   if (find_one_thread (ptid) == 0)
  367.     return;

  368.   /* Require 4 successive iterations which do not find any new threads.
  369.      The 4 is a heuristic: there is an inherent race here, and I have
  370.      seen that 2 iterations in a row are not always sufficient to
  371.      "capture" all threads.  */
  372.   for (loop = 0, iteration = 0; loop < 4; ++loop, ++iteration)
  373.     {
  374.       int new_thread_count = 0;

  375.       /* Iterate over all user-space threads to discover new threads.  */
  376.       err = thread_db->td_ta_thr_iter_p (thread_db->thread_agent,
  377.                                          find_new_threads_callback,
  378.                                          &new_thread_count,
  379.                                          TD_THR_ANY_STATE,
  380.                                          TD_THR_LOWEST_PRIORITY,
  381.                                          TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
  382.       if (debug_threads)
  383.         debug_printf ("Found %d threads in iteration %d.\n",
  384.                       new_thread_count, iteration);

  385.       if (new_thread_count != 0)
  386.         {
  387.           /* Found new threads.  Restart iteration from beginning.  */
  388.           loop = -1;
  389.         }
  390.     }
  391.   if (err != TD_OK)
  392.     error ("Cannot find new threads: %s", thread_db_err_str (err));
  393. }

  394. /* Cache all future symbols that thread_db might request.  We can not
  395.    request symbols at arbitrary states in the remote protocol, only
  396.    when the client tells us that new symbols are available.  So when
  397.    we load the thread library, make sure to check the entire list.  */

  398. static void
  399. thread_db_look_up_symbols (void)
  400. {
  401.   struct thread_db *thread_db = current_process ()->private->thread_db;
  402.   const char **sym_list;
  403.   CORE_ADDR unused;

  404.   for (sym_list = thread_db->td_symbol_list_p (); *sym_list; sym_list++)
  405.     look_up_one_symbol (*sym_list, &unused, 1);

  406.   /* We're not interested in any other libraries loaded after this
  407.      point, only in symbols in libpthread.so.  */
  408.   thread_db->all_symbols_looked_up = 1;
  409. }

  410. int
  411. thread_db_look_up_one_symbol (const char *name, CORE_ADDR *addrp)
  412. {
  413.   struct thread_db *thread_db = current_process ()->private->thread_db;
  414.   int may_ask_gdb = !thread_db->all_symbols_looked_up;

  415.   /* If we've passed the call to thread_db_look_up_symbols, then
  416.      anything not in the cache must not exist; we're not interested
  417.      in any libraries loaded after that point, only in symbols in
  418.      libpthread.so.  It might not be an appropriate time to look
  419.      up a symbol, e.g. while we're trying to fetch registers.  */
  420.   return look_up_one_symbol (name, addrp, may_ask_gdb);
  421. }

  422. int
  423. thread_db_get_tls_address (struct thread_info *thread, CORE_ADDR offset,
  424.                            CORE_ADDR load_module, CORE_ADDR *address)
  425. {
  426.   psaddr_t addr;
  427.   td_err_e err;
  428.   struct lwp_info *lwp;
  429.   struct thread_info *saved_thread;
  430.   struct process_info *proc;
  431.   struct thread_db *thread_db;

  432.   proc = get_thread_process (thread);
  433.   thread_db = proc->private->thread_db;

  434.   /* If the thread layer is not (yet) initialized, fail.  */
  435.   if (thread_db == NULL || !thread_db->all_symbols_looked_up)
  436.     return TD_ERR;

  437.   /* If td_thr_tls_get_addr is missing rather do not expect td_thr_tlsbase
  438.      could work.  */
  439.   if (thread_db->td_thr_tls_get_addr_p == NULL
  440.       || (load_module == 0 && thread_db->td_thr_tlsbase_p == NULL))
  441.     return -1;

  442.   lwp = get_thread_lwp (thread);
  443.   if (!lwp->thread_known)
  444.     find_one_thread (thread->entry.id);
  445.   if (!lwp->thread_known)
  446.     return TD_NOTHR;

  447.   saved_thread = current_thread;
  448.   current_thread = thread;

  449.   if (load_module != 0)
  450.     {
  451.       /* Note the cast through uintptr_t: this interface only works if
  452.          a target address fits in a psaddr_t, which is a host pointer.
  453.          So a 32-bit debugger can not access 64-bit TLS through this.  */
  454.       err = thread_db->td_thr_tls_get_addr_p (&lwp->th,
  455.                                              (psaddr_t) (uintptr_t) load_module,
  456.                                               offset, &addr);
  457.     }
  458.   else
  459.     {
  460.       /* This code path handles the case of -static -pthread executables:
  461.          https://sourceware.org/ml/libc-help/2014-03/msg00024.html
  462.          For older GNU libc r_debug.r_map is NULL.  For GNU libc after
  463.          PR libc/16831 due to GDB PR threads/16954 LOAD_MODULE is also NULL.
  464.          The constant number 1 depends on GNU __libc_setup_tls
  465.          initialization of l_tls_modid to 1.  */
  466.       err = thread_db->td_thr_tlsbase_p (&lwp->th, 1, &addr);
  467.       addr = (char *) addr + offset;
  468.     }

  469.   current_thread = saved_thread;
  470.   if (err == TD_OK)
  471.     {
  472.       *address = (CORE_ADDR) (uintptr_t) addr;
  473.       return 0;
  474.     }
  475.   else
  476.     return err;
  477. }

  478. #ifdef USE_LIBTHREAD_DB_DIRECTLY

  479. static int
  480. thread_db_load_search (void)
  481. {
  482.   td_err_e err;
  483.   struct thread_db *tdb;
  484.   struct process_info *proc = current_process ();

  485.   gdb_assert (proc->private->thread_db == NULL);

  486.   tdb = xcalloc (1, sizeof (*tdb));
  487.   proc->private->thread_db = tdb;

  488.   tdb->td_ta_new_p = &td_ta_new;

  489.   /* Attempt to open a connection to the thread library.  */
  490.   err = tdb->td_ta_new_p (&tdb->proc_handle, &tdb->thread_agent);
  491.   if (err != TD_OK)
  492.     {
  493.       if (debug_threads)
  494.         debug_printf ("td_ta_new(): %s\n", thread_db_err_str (err));
  495.       free (tdb);
  496.       proc->private->thread_db = NULL;
  497.       return 0;
  498.     }

  499.   tdb->td_ta_map_lwp2thr_p = &td_ta_map_lwp2thr;
  500.   tdb->td_thr_get_info_p = &td_thr_get_info;
  501.   tdb->td_ta_thr_iter_p = &td_ta_thr_iter;
  502.   tdb->td_symbol_list_p = &td_symbol_list;

  503.   /* This is required only when thread_db_use_events is on.  */
  504.   tdb->td_thr_event_enable_p = &td_thr_event_enable;

  505.   /* These are not essential.  */
  506.   tdb->td_ta_event_addr_p = &td_ta_event_addr;
  507.   tdb->td_ta_set_event_p = &td_ta_set_event;
  508.   tdb->td_ta_event_getmsg_p = &td_ta_event_getmsg;
  509.   tdb->td_thr_tls_get_addr_p = &td_thr_tls_get_addr;
  510.   tdb->td_thr_tlsbase_p = &td_thr_tlsbase;

  511.   return 1;
  512. }

  513. #else

  514. static int
  515. try_thread_db_load_1 (void *handle)
  516. {
  517.   td_err_e err;
  518.   struct thread_db *tdb;
  519.   struct process_info *proc = current_process ();

  520.   gdb_assert (proc->private->thread_db == NULL);

  521.   tdb = xcalloc (1, sizeof (*tdb));
  522.   proc->private->thread_db = tdb;

  523.   tdb->handle = handle;

  524.   /* Initialize pointers to the dynamic library functions we will use.
  525.      Essential functions first.  */

  526. #define CHK(required, a)                                        \
  527.   do                                                                \
  528.     {                                                                \
  529.       if ((a) == NULL)                                                \
  530.         {                                                        \
  531.           if (debug_threads)                                        \
  532.             debug_printf ("dlsym: %s\n", dlerror ());                \
  533.           if (required)                                                \
  534.             {                                                        \
  535.               free (tdb);                                        \
  536.               proc->private->thread_db = NULL;                        \
  537.               return 0;                                                \
  538.             }                                                        \
  539.         }                                                        \
  540.     }                                                                \
  541.   while (0)

  542.   CHK (1, tdb->td_ta_new_p = dlsym (handle, "td_ta_new"));

  543.   /* Attempt to open a connection to the thread library.  */
  544.   err = tdb->td_ta_new_p (&tdb->proc_handle, &tdb->thread_agent);
  545.   if (err != TD_OK)
  546.     {
  547.       if (debug_threads)
  548.         debug_printf ("td_ta_new(): %s\n", thread_db_err_str (err));
  549.       free (tdb);
  550.       proc->private->thread_db = NULL;
  551.       return 0;
  552.     }

  553.   CHK (1, tdb->td_ta_map_lwp2thr_p = dlsym (handle, "td_ta_map_lwp2thr"));
  554.   CHK (1, tdb->td_thr_get_info_p = dlsym (handle, "td_thr_get_info"));
  555.   CHK (1, tdb->td_ta_thr_iter_p = dlsym (handle, "td_ta_thr_iter"));
  556.   CHK (1, tdb->td_symbol_list_p = dlsym (handle, "td_symbol_list"));

  557.   /* This is required only when thread_db_use_events is on.  */
  558.   CHK (thread_db_use_events,
  559.        tdb->td_thr_event_enable_p = dlsym (handle, "td_thr_event_enable"));

  560.   /* These are not essential.  */
  561.   CHK (0, tdb->td_ta_event_addr_p = dlsym (handle, "td_ta_event_addr"));
  562.   CHK (0, tdb->td_ta_set_event_p = dlsym (handle, "td_ta_set_event"));
  563.   CHK (0, tdb->td_ta_event_getmsg_p = dlsym (handle, "td_ta_event_getmsg"));
  564.   CHK (0, tdb->td_thr_tls_get_addr_p = dlsym (handle, "td_thr_tls_get_addr"));
  565.   CHK (0, tdb->td_thr_tlsbase_p = dlsym (handle, "td_thr_tlsbase"));

  566. #undef CHK

  567.   return 1;
  568. }

  569. #ifdef HAVE_DLADDR

  570. /* Lookup a library in which given symbol resides.
  571.    Note: this is looking in the GDBSERVER process, not in the inferior.
  572.    Returns library name, or NULL.  */

  573. static const char *
  574. dladdr_to_soname (const void *addr)
  575. {
  576.   Dl_info info;

  577.   if (dladdr (addr, &info) != 0)
  578.     return info.dli_fname;
  579.   return NULL;
  580. }

  581. #endif

  582. static int
  583. try_thread_db_load (const char *library)
  584. {
  585.   void *handle;

  586.   if (debug_threads)
  587.     debug_printf ("Trying host libthread_db library: %s.\n",
  588.                   library);
  589.   handle = dlopen (library, RTLD_NOW);
  590.   if (handle == NULL)
  591.     {
  592.       if (debug_threads)
  593.         debug_printf ("dlopen failed: %s.\n", dlerror ());
  594.       return 0;
  595.     }

  596. #ifdef HAVE_DLADDR
  597.   if (debug_threads && strchr (library, '/') == NULL)
  598.     {
  599.       void *td_init;

  600.       td_init = dlsym (handle, "td_init");
  601.       if (td_init != NULL)
  602.         {
  603.           const char *const libpath = dladdr_to_soname (td_init);

  604.           if (libpath != NULL)
  605.             fprintf (stderr, "Host %s resolved to: %s.\n",
  606.                      library, libpath);
  607.         }
  608.     }
  609. #endif

  610.   if (try_thread_db_load_1 (handle))
  611.     return 1;

  612.   /* This library "refused" to work on current inferior.  */
  613.   dlclose (handle);
  614.   return 0;
  615. }

  616. /* Handle $sdir in libthread-db-search-path.
  617.    Look for libthread_db in the system dirs, or wherever a plain
  618.    dlopen(file_without_path) will look.
  619.    The result is true for success.  */

  620. static int
  621. try_thread_db_load_from_sdir (void)
  622. {
  623.   return try_thread_db_load (LIBTHREAD_DB_SO);
  624. }

  625. /* Try to load libthread_db from directory DIR of length DIR_LEN.
  626.    The result is true for success.  */

  627. static int
  628. try_thread_db_load_from_dir (const char *dir, size_t dir_len)
  629. {
  630.   char path[PATH_MAX];

  631.   if (dir_len + 1 + strlen (LIBTHREAD_DB_SO) + 1 > sizeof (path))
  632.     {
  633.       char *cp = xmalloc (dir_len + 1);

  634.       memcpy (cp, dir, dir_len);
  635.       cp[dir_len] = '\0';
  636.       warning (_("libthread-db-search-path component too long,"
  637.                  " ignored: %s."), cp);
  638.       free (cp);
  639.       return 0;
  640.     }

  641.   memcpy (path, dir, dir_len);
  642.   path[dir_len] = '/';
  643.   strcpy (path + dir_len + 1, LIBTHREAD_DB_SO);
  644.   return try_thread_db_load (path);
  645. }

  646. /* Search libthread_db_search_path for libthread_db which "agrees"
  647.    to work on current inferior.
  648.    The result is true for success.  */

  649. static int
  650. thread_db_load_search (void)
  651. {
  652.   VEC (char_ptr) *dir_vec;
  653.   char *this_dir;
  654.   int i, rc = 0;

  655.   if (libthread_db_search_path == NULL)
  656.     libthread_db_search_path = xstrdup (LIBTHREAD_DB_SEARCH_PATH);

  657.   dir_vec = dirnames_to_char_ptr_vec (libthread_db_search_path);

  658.   for (i = 0; VEC_iterate (char_ptr, dir_vec, i, this_dir); ++i)
  659.     {
  660.       const int pdir_len = sizeof ("$pdir") - 1;
  661.       size_t this_dir_len;

  662.       this_dir_len = strlen (this_dir);

  663.       if (strncmp (this_dir, "$pdir", pdir_len) == 0
  664.           && (this_dir[pdir_len] == '\0'
  665.               || this_dir[pdir_len] == '/'))
  666.         {
  667.           /* We don't maintain a list of loaded libraries so we don't know
  668.              where libpthread lives.  We *could* fetch the info, but we don't
  669.              do that yet.  Ignore it.  */
  670.         }
  671.       else if (strcmp (this_dir, "$sdir") == 0)
  672.         {
  673.           if (try_thread_db_load_from_sdir ())
  674.             {
  675.               rc = 1;
  676.               break;
  677.             }
  678.         }
  679.       else
  680.         {
  681.           if (try_thread_db_load_from_dir (this_dir, this_dir_len))
  682.             {
  683.               rc = 1;
  684.               break;
  685.             }
  686.         }
  687.     }

  688.   free_char_ptr_vec (dir_vec);
  689.   if (debug_threads)
  690.     debug_printf ("thread_db_load_search returning %d\n", rc);
  691.   return rc;
  692. }

  693. #endif  /* USE_LIBTHREAD_DB_DIRECTLY */

  694. int
  695. thread_db_init (int use_events)
  696. {
  697.   struct process_info *proc = current_process ();

  698.   /* FIXME drow/2004-10-16: This is the "overall process ID", which
  699.      GNU/Linux calls tgid, "thread group ID".  When we support
  700.      attaching to threads, the original thread may not be the correct
  701.      thread.  We would have to get the process ID from /proc for NPTL.
  702.      For LinuxThreads we could do something similar: follow the chain
  703.      of parent processes until we find the highest one we're attached
  704.      to, and use its tgid.

  705.      This isn't the only place in gdbserver that assumes that the first
  706.      process in the list is the thread group leader.  */

  707.   thread_db_use_events = use_events;

  708.   if (thread_db_load_search ())
  709.     {
  710.       if (use_events && thread_db_enable_reporting () == 0)
  711.         {
  712.           /* Keep trying; maybe event reporting will work later.  */
  713.           thread_db_mourn (proc);
  714.           return 0;
  715.         }
  716.       thread_db_find_new_threads ();
  717.       thread_db_look_up_symbols ();
  718.       return 1;
  719.     }

  720.   return 0;
  721. }

  722. static int
  723. any_thread_of (struct inferior_list_entry *entry, void *args)
  724. {
  725.   int *pid_p = args;

  726.   if (ptid_get_pid (entry->id) == *pid_p)
  727.     return 1;

  728.   return 0;
  729. }

  730. static void
  731. switch_to_process (struct process_info *proc)
  732. {
  733.   int pid = pid_of (proc);

  734.   current_thread =
  735.     (struct thread_info *) find_inferior (&all_threads,
  736.                                           any_thread_of, &pid);
  737. }

  738. /* Disconnect from libthread_db and free resources.  */

  739. static void
  740. disable_thread_event_reporting (struct process_info *proc)
  741. {
  742.   struct thread_db *thread_db = proc->private->thread_db;
  743.   if (thread_db)
  744.     {
  745.       td_err_e (*td_ta_clear_event_p) (const td_thragent_t *ta,
  746.                                        td_thr_events_t *event);

  747. #ifndef USE_LIBTHREAD_DB_DIRECTLY
  748.       td_ta_clear_event_p = dlsym (thread_db->handle, "td_ta_clear_event");
  749. #else
  750.       td_ta_clear_event_p = &td_ta_clear_event;
  751. #endif

  752.       if (td_ta_clear_event_p != NULL)
  753.         {
  754.           struct thread_info *saved_thread = current_thread;
  755.           td_thr_events_t events;

  756.           switch_to_process (proc);

  757.           /* Set the process wide mask saying we aren't interested
  758.              in any events anymore.  */
  759.           td_event_fillset (&events);
  760.           (*td_ta_clear_event_p) (thread_db->thread_agent, &events);

  761.           current_thread = saved_thread;
  762.         }
  763.     }
  764. }

  765. static void
  766. remove_thread_event_breakpoints (struct process_info *proc)
  767. {
  768.   struct thread_db *thread_db = proc->private->thread_db;

  769.   if (thread_db->td_create_bp != NULL)
  770.     {
  771.       struct thread_info *saved_thread = current_thread;

  772.       switch_to_process (proc);

  773.       delete_breakpoint (thread_db->td_create_bp);
  774.       thread_db->td_create_bp = NULL;

  775.       current_thread = saved_thread;
  776.     }
  777. }

  778. void
  779. thread_db_detach (struct process_info *proc)
  780. {
  781.   struct thread_db *thread_db = proc->private->thread_db;

  782.   if (thread_db)
  783.     {
  784.       disable_thread_event_reporting (proc);
  785.       remove_thread_event_breakpoints (proc);
  786.     }
  787. }

  788. /* Disconnect from libthread_db and free resources.  */

  789. void
  790. thread_db_mourn (struct process_info *proc)
  791. {
  792.   struct thread_db *thread_db = proc->private->thread_db;
  793.   if (thread_db)
  794.     {
  795.       td_err_e (*td_ta_delete_p) (td_thragent_t *);

  796. #ifndef USE_LIBTHREAD_DB_DIRECTLY
  797.       td_ta_delete_p = dlsym (thread_db->handle, "td_ta_delete");
  798. #else
  799.       td_ta_delete_p = &td_ta_delete;
  800. #endif

  801.       if (td_ta_delete_p != NULL)
  802.         (*td_ta_delete_p) (thread_db->thread_agent);

  803. #ifndef USE_LIBTHREAD_DB_DIRECTLY
  804.       dlclose (thread_db->handle);
  805. #endif  /* USE_LIBTHREAD_DB_DIRECTLY  */

  806.       free (thread_db);
  807.       proc->private->thread_db = NULL;
  808.     }
  809. }

  810. /* Handle "set libthread-db-search-path" monitor command and return 1.
  811.    For any other command, return 0.  */

  812. int
  813. thread_db_handle_monitor_command (char *mon)
  814. {
  815.   const char *cmd = "set libthread-db-search-path";
  816.   size_t cmd_len = strlen (cmd);

  817.   if (strncmp (mon, cmd, cmd_len) == 0
  818.       && (mon[cmd_len] == '\0'
  819.           || mon[cmd_len] == ' '))
  820.     {
  821.       const char *cp = mon + cmd_len;

  822.       if (libthread_db_search_path != NULL)
  823.         free (libthread_db_search_path);

  824.       /* Skip leading space (if any).  */
  825.       while (isspace (*cp))
  826.         ++cp;

  827.       if (*cp == '\0')
  828.         cp = LIBTHREAD_DB_SEARCH_PATH;
  829.       libthread_db_search_path = xstrdup (cp);

  830.       monitor_output ("libthread-db-search-path set to `");
  831.       monitor_output (libthread_db_search_path);
  832.       monitor_output ("'\n");
  833.       return 1;
  834.     }

  835.   /* Tell server.c to perform default processing.  */
  836.   return 0;
  837. }