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