gdb/linux-thread-db.c - gdb

Global variables defined

Data types defined

Functions defined

Source code

  1. /* libthread_db assisted debugging support, generic parts.

  2.    Copyright (C) 1999-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

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

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

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

  14. #include "defs.h"
  15. #include <dlfcn.h>
  16. #include "gdb_proc_service.h"
  17. #include "nat/gdb_thread_db.h"
  18. #include "gdb_vecs.h"
  19. #include "bfd.h"
  20. #include "command.h"
  21. #include "gdbcmd.h"
  22. #include "gdbthread.h"
  23. #include "inferior.h"
  24. #include "infrun.h"
  25. #include "symfile.h"
  26. #include "objfiles.h"
  27. #include "target.h"
  28. #include "regcache.h"
  29. #include "solib.h"
  30. #include "solib-svr4.h"
  31. #include "gdbcore.h"
  32. #include "observer.h"
  33. #include "linux-nat.h"
  34. #include "nat/linux-procfs.h"
  35. #include "nat/linux-ptrace.h"
  36. #include "nat/linux-osdata.h"
  37. #include "auto-load.h"
  38. #include "cli/cli-utils.h"

  39. #include <signal.h>
  40. #include <ctype.h>

  41. /* GNU/Linux libthread_db support.

  42.    libthread_db is a library, provided along with libpthread.so, which
  43.    exposes the internals of the thread library to a debugger.  It
  44.    allows GDB to find existing threads, new threads as they are
  45.    created, thread IDs (usually, the result of pthread_self), and
  46.    thread-local variables.

  47.    The libthread_db interface originates on Solaris, where it is
  48.    both more powerful and more complicated.  This implementation
  49.    only works for LinuxThreads and NPTL, the two glibc threading
  50.    libraries.  It assumes that each thread is permanently assigned
  51.    to a single light-weight process (LWP).

  52.    libthread_db-specific information is stored in the "private" field
  53.    of struct thread_info.  When the field is NULL we do not yet have
  54.    information about the new thread; this could be temporary (created,
  55.    but the thread library's data structures do not reflect it yet)
  56.    or permanent (created using clone instead of pthread_create).

  57.    Process IDs managed by linux-thread-db.c match those used by
  58.    linux-nat.c: a common PID for all processes, an LWP ID for each
  59.    thread, and no TID.  We save the TID in private.  Keeping it out
  60.    of the ptid_t prevents thread IDs changing when libpthread is
  61.    loaded or unloaded.  */

  62. static char *libthread_db_search_path;

  63. /* Set to non-zero if thread_db auto-loading is enabled
  64.    by the "set auto-load libthread-db" command.  */
  65. static int auto_load_thread_db = 1;

  66. /* Returns true if we need to use thread_db thread create/death event
  67.    breakpoints to learn about threads.  */

  68. static int
  69. thread_db_use_events (void)
  70. {
  71.   /* Not necessary if the kernel supports clone events.  */
  72.   return !linux_supports_traceclone ();
  73. }

  74. /* "show" command for the auto_load_thread_db configuration variable.  */

  75. static void
  76. show_auto_load_thread_db (struct ui_file *file, int from_tty,
  77.                           struct cmd_list_element *c, const char *value)
  78. {
  79.   fprintf_filtered (file, _("Auto-loading of inferior specific libthread_db "
  80.                             "is %s.\n"),
  81.                     value);
  82. }

  83. static void
  84. set_libthread_db_search_path (char *ignored, int from_tty,
  85.                               struct cmd_list_element *c)
  86. {
  87.   if (*libthread_db_search_path == '\0')
  88.     {
  89.       xfree (libthread_db_search_path);
  90.       libthread_db_search_path = xstrdup (LIBTHREAD_DB_SEARCH_PATH);
  91.     }
  92. }

  93. /* If non-zero, print details of libthread_db processing.  */

  94. static unsigned int libthread_db_debug;

  95. static void
  96. show_libthread_db_debug (struct ui_file *file, int from_tty,
  97.                          struct cmd_list_element *c, const char *value)
  98. {
  99.   fprintf_filtered (file, _("libthread-db debugging is %s.\n"), value);
  100. }

  101. /* If we're running on GNU/Linux, we must explicitly attach to any new
  102.    threads.  */

  103. /* This module's target vector.  */
  104. static struct target_ops thread_db_ops;

  105. /* Non-zero if we have determined the signals used by the threads
  106.    library.  */
  107. static int thread_signals;
  108. static sigset_t thread_stop_set;
  109. static sigset_t thread_print_set;

  110. struct thread_db_info
  111. {
  112.   struct thread_db_info *next;

  113.   /* Process id this object refers to.  */
  114.   int pid;

  115.   /* Handle from dlopen for libthread_db.so.  */
  116.   void *handle;

  117.   /* Absolute pathname from gdb_realpath to disk file used for dlopen-ing
  118.      HANDLE.  It may be NULL for system library.  */
  119.   char *filename;

  120.   /* Structure that identifies the child process for the
  121.      <proc_service.h> interface.  */
  122.   struct ps_prochandle proc_handle;

  123.   /* Connection to the libthread_db library.  */
  124.   td_thragent_t *thread_agent;

  125.   /* True if we need to apply the workaround for glibc/BZ5983.  When
  126.      we catch a PTRACE_O_TRACEFORK, and go query the child's thread
  127.      list, nptl_db returns the parent's threads in addition to the new
  128.      (single) child thread.  If this flag is set, we do extra work to
  129.      be able to ignore such stale entries.  */
  130.   int need_stale_parent_threads_check;

  131.   /* Location of the thread creation event breakpoint.  The code at
  132.      this location in the child process will be called by the pthread
  133.      library whenever a new thread is created.  By setting a special
  134.      breakpoint at this location, GDB can detect when a new thread is
  135.      created.  We obtain this location via the td_ta_event_addr
  136.      call.  */
  137.   CORE_ADDR td_create_bp_addr;

  138.   /* Location of the thread death event breakpoint.  */
  139.   CORE_ADDR td_death_bp_addr;

  140.   /* Pointers to the libthread_db functions.  */

  141.   td_err_e (*td_init_p) (void);

  142.   td_err_e (*td_ta_new_p) (struct ps_prochandle * ps,
  143.                                 td_thragent_t **ta);
  144.   td_err_e (*td_ta_map_id2thr_p) (const td_thragent_t *ta, thread_t pt,
  145.                                   td_thrhandle_t *__th);
  146.   td_err_e (*td_ta_map_lwp2thr_p) (const td_thragent_t *ta,
  147.                                    lwpid_t lwpid, td_thrhandle_t *th);
  148.   td_err_e (*td_ta_thr_iter_p) (const td_thragent_t *ta,
  149.                                 td_thr_iter_f *callback, void *cbdata_p,
  150.                                 td_thr_state_e state, int ti_pri,
  151.                                 sigset_t *ti_sigmask_p,
  152.                                 unsigned int ti_user_flags);
  153.   td_err_e (*td_ta_event_addr_p) (const td_thragent_t *ta,
  154.                                   td_event_e event, td_notify_t *ptr);
  155.   td_err_e (*td_ta_set_event_p) (const td_thragent_t *ta,
  156.                                  td_thr_events_t *event);
  157.   td_err_e (*td_ta_clear_event_p) (const td_thragent_t *ta,
  158.                                    td_thr_events_t *event);
  159.   td_err_e (*td_ta_event_getmsg_p) (const td_thragent_t *ta,
  160.                                     td_event_msg_t *msg);

  161.   td_err_e (*td_thr_validate_p) (const td_thrhandle_t *th);
  162.   td_err_e (*td_thr_get_info_p) (const td_thrhandle_t *th,
  163.                                  td_thrinfo_t *infop);
  164.   td_err_e (*td_thr_event_enable_p) (const td_thrhandle_t *th,
  165.                                      int event);

  166.   td_err_e (*td_thr_tls_get_addr_p) (const td_thrhandle_t *th,
  167.                                      psaddr_t map_address,
  168.                                      size_t offset, psaddr_t *address);
  169.   td_err_e (*td_thr_tlsbase_p) (const td_thrhandle_t *th,
  170.                                 unsigned long int modid,
  171.                                 psaddr_t *base);
  172. };

  173. /* List of known processes using thread_db, and the required
  174.    bookkeeping.  */
  175. struct thread_db_info *thread_db_list;

  176. static void thread_db_find_new_threads_1 (ptid_t ptid);
  177. static void thread_db_find_new_threads_2 (ptid_t ptid, int until_no_new);

  178. /* Add the current inferior to the list of processes using libpthread.
  179.    Return a pointer to the newly allocated object that was added to
  180.    THREAD_DB_LIST.  HANDLE is the handle returned by dlopen'ing
  181.    LIBTHREAD_DB_SO.  */

  182. static struct thread_db_info *
  183. add_thread_db_info (void *handle)
  184. {
  185.   struct thread_db_info *info;

  186.   info = xcalloc (1, sizeof (*info));
  187.   info->pid = ptid_get_pid (inferior_ptid);
  188.   info->handle = handle;

  189.   /* The workaround works by reading from /proc/pid/status, so it is
  190.      disabled for core files.  */
  191.   if (target_has_execution)
  192.     info->need_stale_parent_threads_check = 1;

  193.   info->next = thread_db_list;
  194.   thread_db_list = info;

  195.   return info;
  196. }

  197. /* Return the thread_db_info object representing the bookkeeping
  198.    related to process PID, if any; NULL otherwise.  */

  199. static struct thread_db_info *
  200. get_thread_db_info (int pid)
  201. {
  202.   struct thread_db_info *info;

  203.   for (info = thread_db_list; info; info = info->next)
  204.     if (pid == info->pid)
  205.       return info;

  206.   return NULL;
  207. }

  208. /* When PID has exited or has been detached, we no longer want to keep
  209.    track of it as using libpthread.  Call this function to discard
  210.    thread_db related info related to PID.  Note that this closes
  211.    LIBTHREAD_DB_SO's dlopen'ed handle.  */

  212. static void
  213. delete_thread_db_info (int pid)
  214. {
  215.   struct thread_db_info *info, *info_prev;

  216.   info_prev = NULL;

  217.   for (info = thread_db_list; info; info_prev = info, info = info->next)
  218.     if (pid == info->pid)
  219.       break;

  220.   if (info == NULL)
  221.     return;

  222.   if (info->handle != NULL)
  223.     dlclose (info->handle);

  224.   xfree (info->filename);

  225.   if (info_prev)
  226.     info_prev->next = info->next;
  227.   else
  228.     thread_db_list = info->next;

  229.   xfree (info);
  230. }

  231. /* Prototypes for local functions.  */
  232. static int attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
  233.                           const td_thrinfo_t *ti_p);
  234. static void detach_thread (ptid_t ptid);


  235. /* Use "struct private_thread_info" to cache thread state.  This is
  236.    a substantial optimization.  */

  237. struct private_thread_info
  238. {
  239.   /* Flag set when we see a TD_DEATH event for this thread.  */
  240.   unsigned int dying:1;

  241.   /* Cached thread state.  */
  242.   td_thrhandle_t th;
  243.   thread_t tid;
  244. };


  245. static char *
  246. thread_db_err_str (td_err_e err)
  247. {
  248.   static char buf[64];

  249.   switch (err)
  250.     {
  251.     case TD_OK:
  252.       return "generic 'call succeeded'";
  253.     case TD_ERR:
  254.       return "generic error";
  255.     case TD_NOTHR:
  256.       return "no thread to satisfy query";
  257.     case TD_NOSV:
  258.       return "no sync handle to satisfy query";
  259.     case TD_NOLWP:
  260.       return "no LWP to satisfy query";
  261.     case TD_BADPH:
  262.       return "invalid process handle";
  263.     case TD_BADTH:
  264.       return "invalid thread handle";
  265.     case TD_BADSH:
  266.       return "invalid synchronization handle";
  267.     case TD_BADTA:
  268.       return "invalid thread agent";
  269.     case TD_BADKEY:
  270.       return "invalid key";
  271.     case TD_NOMSG:
  272.       return "no event message for getmsg";
  273.     case TD_NOFPREGS:
  274.       return "FPU register set not available";
  275.     case TD_NOLIBTHREAD:
  276.       return "application not linked with libthread";
  277.     case TD_NOEVENT:
  278.       return "requested event is not supported";
  279.     case TD_NOCAPAB:
  280.       return "capability not available";
  281.     case TD_DBERR:
  282.       return "debugger service failed";
  283.     case TD_NOAPLIC:
  284.       return "operation not applicable to";
  285.     case TD_NOTSD:
  286.       return "no thread-specific data for this thread";
  287.     case TD_MALLOC:
  288.       return "malloc failed";
  289.     case TD_PARTIALREG:
  290.       return "only part of register set was written/read";
  291.     case TD_NOXREGS:
  292.       return "X register set not available for this thread";
  293. #ifdef THREAD_DB_HAS_TD_NOTALLOC
  294.     case TD_NOTALLOC:
  295.       return "thread has not yet allocated TLS for given module";
  296. #endif
  297. #ifdef THREAD_DB_HAS_TD_VERSION
  298.     case TD_VERSION:
  299.       return "versions of libpthread and libthread_db do not match";
  300. #endif
  301. #ifdef THREAD_DB_HAS_TD_NOTLS
  302.     case TD_NOTLS:
  303.       return "there is no TLS segment in the given module";
  304. #endif
  305.     default:
  306.       snprintf (buf, sizeof (buf), "unknown thread_db error '%d'", err);
  307.       return buf;
  308.     }
  309. }

  310. /* Return 1 if any threads have been registered.  There may be none if
  311.    the threading library is not fully initialized yet.  */

  312. static int
  313. have_threads_callback (struct thread_info *thread, void *args)
  314. {
  315.   int pid = * (int *) args;

  316.   if (ptid_get_pid (thread->ptid) != pid)
  317.     return 0;

  318.   return thread->private != NULL;
  319. }

  320. static int
  321. have_threads (ptid_t ptid)
  322. {
  323.   int pid = ptid_get_pid (ptid);

  324.   return iterate_over_threads (have_threads_callback, &pid) != NULL;
  325. }

  326. struct thread_get_info_inout
  327. {
  328.   struct thread_info *thread_info;
  329.   struct thread_db_info *thread_db_info;
  330. };

  331. /* A callback function for td_ta_thr_iter, which we use to map all
  332.    threads to LWPs.

  333.    THP is a handle to the current thread; if INFOP is not NULL, the
  334.    struct thread_info associated with this thread is returned in
  335.    *INFOP.

  336.    If the thread is a zombie, TD_THR_ZOMBIE is returned.  Otherwise,
  337.    zero is returned to indicate success.  */

  338. static int
  339. thread_get_info_callback (const td_thrhandle_t *thp, void *argp)
  340. {
  341.   td_thrinfo_t ti;
  342.   td_err_e err;
  343.   ptid_t thread_ptid;
  344.   struct thread_get_info_inout *inout;
  345.   struct thread_db_info *info;

  346.   inout = argp;
  347.   info = inout->thread_db_info;

  348.   err = info->td_thr_get_info_p (thp, &ti);
  349.   if (err != TD_OK)
  350.     error (_("thread_get_info_callback: cannot get thread info: %s"),
  351.            thread_db_err_str (err));

  352.   /* Fill the cache.  */
  353.   thread_ptid = ptid_build (info->pid, ti.ti_lid, 0);
  354.   inout->thread_info = find_thread_ptid (thread_ptid);

  355.   if (inout->thread_info == NULL)
  356.     {
  357.       /* New thread.  Attach to it now (why wait?).  */
  358.       if (!have_threads (thread_ptid))
  359.          thread_db_find_new_threads_1 (thread_ptid);
  360.       else
  361.         attach_thread (thread_ptid, thp, &ti);
  362.       inout->thread_info = find_thread_ptid (thread_ptid);
  363.       gdb_assert (inout->thread_info != NULL);
  364.     }

  365.   return 0;
  366. }

  367. /* Fetch the user-level thread id of PTID.  */

  368. static void
  369. thread_from_lwp (ptid_t ptid)
  370. {
  371.   td_thrhandle_t th;
  372.   td_err_e err;
  373.   struct thread_db_info *info;
  374.   struct thread_get_info_inout io = {0};

  375.   /* Just in case td_ta_map_lwp2thr doesn't initialize it completely.  */
  376.   th.th_unique = 0;

  377.   /* This ptid comes from linux-nat.c, which should always fill in the
  378.      LWP.  */
  379.   gdb_assert (ptid_get_lwp (ptid) != 0);

  380.   info = get_thread_db_info (ptid_get_pid (ptid));

  381.   /* Access an lwp we know is stopped.  */
  382.   info->proc_handle.ptid = ptid;
  383.   err = info->td_ta_map_lwp2thr_p (info->thread_agent, ptid_get_lwp (ptid),
  384.                                    &th);
  385.   if (err != TD_OK)
  386.     error (_("Cannot find user-level thread for LWP %ld: %s"),
  387.            ptid_get_lwp (ptid), thread_db_err_str (err));

  388.   /* Long-winded way of fetching the thread info.  */
  389.   io.thread_db_info = info;
  390.   io.thread_info = NULL;
  391.   thread_get_info_callback (&th, &io);
  392. }


  393. /* Attach to lwp PTID, doing whatever else is required to have this
  394.    LWP under the debugger's control --- e.g., enabling event
  395.    reporting.  Returns true on success.  */
  396. int
  397. thread_db_attach_lwp (ptid_t ptid)
  398. {
  399.   td_thrhandle_t th;
  400.   td_thrinfo_t ti;
  401.   td_err_e err;
  402.   struct thread_db_info *info;

  403.   info = get_thread_db_info (ptid_get_pid (ptid));

  404.   if (info == NULL)
  405.     return 0;

  406.   /* This ptid comes from linux-nat.c, which should always fill in the
  407.      LWP.  */
  408.   gdb_assert (ptid_get_lwp (ptid) != 0);

  409.   /* Access an lwp we know is stopped.  */
  410.   info->proc_handle.ptid = ptid;

  411.   /* If we have only looked at the first thread before libpthread was
  412.      initialized, we may not know its thread ID yet.  Make sure we do
  413.      before we add another thread to the list.  */
  414.   if (!have_threads (ptid))
  415.     thread_db_find_new_threads_1 (ptid);

  416.   err = info->td_ta_map_lwp2thr_p (info->thread_agent, ptid_get_lwp (ptid),
  417.                                    &th);
  418.   if (err != TD_OK)
  419.     /* Cannot find user-level thread.  */
  420.     return 0;

  421.   err = info->td_thr_get_info_p (&th, &ti);
  422.   if (err != TD_OK)
  423.     {
  424.       warning (_("Cannot get thread info: %s"), thread_db_err_str (err));
  425.       return 0;
  426.     }

  427.   attach_thread (ptid, &th, &ti);
  428.   return 1;
  429. }

  430. static void *
  431. verbose_dlsym (void *handle, const char *name)
  432. {
  433.   void *sym = dlsym (handle, name);
  434.   if (sym == NULL)
  435.     warning (_("Symbol \"%s\" not found in libthread_db: %s"),
  436.              name, dlerror ());
  437.   return sym;
  438. }

  439. static td_err_e
  440. enable_thread_event (int event, CORE_ADDR *bp)
  441. {
  442.   td_notify_t notify;
  443.   td_err_e err;
  444.   struct thread_db_info *info;

  445.   info = get_thread_db_info (ptid_get_pid (inferior_ptid));

  446.   /* Access an lwp we know is stopped.  */
  447.   info->proc_handle.ptid = inferior_ptid;

  448.   /* Get the breakpoint address for thread EVENT.  */
  449.   err = info->td_ta_event_addr_p (info->thread_agent, event, &notify);
  450.   if (err != TD_OK)
  451.     return err;

  452.   /* Set up the breakpoint.  */
  453.   gdb_assert (exec_bfd);
  454.   (*bp) = (gdbarch_convert_from_func_ptr_addr
  455.            (target_gdbarch (),
  456.             /* Do proper sign extension for the target.  */
  457.             (bfd_get_sign_extend_vma (exec_bfd) > 0
  458.              ? (CORE_ADDR) (intptr_t) notify.u.bptaddr
  459.              : (CORE_ADDR) (uintptr_t) notify.u.bptaddr),
  460.             &current_target));
  461.   create_thread_event_breakpoint (target_gdbarch (), *bp);

  462.   return TD_OK;
  463. }

  464. /* Verify inferior's '\0'-terminated symbol VER_SYMBOL starts with "%d.%d" and
  465.    return 1 if this version is lower (and not equal) to
  466.    VER_MAJOR_MIN.VER_MINOR_MIN.  Return 0 in all other cases.  */

  467. static int
  468. inferior_has_bug (const char *ver_symbol, int ver_major_min, int ver_minor_min)
  469. {
  470.   struct bound_minimal_symbol version_msym;
  471.   CORE_ADDR version_addr;
  472.   char *version;
  473.   int err, got, retval = 0;

  474.   version_msym = lookup_minimal_symbol (ver_symbol, NULL, NULL);
  475.   if (version_msym.minsym == NULL)
  476.     return 0;

  477.   version_addr = BMSYMBOL_VALUE_ADDRESS (version_msym);
  478.   got = target_read_string (version_addr, &version, 32, &err);
  479.   if (err == 0 && memchr (version, 0, got) == &version[got -1])
  480.     {
  481.       int major, minor;

  482.       retval = (sscanf (version, "%d.%d", &major, &minor) == 2
  483.                 && (major < ver_major_min
  484.                     || (major == ver_major_min && minor < ver_minor_min)));
  485.     }
  486.   xfree (version);

  487.   return retval;
  488. }

  489. static void
  490. enable_thread_event_reporting (void)
  491. {
  492.   td_thr_events_t events;
  493.   td_err_e err;
  494.   struct thread_db_info *info;

  495.   info = get_thread_db_info (ptid_get_pid (inferior_ptid));

  496.   /* We cannot use the thread event reporting facility if these
  497.      functions aren't available.  */
  498.   if (info->td_ta_event_addr_p == NULL
  499.       || info->td_ta_set_event_p == NULL
  500.       || info->td_ta_event_getmsg_p == NULL
  501.       || info->td_thr_event_enable_p == NULL)
  502.     return;

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

  506.   /* There is a bug fixed between linuxthreads 2.1.3 and 2.2 by
  507.        commit 2e4581e4fba917f1779cd0a010a45698586c190a
  508.        * manager.c (pthread_exited): Correctly report event as TD_REAP
  509.        instead of TD_DEATH.  Fix comments.
  510.      where event reporting facility is broken for TD_DEATH events,
  511.      so don't enable it if we have glibc but a lower version.  */
  512.   if (!inferior_has_bug ("__linuxthreads_version", 2, 2))
  513.     td_event_addset (&events, TD_DEATH);

  514.   err = info->td_ta_set_event_p (info->thread_agent, &events);
  515.   if (err != TD_OK)
  516.     {
  517.       warning (_("Unable to set global thread event mask: %s"),
  518.                thread_db_err_str (err));
  519.       return;
  520.     }

  521.   /* Delete previous thread event breakpoints, if any.  */
  522.   remove_thread_event_breakpoints ();
  523.   info->td_create_bp_addr = 0;
  524.   info->td_death_bp_addr = 0;

  525.   /* Set up the thread creation event.  */
  526.   err = enable_thread_event (TD_CREATE, &info->td_create_bp_addr);
  527.   if (err != TD_OK)
  528.     {
  529.       warning (_("Unable to get location for thread creation breakpoint: %s"),
  530.                thread_db_err_str (err));
  531.       return;
  532.     }

  533.   /* Set up the thread death event.  */
  534.   err = enable_thread_event (TD_DEATH, &info->td_death_bp_addr);
  535.   if (err != TD_OK)
  536.     {
  537.       warning (_("Unable to get location for thread death breakpoint: %s"),
  538.                thread_db_err_str (err));
  539.       return;
  540.     }
  541. }

  542. /* Similar as thread_db_find_new_threads_1, but try to silently ignore errors
  543.    if appropriate.

  544.    Return 1 if the caller should abort libthread_db initialization.  Return 0
  545.    otherwise.  */

  546. static int
  547. thread_db_find_new_threads_silently (ptid_t ptid)
  548. {
  549.   volatile struct gdb_exception except;

  550.   TRY_CATCH (except, RETURN_MASK_ERROR)
  551.     {
  552.       thread_db_find_new_threads_2 (ptid, 1);
  553.     }

  554.   if (except.reason < 0)
  555.     {
  556.       if (libthread_db_debug)
  557.         exception_fprintf (gdb_stdlog, except,
  558.                            "Warning: thread_db_find_new_threads_silently: ");

  559.       /* There is a bug fixed between nptl 2.6.1 and 2.7 by
  560.            commit 7d9d8bd18906fdd17364f372b160d7ab896ce909
  561.          where calls to td_thr_get_info fail with TD_ERR for statically linked
  562.          executables if td_thr_get_info is called before glibc has initialized
  563.          itself.

  564.          If the nptl bug is NOT present in the inferior and still thread_db
  565.          reports an error return 1.  It means the inferior has corrupted thread
  566.          list and GDB should fall back only to LWPs.

  567.          If the nptl bug is present in the inferior return 0 to silently ignore
  568.          such errors, and let gdb enumerate threads again later.  In such case
  569.          GDB cannot properly display LWPs if the inferior thread list is
  570.          corrupted.  For core files it does not apply, no 'later enumeration'
  571.          is possible.  */

  572.       if (!target_has_execution || !inferior_has_bug ("nptl_version", 2, 7))
  573.         {
  574.           exception_fprintf (gdb_stderr, except,
  575.                              _("Warning: couldn't activate thread debugging "
  576.                                "using libthread_db: "));
  577.           return 1;
  578.         }
  579.     }
  580.   return 0;
  581. }

  582. /* Lookup a library in which given symbol resides.
  583.    Note: this is looking in GDB process, not in the inferior.
  584.    Returns library name, or NULL.  */

  585. static const char *
  586. dladdr_to_soname (const void *addr)
  587. {
  588.   Dl_info info;

  589.   if (dladdr (addr, &info) != 0)
  590.     return info.dli_fname;
  591.   return NULL;
  592. }

  593. /* Attempt to initialize dlopen()ed libthread_db, described by INFO.
  594.    Return 1 on success.
  595.    Failure could happen if libthread_db does not have symbols we expect,
  596.    or when it refuses to work with the current inferior (e.g. due to
  597.    version mismatch between libthread_db and libpthread).  */

  598. static int
  599. try_thread_db_load_1 (struct thread_db_info *info)
  600. {
  601.   td_err_e err;

  602.   /* Initialize pointers to the dynamic library functions we will use.
  603.      Essential functions first.  */

  604.   info->td_init_p = verbose_dlsym (info->handle, "td_init");
  605.   if (info->td_init_p == NULL)
  606.     return 0;

  607.   err = info->td_init_p ();
  608.   if (err != TD_OK)
  609.     {
  610.       warning (_("Cannot initialize libthread_db: %s"),
  611.                thread_db_err_str (err));
  612.       return 0;
  613.     }

  614.   info->td_ta_new_p = verbose_dlsym (info->handle, "td_ta_new");
  615.   if (info->td_ta_new_p == NULL)
  616.     return 0;

  617.   /* Initialize the structure that identifies the child process.  */
  618.   info->proc_handle.ptid = inferior_ptid;

  619.   /* Now attempt to open a connection to the thread library.  */
  620.   err = info->td_ta_new_p (&info->proc_handle, &info->thread_agent);
  621.   if (err != TD_OK)
  622.     {
  623.       if (libthread_db_debug)
  624.         fprintf_unfiltered (gdb_stdlog, _("td_ta_new failed: %s\n"),
  625.                             thread_db_err_str (err));
  626.       else
  627.         switch (err)
  628.           {
  629.             case TD_NOLIBTHREAD:
  630. #ifdef THREAD_DB_HAS_TD_VERSION
  631.             case TD_VERSION:
  632. #endif
  633.               /* The errors above are not unexpected and silently ignored:
  634.                  they just mean we haven't found correct version of
  635.                  libthread_db yet.  */
  636.               break;
  637.             default:
  638.               warning (_("td_ta_new failed: %s"), thread_db_err_str (err));
  639.           }
  640.       return 0;
  641.     }

  642.   info->td_ta_map_id2thr_p = verbose_dlsym (info->handle, "td_ta_map_id2thr");
  643.   if (info->td_ta_map_id2thr_p == NULL)
  644.     return 0;

  645.   info->td_ta_map_lwp2thr_p = verbose_dlsym (info->handle,
  646.                                              "td_ta_map_lwp2thr");
  647.   if (info->td_ta_map_lwp2thr_p == NULL)
  648.     return 0;

  649.   info->td_ta_thr_iter_p = verbose_dlsym (info->handle, "td_ta_thr_iter");
  650.   if (info->td_ta_thr_iter_p == NULL)
  651.     return 0;

  652.   info->td_thr_validate_p = verbose_dlsym (info->handle, "td_thr_validate");
  653.   if (info->td_thr_validate_p == NULL)
  654.     return 0;

  655.   info->td_thr_get_info_p = verbose_dlsym (info->handle, "td_thr_get_info");
  656.   if (info->td_thr_get_info_p == NULL)
  657.     return 0;

  658.   /* These are not essential.  */
  659.   info->td_ta_event_addr_p = dlsym (info->handle, "td_ta_event_addr");
  660.   info->td_ta_set_event_p = dlsym (info->handle, "td_ta_set_event");
  661.   info->td_ta_clear_event_p = dlsym (info->handle, "td_ta_clear_event");
  662.   info->td_ta_event_getmsg_p = dlsym (info->handle, "td_ta_event_getmsg");
  663.   info->td_thr_event_enable_p = dlsym (info->handle, "td_thr_event_enable");
  664.   info->td_thr_tls_get_addr_p = dlsym (info->handle, "td_thr_tls_get_addr");
  665.   info->td_thr_tlsbase_p = dlsym (info->handle, "td_thr_tlsbase");

  666.   if (thread_db_find_new_threads_silently (inferior_ptid) != 0)
  667.     {
  668.       /* Even if libthread_db initializes, if the thread list is
  669.          corrupted, we'd not manage to list any threads.  Better reject this
  670.          thread_db, and fall back to at least listing LWPs.  */
  671.       return 0;
  672.     }

  673.   printf_unfiltered (_("[Thread debugging using libthread_db enabled]\n"));

  674.   if (*libthread_db_search_path || libthread_db_debug)
  675.     {
  676.       struct ui_file *file;
  677.       const char *library;

  678.       library = dladdr_to_soname (*info->td_ta_new_p);
  679.       if (library == NULL)
  680.         library = LIBTHREAD_DB_SO;

  681.       /* If we'd print this to gdb_stdout when debug output is
  682.          disabled, still print it to gdb_stdout if debug output is
  683.          enabled.  User visible output should not depend on debug
  684.          settings.  */
  685.       file = *libthread_db_search_path != '\0' ? gdb_stdout : gdb_stdlog;
  686.       fprintf_unfiltered (file, _("Using host libthread_db library \"%s\".\n"),
  687.                           library);
  688.     }

  689.   /* The thread library was detected.  Activate the thread_db target
  690.      if this is the first process using it.  */
  691.   if (thread_db_list->next == NULL)
  692.     push_target (&thread_db_ops);

  693.   /* Enable event reporting, but not when debugging a core file.  */
  694.   if (target_has_execution && thread_db_use_events ())
  695.     enable_thread_event_reporting ();

  696.   return 1;
  697. }

  698. /* Attempt to use LIBRARY as libthread_db.  LIBRARY could be absolute,
  699.    relative, or just LIBTHREAD_DB.  */

  700. static int
  701. try_thread_db_load (const char *library, int check_auto_load_safe)
  702. {
  703.   void *handle;
  704.   struct thread_db_info *info;

  705.   if (libthread_db_debug)
  706.     fprintf_unfiltered (gdb_stdlog,
  707.                         _("Trying host libthread_db library: %s.\n"),
  708.                         library);

  709.   if (check_auto_load_safe)
  710.     {
  711.       if (access (library, R_OK) != 0)
  712.         {
  713.           /* Do not print warnings by file_is_auto_load_safe if the library does
  714.              not exist at this place.  */
  715.           if (libthread_db_debug)
  716.             fprintf_unfiltered (gdb_stdlog, _("open failed: %s.\n"),
  717.                                 safe_strerror (errno));
  718.           return 0;
  719.         }

  720.       if (!file_is_auto_load_safe (library, _("auto-load: Loading libthread-db "
  721.                                               "library \"%s\" from explicit "
  722.                                               "directory.\n"),
  723.                                    library))
  724.         return 0;
  725.     }

  726.   handle = dlopen (library, RTLD_NOW);
  727.   if (handle == NULL)
  728.     {
  729.       if (libthread_db_debug)
  730.         fprintf_unfiltered (gdb_stdlog, _("dlopen failed: %s.\n"), dlerror ());
  731.       return 0;
  732.     }

  733.   if (libthread_db_debug && strchr (library, '/') == NULL)
  734.     {
  735.       void *td_init;

  736.       td_init = dlsym (handle, "td_init");
  737.       if (td_init != NULL)
  738.         {
  739.           const char *const libpath = dladdr_to_soname (td_init);

  740.           if (libpath != NULL)
  741.             fprintf_unfiltered (gdb_stdlog, _("Host %s resolved to: %s.\n"),
  742.                                library, libpath);
  743.         }
  744.     }

  745.   info = add_thread_db_info (handle);

  746.   /* Do not save system library name, that one is always trusted.  */
  747.   if (strchr (library, '/') != NULL)
  748.     info->filename = gdb_realpath (library);

  749.   if (try_thread_db_load_1 (info))
  750.     return 1;

  751.   /* This library "refused" to work on current inferior.  */
  752.   delete_thread_db_info (ptid_get_pid (inferior_ptid));
  753.   return 0;
  754. }

  755. /* Subroutine of try_thread_db_load_from_pdir to simplify it.
  756.    Try loading libthread_db in directory(OBJ)/SUBDIR.
  757.    SUBDIR may be NULL.  It may also be something like "../lib64".
  758.    The result is true for success.  */

  759. static int
  760. try_thread_db_load_from_pdir_1 (struct objfile *obj, const char *subdir)
  761. {
  762.   struct cleanup *cleanup;
  763.   char *path, *cp;
  764.   int result;
  765.   const char *obj_name = objfile_name (obj);

  766.   if (obj_name[0] != '/')
  767.     {
  768.       warning (_("Expected absolute pathname for libpthread in the"
  769.                  " inferior, but got %s."), obj_name);
  770.       return 0;
  771.     }

  772.   path = xmalloc (strlen (obj_name) + (subdir ? strlen (subdir) + 1 : 0)
  773.                   + 1 + strlen (LIBTHREAD_DB_SO) + 1);
  774.   cleanup = make_cleanup (xfree, path);

  775.   strcpy (path, obj_name);
  776.   cp = strrchr (path, '/');
  777.   /* This should at minimum hit the first character.  */
  778.   gdb_assert (cp != NULL);
  779.   cp[1] = '\0';
  780.   if (subdir != NULL)
  781.     {
  782.       strcat (cp, subdir);
  783.       strcat (cp, "/");
  784.     }
  785.   strcat (cp, LIBTHREAD_DB_SO);

  786.   result = try_thread_db_load (path, 1);

  787.   do_cleanups (cleanup);
  788.   return result;
  789. }

  790. /* Handle $pdir in libthread-db-search-path.
  791.    Look for libthread_db in directory(libpthread)/SUBDIR.
  792.    SUBDIR may be NULL.  It may also be something like "../lib64".
  793.    The result is true for success.  */

  794. static int
  795. try_thread_db_load_from_pdir (const char *subdir)
  796. {
  797.   struct objfile *obj;

  798.   if (!auto_load_thread_db)
  799.     return 0;

  800.   ALL_OBJFILES (obj)
  801.     if (libpthread_name_p (objfile_name (obj)))
  802.       {
  803.         if (try_thread_db_load_from_pdir_1 (obj, subdir))
  804.           return 1;

  805.         /* We may have found the separate-debug-info version of
  806.            libpthread, and it may live in a directory without a matching
  807.            libthread_db.  */
  808.         if (obj->separate_debug_objfile_backlink != NULL)
  809.           return try_thread_db_load_from_pdir_1 (obj->separate_debug_objfile_backlink,
  810.                                                  subdir);

  811.         return 0;
  812.       }

  813.   return 0;
  814. }

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

  819. static int
  820. try_thread_db_load_from_sdir (void)
  821. {
  822.   return try_thread_db_load (LIBTHREAD_DB_SO, 0);
  823. }

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

  826. static int
  827. try_thread_db_load_from_dir (const char *dir, size_t dir_len)
  828. {
  829.   struct cleanup *cleanup;
  830.   char *path;
  831.   int result;

  832.   if (!auto_load_thread_db)
  833.     return 0;

  834.   path = xmalloc (dir_len + 1 + strlen (LIBTHREAD_DB_SO) + 1);
  835.   cleanup = make_cleanup (xfree, path);

  836.   memcpy (path, dir, dir_len);
  837.   path[dir_len] = '/';
  838.   strcpy (path + dir_len + 1, LIBTHREAD_DB_SO);

  839.   result = try_thread_db_load (path, 1);

  840.   do_cleanups (cleanup);
  841.   return result;
  842. }

  843. /* Search libthread_db_search_path for libthread_db which "agrees"
  844.    to work on current inferior.
  845.    The result is true for success.  */

  846. static int
  847. thread_db_load_search (void)
  848. {
  849.   VEC (char_ptr) *dir_vec;
  850.   struct cleanup *cleanups;
  851.   char *this_dir;
  852.   int i, rc = 0;

  853.   dir_vec = dirnames_to_char_ptr_vec (libthread_db_search_path);
  854.   cleanups = make_cleanup_free_char_ptr_vec (dir_vec);

  855.   for (i = 0; VEC_iterate (char_ptr, dir_vec, i, this_dir); ++i)
  856.     {
  857.       const int pdir_len = sizeof ("$pdir") - 1;
  858.       size_t this_dir_len;

  859.       this_dir_len = strlen (this_dir);

  860.       if (strncmp (this_dir, "$pdir", pdir_len) == 0
  861.           && (this_dir[pdir_len] == '\0'
  862.               || this_dir[pdir_len] == '/'))
  863.         {
  864.           char *subdir = NULL;
  865.           struct cleanup *free_subdir_cleanup
  866.             = make_cleanup (null_cleanup, NULL);

  867.           if (this_dir[pdir_len] == '/')
  868.             {
  869.               subdir = xmalloc (strlen (this_dir));
  870.               make_cleanup (xfree, subdir);
  871.               strcpy (subdir, this_dir + pdir_len + 1);
  872.             }
  873.           rc = try_thread_db_load_from_pdir (subdir);
  874.           do_cleanups (free_subdir_cleanup);
  875.           if (rc)
  876.             break;
  877.         }
  878.       else if (strcmp (this_dir, "$sdir") == 0)
  879.         {
  880.           if (try_thread_db_load_from_sdir ())
  881.             {
  882.               rc = 1;
  883.               break;
  884.             }
  885.         }
  886.       else
  887.         {
  888.           if (try_thread_db_load_from_dir (this_dir, this_dir_len))
  889.             {
  890.               rc = 1;
  891.               break;
  892.             }
  893.         }
  894.     }

  895.   do_cleanups (cleanups);
  896.   if (libthread_db_debug)
  897.     fprintf_unfiltered (gdb_stdlog,
  898.                         _("thread_db_load_search returning %d\n"), rc);
  899.   return rc;
  900. }

  901. /* Return non-zero if the inferior has a libpthread.  */

  902. static int
  903. has_libpthread (void)
  904. {
  905.   struct objfile *obj;

  906.   ALL_OBJFILES (obj)
  907.     if (libpthread_name_p (objfile_name (obj)))
  908.       return 1;

  909.   return 0;
  910. }

  911. /* Attempt to load and initialize libthread_db.
  912.    Return 1 on success.  */

  913. static int
  914. thread_db_load (void)
  915. {
  916.   struct thread_db_info *info;

  917.   info = get_thread_db_info (ptid_get_pid (inferior_ptid));

  918.   if (info != NULL)
  919.     return 1;

  920.   /* Don't attempt to use thread_db on executables not running
  921.      yet.  */
  922.   if (!target_has_registers)
  923.     return 0;

  924.   /* Don't attempt to use thread_db for remote targets.  */
  925.   if (!(target_can_run (&current_target) || core_bfd))
  926.     return 0;

  927.   if (thread_db_load_search ())
  928.     return 1;

  929.   /* We couldn't find a libthread_db.
  930.      If the inferior has a libpthread warn the user.  */
  931.   if (has_libpthread ())
  932.     {
  933.       warning (_("Unable to find libthread_db matching inferior's thread"
  934.                  " library, thread debugging will not be available."));
  935.       return 0;
  936.     }

  937.   /* Either this executable isn't using libpthread at all, or it is
  938.      statically linked.  Since we can't easily distinguish these two cases,
  939.      no warning is issued.  */
  940.   return 0;
  941. }

  942. static void
  943. disable_thread_event_reporting (struct thread_db_info *info)
  944. {
  945.   if (info->td_ta_clear_event_p != NULL)
  946.     {
  947.       td_thr_events_t events;

  948.       /* Set the process wide mask saying we aren't interested in any
  949.          events anymore.  */
  950.       td_event_fillset (&events);
  951.       info->td_ta_clear_event_p (info->thread_agent, &events);
  952.     }

  953.   info->td_create_bp_addr = 0;
  954.   info->td_death_bp_addr = 0;
  955. }

  956. static void
  957. check_thread_signals (void)
  958. {
  959.   if (!thread_signals)
  960.     {
  961.       sigset_t mask;
  962.       int i;

  963.       lin_thread_get_thread_signals (&mask);
  964.       sigemptyset (&thread_stop_set);
  965.       sigemptyset (&thread_print_set);

  966.       for (i = 1; i < NSIG; i++)
  967.         {
  968.           if (sigismember (&mask, i))
  969.             {
  970.               if (signal_stop_update (gdb_signal_from_host (i), 0))
  971.                 sigaddset (&thread_stop_set, i);
  972.               if (signal_print_update (gdb_signal_from_host (i), 0))
  973.                 sigaddset (&thread_print_set, i);
  974.               thread_signals = 1;
  975.             }
  976.         }
  977.     }
  978. }

  979. /* Check whether thread_db is usable.  This function is called when
  980.    an inferior is created (or otherwise acquired, e.g. attached to)
  981.    and when new shared libraries are loaded into a running process.  */

  982. void
  983. check_for_thread_db (void)
  984. {
  985.   /* Do nothing if we couldn't load libthread_db.so.1.  */
  986.   if (!thread_db_load ())
  987.     return;
  988. }

  989. /* This function is called via the new_objfile observer.  */

  990. static void
  991. thread_db_new_objfile (struct objfile *objfile)
  992. {
  993.   /* This observer must always be called with inferior_ptid set
  994.      correctly.  */

  995.   if (objfile != NULL
  996.       /* libpthread with separate debug info has its debug info file already
  997.          loaded (and notified without successful thread_db initialization)
  998.          the time observer_notify_new_objfile is called for the library itself.
  999.          Static executables have their separate debug info loaded already
  1000.          before the inferior has started.  */
  1001.       && objfile->separate_debug_objfile_backlink == NULL
  1002.       /* Only check for thread_db if we loaded libpthread,
  1003.          or if this is the main symbol file.
  1004.          We need to check OBJF_MAINLINE to handle the case of debugging
  1005.          a statically linked executable AND the symbol file is specified AFTER
  1006.          the exec file is loaded (e.g., gdb -c core ; file foo).
  1007.          For dynamically linked executables, libpthread can be near the end
  1008.          of the list of shared libraries to load, and in an app of several
  1009.          thousand shared libraries, this can otherwise be painful.  */
  1010.       && ((objfile->flags & OBJF_MAINLINE) != 0
  1011.           || libpthread_name_p (objfile_name (objfile))))
  1012.     check_for_thread_db ();
  1013. }

  1014. static void
  1015. check_pid_namespace_match (void)
  1016. {
  1017.   /* Check is only relevant for local targets targets.  */
  1018.   if (target_can_run (&current_target))
  1019.     {
  1020.       /* If the child is in a different PID namespace, its idea of its
  1021.          PID will differ from our idea of its PID.  When we scan the
  1022.          child's thread list, we'll mistakenly think it has no threads
  1023.          since the thread PID fields won't match the PID we give to
  1024.          libthread_db.  */
  1025.       char *our_pid_ns = linux_proc_pid_get_ns (getpid (), "pid");
  1026.       char *inferior_pid_ns = linux_proc_pid_get_ns (
  1027.         ptid_get_pid (inferior_ptid), "pid");

  1028.       if (our_pid_ns != NULL && inferior_pid_ns != NULL
  1029.           && strcmp (our_pid_ns, inferior_pid_ns) != 0)
  1030.         {
  1031.           warning (_ ("Target and debugger are in different PID "
  1032.                       "namespaces; thread lists and other data are "
  1033.                       "likely unreliable"));
  1034.         }

  1035.       xfree (our_pid_ns);
  1036.       xfree (inferior_pid_ns);
  1037.     }
  1038. }

  1039. /* This function is called via the inferior_created observer.
  1040.    This handles the case of debugging statically linked executables.  */

  1041. static void
  1042. thread_db_inferior_created (struct target_ops *target, int from_tty)
  1043. {
  1044.   check_pid_namespace_match ();
  1045.   check_for_thread_db ();
  1046. }

  1047. /* Update the thread's state (what's displayed in "info threads"),
  1048.    from libthread_db thread state information.  */

  1049. static void
  1050. update_thread_state (struct private_thread_info *private,
  1051.                      const td_thrinfo_t *ti_p)
  1052. {
  1053.   private->dying = (ti_p->ti_state == TD_THR_UNKNOWN
  1054.                     || ti_p->ti_state == TD_THR_ZOMBIE);
  1055. }

  1056. /* Attach to a new thread.  This function is called when we receive a
  1057.    TD_CREATE event or when we iterate over all threads and find one
  1058.    that wasn't already in our list.  Returns true on success.  */

  1059. static int
  1060. attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
  1061.                const td_thrinfo_t *ti_p)
  1062. {
  1063.   struct private_thread_info *private;
  1064.   struct thread_info *tp;
  1065.   td_err_e err;
  1066.   struct thread_db_info *info;

  1067.   /* If we're being called after a TD_CREATE event, we may already
  1068.      know about this thread.  There are two ways this can happen.  We
  1069.      may have iterated over all threads between the thread creation
  1070.      and the TD_CREATE event, for instance when the user has issued
  1071.      the `info threads' command before the SIGTRAP for hitting the
  1072.      thread creation breakpoint was reported.  Alternatively, the
  1073.      thread may have exited and a new one been created with the same
  1074.      thread ID.  In the first case we don't need to do anything; in
  1075.      the second case we should discard information about the dead
  1076.      thread and attach to the new one.  */
  1077.   tp = find_thread_ptid (ptid);
  1078.   if (tp != NULL)
  1079.     {
  1080.       /* If tp->private is NULL, then GDB is already attached to this
  1081.          thread, but we do not know anything about it.  We can learn
  1082.          about it here.  This can only happen if we have some other
  1083.          way besides libthread_db to notice new threads (i.e.
  1084.          PTRACE_EVENT_CLONE); assume the same mechanism notices thread
  1085.          exit, so this can not be a stale thread recreated with the
  1086.          same ID.  */
  1087.       if (tp->private != NULL)
  1088.         {
  1089.           if (!tp->private->dying)
  1090.             return 0;

  1091.           delete_thread (ptid);
  1092.           tp = NULL;
  1093.         }
  1094.     }

  1095.   if (target_has_execution)
  1096.     check_thread_signals ();

  1097.   /* Under GNU/Linux, we have to attach to each and every thread.  */
  1098.   if (target_has_execution
  1099.       && tp == NULL)
  1100.     {
  1101.       int res;

  1102.       res = lin_lwp_attach_lwp (ptid_build (ptid_get_pid (ptid),
  1103.                                             ti_p->ti_lid, 0));
  1104.       if (res < 0)
  1105.         {
  1106.           /* Error, stop iterating.  */
  1107.           return 0;
  1108.         }
  1109.       else if (res > 0)
  1110.         {
  1111.           /* Pretend this thread doesn't exist yet, and keep
  1112.              iterating.  */
  1113.           return 1;
  1114.         }

  1115.       /* Otherwise, we sucessfully attached to the thread.  */
  1116.     }

  1117.   /* Construct the thread's private data.  */
  1118.   private = xmalloc (sizeof (struct private_thread_info));
  1119.   memset (private, 0, sizeof (struct private_thread_info));

  1120.   /* A thread ID of zero may mean the thread library has not initialized
  1121.      yet.  But we shouldn't even get here if that's the case.  FIXME:
  1122.      if we change GDB to always have at least one thread in the thread
  1123.      list this will have to go somewhere else; maybe private == NULL
  1124.      until the thread_db target claims it.  */
  1125.   gdb_assert (ti_p->ti_tid != 0);
  1126.   private->th = *th_p;
  1127.   private->tid = ti_p->ti_tid;
  1128.   update_thread_state (private, ti_p);

  1129.   /* Add the thread to GDB's thread list.  */
  1130.   if (tp == NULL)
  1131.     add_thread_with_info (ptid, private);
  1132.   else
  1133.     tp->private = private;

  1134.   info = get_thread_db_info (ptid_get_pid (ptid));

  1135.   /* Enable thread event reporting for this thread, except when
  1136.      debugging a core file.  */
  1137.   if (target_has_execution && thread_db_use_events ())
  1138.     {
  1139.       err = info->td_thr_event_enable_p (th_p, 1);
  1140.       if (err != TD_OK)
  1141.         error (_("Cannot enable thread event reporting for %s: %s"),
  1142.                target_pid_to_str (ptid), thread_db_err_str (err));
  1143.     }

  1144.   return 1;
  1145. }

  1146. static void
  1147. detach_thread (ptid_t ptid)
  1148. {
  1149.   struct thread_info *thread_info;

  1150.   /* Don't delete the thread now, because it still reports as active
  1151.      until it has executed a few instructions after the event
  1152.      breakpoint - if we deleted it now, "info threads" would cause us
  1153.      to re-attach to it.  Just mark it as having had a TD_DEATH
  1154.      event.  This means that we won't delete it from our thread list
  1155.      until we notice that it's dead (via prune_threads), or until
  1156.      something re-uses its thread ID.  We'll report the thread exit
  1157.      when the underlying LWP dies.  */
  1158.   thread_info = find_thread_ptid (ptid);
  1159.   gdb_assert (thread_info != NULL && thread_info->private != NULL);
  1160.   thread_info->private->dying = 1;
  1161. }

  1162. static void
  1163. thread_db_detach (struct target_ops *ops, const char *args, int from_tty)
  1164. {
  1165.   struct target_ops *target_beneath = find_target_beneath (ops);
  1166.   struct thread_db_info *info;

  1167.   info = get_thread_db_info (ptid_get_pid (inferior_ptid));

  1168.   if (info)
  1169.     {
  1170.       if (target_has_execution && thread_db_use_events ())
  1171.         {
  1172.           disable_thread_event_reporting (info);

  1173.           /* Delete the old thread event breakpoints.  Note that
  1174.              unlike when mourning, we can remove them here because
  1175.              there's still a live inferior to poke at.  In any case,
  1176.              GDB will not try to insert anything in the inferior when
  1177.              removing a breakpoint.  */
  1178.           remove_thread_event_breakpoints ();
  1179.         }

  1180.       delete_thread_db_info (ptid_get_pid (inferior_ptid));
  1181.     }

  1182.   target_beneath->to_detach (target_beneath, args, from_tty);

  1183.   /* NOTE: From this point on, inferior_ptid is null_ptid.  */

  1184.   /* If there are no more processes using libpthread, detach the
  1185.      thread_db target ops.  */
  1186.   if (!thread_db_list)
  1187.     unpush_target (&thread_db_ops);
  1188. }

  1189. /* Check if PID is currently stopped at the location of a thread event
  1190.    breakpoint location.  If it is, read the event message and act upon
  1191.    the event.  */

  1192. static void
  1193. check_event (ptid_t ptid)
  1194. {
  1195.   struct regcache *regcache = get_thread_regcache (ptid);
  1196.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  1197.   td_event_msg_t msg;
  1198.   td_thrinfo_t ti;
  1199.   td_err_e err;
  1200.   CORE_ADDR stop_pc;
  1201.   int loop = 0;
  1202.   struct thread_db_info *info;

  1203.   info = get_thread_db_info (ptid_get_pid (ptid));

  1204.   /* Bail out early if we're not at a thread event breakpoint.  */
  1205.   stop_pc = regcache_read_pc (regcache)
  1206.             - target_decr_pc_after_break (gdbarch);
  1207.   if (stop_pc != info->td_create_bp_addr
  1208.       && stop_pc != info->td_death_bp_addr)
  1209.     return;

  1210.   /* Access an lwp we know is stopped.  */
  1211.   info->proc_handle.ptid = ptid;

  1212.   /* If we have only looked at the first thread before libpthread was
  1213.      initialized, we may not know its thread ID yet.  Make sure we do
  1214.      before we add another thread to the list.  */
  1215.   if (!have_threads (ptid))
  1216.     thread_db_find_new_threads_1 (ptid);

  1217.   /* If we are at a create breakpoint, we do not know what new lwp
  1218.      was created and cannot specifically locate the event message for it.
  1219.      We have to call td_ta_event_getmsg() to get
  1220.      the latest message.  Since we have no way of correlating whether
  1221.      the event message we get back corresponds to our breakpoint, we must
  1222.      loop and read all event messages, processing them appropriately.
  1223.      This guarantees we will process the correct message before continuing
  1224.      from the breakpoint.

  1225.      Currently, death events are not enabled.  If they are enabled,
  1226.      the death event can use the td_thr_event_getmsg() interface to
  1227.      get the message specifically for that lwp and avoid looping
  1228.      below.  */

  1229.   loop = 1;

  1230.   do
  1231.     {
  1232.       err = info->td_ta_event_getmsg_p (info->thread_agent, &msg);
  1233.       if (err != TD_OK)
  1234.         {
  1235.           if (err == TD_NOMSG)
  1236.             return;

  1237.           error (_("Cannot get thread event message: %s"),
  1238.                  thread_db_err_str (err));
  1239.         }

  1240.       err = info->td_thr_get_info_p (msg.th_p, &ti);
  1241.       if (err != TD_OK)
  1242.         error (_("Cannot get thread info: %s"), thread_db_err_str (err));

  1243.       ptid = ptid_build (ptid_get_pid (ptid), ti.ti_lid, 0);

  1244.       switch (msg.event)
  1245.         {
  1246.         case TD_CREATE:
  1247.           /* Call attach_thread whether or not we already know about a
  1248.              thread with this thread ID.  */
  1249.           attach_thread (ptid, msg.th_p, &ti);

  1250.           break;

  1251.         case TD_DEATH:

  1252.           if (!in_thread_list (ptid))
  1253.             error (_("Spurious thread death event."));

  1254.           detach_thread (ptid);

  1255.           break;

  1256.         default:
  1257.           error (_("Spurious thread event."));
  1258.         }
  1259.     }
  1260.   while (loop);
  1261. }

  1262. static ptid_t
  1263. thread_db_wait (struct target_ops *ops,
  1264.                 ptid_t ptid, struct target_waitstatus *ourstatus,
  1265.                 int options)
  1266. {
  1267.   struct thread_db_info *info;
  1268.   struct target_ops *beneath = find_target_beneath (ops);

  1269.   ptid = beneath->to_wait (beneath, ptid, ourstatus, options);

  1270.   if (ourstatus->kind == TARGET_WAITKIND_IGNORE)
  1271.     return ptid;

  1272.   if (ourstatus->kind == TARGET_WAITKIND_EXITED
  1273.       || ourstatus->kind == TARGET_WAITKIND_SIGNALLED)
  1274.     return ptid;

  1275.   info = get_thread_db_info (ptid_get_pid (ptid));

  1276.   /* If this process isn't using thread_db, we're done.  */
  1277.   if (info == NULL)
  1278.     return ptid;

  1279.   if (ourstatus->kind == TARGET_WAITKIND_EXECD)
  1280.     {
  1281.       /* New image, it may or may not end up using thread_db.  Assume
  1282.          not unless we find otherwise.  */
  1283.       delete_thread_db_info (ptid_get_pid (ptid));
  1284.       if (!thread_db_list)
  1285.          unpush_target (&thread_db_ops);

  1286.       /* Thread event breakpoints are deleted by
  1287.          update_breakpoints_after_exec.  */

  1288.       return ptid;
  1289.     }

  1290.   /* If we do not know about the main thread yet, this would be a good time to
  1291.      find it.  */
  1292.   if (ourstatus->kind == TARGET_WAITKIND_STOPPED && !have_threads (ptid))
  1293.     thread_db_find_new_threads_1 (ptid);

  1294.   if (ourstatus->kind == TARGET_WAITKIND_STOPPED
  1295.       && ourstatus->value.sig == GDB_SIGNAL_TRAP)
  1296.     /* Check for a thread event.  */
  1297.     check_event (ptid);

  1298.   if (have_threads (ptid))
  1299.     {
  1300.       /* Fill in the thread's user-level thread id.  */
  1301.       thread_from_lwp (ptid);
  1302.     }

  1303.   return ptid;
  1304. }

  1305. static void
  1306. thread_db_mourn_inferior (struct target_ops *ops)
  1307. {
  1308.   struct target_ops *target_beneath = find_target_beneath (ops);

  1309.   delete_thread_db_info (ptid_get_pid (inferior_ptid));

  1310.   target_beneath->to_mourn_inferior (target_beneath);

  1311.   /* Delete the old thread event breakpoints.  Do this after mourning
  1312.      the inferior, so that we don't try to uninsert them.  */
  1313.   remove_thread_event_breakpoints ();

  1314.   /* Detach thread_db target ops.  */
  1315.   if (!thread_db_list)
  1316.     unpush_target (ops);
  1317. }

  1318. struct callback_data
  1319. {
  1320.   struct thread_db_info *info;
  1321.   int new_threads;
  1322. };

  1323. static int
  1324. find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
  1325. {
  1326.   td_thrinfo_t ti;
  1327.   td_err_e err;
  1328.   ptid_t ptid;
  1329.   struct thread_info *tp;
  1330.   struct callback_data *cb_data = data;
  1331.   struct thread_db_info *info = cb_data->info;

  1332.   err = info->td_thr_get_info_p (th_p, &ti);
  1333.   if (err != TD_OK)
  1334.     error (_("find_new_threads_callback: cannot get thread info: %s"),
  1335.            thread_db_err_str (err));

  1336.   if (ti.ti_lid == -1)
  1337.     {
  1338.       /* A thread with kernel thread ID -1 is either a thread that
  1339.          exited and was joined, or a thread that is being created but
  1340.          hasn't started yet, and that is reusing the tcb/stack of a
  1341.          thread that previously exited and was joined.  (glibc marks
  1342.          terminated and joined threads with kernel thread ID -1.  See
  1343.          glibc PR17707.  */
  1344.       return 0;
  1345.     }

  1346.   if (ti.ti_tid == 0)
  1347.     {
  1348.       /* A thread ID of zero means that this is the main thread, but
  1349.          glibc has not yet initialized thread-local storage and the
  1350.          pthread library.  We do not know what the thread's TID will
  1351.          be yet.  Just enable event reporting and otherwise ignore
  1352.          it.  */

  1353.       /* In that case, we're not stopped in a fork syscall and don't
  1354.          need this glibc bug workaround.  */
  1355.       info->need_stale_parent_threads_check = 0;

  1356.       if (target_has_execution && thread_db_use_events ())
  1357.         {
  1358.           err = info->td_thr_event_enable_p (th_p, 1);
  1359.           if (err != TD_OK)
  1360.             error (_("Cannot enable thread event reporting for LWP %d: %s"),
  1361.                    (int) ti.ti_lid, thread_db_err_str (err));
  1362.         }

  1363.       return 0;
  1364.     }

  1365.   /* Ignore stale parent threads, caused by glibc/BZ5983.  This is a
  1366.      bit expensive, as it needs to open /proc/pid/status, so try to
  1367.      avoid doing the work if we know we don't have to.  */
  1368.   if (info->need_stale_parent_threads_check)
  1369.     {
  1370.       int tgid = linux_proc_get_tgid (ti.ti_lid);

  1371.       if (tgid != -1 && tgid != info->pid)
  1372.         return 0;
  1373.     }

  1374.   ptid = ptid_build (info->pid, ti.ti_lid, 0);
  1375.   tp = find_thread_ptid (ptid);
  1376.   if (tp == NULL || tp->private == NULL)
  1377.     {
  1378.       if (attach_thread (ptid, th_p, &ti))
  1379.         cb_data->new_threads += 1;
  1380.       else
  1381.         /* Problem attaching this thread; perhaps it exited before we
  1382.            could attach it?
  1383.            This could mean that the thread list inside glibc itself is in
  1384.            inconsistent state, and libthread_db could go on looping forever
  1385.            (observed with glibc-2.3.6).  To prevent that, terminate
  1386.            iteration: thread_db_find_new_threads_2 will retry.  */
  1387.         return 1;
  1388.     }
  1389.   else if (target_has_execution && !thread_db_use_events ())
  1390.     {
  1391.       /* Need to update this if not using the libthread_db events
  1392.          (particularly, the TD_DEATH event).  */
  1393.       update_thread_state (tp->private, &ti);
  1394.     }

  1395.   return 0;
  1396. }

  1397. /* Helper for thread_db_find_new_threads_2.
  1398.    Returns number of new threads found.  */

  1399. static int
  1400. find_new_threads_once (struct thread_db_info *info, int iteration,
  1401.                        td_err_e *errp)
  1402. {
  1403.   volatile struct gdb_exception except;
  1404.   struct callback_data data;
  1405.   td_err_e err = TD_ERR;

  1406.   data.info = info;
  1407.   data.new_threads = 0;

  1408.   TRY_CATCH (except, RETURN_MASK_ERROR)
  1409.     {
  1410.       /* Iterate over all user-space threads to discover new threads.  */
  1411.       err = info->td_ta_thr_iter_p (info->thread_agent,
  1412.                                     find_new_threads_callback,
  1413.                                     &data,
  1414.                                     TD_THR_ANY_STATE,
  1415.                                     TD_THR_LOWEST_PRIORITY,
  1416.                                     TD_SIGNO_MASK,
  1417.                                     TD_THR_ANY_USER_FLAGS);
  1418.     }

  1419.   if (libthread_db_debug)
  1420.     {
  1421.       if (except.reason < 0)
  1422.         exception_fprintf (gdb_stdlog, except,
  1423.                            "Warning: find_new_threads_once: ");

  1424.       fprintf_unfiltered (gdb_stdlog,
  1425.                           _("Found %d new threads in iteration %d.\n"),
  1426.                           data.new_threads, iteration);
  1427.     }

  1428.   if (errp != NULL)
  1429.     *errp = err;

  1430.   return data.new_threads;
  1431. }

  1432. /* Search for new threads, accessing memory through stopped thread
  1433.    PTID.  If UNTIL_NO_NEW is true, repeat searching until several
  1434.    searches in a row do not discover any new threads.  */

  1435. static void
  1436. thread_db_find_new_threads_2 (ptid_t ptid, int until_no_new)
  1437. {
  1438.   td_err_e err = TD_OK;
  1439.   struct thread_db_info *info;
  1440.   int i, loop;

  1441.   info = get_thread_db_info (ptid_get_pid (ptid));

  1442.   /* Access an lwp we know is stopped.  */
  1443.   info->proc_handle.ptid = ptid;

  1444.   if (until_no_new)
  1445.     {
  1446.       /* Require 4 successive iterations which do not find any new threads.
  1447.          The 4 is a heuristic: there is an inherent race here, and I have
  1448.          seen that 2 iterations in a row are not always sufficient to
  1449.          "capture" all threads.  */
  1450.       for (i = 0, loop = 0; loop < 4 && err == TD_OK; ++i, ++loop)
  1451.         if (find_new_threads_once (info, i, &err) != 0)
  1452.           {
  1453.             /* Found some new threads.  Restart the loop from beginning.  */
  1454.             loop = -1;
  1455.           }
  1456.     }
  1457.   else
  1458.     find_new_threads_once (info, 0, &err);

  1459.   if (err != TD_OK)
  1460.     error (_("Cannot find new threads: %s"), thread_db_err_str (err));
  1461. }

  1462. static void
  1463. thread_db_find_new_threads_1 (ptid_t ptid)
  1464. {
  1465.   thread_db_find_new_threads_2 (ptid, 0);
  1466. }

  1467. static int
  1468. update_thread_core (struct lwp_info *info, void *closure)
  1469. {
  1470.   info->core = linux_common_core_of_thread (info->ptid);
  1471.   return 0;
  1472. }

  1473. static void
  1474. thread_db_update_thread_list (struct target_ops *ops)
  1475. {
  1476.   struct thread_db_info *info;
  1477.   struct inferior *inf;

  1478.   prune_threads ();

  1479.   ALL_INFERIORS (inf)
  1480.     {
  1481.       struct thread_info *thread;

  1482.       if (inf->pid == 0)
  1483.         continue;

  1484.       info = get_thread_db_info (inf->pid);
  1485.       if (info == NULL)
  1486.         continue;

  1487.       thread = any_live_thread_of_process (inf->pid);
  1488.       if (thread == NULL || thread->executing)
  1489.         continue;

  1490.       thread_db_find_new_threads_1 (thread->ptid);
  1491.     }

  1492.   if (target_has_execution)
  1493.     iterate_over_lwps (minus_one_ptid /* iterate over all */,
  1494.                        update_thread_core, NULL);
  1495. }

  1496. static char *
  1497. thread_db_pid_to_str (struct target_ops *ops, ptid_t ptid)
  1498. {
  1499.   struct thread_info *thread_info = find_thread_ptid (ptid);
  1500.   struct target_ops *beneath;

  1501.   if (thread_info != NULL && thread_info->private != NULL)
  1502.     {
  1503.       static char buf[64];
  1504.       thread_t tid;

  1505.       tid = thread_info->private->tid;
  1506.       snprintf (buf, sizeof (buf), "Thread 0x%lx (LWP %ld)",
  1507.                 tid, ptid_get_lwp (ptid));

  1508.       return buf;
  1509.     }

  1510.   beneath = find_target_beneath (ops);
  1511.   return beneath->to_pid_to_str (beneath, ptid);
  1512. }

  1513. /* Return a string describing the state of the thread specified by
  1514.    INFO.  */

  1515. static char *
  1516. thread_db_extra_thread_info (struct target_ops *self,
  1517.                              struct thread_info *info)
  1518. {
  1519.   if (info->private == NULL)
  1520.     return NULL;

  1521.   if (info->private->dying)
  1522.     return "Exiting";

  1523.   return NULL;
  1524. }

  1525. /* Get the address of the thread local variable in load module LM which
  1526.    is stored at OFFSET within the thread local storage for thread PTID.  */

  1527. static CORE_ADDR
  1528. thread_db_get_thread_local_address (struct target_ops *ops,
  1529.                                     ptid_t ptid,
  1530.                                     CORE_ADDR lm,
  1531.                                     CORE_ADDR offset)
  1532. {
  1533.   struct thread_info *thread_info;
  1534.   struct target_ops *beneath;

  1535.   /* If we have not discovered any threads yet, check now.  */
  1536.   if (!have_threads (ptid))
  1537.     thread_db_find_new_threads_1 (ptid);

  1538.   /* Find the matching thread.  */
  1539.   thread_info = find_thread_ptid (ptid);

  1540.   if (thread_info != NULL && thread_info->private != NULL)
  1541.     {
  1542.       td_err_e err;
  1543.       psaddr_t address;
  1544.       struct thread_db_info *info;

  1545.       info = get_thread_db_info (ptid_get_pid (ptid));

  1546.       /* Finally, get the address of the variable.  */
  1547.       if (lm != 0)
  1548.         {
  1549.           /* glibc doesn't provide the needed interface.  */
  1550.           if (!info->td_thr_tls_get_addr_p)
  1551.             throw_error (TLS_NO_LIBRARY_SUPPORT_ERROR,
  1552.                          _("No TLS library support"));

  1553.           /* Note the cast through uintptr_t: this interface only works if
  1554.              a target address fits in a psaddr_t, which is a host pointer.
  1555.              So a 32-bit debugger can not access 64-bit TLS through this.  */
  1556.           err = info->td_thr_tls_get_addr_p (&thread_info->private->th,
  1557.                                              (psaddr_t)(uintptr_t) lm,
  1558.                                              offset, &address);
  1559.         }
  1560.       else
  1561.         {
  1562.           /* If glibc doesn't provide the needed interface throw an error
  1563.              that LM is zero - normally cases it should not be.  */
  1564.           if (!info->td_thr_tlsbase_p)
  1565.             throw_error (TLS_LOAD_MODULE_NOT_FOUND_ERROR,
  1566.                          _("TLS load module not found"));

  1567.           /* This code path handles the case of -static -pthread executables:
  1568.              https://sourceware.org/ml/libc-help/2014-03/msg00024.html
  1569.              For older GNU libc r_debug.r_map is NULL.  For GNU libc after
  1570.              PR libc/16831 due to GDB PR threads/16954 LOAD_MODULE is also NULL.
  1571.              The constant number 1 depends on GNU __libc_setup_tls
  1572.              initialization of l_tls_modid to 1.  */
  1573.           err = info->td_thr_tlsbase_p (&thread_info->private->th,
  1574.                                         1, &address);
  1575.           address = (char *) address + offset;
  1576.         }

  1577. #ifdef THREAD_DB_HAS_TD_NOTALLOC
  1578.       /* The memory hasn't been allocated, yet.  */
  1579.       if (err == TD_NOTALLOC)
  1580.           /* Now, if libthread_db provided the initialization image's
  1581.              address, we *could* try to build a non-lvalue value from
  1582.              the initialization image.  */
  1583.         throw_error (TLS_NOT_ALLOCATED_YET_ERROR,
  1584.                      _("TLS not allocated yet"));
  1585. #endif

  1586.       /* Something else went wrong.  */
  1587.       if (err != TD_OK)
  1588.         throw_error (TLS_GENERIC_ERROR,
  1589.                      (("%s")), thread_db_err_str (err));

  1590.       /* Cast assuming host == target.  Joy.  */
  1591.       /* Do proper sign extension for the target.  */
  1592.       gdb_assert (exec_bfd);
  1593.       return (bfd_get_sign_extend_vma (exec_bfd) > 0
  1594.               ? (CORE_ADDR) (intptr_t) address
  1595.               : (CORE_ADDR) (uintptr_t) address);
  1596.     }

  1597.   beneath = find_target_beneath (ops);
  1598.   return beneath->to_get_thread_local_address (beneath, ptid, lm, offset);
  1599. }

  1600. /* Callback routine used to find a thread based on the TID part of
  1601.    its PTID.  */

  1602. static int
  1603. thread_db_find_thread_from_tid (struct thread_info *thread, void *data)
  1604. {
  1605.   long *tid = (long *) data;

  1606.   if (thread->private->tid == *tid)
  1607.     return 1;

  1608.   return 0;
  1609. }

  1610. /* Implement the to_get_ada_task_ptid target method for this target.  */

  1611. static ptid_t
  1612. thread_db_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
  1613. {
  1614.   struct thread_info *thread_info;

  1615.   thread_db_find_new_threads_1 (inferior_ptid);
  1616.   thread_info = iterate_over_threads (thread_db_find_thread_from_tid, &thread);

  1617.   gdb_assert (thread_info != NULL);

  1618.   return (thread_info->ptid);
  1619. }

  1620. static void
  1621. thread_db_resume (struct target_ops *ops,
  1622.                   ptid_t ptid, int step, enum gdb_signal signo)
  1623. {
  1624.   struct target_ops *beneath = find_target_beneath (ops);
  1625.   struct thread_db_info *info;

  1626.   if (ptid_equal (ptid, minus_one_ptid))
  1627.     info = get_thread_db_info (ptid_get_pid (inferior_ptid));
  1628.   else
  1629.     info = get_thread_db_info (ptid_get_pid (ptid));

  1630.   /* This workaround is only needed for child fork lwps stopped in a
  1631.      PTRACE_O_TRACEFORK event.  When the inferior is resumed, the
  1632.      workaround can be disabled.  */
  1633.   if (info)
  1634.     info->need_stale_parent_threads_check = 0;

  1635.   beneath->to_resume (beneath, ptid, step, signo);
  1636. }

  1637. /* qsort helper function for info_auto_load_libthread_db, sort the
  1638.    thread_db_info pointers primarily by their FILENAME and secondarily by their
  1639.    PID, both in ascending order.  */

  1640. static int
  1641. info_auto_load_libthread_db_compare (const void *ap, const void *bp)
  1642. {
  1643.   struct thread_db_info *a = *(struct thread_db_info **) ap;
  1644.   struct thread_db_info *b = *(struct thread_db_info **) bp;
  1645.   int retval;

  1646.   retval = strcmp (a->filename, b->filename);
  1647.   if (retval)
  1648.     return retval;

  1649.   return (a->pid > b->pid) - (a->pid - b->pid);
  1650. }

  1651. /* Implement 'info auto-load libthread-db'.  */

  1652. static void
  1653. info_auto_load_libthread_db (char *args, int from_tty)
  1654. {
  1655.   struct ui_out *uiout = current_uiout;
  1656.   const char *cs = args ? args : "";
  1657.   struct thread_db_info *info, **array;
  1658.   unsigned info_count, unique_filenames;
  1659.   size_t max_filename_len, max_pids_len, pids_len;
  1660.   struct cleanup *back_to;
  1661.   char *pids;
  1662.   int i;

  1663.   cs = skip_spaces_const (cs);
  1664.   if (*cs)
  1665.     error (_("'info auto-load libthread-db' does not accept any parameters"));

  1666.   info_count = 0;
  1667.   for (info = thread_db_list; info; info = info->next)
  1668.     if (info->filename != NULL)
  1669.       info_count++;

  1670.   array = xmalloc (sizeof (*array) * info_count);
  1671.   back_to = make_cleanup (xfree, array);

  1672.   info_count = 0;
  1673.   for (info = thread_db_list; info; info = info->next)
  1674.     if (info->filename != NULL)
  1675.       array[info_count++] = info;

  1676.   /* Sort ARRAY by filenames and PIDs.  */

  1677.   qsort (array, info_count, sizeof (*array),
  1678.          info_auto_load_libthread_db_compare);

  1679.   /* Calculate the number of unique filenames (rows) and the maximum string
  1680.      length of PIDs list for the unique filenames (columns).  */

  1681.   unique_filenames = 0;
  1682.   max_filename_len = 0;
  1683.   max_pids_len = 0;
  1684.   pids_len = 0;
  1685.   for (i = 0; i < info_count; i++)
  1686.     {
  1687.       int pid = array[i]->pid;
  1688.       size_t this_pid_len;

  1689.       for (this_pid_len = 0; pid != 0; pid /= 10)
  1690.         this_pid_len++;

  1691.       if (i == 0 || strcmp (array[i - 1]->filename, array[i]->filename) != 0)
  1692.         {
  1693.           unique_filenames++;
  1694.           max_filename_len = max (max_filename_len,
  1695.                                   strlen (array[i]->filename));

  1696.           if (i > 0)
  1697.             {
  1698.               pids_len -= strlen (", ");
  1699.               max_pids_len = max (max_pids_len, pids_len);
  1700.             }
  1701.           pids_len = 0;
  1702.         }
  1703.       pids_len += this_pid_len + strlen (", ");
  1704.     }
  1705.   if (i)
  1706.     {
  1707.       pids_len -= strlen (", ");
  1708.       max_pids_len = max (max_pids_len, pids_len);
  1709.     }

  1710.   /* Table header shifted right by preceding "libthread-db:  " would not match
  1711.      its columns.  */
  1712.   if (info_count > 0 && args == auto_load_info_scripts_pattern_nl)
  1713.     ui_out_text (uiout, "\n");

  1714.   make_cleanup_ui_out_table_begin_end (uiout, 2, unique_filenames,
  1715.                                        "LinuxThreadDbTable");

  1716.   ui_out_table_header (uiout, max_filename_len, ui_left, "filename",
  1717.                        "Filename");
  1718.   ui_out_table_header (uiout, pids_len, ui_left, "PIDs", "Pids");
  1719.   ui_out_table_body (uiout);

  1720.   pids = xmalloc (max_pids_len + 1);
  1721.   make_cleanup (xfree, pids);

  1722.   /* Note I is incremented inside the cycle, not at its end.  */
  1723.   for (i = 0; i < info_count;)
  1724.     {
  1725.       struct cleanup *chain = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
  1726.       char *pids_end;

  1727.       info = array[i];
  1728.       ui_out_field_string (uiout, "filename", info->filename);
  1729.       pids_end = pids;

  1730.       while (i < info_count && strcmp (info->filename, array[i]->filename) == 0)
  1731.         {
  1732.           if (pids_end != pids)
  1733.             {
  1734.               *pids_end++ = ',';
  1735.               *pids_end++ = ' ';
  1736.             }
  1737.           pids_end += xsnprintf (pids_end, &pids[max_pids_len + 1] - pids_end,
  1738.                                  "%u", array[i]->pid);
  1739.           gdb_assert (pids_end < &pids[max_pids_len + 1]);

  1740.           i++;
  1741.         }
  1742.       *pids_end = '\0';

  1743.       ui_out_field_string (uiout, "pids", pids);

  1744.       ui_out_text (uiout, "\n");
  1745.       do_cleanups (chain);
  1746.     }

  1747.   do_cleanups (back_to);

  1748.   if (info_count == 0)
  1749.     ui_out_message (uiout, 0, _("No auto-loaded libthread-db.\n"));
  1750. }

  1751. static void
  1752. init_thread_db_ops (void)
  1753. {
  1754.   thread_db_ops.to_shortname = "multi-thread";
  1755.   thread_db_ops.to_longname = "multi-threaded child process.";
  1756.   thread_db_ops.to_doc = "Threads and pthreads support.";
  1757.   thread_db_ops.to_detach = thread_db_detach;
  1758.   thread_db_ops.to_wait = thread_db_wait;
  1759.   thread_db_ops.to_resume = thread_db_resume;
  1760.   thread_db_ops.to_mourn_inferior = thread_db_mourn_inferior;
  1761.   thread_db_ops.to_update_thread_list = thread_db_update_thread_list;
  1762.   thread_db_ops.to_pid_to_str = thread_db_pid_to_str;
  1763.   thread_db_ops.to_stratum = thread_stratum;
  1764.   thread_db_ops.to_has_thread_control = tc_schedlock;
  1765.   thread_db_ops.to_get_thread_local_address
  1766.     = thread_db_get_thread_local_address;
  1767.   thread_db_ops.to_extra_thread_info = thread_db_extra_thread_info;
  1768.   thread_db_ops.to_get_ada_task_ptid = thread_db_get_ada_task_ptid;
  1769.   thread_db_ops.to_magic = OPS_MAGIC;

  1770.   complete_target_initialization (&thread_db_ops);
  1771. }

  1772. /* Provide a prototype to silence -Wmissing-prototypes.  */
  1773. extern initialize_file_ftype _initialize_thread_db;

  1774. void
  1775. _initialize_thread_db (void)
  1776. {
  1777.   init_thread_db_ops ();

  1778.   /* Defer loading of libthread_db.so until inferior is running.
  1779.      This allows gdb to load correct libthread_db for a given
  1780.      executable -- there could be mutiple versions of glibc,
  1781.      compiled with LinuxThreads or NPTL, and until there is
  1782.      a running inferior, we can't tell which libthread_db is
  1783.      the correct one to load.  */

  1784.   libthread_db_search_path = xstrdup (LIBTHREAD_DB_SEARCH_PATH);

  1785.   add_setshow_optional_filename_cmd ("libthread-db-search-path",
  1786.                                      class_support,
  1787.                                      &libthread_db_search_path, _("\
  1788. Set search path for libthread_db."), _("\
  1789. Show the current search path or libthread_db."), _("\
  1790. This path is used to search for libthread_db to be loaded into \
  1791. gdb itself.\n\
  1792. Its value is a colon (':') separate list of directories to search.\n\
  1793. Setting the search path to an empty list resets it to its default value."),
  1794.                             set_libthread_db_search_path,
  1795.                             NULL,
  1796.                             &setlist, &showlist);

  1797.   add_setshow_zuinteger_cmd ("libthread-db", class_maintenance,
  1798.                              &libthread_db_debug, _("\
  1799. Set libthread-db debugging."), _("\
  1800. Show libthread-db debugging."), _("\
  1801. When non-zero, libthread-db debugging is enabled."),
  1802.                              NULL,
  1803.                              show_libthread_db_debug,
  1804.                              &setdebuglist, &showdebuglist);

  1805.   add_setshow_boolean_cmd ("libthread-db", class_support,
  1806.                            &auto_load_thread_db, _("\
  1807. Enable or disable auto-loading of inferior specific libthread_db."), _("\
  1808. Show whether auto-loading inferior specific libthread_db is enabled."), _("\
  1809. If enabled, libthread_db will be searched in 'set libthread-db-search-path'\n\
  1810. locations to load libthread_db compatible with the inferior.\n\
  1811. Standard system libthread_db still gets loaded even with this option off.\n\
  1812. This options has security implications for untrusted inferiors."),
  1813.                            NULL, show_auto_load_thread_db,
  1814.                            auto_load_set_cmdlist_get (),
  1815.                            auto_load_show_cmdlist_get ());

  1816.   add_cmd ("libthread-db", class_info, info_auto_load_libthread_db,
  1817.            _("Print the list of loaded inferior specific libthread_db.\n\
  1818. Usage: info auto-load libthread-db"),
  1819.            auto_load_info_cmdlist_get ());

  1820.   /* Add ourselves to objfile event chain.  */
  1821.   observer_attach_new_objfile (thread_db_new_objfile);

  1822.   /* Add ourselves to inferior_created event chain.
  1823.      This is needed to handle debugging statically linked programs where
  1824.      the new_objfile observer won't get called for libpthread.  */
  1825.   observer_attach_inferior_created (thread_db_inferior_created);
  1826. }