1/* libthread_db assisted debugging support, generic parts.
2
3   Copyright (C) 1999-2020 Free Software Foundation, Inc.
4
5   This file is part of GDB.
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 3 of the License, or
10   (at your option) any later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20#include "defs.h"
21#include <dlfcn.h>
22#include "gdb_proc_service.h"
23#include "nat/gdb_thread_db.h"
24#include "gdbsupport/gdb_vecs.h"
25#include "bfd.h"
26#include "command.h"
27#include "gdbcmd.h"
28#include "gdbthread.h"
29#include "inferior.h"
30#include "infrun.h"
31#include "symfile.h"
32#include "objfiles.h"
33#include "target.h"
34#include "regcache.h"
35#include "solib.h"
36#include "solib-svr4.h"
37#include "gdbcore.h"
38#include "observable.h"
39#include "linux-nat.h"
40#include "nat/linux-procfs.h"
41#include "nat/linux-ptrace.h"
42#include "nat/linux-osdata.h"
43#include "auto-load.h"
44#include "cli/cli-utils.h"
45#include <signal.h>
46#include <ctype.h>
47#include "nat/linux-namespaces.h"
48#include <algorithm>
49#include "gdbsupport/pathstuff.h"
50#include "valprint.h"
51#include "cli/cli-style.h"
52
53/* GNU/Linux libthread_db support.
54
55   libthread_db is a library, provided along with libpthread.so, which
56   exposes the internals of the thread library to a debugger.  It
57   allows GDB to find existing threads, new threads as they are
58   created, thread IDs (usually, the result of pthread_self), and
59   thread-local variables.
60
61   The libthread_db interface originates on Solaris, where it is both
62   more powerful and more complicated.  This implementation only works
63   for NPTL, the glibc threading library.  It assumes that each thread
64   is permanently assigned to a single light-weight process (LWP).  At
65   some point it also supported the older LinuxThreads library, but it
66   no longer does.
67
68   libthread_db-specific information is stored in the "private" field
69   of struct thread_info.  When the field is NULL we do not yet have
70   information about the new thread; this could be temporary (created,
71   but the thread library's data structures do not reflect it yet)
72   or permanent (created using clone instead of pthread_create).
73
74   Process IDs managed by linux-thread-db.c match those used by
75   linux-nat.c: a common PID for all processes, an LWP ID for each
76   thread, and no TID.  We save the TID in private.  Keeping it out
77   of the ptid_t prevents thread IDs changing when libpthread is
78   loaded or unloaded.  */
79
80static const target_info thread_db_target_info = {
81  "multi-thread",
82  N_("multi-threaded child process."),
83  N_("Threads and pthreads support.")
84};
85
86class thread_db_target final : public target_ops
87{
88public:
89  const target_info &info () const override
90  { return thread_db_target_info; }
91
92  strata stratum () const override { return thread_stratum; }
93
94  void detach (inferior *, int) override;
95  ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
96  void resume (ptid_t, int, enum gdb_signal) override;
97  void mourn_inferior () override;
98  void update_thread_list () override;
99  std::string pid_to_str (ptid_t) override;
100  CORE_ADDR get_thread_local_address (ptid_t ptid,
101				      CORE_ADDR load_module_addr,
102				      CORE_ADDR offset) override;
103  const char *extra_thread_info (struct thread_info *) override;
104  ptid_t get_ada_task_ptid (long lwp, long thread) override;
105
106  thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
107					     int handle_len,
108					     inferior *inf) override;
109  gdb::byte_vector thread_info_to_thread_handle (struct thread_info *) override;
110};
111
112static char *libthread_db_search_path;
113
114/* Set to true if thread_db auto-loading is enabled
115   by the "set auto-load libthread-db" command.  */
116static bool auto_load_thread_db = true;
117
118/* Set to true if load-time libthread_db tests have been enabled
119   by the "maintenance set check-libthread-db" command.  */
120static bool check_thread_db_on_load = false;
121
122/* "show" command for the auto_load_thread_db configuration variable.  */
123
124static void
125show_auto_load_thread_db (struct ui_file *file, int from_tty,
126			  struct cmd_list_element *c, const char *value)
127{
128  fprintf_filtered (file, _("Auto-loading of inferior specific libthread_db "
129			    "is %s.\n"),
130		    value);
131}
132
133static void
134set_libthread_db_search_path (const char *ignored, int from_tty,
135			      struct cmd_list_element *c)
136{
137  if (*libthread_db_search_path == '\0')
138    {
139      xfree (libthread_db_search_path);
140      libthread_db_search_path = xstrdup (LIBTHREAD_DB_SEARCH_PATH);
141    }
142}
143
144/* If non-zero, print details of libthread_db processing.  */
145
146static unsigned int libthread_db_debug;
147
148static void
149show_libthread_db_debug (struct ui_file *file, int from_tty,
150			 struct cmd_list_element *c, const char *value)
151{
152  fprintf_filtered (file, _("libthread-db debugging is %s.\n"), value);
153}
154
155/* If we're running on GNU/Linux, we must explicitly attach to any new
156   threads.  */
157
158/* This module's target vector.  */
159static thread_db_target the_thread_db_target;
160
161/* Non-zero if we have determined the signals used by the threads
162   library.  */
163static int thread_signals;
164static sigset_t thread_stop_set;
165static sigset_t thread_print_set;
166
167struct thread_db_info
168{
169  struct thread_db_info *next;
170
171  /* The target this thread_db_info is bound to.  */
172  process_stratum_target *process_target;
173
174  /* Process id this object refers to.  */
175  int pid;
176
177  /* Handle from dlopen for libthread_db.so.  */
178  void *handle;
179
180  /* Absolute pathname from gdb_realpath to disk file used for dlopen-ing
181     HANDLE.  It may be NULL for system library.  */
182  char *filename;
183
184  /* Structure that identifies the child process for the
185     <proc_service.h> interface.  */
186  struct ps_prochandle proc_handle;
187
188  /* Connection to the libthread_db library.  */
189  td_thragent_t *thread_agent;
190
191  /* True if we need to apply the workaround for glibc/BZ5983.  When
192     we catch a PTRACE_O_TRACEFORK, and go query the child's thread
193     list, nptl_db returns the parent's threads in addition to the new
194     (single) child thread.  If this flag is set, we do extra work to
195     be able to ignore such stale entries.  */
196  int need_stale_parent_threads_check;
197
198  /* Pointers to the libthread_db functions.  */
199
200  td_init_ftype *td_init_p;
201  td_ta_new_ftype *td_ta_new_p;
202  td_ta_delete_ftype *td_ta_delete_p;
203  td_ta_map_lwp2thr_ftype *td_ta_map_lwp2thr_p;
204  td_ta_thr_iter_ftype *td_ta_thr_iter_p;
205  td_thr_get_info_ftype *td_thr_get_info_p;
206  td_thr_tls_get_addr_ftype *td_thr_tls_get_addr_p;
207  td_thr_tlsbase_ftype *td_thr_tlsbase_p;
208};
209
210/* List of known processes using thread_db, and the required
211   bookkeeping.  */
212struct thread_db_info *thread_db_list;
213
214static void thread_db_find_new_threads_1 (thread_info *stopped);
215static void thread_db_find_new_threads_2 (thread_info *stopped,
216					  bool until_no_new);
217
218static void check_thread_signals (void);
219
220static struct thread_info *record_thread
221  (struct thread_db_info *info, struct thread_info *tp,
222   ptid_t ptid, const td_thrhandle_t *th_p, const td_thrinfo_t *ti_p);
223
224/* Add the current inferior to the list of processes using libpthread.
225   Return a pointer to the newly allocated object that was added to
226   THREAD_DB_LIST.  HANDLE is the handle returned by dlopen'ing
227   LIBTHREAD_DB_SO.  */
228
229static struct thread_db_info *
230add_thread_db_info (void *handle)
231{
232  struct thread_db_info *info = XCNEW (struct thread_db_info);
233
234  info->process_target = current_inferior ()->process_target ();
235  info->pid = inferior_ptid.pid ();
236  info->handle = handle;
237
238  /* The workaround works by reading from /proc/pid/status, so it is
239     disabled for core files.  */
240  if (target_has_execution)
241    info->need_stale_parent_threads_check = 1;
242
243  info->next = thread_db_list;
244  thread_db_list = info;
245
246  return info;
247}
248
249/* Return the thread_db_info object representing the bookkeeping
250   related to process PID, if any; NULL otherwise.  */
251
252static struct thread_db_info *
253get_thread_db_info (process_stratum_target *targ, int pid)
254{
255  struct thread_db_info *info;
256
257  for (info = thread_db_list; info; info = info->next)
258    if (targ == info->process_target && pid == info->pid)
259      return info;
260
261  return NULL;
262}
263
264static const char *thread_db_err_str (td_err_e err);
265
266/* When PID has exited or has been detached, we no longer want to keep
267   track of it as using libpthread.  Call this function to discard
268   thread_db related info related to PID.  Note that this closes
269   LIBTHREAD_DB_SO's dlopen'ed handle.  */
270
271static void
272delete_thread_db_info (process_stratum_target *targ, int pid)
273{
274  struct thread_db_info *info, *info_prev;
275
276  info_prev = NULL;
277
278  for (info = thread_db_list; info; info_prev = info, info = info->next)
279    if (targ == info->process_target && pid == info->pid)
280      break;
281
282  if (info == NULL)
283    return;
284
285  if (info->thread_agent != NULL && info->td_ta_delete_p != NULL)
286    {
287      td_err_e err = info->td_ta_delete_p (info->thread_agent);
288
289      if (err != TD_OK)
290	warning (_("Cannot deregister process %d from libthread_db: %s"),
291		 pid, thread_db_err_str (err));
292      info->thread_agent = NULL;
293    }
294
295  if (info->handle != NULL)
296    dlclose (info->handle);
297
298  xfree (info->filename);
299
300  if (info_prev)
301    info_prev->next = info->next;
302  else
303    thread_db_list = info->next;
304
305  xfree (info);
306}
307
308/* Use "struct private_thread_info" to cache thread state.  This is
309   a substantial optimization.  */
310
311struct thread_db_thread_info : public private_thread_info
312{
313  /* Flag set when we see a TD_DEATH event for this thread.  */
314  bool dying = false;
315
316  /* Cached thread state.  */
317  td_thrhandle_t th {};
318  thread_t tid {};
319};
320
321static thread_db_thread_info *
322get_thread_db_thread_info (thread_info *thread)
323{
324  return static_cast<thread_db_thread_info *> (thread->priv.get ());
325}
326
327static const char *
328thread_db_err_str (td_err_e err)
329{
330  static char buf[64];
331
332  switch (err)
333    {
334    case TD_OK:
335      return "generic 'call succeeded'";
336    case TD_ERR:
337      return "generic error";
338    case TD_NOTHR:
339      return "no thread to satisfy query";
340    case TD_NOSV:
341      return "no sync handle to satisfy query";
342    case TD_NOLWP:
343      return "no LWP to satisfy query";
344    case TD_BADPH:
345      return "invalid process handle";
346    case TD_BADTH:
347      return "invalid thread handle";
348    case TD_BADSH:
349      return "invalid synchronization handle";
350    case TD_BADTA:
351      return "invalid thread agent";
352    case TD_BADKEY:
353      return "invalid key";
354    case TD_NOMSG:
355      return "no event message for getmsg";
356    case TD_NOFPREGS:
357      return "FPU register set not available";
358    case TD_NOLIBTHREAD:
359      return "application not linked with libthread";
360    case TD_NOEVENT:
361      return "requested event is not supported";
362    case TD_NOCAPAB:
363      return "capability not available";
364    case TD_DBERR:
365      return "debugger service failed";
366    case TD_NOAPLIC:
367      return "operation not applicable to";
368    case TD_NOTSD:
369      return "no thread-specific data for this thread";
370    case TD_MALLOC:
371      return "malloc failed";
372    case TD_PARTIALREG:
373      return "only part of register set was written/read";
374    case TD_NOXREGS:
375      return "X register set not available for this thread";
376#ifdef THREAD_DB_HAS_TD_NOTALLOC
377    case TD_NOTALLOC:
378      return "thread has not yet allocated TLS for given module";
379#endif
380#ifdef THREAD_DB_HAS_TD_VERSION
381    case TD_VERSION:
382      return "versions of libpthread and libthread_db do not match";
383#endif
384#ifdef THREAD_DB_HAS_TD_NOTLS
385    case TD_NOTLS:
386      return "there is no TLS segment in the given module";
387#endif
388    default:
389      snprintf (buf, sizeof (buf), "unknown thread_db error '%d'", err);
390      return buf;
391    }
392}
393
394/* Fetch the user-level thread id of PTID.  STOPPED is a stopped
395   thread that we can use to access memory.  */
396
397static struct thread_info *
398thread_from_lwp (thread_info *stopped, ptid_t ptid)
399{
400  td_thrhandle_t th;
401  td_thrinfo_t ti;
402  td_err_e err;
403  struct thread_db_info *info;
404  struct thread_info *tp;
405
406  /* Just in case td_ta_map_lwp2thr doesn't initialize it completely.  */
407  th.th_unique = 0;
408
409  /* This ptid comes from linux-nat.c, which should always fill in the
410     LWP.  */
411  gdb_assert (ptid.lwp () != 0);
412
413  info = get_thread_db_info (stopped->inf->process_target (), ptid.pid ());
414
415  /* Access an lwp we know is stopped.  */
416  info->proc_handle.thread = stopped;
417  err = info->td_ta_map_lwp2thr_p (info->thread_agent, ptid.lwp (),
418				   &th);
419  if (err != TD_OK)
420    error (_("Cannot find user-level thread for LWP %ld: %s"),
421	   ptid.lwp (), thread_db_err_str (err));
422
423  err = info->td_thr_get_info_p (&th, &ti);
424  if (err != TD_OK)
425    error (_("thread_get_info_callback: cannot get thread info: %s"),
426	   thread_db_err_str (err));
427
428  /* Fill the cache.  */
429  tp = find_thread_ptid (stopped->inf->process_target (), ptid);
430  return record_thread (info, tp, ptid, &th, &ti);
431}
432
433
434/* See linux-nat.h.  */
435
436int
437thread_db_notice_clone (ptid_t parent, ptid_t child)
438{
439  struct thread_db_info *info;
440
441  info = get_thread_db_info (linux_target, child.pid ());
442
443  if (info == NULL)
444    return 0;
445
446  thread_info *stopped = find_thread_ptid (linux_target, parent);
447
448  thread_from_lwp (stopped, child);
449
450  /* If we do not know about the main thread's pthread info yet, this
451     would be a good time to find it.  */
452  thread_from_lwp (stopped, parent);
453  return 1;
454}
455
456static void *
457verbose_dlsym (void *handle, const char *name)
458{
459  void *sym = dlsym (handle, name);
460  if (sym == NULL)
461    warning (_("Symbol \"%s\" not found in libthread_db: %s"),
462	     name, dlerror ());
463  return sym;
464}
465
466/* Verify inferior's '\0'-terminated symbol VER_SYMBOL starts with "%d.%d" and
467   return 1 if this version is lower (and not equal) to
468   VER_MAJOR_MIN.VER_MINOR_MIN.  Return 0 in all other cases.  */
469
470static int
471inferior_has_bug (const char *ver_symbol, int ver_major_min, int ver_minor_min)
472{
473  struct bound_minimal_symbol version_msym;
474  CORE_ADDR version_addr;
475  int got, retval = 0;
476
477  version_msym = lookup_minimal_symbol (ver_symbol, NULL, NULL);
478  if (version_msym.minsym == NULL)
479    return 0;
480
481  version_addr = BMSYMBOL_VALUE_ADDRESS (version_msym);
482  gdb::unique_xmalloc_ptr<char> version
483    = target_read_string (version_addr, 32, &got);
484  if (version != nullptr
485      && memchr (version.get (), 0, got) == version.get () + got - 1)
486    {
487      int major, minor;
488
489      retval = (sscanf (version.get (), "%d.%d", &major, &minor) == 2
490		&& (major < ver_major_min
491		    || (major == ver_major_min && minor < ver_minor_min)));
492    }
493
494  return retval;
495}
496
497/* Similar as thread_db_find_new_threads_1, but try to silently ignore errors
498   if appropriate.
499
500   Return 1 if the caller should abort libthread_db initialization.  Return 0
501   otherwise.  */
502
503static int
504thread_db_find_new_threads_silently (thread_info *stopped)
505{
506
507  try
508    {
509      thread_db_find_new_threads_2 (stopped, true);
510    }
511
512  catch (const gdb_exception_error &except)
513    {
514      if (libthread_db_debug)
515	exception_fprintf (gdb_stdlog, except,
516			   "Warning: thread_db_find_new_threads_silently: ");
517
518      /* There is a bug fixed between nptl 2.6.1 and 2.7 by
519	   commit 7d9d8bd18906fdd17364f372b160d7ab896ce909
520	 where calls to td_thr_get_info fail with TD_ERR for statically linked
521	 executables if td_thr_get_info is called before glibc has initialized
522	 itself.
523
524	 If the nptl bug is NOT present in the inferior and still thread_db
525	 reports an error return 1.  It means the inferior has corrupted thread
526	 list and GDB should fall back only to LWPs.
527
528	 If the nptl bug is present in the inferior return 0 to silently ignore
529	 such errors, and let gdb enumerate threads again later.  In such case
530	 GDB cannot properly display LWPs if the inferior thread list is
531	 corrupted.  For core files it does not apply, no 'later enumeration'
532	 is possible.  */
533
534      if (!target_has_execution || !inferior_has_bug ("nptl_version", 2, 7))
535	{
536	  exception_fprintf (gdb_stderr, except,
537			     _("Warning: couldn't activate thread debugging "
538			       "using libthread_db: "));
539	  return 1;
540	}
541    }
542
543  return 0;
544}
545
546/* Lookup a library in which given symbol resides.
547   Note: this is looking in GDB process, not in the inferior.
548   Returns library name, or NULL.  */
549
550static const char *
551dladdr_to_soname (const void *addr)
552{
553  Dl_info info;
554
555  if (dladdr (addr, &info) != 0)
556    return info.dli_fname;
557  return NULL;
558}
559
560/* State for check_thread_db_callback.  */
561
562struct check_thread_db_info
563{
564  /* The libthread_db under test.  */
565  struct thread_db_info *info;
566
567  /* True if progress should be logged.  */
568  bool log_progress;
569
570  /* True if the callback was called.  */
571  bool threads_seen;
572
573  /* Name of last libthread_db function called.  */
574  const char *last_call;
575
576  /* Value returned by last libthread_db call.  */
577  td_err_e last_result;
578};
579
580static struct check_thread_db_info *tdb_testinfo;
581
582/* Callback for check_thread_db.  */
583
584static int
585check_thread_db_callback (const td_thrhandle_t *th, void *arg)
586{
587  gdb_assert (tdb_testinfo != NULL);
588  tdb_testinfo->threads_seen = true;
589
590#define LOG(fmt, args...)						\
591  do									\
592    {									\
593      if (tdb_testinfo->log_progress)					\
594	{								\
595	  debug_printf (fmt, ## args);					\
596	  gdb_flush (gdb_stdlog);					\
597	}								\
598    }									\
599  while (0)
600
601#define CHECK_1(expr, args...)						\
602  do									\
603    {									\
604      if (!(expr))							\
605	{								\
606	  LOG (" ... FAIL!\n");						\
607	  error (args);							\
608	}								\
609    }									\
610  while (0)
611
612#define CHECK(expr)							\
613  CHECK_1 (expr, "(%s) == false", #expr)
614
615#define CALL_UNCHECKED(func, args...)					\
616  do									\
617    {									\
618      tdb_testinfo->last_call = #func;					\
619      tdb_testinfo->last_result						\
620	= tdb_testinfo->info->func ## _p (args);			\
621    }									\
622  while (0)
623
624#define CHECK_CALL()							\
625  CHECK_1 (tdb_testinfo->last_result == TD_OK,				\
626	   _("%s failed: %s"),						\
627	   tdb_testinfo->last_call,					\
628	   thread_db_err_str (tdb_testinfo->last_result))		\
629
630#define CALL(func, args...)						\
631  do									\
632    {									\
633      CALL_UNCHECKED (func, args);					\
634      CHECK_CALL ();							\
635    }									\
636  while (0)
637
638  LOG ("  Got thread");
639
640  /* Check td_ta_thr_iter passed consistent arguments.  */
641  CHECK (th != NULL);
642  CHECK (arg == (void *) tdb_testinfo);
643  CHECK (th->th_ta_p == tdb_testinfo->info->thread_agent);
644
645  LOG (" %s", core_addr_to_string_nz ((CORE_ADDR) th->th_unique));
646
647  /* Check td_thr_get_info.  */
648  td_thrinfo_t ti;
649  CALL (td_thr_get_info, th, &ti);
650
651  LOG (" => %d", ti.ti_lid);
652
653  CHECK (ti.ti_ta_p == th->th_ta_p);
654  CHECK (ti.ti_tid == (thread_t) th->th_unique);
655
656  /* Check td_ta_map_lwp2thr.  */
657  td_thrhandle_t th2;
658  memset (&th2, 23, sizeof (td_thrhandle_t));
659  CALL_UNCHECKED (td_ta_map_lwp2thr, th->th_ta_p, ti.ti_lid, &th2);
660
661  if (tdb_testinfo->last_result == TD_ERR && !target_has_execution)
662    {
663      /* Some platforms require execution for td_ta_map_lwp2thr.  */
664      LOG (_("; can't map_lwp2thr"));
665    }
666  else
667    {
668      CHECK_CALL ();
669
670      LOG (" => %s", core_addr_to_string_nz ((CORE_ADDR) th2.th_unique));
671
672      CHECK (memcmp (th, &th2, sizeof (td_thrhandle_t)) == 0);
673    }
674
675  /* Attempt TLS access.  Assuming errno is TLS, this calls
676     thread_db_get_thread_local_address, which in turn calls
677     td_thr_tls_get_addr for live inferiors or td_thr_tlsbase
678     for core files.  This test is skipped if the thread has
679     not been recorded; proceeding in that case would result
680     in the test having the side-effect of noticing threads
681     which seems wrong.
682
683     Note that in glibc's libthread_db td_thr_tls_get_addr is
684     a thin wrapper around td_thr_tlsbase; this check always
685     hits the bulk of the code.
686
687     Note also that we don't actually check any libthread_db
688     calls are made, we just assume they were; future changes
689     to how GDB accesses TLS could result in this passing
690     without exercising the calls it's supposed to.  */
691  ptid_t ptid = ptid_t (tdb_testinfo->info->pid, ti.ti_lid, 0);
692  thread_info *thread_info = find_thread_ptid (linux_target, ptid);
693  if (thread_info != NULL && thread_info->priv != NULL)
694    {
695      LOG ("; errno");
696
697      scoped_restore_current_thread restore_current_thread;
698      switch_to_thread (thread_info);
699
700      expression_up expr = parse_expression ("(int) errno");
701      struct value *val = evaluate_expression (expr.get ());
702
703      if (tdb_testinfo->log_progress)
704	{
705	  struct value_print_options opts;
706
707	  get_user_print_options (&opts);
708	  LOG (" = ");
709	  value_print (val, gdb_stdlog, &opts);
710	}
711    }
712
713  LOG (" ... OK\n");
714
715#undef LOG
716#undef CHECK_1
717#undef CHECK
718#undef CALL_UNCHECKED
719#undef CHECK_CALL
720#undef CALL
721
722  return 0;
723}
724
725/* Run integrity checks on the dlopen()ed libthread_db described by
726   INFO.  Returns true on success, displays a warning and returns
727   false on failure.  Logs progress messages to gdb_stdlog during
728   the test if LOG_PROGRESS is true.  */
729
730static bool
731check_thread_db (struct thread_db_info *info, bool log_progress)
732{
733  bool test_passed = true;
734
735  if (log_progress)
736    debug_printf (_("Running libthread_db integrity checks:\n"));
737
738  /* GDB avoids using td_ta_thr_iter wherever possible (see comment
739     in try_thread_db_load_1 below) so in order to test it we may
740     have to locate it ourselves.  */
741  td_ta_thr_iter_ftype *td_ta_thr_iter_p = info->td_ta_thr_iter_p;
742  if (td_ta_thr_iter_p == NULL)
743    {
744      void *thr_iter = verbose_dlsym (info->handle, "td_ta_thr_iter");
745      if (thr_iter == NULL)
746	return 0;
747
748      td_ta_thr_iter_p = (td_ta_thr_iter_ftype *) thr_iter;
749    }
750
751  /* Set up the test state we share with the callback.  */
752  gdb_assert (tdb_testinfo == NULL);
753  struct check_thread_db_info tdb_testinfo_buf;
754  tdb_testinfo = &tdb_testinfo_buf;
755
756  memset (tdb_testinfo, 0, sizeof (struct check_thread_db_info));
757  tdb_testinfo->info = info;
758  tdb_testinfo->log_progress = log_progress;
759
760  /* td_ta_thr_iter shouldn't be used on running processes.  Note that
761     it's possible the inferior will stop midway through modifying one
762     of its thread lists, in which case the check will spuriously
763     fail.  */
764  linux_stop_and_wait_all_lwps ();
765
766  try
767    {
768      td_err_e err = td_ta_thr_iter_p (info->thread_agent,
769				       check_thread_db_callback,
770				       tdb_testinfo,
771				       TD_THR_ANY_STATE,
772				       TD_THR_LOWEST_PRIORITY,
773				       TD_SIGNO_MASK,
774				       TD_THR_ANY_USER_FLAGS);
775
776      if (err != TD_OK)
777	error (_("td_ta_thr_iter failed: %s"), thread_db_err_str (err));
778
779      if (!tdb_testinfo->threads_seen)
780	error (_("no threads seen"));
781    }
782  catch (const gdb_exception_error &except)
783    {
784      if (warning_pre_print)
785	fputs_unfiltered (warning_pre_print, gdb_stderr);
786
787      exception_fprintf (gdb_stderr, except,
788			 _("libthread_db integrity checks failed: "));
789
790      test_passed = false;
791    }
792
793  if (test_passed && log_progress)
794    debug_printf (_("libthread_db integrity checks passed.\n"));
795
796  tdb_testinfo = NULL;
797
798  linux_unstop_all_lwps ();
799
800  return test_passed;
801}
802
803/* Attempt to initialize dlopen()ed libthread_db, described by INFO.
804   Return true on success.
805   Failure could happen if libthread_db does not have symbols we expect,
806   or when it refuses to work with the current inferior (e.g. due to
807   version mismatch between libthread_db and libpthread).  */
808
809static bool
810try_thread_db_load_1 (struct thread_db_info *info)
811{
812  td_err_e err;
813
814  /* Initialize pointers to the dynamic library functions we will use.
815     Essential functions first.  */
816
817#define TDB_VERBOSE_DLSYM(info, func)			\
818  info->func ## _p = (func ## _ftype *) verbose_dlsym (info->handle, #func)
819
820#define TDB_DLSYM(info, func)			\
821  info->func ## _p = (func ## _ftype *) dlsym (info->handle, #func)
822
823#define CHK(a)								\
824  do									\
825    {									\
826      if ((a) == NULL)							\
827	return false;							\
828  } while (0)
829
830  CHK (TDB_VERBOSE_DLSYM (info, td_init));
831
832  err = info->td_init_p ();
833  if (err != TD_OK)
834    {
835      warning (_("Cannot initialize libthread_db: %s"),
836	       thread_db_err_str (err));
837      return false;
838    }
839
840  CHK (TDB_VERBOSE_DLSYM (info, td_ta_new));
841
842  /* Initialize the structure that identifies the child process.  */
843  info->proc_handle.thread = inferior_thread ();
844
845  /* Now attempt to open a connection to the thread library.  */
846  err = info->td_ta_new_p (&info->proc_handle, &info->thread_agent);
847  if (err != TD_OK)
848    {
849      if (libthread_db_debug)
850	fprintf_unfiltered (gdb_stdlog, _("td_ta_new failed: %s\n"),
851			    thread_db_err_str (err));
852      else
853        switch (err)
854          {
855            case TD_NOLIBTHREAD:
856#ifdef THREAD_DB_HAS_TD_VERSION
857            case TD_VERSION:
858#endif
859              /* The errors above are not unexpected and silently ignored:
860                 they just mean we haven't found correct version of
861                 libthread_db yet.  */
862              break;
863            default:
864              warning (_("td_ta_new failed: %s"), thread_db_err_str (err));
865          }
866      return false;
867    }
868
869  /* These are essential.  */
870  CHK (TDB_VERBOSE_DLSYM (info, td_ta_map_lwp2thr));
871  CHK (TDB_VERBOSE_DLSYM (info, td_thr_get_info));
872
873  /* These are not essential.  */
874  TDB_DLSYM (info, td_thr_tls_get_addr);
875  TDB_DLSYM (info, td_thr_tlsbase);
876  TDB_DLSYM (info, td_ta_delete);
877
878  /* It's best to avoid td_ta_thr_iter if possible.  That walks data
879     structures in the inferior's address space that may be corrupted,
880     or, if the target is running, may change while we walk them.  If
881     there's execution (and /proc is mounted), then we're already
882     attached to all LWPs.  Use thread_from_lwp, which uses
883     td_ta_map_lwp2thr instead, which does not walk the thread list.
884
885     td_ta_map_lwp2thr uses ps_get_thread_area, but we can't use that
886     currently on core targets, as it uses ptrace directly.  */
887  if (target_has_execution
888      && linux_proc_task_list_dir_exists (inferior_ptid.pid ()))
889    info->td_ta_thr_iter_p = NULL;
890  else
891    CHK (TDB_VERBOSE_DLSYM (info, td_ta_thr_iter));
892
893#undef TDB_VERBOSE_DLSYM
894#undef TDB_DLSYM
895#undef CHK
896
897  /* Run integrity checks if requested.  */
898  if (check_thread_db_on_load)
899    {
900      if (!check_thread_db (info, libthread_db_debug))
901	return false;
902    }
903
904  if (info->td_ta_thr_iter_p == NULL)
905    {
906      struct lwp_info *lp;
907      int pid = inferior_ptid.pid ();
908      thread_info *curr_thread = inferior_thread ();
909
910      linux_stop_and_wait_all_lwps ();
911
912      ALL_LWPS (lp)
913	if (lp->ptid.pid () == pid)
914	  thread_from_lwp (curr_thread, lp->ptid);
915
916      linux_unstop_all_lwps ();
917    }
918  else if (thread_db_find_new_threads_silently (inferior_thread ()) != 0)
919    {
920      /* Even if libthread_db initializes, if the thread list is
921         corrupted, we'd not manage to list any threads.  Better reject this
922         thread_db, and fall back to at least listing LWPs.  */
923      return false;
924    }
925
926  printf_unfiltered (_("[Thread debugging using libthread_db enabled]\n"));
927
928  if (*libthread_db_search_path || libthread_db_debug)
929    {
930      struct ui_file *file;
931      const char *library;
932
933      library = dladdr_to_soname ((const void *) *info->td_ta_new_p);
934      if (library == NULL)
935	library = LIBTHREAD_DB_SO;
936
937      /* If we'd print this to gdb_stdout when debug output is
938	 disabled, still print it to gdb_stdout if debug output is
939	 enabled.  User visible output should not depend on debug
940	 settings.  */
941      file = *libthread_db_search_path != '\0' ? gdb_stdout : gdb_stdlog;
942      fprintf_unfiltered (file,
943			  _("Using host libthread_db library \"%ps\".\n"),
944			  styled_string (file_name_style.style (), library));
945    }
946
947  /* The thread library was detected.  Activate the thread_db target
948     for this process.  */
949  push_target (&the_thread_db_target);
950  return true;
951}
952
953/* Attempt to use LIBRARY as libthread_db.  LIBRARY could be absolute,
954   relative, or just LIBTHREAD_DB.  */
955
956static bool
957try_thread_db_load (const char *library, bool check_auto_load_safe)
958{
959  void *handle;
960  struct thread_db_info *info;
961
962  if (libthread_db_debug)
963    fprintf_unfiltered (gdb_stdlog,
964			_("Trying host libthread_db library: %s.\n"),
965			library);
966
967  if (check_auto_load_safe)
968    {
969      if (access (library, R_OK) != 0)
970	{
971	  /* Do not print warnings by file_is_auto_load_safe if the library does
972	     not exist at this place.  */
973	  if (libthread_db_debug)
974	    fprintf_unfiltered (gdb_stdlog, _("open failed: %s.\n"),
975				safe_strerror (errno));
976	  return false;
977	}
978
979      if (!file_is_auto_load_safe (library, _("auto-load: Loading libthread-db "
980					      "library \"%s\" from explicit "
981					      "directory.\n"),
982				   library))
983	return false;
984    }
985
986  handle = dlopen (library, RTLD_NOW);
987  if (handle == NULL)
988    {
989      if (libthread_db_debug)
990	fprintf_unfiltered (gdb_stdlog, _("dlopen failed: %s.\n"), dlerror ());
991      return false;
992    }
993
994  if (libthread_db_debug && strchr (library, '/') == NULL)
995    {
996      void *td_init;
997
998      td_init = dlsym (handle, "td_init");
999      if (td_init != NULL)
1000        {
1001          const char *const libpath = dladdr_to_soname (td_init);
1002
1003          if (libpath != NULL)
1004            fprintf_unfiltered (gdb_stdlog, _("Host %s resolved to: %s.\n"),
1005                               library, libpath);
1006        }
1007    }
1008
1009  info = add_thread_db_info (handle);
1010
1011  /* Do not save system library name, that one is always trusted.  */
1012  if (strchr (library, '/') != NULL)
1013    info->filename = gdb_realpath (library).release ();
1014
1015  if (try_thread_db_load_1 (info))
1016    return true;
1017
1018  /* This library "refused" to work on current inferior.  */
1019  delete_thread_db_info (current_inferior ()->process_target (),
1020			 inferior_ptid.pid ());
1021  return false;
1022}
1023
1024/* Subroutine of try_thread_db_load_from_pdir to simplify it.
1025   Try loading libthread_db in directory(OBJ)/SUBDIR.
1026   SUBDIR may be NULL.  It may also be something like "../lib64".
1027   The result is true for success.  */
1028
1029static bool
1030try_thread_db_load_from_pdir_1 (struct objfile *obj, const char *subdir)
1031{
1032  const char *obj_name = objfile_name (obj);
1033
1034  if (obj_name[0] != '/')
1035    {
1036      warning (_("Expected absolute pathname for libpthread in the"
1037		 " inferior, but got %ps."),
1038	       styled_string (file_name_style.style (), obj_name));
1039      return false;
1040    }
1041
1042  std::string path = obj_name;
1043  size_t cp = path.rfind ('/');
1044  /* This should at minimum hit the first character.  */
1045  gdb_assert (cp != std::string::npos);
1046  path.resize (cp + 1);
1047  if (subdir != NULL)
1048    path = path + subdir + "/";
1049  path += LIBTHREAD_DB_SO;
1050
1051  return try_thread_db_load (path.c_str (), true);
1052}
1053
1054/* Handle $pdir in libthread-db-search-path.
1055   Look for libthread_db in directory(libpthread)/SUBDIR.
1056   SUBDIR may be NULL.  It may also be something like "../lib64".
1057   The result is true for success.  */
1058
1059static bool
1060try_thread_db_load_from_pdir (const char *subdir)
1061{
1062  if (!auto_load_thread_db)
1063    return false;
1064
1065  for (objfile *obj : current_program_space->objfiles ())
1066    if (libpthread_name_p (objfile_name (obj)))
1067      {
1068	if (try_thread_db_load_from_pdir_1 (obj, subdir))
1069	  return true;
1070
1071	/* We may have found the separate-debug-info version of
1072	   libpthread, and it may live in a directory without a matching
1073	   libthread_db.  */
1074	if (obj->separate_debug_objfile_backlink != NULL)
1075	  return try_thread_db_load_from_pdir_1 (obj->separate_debug_objfile_backlink,
1076						 subdir);
1077
1078	return false;
1079      }
1080
1081  return false;
1082}
1083
1084/* Handle $sdir in libthread-db-search-path.
1085   Look for libthread_db in the system dirs, or wherever a plain
1086   dlopen(file_without_path) will look.
1087   The result is true for success.  */
1088
1089static bool
1090try_thread_db_load_from_sdir (void)
1091{
1092  return try_thread_db_load (LIBTHREAD_DB_SO, false);
1093}
1094
1095/* Try to load libthread_db from directory DIR of length DIR_LEN.
1096   The result is true for success.  */
1097
1098static bool
1099try_thread_db_load_from_dir (const char *dir, size_t dir_len)
1100{
1101  if (!auto_load_thread_db)
1102    return false;
1103
1104  std::string path = std::string (dir, dir_len) + "/" + LIBTHREAD_DB_SO;
1105
1106  return try_thread_db_load (path.c_str (), true);
1107}
1108
1109/* Search libthread_db_search_path for libthread_db which "agrees"
1110   to work on current inferior.
1111   The result is true for success.  */
1112
1113static bool
1114thread_db_load_search (void)
1115{
1116  bool rc = false;
1117
1118  std::vector<gdb::unique_xmalloc_ptr<char>> dir_vec
1119    = dirnames_to_char_ptr_vec (libthread_db_search_path);
1120
1121  for (const gdb::unique_xmalloc_ptr<char> &this_dir_up : dir_vec)
1122    {
1123      const char *this_dir = this_dir_up.get ();
1124      const int pdir_len = sizeof ("$pdir") - 1;
1125      size_t this_dir_len;
1126
1127      this_dir_len = strlen (this_dir);
1128
1129      if (strncmp (this_dir, "$pdir", pdir_len) == 0
1130	  && (this_dir[pdir_len] == '\0'
1131	      || this_dir[pdir_len] == '/'))
1132	{
1133	  const char *subdir = NULL;
1134
1135	  std::string subdir_holder;
1136	  if (this_dir[pdir_len] == '/')
1137	    {
1138	      subdir_holder = std::string (this_dir + pdir_len + 1);
1139	      subdir = subdir_holder.c_str ();
1140	    }
1141	  rc = try_thread_db_load_from_pdir (subdir);
1142	  if (rc)
1143	    break;
1144	}
1145      else if (strcmp (this_dir, "$sdir") == 0)
1146	{
1147	  if (try_thread_db_load_from_sdir ())
1148	    {
1149	      rc = 1;
1150	      break;
1151	    }
1152	}
1153      else
1154	{
1155	  if (try_thread_db_load_from_dir (this_dir, this_dir_len))
1156	    {
1157	      rc = 1;
1158	      break;
1159	    }
1160	}
1161    }
1162
1163  if (libthread_db_debug)
1164    fprintf_unfiltered (gdb_stdlog,
1165			_("thread_db_load_search returning %d\n"), rc);
1166  return rc;
1167}
1168
1169/* Return true if the inferior has a libpthread.  */
1170
1171static bool
1172has_libpthread (void)
1173{
1174  for (objfile *obj : current_program_space->objfiles ())
1175    if (libpthread_name_p (objfile_name (obj)))
1176      return true;
1177
1178  return false;
1179}
1180
1181/* Attempt to load and initialize libthread_db.
1182   Return 1 on success.  */
1183
1184static bool
1185thread_db_load (void)
1186{
1187  struct thread_db_info *info;
1188
1189  info = get_thread_db_info (current_inferior ()->process_target (),
1190			     inferior_ptid.pid ());
1191
1192  if (info != NULL)
1193    return true;
1194
1195  /* Don't attempt to use thread_db on executables not running
1196     yet.  */
1197  if (!target_has_registers)
1198    return false;
1199
1200  /* Don't attempt to use thread_db for remote targets.  */
1201  if (!(target_can_run () || core_bfd))
1202    return false;
1203
1204  if (thread_db_load_search ())
1205    return true;
1206
1207  /* We couldn't find a libthread_db.
1208     If the inferior has a libpthread warn the user.  */
1209  if (has_libpthread ())
1210    {
1211      warning (_("Unable to find libthread_db matching inferior's thread"
1212		 " library, thread debugging will not be available."));
1213      return false;
1214    }
1215
1216  /* Either this executable isn't using libpthread at all, or it is
1217     statically linked.  Since we can't easily distinguish these two cases,
1218     no warning is issued.  */
1219  return false;
1220}
1221
1222static void
1223check_thread_signals (void)
1224{
1225  if (!thread_signals)
1226    {
1227      sigset_t mask;
1228      int i;
1229
1230      lin_thread_get_thread_signals (&mask);
1231      sigemptyset (&thread_stop_set);
1232      sigemptyset (&thread_print_set);
1233
1234      for (i = 1; i < NSIG; i++)
1235	{
1236	  if (sigismember (&mask, i))
1237	    {
1238	      if (signal_stop_update (gdb_signal_from_host (i), 0))
1239		sigaddset (&thread_stop_set, i);
1240	      if (signal_print_update (gdb_signal_from_host (i), 0))
1241		sigaddset (&thread_print_set, i);
1242	      thread_signals = 1;
1243	    }
1244	}
1245    }
1246}
1247
1248/* Check whether thread_db is usable.  This function is called when
1249   an inferior is created (or otherwise acquired, e.g. attached to)
1250   and when new shared libraries are loaded into a running process.  */
1251
1252void
1253check_for_thread_db (void)
1254{
1255  /* Do nothing if we couldn't load libthread_db.so.1.  */
1256  if (!thread_db_load ())
1257    return;
1258}
1259
1260/* This function is called via the new_objfile observer.  */
1261
1262static void
1263thread_db_new_objfile (struct objfile *objfile)
1264{
1265  /* This observer must always be called with inferior_ptid set
1266     correctly.  */
1267
1268  if (objfile != NULL
1269      /* libpthread with separate debug info has its debug info file already
1270	 loaded (and notified without successful thread_db initialization)
1271	 the time gdb::observers::new_objfile.notify is called for the library itself.
1272	 Static executables have their separate debug info loaded already
1273	 before the inferior has started.  */
1274      && objfile->separate_debug_objfile_backlink == NULL
1275      /* Only check for thread_db if we loaded libpthread,
1276	 or if this is the main symbol file.
1277	 We need to check OBJF_MAINLINE to handle the case of debugging
1278	 a statically linked executable AND the symbol file is specified AFTER
1279	 the exec file is loaded (e.g., gdb -c core ; file foo).
1280	 For dynamically linked executables, libpthread can be near the end
1281	 of the list of shared libraries to load, and in an app of several
1282	 thousand shared libraries, this can otherwise be painful.  */
1283      && ((objfile->flags & OBJF_MAINLINE) != 0
1284	  || libpthread_name_p (objfile_name (objfile))))
1285    check_for_thread_db ();
1286}
1287
1288static void
1289check_pid_namespace_match (void)
1290{
1291  /* Check is only relevant for local targets targets.  */
1292  if (target_can_run ())
1293    {
1294      /* If the child is in a different PID namespace, its idea of its
1295	 PID will differ from our idea of its PID.  When we scan the
1296	 child's thread list, we'll mistakenly think it has no threads
1297	 since the thread PID fields won't match the PID we give to
1298	 libthread_db.  */
1299      if (!linux_ns_same (inferior_ptid.pid (), LINUX_NS_PID))
1300	{
1301	  warning (_ ("Target and debugger are in different PID "
1302		      "namespaces; thread lists and other data are "
1303		      "likely unreliable.  "
1304		      "Connect to gdbserver inside the container."));
1305	}
1306    }
1307}
1308
1309/* This function is called via the inferior_created observer.
1310   This handles the case of debugging statically linked executables.  */
1311
1312static void
1313thread_db_inferior_created (struct target_ops *target, int from_tty)
1314{
1315  check_pid_namespace_match ();
1316  check_for_thread_db ();
1317}
1318
1319/* Update the thread's state (what's displayed in "info threads"),
1320   from libthread_db thread state information.  */
1321
1322static void
1323update_thread_state (thread_db_thread_info *priv,
1324		     const td_thrinfo_t *ti_p)
1325{
1326  priv->dying = (ti_p->ti_state == TD_THR_UNKNOWN
1327		 || ti_p->ti_state == TD_THR_ZOMBIE);
1328}
1329
1330/* Record a new thread in GDB's thread list.  Creates the thread's
1331   private info.  If TP is NULL or TP is marked as having exited,
1332   creates a new thread.  Otherwise, uses TP.  */
1333
1334static struct thread_info *
1335record_thread (struct thread_db_info *info,
1336	       struct thread_info *tp,
1337	       ptid_t ptid, const td_thrhandle_t *th_p,
1338	       const td_thrinfo_t *ti_p)
1339{
1340  /* A thread ID of zero may mean the thread library has not
1341     initialized yet.  Leave private == NULL until the thread library
1342     has initialized.  */
1343  if (ti_p->ti_tid == 0)
1344    return tp;
1345
1346  /* Construct the thread's private data.  */
1347  thread_db_thread_info *priv = new thread_db_thread_info;
1348
1349  priv->th = *th_p;
1350  priv->tid = ti_p->ti_tid;
1351  update_thread_state (priv, ti_p);
1352
1353  /* Add the thread to GDB's thread list.  If we already know about a
1354     thread with this PTID, but it's marked exited, then the kernel
1355     reused the tid of an old thread.  */
1356  if (tp == NULL || tp->state == THREAD_EXITED)
1357    tp = add_thread_with_info (info->process_target, ptid, priv);
1358  else
1359    tp->priv.reset (priv);
1360
1361  if (target_has_execution)
1362    check_thread_signals ();
1363
1364  return tp;
1365}
1366
1367void
1368thread_db_target::detach (inferior *inf, int from_tty)
1369{
1370  delete_thread_db_info (inf->process_target (), inf->pid);
1371
1372  beneath ()->detach (inf, from_tty);
1373
1374  /* NOTE: From this point on, inferior_ptid is null_ptid.  */
1375
1376  /* Detach the thread_db target from this inferior.  */
1377  unpush_target (this);
1378}
1379
1380ptid_t
1381thread_db_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
1382			int options)
1383{
1384  struct thread_db_info *info;
1385
1386  process_stratum_target *beneath
1387    = as_process_stratum_target (this->beneath ());
1388
1389  ptid = beneath->wait (ptid, ourstatus, options);
1390
1391  switch (ourstatus->kind)
1392    {
1393    case TARGET_WAITKIND_IGNORE:
1394    case TARGET_WAITKIND_EXITED:
1395    case TARGET_WAITKIND_THREAD_EXITED:
1396    case TARGET_WAITKIND_SIGNALLED:
1397      return ptid;
1398    }
1399
1400  info = get_thread_db_info (beneath, ptid.pid ());
1401
1402  /* If this process isn't using thread_db, we're done.  */
1403  if (info == NULL)
1404    return ptid;
1405
1406  if (ourstatus->kind == TARGET_WAITKIND_EXECD)
1407    {
1408      /* New image, it may or may not end up using thread_db.  Assume
1409	 not unless we find otherwise.  */
1410      delete_thread_db_info (beneath, ptid.pid ());
1411      unpush_target (this);
1412
1413      return ptid;
1414    }
1415
1416  /* Fill in the thread's user-level thread id and status.  */
1417  thread_from_lwp (find_thread_ptid (beneath, ptid), ptid);
1418
1419  return ptid;
1420}
1421
1422void
1423thread_db_target::mourn_inferior ()
1424{
1425  process_stratum_target *target_beneath
1426    = as_process_stratum_target (this->beneath ());
1427
1428  delete_thread_db_info (target_beneath, inferior_ptid.pid ());
1429
1430  target_beneath->mourn_inferior ();
1431
1432  /* Detach the thread_db target from this inferior.  */
1433  unpush_target (this);
1434}
1435
1436struct callback_data
1437{
1438  struct thread_db_info *info;
1439  int new_threads;
1440};
1441
1442static int
1443find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
1444{
1445  td_thrinfo_t ti;
1446  td_err_e err;
1447  struct thread_info *tp;
1448  struct callback_data *cb_data = (struct callback_data *) data;
1449  struct thread_db_info *info = cb_data->info;
1450
1451  err = info->td_thr_get_info_p (th_p, &ti);
1452  if (err != TD_OK)
1453    error (_("find_new_threads_callback: cannot get thread info: %s"),
1454	   thread_db_err_str (err));
1455
1456  if (ti.ti_lid == -1)
1457    {
1458      /* A thread with kernel thread ID -1 is either a thread that
1459	 exited and was joined, or a thread that is being created but
1460	 hasn't started yet, and that is reusing the tcb/stack of a
1461	 thread that previously exited and was joined.  (glibc marks
1462	 terminated and joined threads with kernel thread ID -1.  See
1463	 glibc PR17707.  */
1464      if (libthread_db_debug)
1465	fprintf_unfiltered (gdb_stdlog,
1466			    "thread_db: skipping exited and "
1467			    "joined thread (0x%lx)\n",
1468			    (unsigned long) ti.ti_tid);
1469      return 0;
1470    }
1471
1472  if (ti.ti_tid == 0)
1473    {
1474      /* A thread ID of zero means that this is the main thread, but
1475	 glibc has not yet initialized thread-local storage and the
1476	 pthread library.  We do not know what the thread's TID will
1477	 be yet.  */
1478
1479      /* In that case, we're not stopped in a fork syscall and don't
1480	 need this glibc bug workaround.  */
1481      info->need_stale_parent_threads_check = 0;
1482
1483      return 0;
1484    }
1485
1486  /* Ignore stale parent threads, caused by glibc/BZ5983.  This is a
1487     bit expensive, as it needs to open /proc/pid/status, so try to
1488     avoid doing the work if we know we don't have to.  */
1489  if (info->need_stale_parent_threads_check)
1490    {
1491      int tgid = linux_proc_get_tgid (ti.ti_lid);
1492
1493      if (tgid != -1 && tgid != info->pid)
1494	return 0;
1495    }
1496
1497  ptid_t ptid (info->pid, ti.ti_lid);
1498  tp = find_thread_ptid (info->process_target, ptid);
1499  if (tp == NULL || tp->priv == NULL)
1500    record_thread (info, tp, ptid, th_p, &ti);
1501
1502  return 0;
1503}
1504
1505/* Helper for thread_db_find_new_threads_2.
1506   Returns number of new threads found.  */
1507
1508static int
1509find_new_threads_once (struct thread_db_info *info, int iteration,
1510		       td_err_e *errp)
1511{
1512  struct callback_data data;
1513  td_err_e err = TD_ERR;
1514
1515  data.info = info;
1516  data.new_threads = 0;
1517
1518  /* See comment in thread_db_update_thread_list.  */
1519  gdb_assert (info->td_ta_thr_iter_p != NULL);
1520
1521  try
1522    {
1523      /* Iterate over all user-space threads to discover new threads.  */
1524      err = info->td_ta_thr_iter_p (info->thread_agent,
1525				    find_new_threads_callback,
1526				    &data,
1527				    TD_THR_ANY_STATE,
1528				    TD_THR_LOWEST_PRIORITY,
1529				    TD_SIGNO_MASK,
1530				    TD_THR_ANY_USER_FLAGS);
1531    }
1532  catch (const gdb_exception_error &except)
1533    {
1534      if (libthread_db_debug)
1535	{
1536	  exception_fprintf (gdb_stdlog, except,
1537			     "Warning: find_new_threads_once: ");
1538	}
1539    }
1540
1541  if (libthread_db_debug)
1542    {
1543      fprintf_unfiltered (gdb_stdlog,
1544			  _("Found %d new threads in iteration %d.\n"),
1545			  data.new_threads, iteration);
1546    }
1547
1548  if (errp != NULL)
1549    *errp = err;
1550
1551  return data.new_threads;
1552}
1553
1554/* Search for new threads, accessing memory through stopped thread
1555   PTID.  If UNTIL_NO_NEW is true, repeat searching until several
1556   searches in a row do not discover any new threads.  */
1557
1558static void
1559thread_db_find_new_threads_2 (thread_info *stopped, bool until_no_new)
1560{
1561  td_err_e err = TD_OK;
1562  struct thread_db_info *info;
1563  int i, loop;
1564
1565  info = get_thread_db_info (stopped->inf->process_target (),
1566			     stopped->ptid.pid ());
1567
1568  /* Access an lwp we know is stopped.  */
1569  info->proc_handle.thread = stopped;
1570
1571  if (until_no_new)
1572    {
1573      /* Require 4 successive iterations which do not find any new threads.
1574	 The 4 is a heuristic: there is an inherent race here, and I have
1575	 seen that 2 iterations in a row are not always sufficient to
1576	 "capture" all threads.  */
1577      for (i = 0, loop = 0; loop < 4 && err == TD_OK; ++i, ++loop)
1578	if (find_new_threads_once (info, i, &err) != 0)
1579	  {
1580	    /* Found some new threads.  Restart the loop from beginning.  */
1581	    loop = -1;
1582	  }
1583    }
1584  else
1585    find_new_threads_once (info, 0, &err);
1586
1587  if (err != TD_OK)
1588    error (_("Cannot find new threads: %s"), thread_db_err_str (err));
1589}
1590
1591static void
1592thread_db_find_new_threads_1 (thread_info *stopped)
1593{
1594  thread_db_find_new_threads_2 (stopped, 0);
1595}
1596
1597/* Implement the to_update_thread_list target method for this
1598   target.  */
1599
1600void
1601thread_db_target::update_thread_list ()
1602{
1603  struct thread_db_info *info;
1604
1605  prune_threads ();
1606
1607  for (inferior *inf : all_inferiors ())
1608    {
1609      if (inf->pid == 0)
1610	continue;
1611
1612      info = get_thread_db_info (inf->process_target (), inf->pid);
1613      if (info == NULL)
1614	continue;
1615
1616      thread_info *thread = any_live_thread_of_inferior (inf);
1617      if (thread == NULL || thread->executing)
1618	continue;
1619
1620      /* It's best to avoid td_ta_thr_iter if possible.  That walks
1621	 data structures in the inferior's address space that may be
1622	 corrupted, or, if the target is running, the list may change
1623	 while we walk it.  In the latter case, it's possible that a
1624	 thread exits just at the exact time that causes GDB to get
1625	 stuck in an infinite loop.  To avoid pausing all threads
1626	 whenever the core wants to refresh the thread list, we
1627	 instead use thread_from_lwp immediately when we see an LWP
1628	 stop.  That uses thread_db entry points that do not walk
1629	 libpthread's thread list, so should be safe, as well as more
1630	 efficient.  */
1631      if (thread->inf->has_execution ())
1632	continue;
1633
1634      thread_db_find_new_threads_1 (thread);
1635    }
1636
1637  /* Give the beneath target a chance to do extra processing.  */
1638  this->beneath ()->update_thread_list ();
1639}
1640
1641std::string
1642thread_db_target::pid_to_str (ptid_t ptid)
1643{
1644  thread_info *thread_info = find_thread_ptid (current_inferior (), ptid);
1645
1646  if (thread_info != NULL && thread_info->priv != NULL)
1647    {
1648      thread_db_thread_info *priv = get_thread_db_thread_info (thread_info);
1649
1650      return string_printf ("Thread 0x%lx (LWP %ld)",
1651			    (unsigned long) priv->tid, ptid.lwp ());
1652    }
1653
1654  return beneath ()->pid_to_str (ptid);
1655}
1656
1657/* Return a string describing the state of the thread specified by
1658   INFO.  */
1659
1660const char *
1661thread_db_target::extra_thread_info (thread_info *info)
1662{
1663  if (info->priv == NULL)
1664    return NULL;
1665
1666  thread_db_thread_info *priv = get_thread_db_thread_info (info);
1667
1668  if (priv->dying)
1669    return "Exiting";
1670
1671  return NULL;
1672}
1673
1674/* Return pointer to the thread_info struct which corresponds to
1675   THREAD_HANDLE (having length HANDLE_LEN).  */
1676
1677thread_info *
1678thread_db_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
1679						int handle_len,
1680						inferior *inf)
1681{
1682  thread_t handle_tid;
1683
1684  /* When debugging a 32-bit target from a 64-bit host, handle_len
1685     will be 4 and sizeof (handle_tid) will be 8.  This requires
1686     a different cast than the more straightforward case where
1687     the sizes are the same.
1688
1689     Use "--target_board unix/-m32" from a native x86_64 linux build
1690     to test the 32/64-bit case.  */
1691  if (handle_len == 4 && sizeof (handle_tid) == 8)
1692    handle_tid = (thread_t) * (const uint32_t *) thread_handle;
1693  else if (handle_len == sizeof (handle_tid))
1694    handle_tid = * (const thread_t *) thread_handle;
1695  else
1696    error (_("Thread handle size mismatch: %d vs %zu (from libthread_db)"),
1697	   handle_len, sizeof (handle_tid));
1698
1699  for (thread_info *tp : inf->non_exited_threads ())
1700    {
1701      thread_db_thread_info *priv = get_thread_db_thread_info (tp);
1702
1703      if (priv != NULL && handle_tid == priv->tid)
1704        return tp;
1705    }
1706
1707  return NULL;
1708}
1709
1710/* Return the thread handle associated the thread_info pointer TP.  */
1711
1712gdb::byte_vector
1713thread_db_target::thread_info_to_thread_handle (struct thread_info *tp)
1714{
1715  thread_db_thread_info *priv = get_thread_db_thread_info (tp);
1716
1717  if (priv == NULL)
1718    return gdb::byte_vector ();
1719
1720  int handle_size = sizeof (priv->tid);
1721  gdb::byte_vector rv (handle_size);
1722
1723  memcpy (rv.data (), &priv->tid, handle_size);
1724
1725  return rv;
1726}
1727
1728/* Get the address of the thread local variable in load module LM which
1729   is stored at OFFSET within the thread local storage for thread PTID.  */
1730
1731CORE_ADDR
1732thread_db_target::get_thread_local_address (ptid_t ptid,
1733					    CORE_ADDR lm,
1734					    CORE_ADDR offset)
1735{
1736  struct thread_info *thread_info;
1737  process_stratum_target *beneath
1738    = as_process_stratum_target (this->beneath ());
1739  /* Find the matching thread.  */
1740  thread_info = find_thread_ptid (beneath, ptid);
1741
1742  /* We may not have discovered the thread yet.  */
1743  if (thread_info != NULL && thread_info->priv == NULL)
1744    thread_info = thread_from_lwp (thread_info, ptid);
1745
1746  if (thread_info != NULL && thread_info->priv != NULL)
1747    {
1748      td_err_e err;
1749      psaddr_t address;
1750      thread_db_info *info = get_thread_db_info (beneath, ptid.pid ());
1751      thread_db_thread_info *priv = get_thread_db_thread_info (thread_info);
1752
1753      /* Finally, get the address of the variable.  */
1754      if (lm != 0)
1755	{
1756	  /* glibc doesn't provide the needed interface.  */
1757	  if (!info->td_thr_tls_get_addr_p)
1758	    throw_error (TLS_NO_LIBRARY_SUPPORT_ERROR,
1759			 _("No TLS library support"));
1760
1761	  /* Note the cast through uintptr_t: this interface only works if
1762	     a target address fits in a psaddr_t, which is a host pointer.
1763	     So a 32-bit debugger can not access 64-bit TLS through this.  */
1764	  err = info->td_thr_tls_get_addr_p (&priv->th,
1765					     (psaddr_t)(uintptr_t) lm,
1766					     offset, &address);
1767	}
1768      else
1769	{
1770	  /* If glibc doesn't provide the needed interface throw an error
1771	     that LM is zero - normally cases it should not be.  */
1772	  if (!info->td_thr_tlsbase_p)
1773	    throw_error (TLS_LOAD_MODULE_NOT_FOUND_ERROR,
1774			 _("TLS load module not found"));
1775
1776	  /* This code path handles the case of -static -pthread executables:
1777	     https://sourceware.org/ml/libc-help/2014-03/msg00024.html
1778	     For older GNU libc r_debug.r_map is NULL.  For GNU libc after
1779	     PR libc/16831 due to GDB PR threads/16954 LOAD_MODULE is also NULL.
1780	     The constant number 1 depends on GNU __libc_setup_tls
1781	     initialization of l_tls_modid to 1.  */
1782	  err = info->td_thr_tlsbase_p (&priv->th, 1, &address);
1783	  address = (char *) address + offset;
1784	}
1785
1786#ifdef THREAD_DB_HAS_TD_NOTALLOC
1787      /* The memory hasn't been allocated, yet.  */
1788      if (err == TD_NOTALLOC)
1789	  /* Now, if libthread_db provided the initialization image's
1790	     address, we *could* try to build a non-lvalue value from
1791	     the initialization image.  */
1792        throw_error (TLS_NOT_ALLOCATED_YET_ERROR,
1793                     _("TLS not allocated yet"));
1794#endif
1795
1796      /* Something else went wrong.  */
1797      if (err != TD_OK)
1798        throw_error (TLS_GENERIC_ERROR,
1799                     (("%s")), thread_db_err_str (err));
1800
1801      /* Cast assuming host == target.  Joy.  */
1802      /* Do proper sign extension for the target.  */
1803      gdb_assert (exec_bfd);
1804      return (bfd_get_sign_extend_vma (exec_bfd) > 0
1805	      ? (CORE_ADDR) (intptr_t) address
1806	      : (CORE_ADDR) (uintptr_t) address);
1807    }
1808
1809  return beneath->get_thread_local_address (ptid, lm, offset);
1810}
1811
1812/* Implement the to_get_ada_task_ptid target method for this target.  */
1813
1814ptid_t
1815thread_db_target::get_ada_task_ptid (long lwp, long thread)
1816{
1817  /* NPTL uses a 1:1 model, so the LWP id suffices.  */
1818  return ptid_t (inferior_ptid.pid (), lwp, 0);
1819}
1820
1821void
1822thread_db_target::resume (ptid_t ptid, int step, enum gdb_signal signo)
1823{
1824  process_stratum_target *beneath
1825    = as_process_stratum_target (this->beneath ());
1826
1827  thread_db_info *info
1828    = get_thread_db_info (beneath, (ptid == minus_one_ptid
1829				    ? inferior_ptid.pid ()
1830				    : ptid.pid ()));
1831
1832  /* This workaround is only needed for child fork lwps stopped in a
1833     PTRACE_O_TRACEFORK event.  When the inferior is resumed, the
1834     workaround can be disabled.  */
1835  if (info)
1836    info->need_stale_parent_threads_check = 0;
1837
1838  beneath->resume (ptid, step, signo);
1839}
1840
1841/* std::sort helper function for info_auto_load_libthread_db, sort the
1842   thread_db_info pointers primarily by their FILENAME and secondarily by their
1843   PID, both in ascending order.  */
1844
1845static bool
1846info_auto_load_libthread_db_compare (const struct thread_db_info *a,
1847				     const struct thread_db_info *b)
1848{
1849  int retval;
1850
1851  retval = strcmp (a->filename, b->filename);
1852  if (retval)
1853    return retval < 0;
1854
1855  return a->pid < b->pid;
1856}
1857
1858/* Implement 'info auto-load libthread-db'.  */
1859
1860static void
1861info_auto_load_libthread_db (const char *args, int from_tty)
1862{
1863  struct ui_out *uiout = current_uiout;
1864  const char *cs = args ? args : "";
1865  struct thread_db_info *info;
1866  unsigned unique_filenames;
1867  size_t max_filename_len, pids_len;
1868  int i;
1869
1870  cs = skip_spaces (cs);
1871  if (*cs)
1872    error (_("'info auto-load libthread-db' does not accept any parameters"));
1873
1874  std::vector<struct thread_db_info *> array;
1875  for (info = thread_db_list; info; info = info->next)
1876    if (info->filename != NULL)
1877      array.push_back (info);
1878
1879  /* Sort ARRAY by filenames and PIDs.  */
1880  std::sort (array.begin (), array.end (),
1881	     info_auto_load_libthread_db_compare);
1882
1883  /* Calculate the number of unique filenames (rows) and the maximum string
1884     length of PIDs list for the unique filenames (columns).  */
1885
1886  unique_filenames = 0;
1887  max_filename_len = 0;
1888  pids_len = 0;
1889  for (i = 0; i < array.size (); i++)
1890    {
1891      int pid = array[i]->pid;
1892      size_t this_pid_len;
1893
1894      for (this_pid_len = 0; pid != 0; pid /= 10)
1895	this_pid_len++;
1896
1897      if (i == 0 || strcmp (array[i - 1]->filename, array[i]->filename) != 0)
1898	{
1899	  unique_filenames++;
1900	  max_filename_len = std::max (max_filename_len,
1901				       strlen (array[i]->filename));
1902
1903	  if (i > 0)
1904	    pids_len -= strlen (", ");
1905	  pids_len = 0;
1906	}
1907      pids_len += this_pid_len + strlen (", ");
1908    }
1909  if (i)
1910    pids_len -= strlen (", ");
1911
1912  /* Table header shifted right by preceding "libthread-db:  " would not match
1913     its columns.  */
1914  if (array.size () > 0 && args == auto_load_info_scripts_pattern_nl)
1915    uiout->text ("\n");
1916
1917  {
1918    ui_out_emit_table table_emitter (uiout, 2, unique_filenames,
1919				     "LinuxThreadDbTable");
1920
1921    uiout->table_header (max_filename_len, ui_left, "filename", "Filename");
1922    uiout->table_header (pids_len, ui_left, "PIDs", "Pids");
1923    uiout->table_body ();
1924
1925    /* Note I is incremented inside the cycle, not at its end.  */
1926    for (i = 0; i < array.size ();)
1927      {
1928	ui_out_emit_tuple tuple_emitter (uiout, NULL);
1929
1930	info = array[i];
1931	uiout->field_string ("filename", info->filename);
1932
1933	std::string pids;
1934	while (i < array.size () && strcmp (info->filename,
1935					    array[i]->filename) == 0)
1936	  {
1937	    if (!pids.empty ())
1938	      pids += ", ";
1939	    string_appendf (pids, "%u", array[i]->pid);
1940	    i++;
1941	  }
1942
1943	uiout->field_string ("pids", pids.c_str ());
1944
1945	uiout->text ("\n");
1946      }
1947  }
1948
1949  if (array.empty ())
1950    uiout->message (_("No auto-loaded libthread-db.\n"));
1951}
1952
1953/* Implement 'maintenance check libthread-db'.  */
1954
1955static void
1956maintenance_check_libthread_db (const char *args, int from_tty)
1957{
1958  int inferior_pid = inferior_ptid.pid ();
1959  struct thread_db_info *info;
1960
1961  if (inferior_pid == 0)
1962    error (_("No inferior running"));
1963
1964  info = get_thread_db_info (current_inferior ()->process_target (),
1965			     inferior_pid);
1966  if (info == NULL)
1967    error (_("No libthread_db loaded"));
1968
1969  check_thread_db (info, true);
1970}
1971
1972void _initialize_thread_db ();
1973void
1974_initialize_thread_db ()
1975{
1976  /* Defer loading of libthread_db.so until inferior is running.
1977     This allows gdb to load correct libthread_db for a given
1978     executable -- there could be multiple versions of glibc,
1979     and until there is a running inferior, we can't tell which
1980     libthread_db is the correct one to load.  */
1981
1982  libthread_db_search_path = xstrdup (LIBTHREAD_DB_SEARCH_PATH);
1983
1984  add_setshow_optional_filename_cmd ("libthread-db-search-path",
1985				     class_support,
1986				     &libthread_db_search_path, _("\
1987Set search path for libthread_db."), _("\
1988Show the current search path or libthread_db."), _("\
1989This path is used to search for libthread_db to be loaded into \
1990gdb itself.\n\
1991Its value is a colon (':') separate list of directories to search.\n\
1992Setting the search path to an empty list resets it to its default value."),
1993			    set_libthread_db_search_path,
1994			    NULL,
1995			    &setlist, &showlist);
1996
1997  add_setshow_zuinteger_cmd ("libthread-db", class_maintenance,
1998			     &libthread_db_debug, _("\
1999Set libthread-db debugging."), _("\
2000Show libthread-db debugging."), _("\
2001When non-zero, libthread-db debugging is enabled."),
2002			     NULL,
2003			     show_libthread_db_debug,
2004			     &setdebuglist, &showdebuglist);
2005
2006  add_setshow_boolean_cmd ("libthread-db", class_support,
2007			   &auto_load_thread_db, _("\
2008Enable or disable auto-loading of inferior specific libthread_db."), _("\
2009Show whether auto-loading inferior specific libthread_db is enabled."), _("\
2010If enabled, libthread_db will be searched in 'set libthread-db-search-path'\n\
2011locations to load libthread_db compatible with the inferior.\n\
2012Standard system libthread_db still gets loaded even with this option off.\n\
2013This option has security implications for untrusted inferiors."),
2014			   NULL, show_auto_load_thread_db,
2015			   auto_load_set_cmdlist_get (),
2016			   auto_load_show_cmdlist_get ());
2017
2018  add_cmd ("libthread-db", class_info, info_auto_load_libthread_db,
2019	   _("Print the list of loaded inferior specific libthread_db.\n\
2020Usage: info auto-load libthread-db"),
2021	   auto_load_info_cmdlist_get ());
2022
2023  add_cmd ("libthread-db", class_maintenance,
2024	   maintenance_check_libthread_db, _("\
2025Run integrity checks on the current inferior's libthread_db."),
2026	   &maintenancechecklist);
2027
2028  add_setshow_boolean_cmd ("check-libthread-db",
2029			   class_maintenance,
2030			   &check_thread_db_on_load, _("\
2031Set whether to check libthread_db at load time."), _("\
2032Show whether to check libthread_db at load time."), _("\
2033If enabled GDB will run integrity checks on inferior specific libthread_db\n\
2034as they are loaded."),
2035			   NULL,
2036			   NULL,
2037			   &maintenance_set_cmdlist,
2038			   &maintenance_show_cmdlist);
2039
2040  /* Add ourselves to objfile event chain.  */
2041  gdb::observers::new_objfile.attach (thread_db_new_objfile);
2042
2043  /* Add ourselves to inferior_created event chain.
2044     This is needed to handle debugging statically linked programs where
2045     the new_objfile observer won't get called for libpthread.  */
2046  gdb::observers::inferior_created.attach (thread_db_inferior_created);
2047}
2048