fbsd-threads.c revision 155412
1/* $FreeBSD: head/gnu/usr.bin/gdb/libgdb/fbsd-threads.c 155412 2006-02-07 02:29:55Z davidxu $ */
2/* FreeBSD libthread_db assisted debugging support.
3   Copyright 1999, 2000, 2001 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 2 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, write to the Free Software
19   Foundation, Inc., 59 Temple Place - Suite 330,
20   Boston, MA 02111-1307, USA.  */
21
22#include <dlfcn.h>
23#include <sys/types.h>
24#include <sys/ptrace.h>
25#include <signal.h>
26
27#include "proc_service.h"
28#include "thread_db.h"
29
30#include "defs.h"
31#include "bfd.h"
32#include "elf-bfd.h"
33#include "gdb_assert.h"
34#include "gdbcore.h"
35#include "gdbthread.h"
36#include "inferior.h"
37#include "objfiles.h"
38#include "regcache.h"
39#include "symfile.h"
40#include "symtab.h"
41#include "target.h"
42#include "gdbcmd.h"
43#include "solib-svr4.h"
44
45
46#define LIBTHREAD_DB_SO "libthread_db.so"
47
48struct ps_prochandle
49{
50  pid_t pid;
51};
52
53extern int child_suppress_run;
54
55extern struct target_ops child_ops;
56
57/* This module's target vectors.  */
58static struct target_ops fbsd_thread_ops;
59static struct target_ops fbsd_core_ops;
60
61/* Saved copy of orignal core_ops. */
62static struct target_ops orig_core_ops;
63extern struct target_ops core_ops;
64
65/* Pointer to the next function on the objfile event chain.  */
66static void (*target_new_objfile_chain) (struct objfile *objfile);
67
68/* Non-zero if there is a thread module */
69static int fbsd_thread_present;
70
71/* Non-zero if we're using this module's target vector.  */
72static int fbsd_thread_active;
73
74/* Non-zero if core_open is called */
75static int fbsd_thread_core = 0;
76
77/* Non-zero if we have to keep this module's target vector active
78   across re-runs.  */
79static int keep_thread_db;
80
81/* Structure that identifies the child process for the
82   <proc_service.h> interface.  */
83static struct ps_prochandle proc_handle;
84
85/* Connection to the libthread_db library.  */
86static td_thragent_t *thread_agent;
87
88/* The last thread we are single stepping */
89static ptid_t last_single_step_thread;
90
91/* Pointers to the libthread_db functions.  */
92
93static td_err_e (*td_init_p) (void);
94
95static td_err_e (*td_ta_new_p) (struct ps_prochandle *ps, td_thragent_t **ta);
96static td_err_e (*td_ta_delete_p) (td_thragent_t *);
97static td_err_e (*td_ta_map_id2thr_p) (const td_thragent_t *ta, thread_t pt,
98				       td_thrhandle_t *__th);
99static td_err_e (*td_ta_map_lwp2thr_p) (const td_thragent_t *ta, lwpid_t lwpid,
100					td_thrhandle_t *th);
101static td_err_e (*td_ta_thr_iter_p) (const td_thragent_t *ta,
102				     td_thr_iter_f *callback,
103				     void *cbdata_p, td_thr_state_e state,
104				     int ti_pri, sigset_t *ti_sigmask_p,
105				     unsigned int ti_user_flags);
106static td_err_e (*td_ta_event_addr_p) (const td_thragent_t *ta,
107				       td_event_e event, td_notify_t *ptr);
108static td_err_e (*td_ta_set_event_p) (const td_thragent_t *ta,
109				      td_thr_events_t *event);
110static td_err_e (*td_ta_event_getmsg_p) (const td_thragent_t *ta,
111					 td_event_msg_t *msg);
112static td_err_e (*td_thr_get_info_p) (const td_thrhandle_t *th,
113				      td_thrinfo_t *infop);
114#ifdef PT_GETXMMREGS
115static td_err_e (*td_thr_getxmmregs_p) (const td_thrhandle_t *th,
116					char *regset);
117#endif
118static td_err_e (*td_thr_getfpregs_p) (const td_thrhandle_t *th,
119				       prfpregset_t *regset);
120static td_err_e (*td_thr_getgregs_p) (const td_thrhandle_t *th,
121				      prgregset_t gregs);
122#ifdef PT_GETXMMREGS
123static td_err_e (*td_thr_setxmmregs_p) (const td_thrhandle_t *th,
124					const char *fpregs);
125#endif
126static td_err_e (*td_thr_setfpregs_p) (const td_thrhandle_t *th,
127				       const prfpregset_t *fpregs);
128static td_err_e (*td_thr_setgregs_p) (const td_thrhandle_t *th,
129				      prgregset_t gregs);
130static td_err_e (*td_thr_event_enable_p) (const td_thrhandle_t *th, int event);
131
132static td_err_e (*td_thr_sstep_p) (td_thrhandle_t *th, int step);
133
134static td_err_e (*td_ta_tsd_iter_p) (const td_thragent_t *ta,
135				 td_key_iter_f *func, void *data);
136static td_err_e (*td_thr_tls_get_addr_p) (const td_thrhandle_t *th,
137                                          void *map_address,
138                                          size_t offset, void **address);
139static td_err_e (*td_thr_dbsuspend_p) (const td_thrhandle_t *);
140static td_err_e (*td_thr_dbresume_p) (const td_thrhandle_t *);
141
142static CORE_ADDR td_create_bp_addr;
143
144/* Location of the thread death event breakpoint.  */
145static CORE_ADDR td_death_bp_addr;
146
147/* Prototypes for local functions.  */
148static void fbsd_thread_find_new_threads (void);
149static int fbsd_thread_alive (ptid_t ptid);
150static void attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
151               const td_thrinfo_t *ti_p, int verbose);
152static void fbsd_thread_detach (char *args, int from_tty);
153
154/* Building process ids.  */
155
156#define GET_PID(ptid)		ptid_get_pid (ptid)
157#define GET_LWP(ptid)		ptid_get_lwp (ptid)
158#define GET_THREAD(ptid)	ptid_get_tid (ptid)
159
160#define IS_LWP(ptid)		(GET_LWP (ptid) != 0)
161#define IS_THREAD(ptid)		(GET_THREAD (ptid) != 0)
162
163#define BUILD_LWP(lwp, pid)	ptid_build (pid, lwp, 0)
164#define BUILD_THREAD(tid, pid)	ptid_build (pid, 0, tid)
165
166static char *
167thread_db_err_str (td_err_e err)
168{
169  static char buf[64];
170
171  switch (err)
172    {
173    case TD_OK:
174      return "generic 'call succeeded'";
175    case TD_ERR:
176      return "generic error";
177    case TD_NOTHR:
178      return "no thread to satisfy query";
179    case TD_NOSV:
180      return "no sync handle to satisfy query";
181    case TD_NOLWP:
182      return "no LWP to satisfy query";
183    case TD_BADPH:
184      return "invalid process handle";
185    case TD_BADTH:
186      return "invalid thread handle";
187    case TD_BADSH:
188      return "invalid synchronization handle";
189    case TD_BADTA:
190      return "invalid thread agent";
191    case TD_BADKEY:
192      return "invalid key";
193    case TD_NOMSG:
194      return "no event message for getmsg";
195    case TD_NOFPREGS:
196      return "FPU register set not available";
197    case TD_NOLIBTHREAD:
198      return "application not linked with libthread";
199    case TD_NOEVENT:
200      return "requested event is not supported";
201    case TD_NOCAPAB:
202      return "capability not available";
203    case TD_DBERR:
204      return "debugger service failed";
205    case TD_NOAPLIC:
206      return "operation not applicable to";
207    case TD_NOTSD:
208      return "no thread-specific data for this thread";
209    case TD_MALLOC:
210      return "malloc failed";
211    case TD_PARTIALREG:
212      return "only part of register set was written/read";
213    case TD_NOXREGS:
214      return "X register set not available for this thread";
215    default:
216      snprintf (buf, sizeof (buf), "unknown thread_db error '%d'", err);
217      return buf;
218    }
219}
220
221static char *
222thread_db_state_str (td_thr_state_e state)
223{
224  static char buf[64];
225
226  switch (state)
227    {
228    case TD_THR_STOPPED:
229      return "stopped by debugger";
230    case TD_THR_RUN:
231      return "runnable";
232    case TD_THR_ACTIVE:
233      return "active";
234    case TD_THR_ZOMBIE:
235      return "zombie";
236    case TD_THR_SLEEP:
237      return "sleeping";
238    case TD_THR_STOPPED_ASLEEP:
239      return "stopped by debugger AND blocked";
240    default:
241      snprintf (buf, sizeof (buf), "unknown thread_db state %d", state);
242      return buf;
243    }
244}
245
246/* Convert LWP to user-level thread id. */
247static ptid_t
248thread_from_lwp (ptid_t ptid, td_thrhandle_t *th, td_thrinfo_t *ti)
249{
250  td_err_e err;
251
252  gdb_assert (IS_LWP (ptid));
253
254  if (fbsd_thread_active)
255    {
256      err = td_ta_map_lwp2thr_p (thread_agent, GET_LWP (ptid), th);
257      if (err == TD_OK)
258        {
259          err = td_thr_get_info_p (th, ti);
260          if (err != TD_OK)
261            error ("Cannot get thread info: %s", thread_db_err_str (err));
262          return BUILD_THREAD (ti->ti_tid, GET_PID (ptid));
263        }
264    }
265
266  /* the LWP is not mapped to user thread */
267  return BUILD_LWP (GET_LWP (ptid), GET_PID (ptid));
268}
269
270static void
271fbsd_core_get_first_lwp (bfd *abfd, asection *asect, void *obj)
272{
273  if (strncmp (bfd_section_name (abfd, asect), ".reg/", 5) != 0)
274    return;
275
276  if (*(lwpid_t *)obj != 0)
277    return;
278
279  *(lwpid_t *)obj = atoi (bfd_section_name (abfd, asect) + 5);
280}
281
282static long
283get_current_lwp (int pid)
284{
285  struct ptrace_lwpinfo pl;
286  lwpid_t lwpid;
287
288  if (!target_has_execution)
289    {
290      lwpid = 0;
291      bfd_map_over_sections (core_bfd, fbsd_core_get_first_lwp, &lwpid);
292      return lwpid;
293    }
294  if (ptrace (PT_LWPINFO, pid, (caddr_t)&pl, sizeof(pl)))
295    perror_with_name("PT_LWPINFO");
296
297  return (long)pl.pl_lwpid;
298}
299
300static void
301get_current_thread ()
302{
303  td_thrhandle_t th;
304  td_thrinfo_t ti;
305  long lwp;
306  ptid_t tmp, ptid;
307
308  lwp = get_current_lwp (proc_handle.pid);
309  tmp = BUILD_LWP (lwp, proc_handle.pid);
310  ptid = thread_from_lwp (tmp, &th, &ti);
311  if (!in_thread_list (ptid))
312    {
313      attach_thread (ptid, &th, &ti, 1);
314    }
315  inferior_ptid = ptid;
316}
317
318static td_err_e
319enable_thread_event (td_thragent_t *thread_agent, int event, CORE_ADDR *bp)
320{
321  td_notify_t notify;
322  td_err_e err;
323
324  /* Get the breakpoint address for thread EVENT.  */
325  err = td_ta_event_addr_p (thread_agent, event, &notify);
326  if (err != TD_OK)
327    return err;
328
329  /* Set up the breakpoint.  */
330  (*bp) = gdbarch_convert_from_func_ptr_addr (current_gdbarch,
331            extract_typed_address(&notify.u.bptaddr, builtin_type_void_func_ptr),
332            &current_target);
333  create_thread_event_breakpoint ((*bp));
334
335  return TD_OK;
336}
337
338static void
339enable_thread_event_reporting (void)
340{
341  td_thr_events_t events;
342  td_notify_t notify;
343  td_err_e err;
344
345  /* We cannot use the thread event reporting facility if these
346     functions aren't available.  */
347  if (td_ta_event_addr_p == NULL || td_ta_set_event_p == NULL
348      || td_ta_event_getmsg_p == NULL || td_thr_event_enable_p == NULL)
349    return;
350
351  /* Set the process wide mask saying which events we're interested in.  */
352  td_event_emptyset (&events);
353  td_event_addset (&events, TD_CREATE);
354  td_event_addset (&events, TD_DEATH);
355
356  err = td_ta_set_event_p (thread_agent, &events);
357  if (err != TD_OK)
358    {
359      warning ("Unable to set global thread event mask: %s",
360	       thread_db_err_str (err));
361      return;
362    }
363
364  /* Delete previous thread event breakpoints, if any.  */
365  remove_thread_event_breakpoints ();
366  td_create_bp_addr = 0;
367  td_death_bp_addr = 0;
368
369  /* Set up the thread creation event.  */
370  err = enable_thread_event (thread_agent, TD_CREATE, &td_create_bp_addr);
371  if (err != TD_OK)
372    {
373      warning ("Unable to get location for thread creation breakpoint: %s",
374	       thread_db_err_str (err));
375      return;
376    }
377
378  /* Set up the thread death event.  */
379  err = enable_thread_event (thread_agent, TD_DEATH, &td_death_bp_addr);
380  if (err != TD_OK)
381    {
382      warning ("Unable to get location for thread death breakpoint: %s",
383	       thread_db_err_str (err));
384      return;
385    }
386}
387
388static void
389disable_thread_event_reporting (void)
390{
391  td_thr_events_t events;
392
393  /* Set the process wide mask saying we aren't interested in any
394     events anymore.  */
395  td_event_emptyset (&events);
396  td_ta_set_event_p (thread_agent, &events);
397
398  /* Delete thread event breakpoints, if any.  */
399  remove_thread_event_breakpoints ();
400  td_create_bp_addr = 0;
401  td_death_bp_addr = 0;
402}
403
404static void
405fbsd_thread_activate (void)
406{
407  fbsd_thread_active = 1;
408  init_thread_list();
409  if (fbsd_thread_core == 0)
410    enable_thread_event_reporting ();
411  fbsd_thread_find_new_threads ();
412  get_current_thread ();
413}
414
415static void
416fbsd_thread_deactivate (void)
417{
418  if (fbsd_thread_core == 0)
419    disable_thread_event_reporting();
420  td_ta_delete_p (thread_agent);
421
422  inferior_ptid = pid_to_ptid (proc_handle.pid);
423  proc_handle.pid = 0;
424  fbsd_thread_active = 0;
425  fbsd_thread_present = 0;
426  init_thread_list ();
427}
428
429static void
430fbsd_thread_new_objfile (struct objfile *objfile)
431{
432  td_err_e err;
433
434  if (objfile == NULL)
435    {
436      /* All symbols have been discarded.  If the thread_db target is
437         active, deactivate it now.  */
438      if (fbsd_thread_active)
439        {
440          gdb_assert (proc_handle.pid == 0);
441          fbsd_thread_active = 0;
442        }
443
444      goto quit;
445    }
446
447  if (!child_suppress_run)
448    goto quit;
449
450  /* Nothing to do.  The thread library was already detected and the
451     target vector was already activated.  */
452  if (fbsd_thread_active)
453    goto quit;
454
455  /* Initialize the structure that identifies the child process.  Note
456     that at this point there is no guarantee that we actually have a
457     child process.  */
458  proc_handle.pid = GET_PID (inferior_ptid);
459
460  /* Now attempt to open a connection to the thread library.  */
461  err = td_ta_new_p (&proc_handle, &thread_agent);
462  switch (err)
463    {
464    case TD_NOLIBTHREAD:
465      /* No thread library was detected.  */
466      break;
467
468    case TD_OK:
469      /* The thread library was detected.  Activate the thread_db target.  */
470      fbsd_thread_present = 1;
471
472      /* We can only poke around if there actually is a child process.
473         If there is no child process alive, postpone the steps below
474         until one has been created.  */
475      if (fbsd_thread_core == 0 && proc_handle.pid != 0)
476        {
477          push_target(&fbsd_thread_ops);
478          fbsd_thread_activate();
479        }
480      else
481        {
482          td_ta_delete_p(thread_agent);
483          thread_agent = NULL;
484        }
485      break;
486
487    default:
488      warning ("Cannot initialize thread debugging library: %s",
489               thread_db_err_str (err));
490      break;
491    }
492
493 quit:
494  if (target_new_objfile_chain)
495    target_new_objfile_chain (objfile);
496}
497
498static void
499fbsd_thread_attach (char *args, int from_tty)
500{
501  fbsd_thread_core = 0;
502
503  child_ops.to_attach (args, from_tty);
504
505  /* Must get symbols from solibs before libthread_db can run! */
506  SOLIB_ADD ((char *) 0, from_tty, (struct target_ops *) 0, auto_solib_add);
507
508  if (fbsd_thread_present && !fbsd_thread_active)
509    push_target(&fbsd_thread_ops);
510}
511
512static void
513fbsd_thread_post_attach (int pid)
514{
515  child_ops.to_post_attach (pid);
516
517  if (fbsd_thread_present && !fbsd_thread_active)
518    {
519      proc_handle.pid = GET_PID (inferior_ptid);
520      fbsd_thread_activate ();
521    }
522}
523
524static void
525fbsd_thread_detach (char *args, int from_tty)
526{
527  fbsd_thread_deactivate ();
528  unpush_target (&fbsd_thread_ops);
529
530  /* Clear gdb solib information and symbol file
531     cache, so that after detach and re-attach, new_objfile
532     hook will be called */
533
534  clear_solib();
535  symbol_file_clear(0);
536  proc_handle.pid = 0;
537  child_ops.to_detach (args, from_tty);
538}
539
540static int
541suspend_thread_callback (const td_thrhandle_t *th_p, void *data)
542{
543  int err = td_thr_dbsuspend_p (th_p);
544  if (err != 0)
545	fprintf_filtered(gdb_stderr, "%s %s\n", __func__, thread_db_err_str (err));
546  return (err);
547}
548
549static int
550resume_thread_callback (const td_thrhandle_t *th_p, void *data)
551{
552  int err = td_thr_dbresume_p (th_p);
553  if (err != 0)
554	fprintf_filtered(gdb_stderr, "%s %s\n", __func__, thread_db_err_str (err));
555  return (err);
556}
557
558static void
559fbsd_thread_resume (ptid_t ptid, int step, enum target_signal signo)
560{
561  td_thrhandle_t th;
562  td_thrinfo_t ti;
563  ptid_t work_ptid;
564  int resume_all, ret;
565  long lwp, thvalid = 0;
566
567  if (!fbsd_thread_active)
568    {
569      child_ops.to_resume (ptid, step, signo);
570      return;
571    }
572
573  if (GET_PID(ptid) != -1 && step != 0)
574    {
575      resume_all = 0;
576      work_ptid = ptid;
577    }
578  else
579    {
580      resume_all = 1;
581      work_ptid = inferior_ptid;
582    }
583
584  lwp = GET_LWP (work_ptid);
585  if (lwp == 0)
586    {
587      /* check user thread */
588      ret = td_ta_map_id2thr_p (thread_agent, GET_THREAD(work_ptid), &th);
589      if (ret)
590        error (thread_db_err_str (ret));
591
592      /* For M:N thread, we need to tell UTS to set/unset single step
593         flag at context switch time, the flag will be written into
594         thread mailbox. This becauses some architecture may not have
595         machine single step flag in ucontext, so we put the flag in mailbox,
596         when the thread switches back, kse_switchin restores the single step
597         state.  */
598      ret = td_thr_sstep_p (&th, step);
599      if (ret)
600        error (thread_db_err_str (ret));
601      ret = td_thr_get_info_p (&th, &ti);
602      if (ret)
603        error (thread_db_err_str (ret));
604      thvalid = 1;
605      lwp = ti.ti_lid;
606    }
607
608  if (lwp)
609    {
610      int req = step ? PT_SETSTEP : PT_CLEARSTEP;
611      if (ptrace (req, (pid_t) lwp, (caddr_t) 1, target_signal_to_host(signo)))
612        perror_with_name ("PT_SETSTEP/PT_CLEARSTEP");
613    }
614
615  if (!ptid_equal (last_single_step_thread, null_ptid))
616    {
617       ret = td_ta_thr_iter_p (thread_agent, resume_thread_callback, NULL,
618          TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
619          TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
620      if (ret != TD_OK)
621        error ("resume error: %s", thread_db_err_str (ret));
622    }
623
624  if (!resume_all)
625    {
626      ret = td_ta_thr_iter_p (thread_agent, suspend_thread_callback, NULL,
627          TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
628          TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
629      if (ret != TD_OK)
630        error ("suspend error: %s", thread_db_err_str (ret));
631      last_single_step_thread = work_ptid;
632    }
633  else
634    last_single_step_thread = null_ptid;
635
636  if (thvalid)
637    {
638      ret = td_thr_dbresume_p (&th);
639      if (ret != TD_OK)
640        error ("resume error: %s", thread_db_err_str (ret));
641    }
642  else
643    {
644      /* it is not necessary, put it here for completness */
645      ret = ptrace(PT_RESUME, lwp, 0, 0);
646    }
647
648  /* now continue the process, suspended thread wont run */
649  if (ptrace (PT_CONTINUE, proc_handle.pid , (caddr_t)1,
650	      target_signal_to_host(signo)))
651    perror_with_name ("PT_CONTINUE");
652}
653
654static void
655attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
656               const td_thrinfo_t *ti_p, int verbose)
657{
658  td_err_e err;
659
660  /* Add the thread to GDB's thread list.  */
661  if (!in_thread_list (ptid)) {
662    add_thread (ptid);
663    if (verbose)
664      printf_unfiltered ("[New %s]\n", target_pid_to_str (ptid));
665  }
666
667  if (ti_p->ti_state == TD_THR_UNKNOWN || ti_p->ti_state == TD_THR_ZOMBIE)
668    return;                     /* A zombie thread -- do not attach.  */
669
670  if (! IS_THREAD(ptid))
671    return;
672  if (fbsd_thread_core != 0)
673    return;
674  /* Enable thread event reporting for this thread. */
675  err = td_thr_event_enable_p (th_p, 1);
676  if (err != TD_OK)
677    error ("Cannot enable thread event reporting for %s: %s",
678           target_pid_to_str (ptid), thread_db_err_str (err));
679}
680
681static void
682detach_thread (ptid_t ptid, int verbose)
683{
684  if (verbose)
685    printf_unfiltered ("[%s exited]\n", target_pid_to_str (ptid));
686}
687
688static void
689check_event (ptid_t ptid)
690{
691  td_event_msg_t msg;
692  td_thrinfo_t ti;
693  td_err_e err;
694  CORE_ADDR stop_pc;
695  int loop = 0;
696
697  /* Bail out early if we're not at a thread event breakpoint.  */
698  stop_pc = read_pc_pid (ptid) - DECR_PC_AFTER_BREAK;
699  if (stop_pc != td_create_bp_addr && stop_pc != td_death_bp_addr)
700    return;
701  loop = 1;
702
703  do
704    {
705      err = td_ta_event_getmsg_p (thread_agent, &msg);
706      if (err != TD_OK)
707        {
708	  if (err == TD_NOMSG)
709	    return;
710          error ("Cannot get thread event message: %s",
711		 thread_db_err_str (err));
712        }
713      err = td_thr_get_info_p (msg.th_p, &ti);
714      if (err != TD_OK)
715        error ("Cannot get thread info: %s", thread_db_err_str (err));
716      ptid = BUILD_THREAD (ti.ti_tid, GET_PID (ptid));
717      switch (msg.event)
718        {
719        case TD_CREATE:
720          /* We may already know about this thread, for instance when the
721             user has issued the `info threads' command before the SIGTRAP
722             for hitting the thread creation breakpoint was reported.  */
723          attach_thread (ptid, msg.th_p, &ti, 1);
724          break;
725       case TD_DEATH:
726         if (!in_thread_list (ptid))
727           error ("Spurious thread death event.");
728         detach_thread (ptid, 1);
729         break;
730       default:
731          error ("Spurious thread event.");
732       }
733    }
734  while (loop);
735}
736
737static ptid_t
738fbsd_thread_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
739{
740  ptid_t ret;
741  long lwp;
742  CORE_ADDR stop_pc;
743  td_thrhandle_t th;
744  td_thrinfo_t ti;
745
746  ret = child_ops.to_wait (ptid, ourstatus);
747  if (GET_PID(ret) >= 0 && ourstatus->kind == TARGET_WAITKIND_STOPPED)
748    {
749      lwp = get_current_lwp (GET_PID(ret));
750      ret = thread_from_lwp (BUILD_LWP(lwp, GET_PID(ret)),
751         &th, &ti);
752      if (!in_thread_list(ret)) {
753        /*
754         * We have to enable event reporting for initial thread
755         * which was not mapped before.
756	 */
757        attach_thread(ret, &th, &ti, 1);
758      }
759      if (ourstatus->value.sig == TARGET_SIGNAL_TRAP)
760        check_event(ret);
761      /* this is a hack, if an event won't cause gdb to stop, for example,
762         SIGARLM, gdb resumes the process immediatly without setting
763         inferior_ptid to the new thread returned here, this is a bug
764         because inferior_ptid may already not exist there, and passing
765         a none existing thread to fbsd_thread_resume causes error. */
766      if (!fbsd_thread_alive (inferior_ptid))
767        {
768          delete_thread (inferior_ptid);
769          inferior_ptid = ret;
770        }
771    }
772
773  return (ret);
774}
775
776static int
777fbsd_thread_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len, int write,
778                        struct mem_attrib *attrib, struct target_ops *target)
779{
780  int err;
781
782  if (target_has_execution)
783    err = child_ops.to_xfer_memory (memaddr, myaddr, len, write, attrib,
784	target);
785  else
786    err = orig_core_ops.to_xfer_memory (memaddr, myaddr, len, write, attrib,
787	target);
788
789  return (err);
790}
791
792static void
793fbsd_lwp_fetch_registers (int regno)
794{
795  gregset_t gregs;
796  fpregset_t fpregs;
797  lwpid_t lwp;
798#ifdef PT_GETXMMREGS
799  char xmmregs[512];
800#endif
801
802  if (!target_has_execution)
803    {
804      orig_core_ops.to_fetch_registers (-1);
805      return;
806    }
807
808  /* XXX: We've replaced the pid with the lwpid for GDB's benefit. */
809  lwp = GET_PID (inferior_ptid);
810
811  if (ptrace (PT_GETREGS, lwp, (caddr_t) &gregs, 0) == -1)
812    error ("Cannot get lwp %d registers: %s\n", lwp, safe_strerror (errno));
813  supply_gregset (&gregs);
814
815#ifdef PT_GETXMMREGS
816  if (ptrace (PT_GETXMMREGS, lwp, xmmregs, 0) == 0)
817    {
818      i387_supply_fxsave (current_regcache, -1, xmmregs);
819    }
820  else
821    {
822#endif
823      if (ptrace (PT_GETFPREGS, lwp, (caddr_t) &fpregs, 0) == -1)
824	error ("Cannot get lwp %d registers: %s\n ", lwp, safe_strerror (errno));
825      supply_fpregset (&fpregs);
826#ifdef PT_GETXMMREGS
827    }
828#endif
829}
830
831static void
832fbsd_thread_fetch_registers (int regno)
833{
834  prgregset_t gregset;
835  prfpregset_t fpregset;
836  td_thrhandle_t th;
837  td_err_e err;
838#ifdef PT_GETXMMREGS
839  char xmmregs[512];
840#endif
841
842  if (!IS_THREAD (inferior_ptid))
843    {
844      fbsd_lwp_fetch_registers (regno);
845      return;
846    }
847
848  err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (inferior_ptid), &th);
849  if (err != TD_OK)
850    error ("Cannot find thread %d: Thread ID=%ld, %s",
851           pid_to_thread_id (inferior_ptid),
852           GET_THREAD (inferior_ptid), thread_db_err_str (err));
853
854  err = td_thr_getgregs_p (&th, gregset);
855  if (err != TD_OK)
856    error ("Cannot fetch general-purpose registers for thread %d: Thread ID=%ld, %s",
857           pid_to_thread_id (inferior_ptid),
858           GET_THREAD (inferior_ptid), thread_db_err_str (err));
859#ifdef PT_GETXMMREGS
860  err = td_thr_getxmmregs_p (&th, xmmregs);
861  if (err == TD_OK)
862    {
863      i387_supply_fxsave (current_regcache, -1, xmmregs);
864    }
865  else
866    {
867#endif
868      err = td_thr_getfpregs_p (&th, &fpregset);
869      if (err != TD_OK)
870	error ("Cannot get floating-point registers for thread %d: Thread ID=%ld, %s",
871	       pid_to_thread_id (inferior_ptid),
872	       GET_THREAD (inferior_ptid), thread_db_err_str (err));
873      supply_fpregset (&fpregset);
874#ifdef PT_GETXMMREGS
875    }
876#endif
877
878  supply_gregset (gregset);
879}
880
881static void
882fbsd_lwp_store_registers (int regno)
883{
884  gregset_t gregs;
885  fpregset_t fpregs;
886  lwpid_t lwp;
887#ifdef PT_GETXMMREGS
888  char xmmregs[512];
889#endif
890
891  /* FIXME, is it possible ? */
892  if (!IS_LWP (inferior_ptid))
893    {
894      child_ops.to_store_registers (regno);
895      return ;
896    }
897
898  lwp = GET_LWP (inferior_ptid);
899  if (regno != -1)
900    if (ptrace (PT_GETREGS, lwp, (caddr_t) &gregs, 0) == -1)
901      error ("Cannot get lwp %d registers: %s\n", lwp, safe_strerror (errno));
902
903  fill_gregset (&gregs, regno);
904  if (ptrace (PT_SETREGS, lwp, (caddr_t) &gregs, 0) == -1)
905      error ("Cannot set lwp %d registers: %s\n", lwp, safe_strerror (errno));
906
907#ifdef PT_GETXMMREGS
908  if (regno != -1)
909    if (ptrace (PT_GETXMMREGS, lwp, xmmregs, 0) == -1)
910      goto noxmm;
911
912  i387_fill_fxsave (xmmregs, regno);
913  if (ptrace (PT_SETXMMREGS, lwp, xmmregs, 0) == -1)
914    goto noxmm;
915
916  return;
917
918noxmm:
919#endif
920
921  if (regno != -1)
922    if (ptrace (PT_GETFPREGS, lwp, (caddr_t) &fpregs, 0) == -1)
923      error ("Cannot get lwp %d float registers: %s\n", lwp,
924             safe_strerror (errno));
925
926  fill_fpregset (&fpregs, regno);
927  if (ptrace (PT_SETFPREGS, lwp, (caddr_t) &fpregs, 0) == -1)
928     error ("Cannot set lwp %d float registers: %s\n", lwp,
929            safe_strerror (errno));
930}
931
932static void
933fbsd_thread_store_registers (int regno)
934{
935  prgregset_t gregset;
936  prfpregset_t fpregset;
937  td_thrhandle_t th;
938  td_err_e err;
939#ifdef PT_GETXMMREGS
940  char xmmregs[512];
941#endif
942
943  if (!IS_THREAD (inferior_ptid))
944    {
945      fbsd_lwp_store_registers (regno);
946      return;
947    }
948
949  err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (inferior_ptid), &th);
950  if (err != TD_OK)
951    error ("Cannot find thread %d: Thread ID=%ld, %s",
952           pid_to_thread_id (inferior_ptid),
953           GET_THREAD (inferior_ptid),
954           thread_db_err_str (err));
955
956  if (regno != -1)
957    {
958      char old_value[MAX_REGISTER_SIZE];
959
960      regcache_collect (regno, old_value);
961      err = td_thr_getgregs_p (&th, gregset);
962      if (err != TD_OK)
963        error ("%s: td_thr_getgregs %s", __func__, thread_db_err_str (err));
964      err = td_thr_getfpregs_p (&th, &fpregset);
965      if (err != TD_OK)
966        error ("%s: td_thr_getfpgregs %s", __func__, thread_db_err_str (err));
967      supply_register (regno, old_value);
968    }
969
970  fill_gregset (gregset, regno);
971  fill_fpregset (&fpregset, regno);
972#ifdef PT_GETXMMREGS
973  i387_fill_fxsave (xmmregs, regno);
974#endif
975
976  err = td_thr_setgregs_p (&th, gregset);
977  if (err != TD_OK)
978    error ("Cannot store general-purpose registers for thread %d: Thread ID=%d, %s",
979           pid_to_thread_id (inferior_ptid), GET_THREAD (inferior_ptid),
980           thread_db_err_str (err));
981
982#ifdef PT_GETXMMREGS
983  err = td_thr_setxmmregs_p (&th, xmmregs);
984  if (err == TD_OK)
985    return;
986#endif
987
988  err = td_thr_setfpregs_p (&th, &fpregset);
989  if (err != TD_OK)
990    error ("Cannot store floating-point registers for thread %d: Thread ID=%d, %s",
991           pid_to_thread_id (inferior_ptid), GET_THREAD (inferior_ptid),
992           thread_db_err_str (err));
993}
994
995static void
996fbsd_thread_kill (void)
997{
998  child_ops.to_kill();
999}
1000
1001static int
1002fbsd_thread_can_run (void)
1003{
1004  return child_suppress_run;
1005}
1006
1007static void
1008fbsd_thread_create_inferior (char *exec_file, char *allargs, char **env)
1009{
1010  if (fbsd_thread_present && !fbsd_thread_active)
1011    push_target(&fbsd_thread_ops);
1012
1013  child_ops.to_create_inferior (exec_file, allargs, env);
1014}
1015
1016static void
1017fbsd_thread_post_startup_inferior (ptid_t ptid)
1018{
1019  if (fbsd_thread_present && !fbsd_thread_active)
1020    {
1021      /* The child process is now the actual multi-threaded
1022         program.  Snatch its process ID... */
1023      proc_handle.pid = GET_PID (ptid);
1024      td_ta_new_p (&proc_handle, &thread_agent);
1025      fbsd_thread_activate();
1026    }
1027}
1028
1029static void
1030fbsd_thread_mourn_inferior (void)
1031{
1032  if (fbsd_thread_active)
1033    fbsd_thread_deactivate ();
1034
1035  unpush_target (&fbsd_thread_ops);
1036
1037  child_ops.to_mourn_inferior ();
1038}
1039
1040static void
1041fbsd_core_check_lwp (bfd *abfd, asection *asect, void *obj)
1042{
1043  lwpid_t lwp;
1044
1045  if (strncmp (bfd_section_name (abfd, asect), ".reg/", 5) != 0)
1046    return;
1047
1048  /* already found */
1049  if (*(lwpid_t *)obj == 0)
1050    return;
1051
1052  lwp = atoi (bfd_section_name (abfd, asect) + 5);
1053  if (*(lwpid_t *)obj == lwp)
1054    *(lwpid_t *)obj = 0;
1055}
1056
1057static int
1058fbsd_thread_alive (ptid_t ptid)
1059{
1060  td_thrhandle_t th;
1061  td_thrinfo_t ti;
1062  td_err_e err;
1063  gregset_t gregs;
1064  lwpid_t lwp;
1065
1066  if (IS_THREAD (ptid))
1067    {
1068      err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (ptid), &th);
1069      if (err != TD_OK)
1070        return 0;
1071
1072      err = td_thr_get_info_p (&th, &ti);
1073      if (err != TD_OK)
1074        return 0;
1075
1076      /* A zombie thread. */
1077      if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
1078        return 0;
1079
1080      return 1;
1081    }
1082  else if (GET_LWP (ptid) == 0)
1083    {
1084      /* we sometimes are called with lwp == 0 */
1085      return 1;
1086    }
1087
1088  if (fbsd_thread_active)
1089    {
1090      err = td_ta_map_lwp2thr_p (thread_agent, GET_LWP (ptid), &th);
1091
1092      /*
1093       * if the lwp was already mapped to user thread, don't use it
1094       * directly, please use user thread id instead.
1095       */
1096      if (err == TD_OK)
1097        return 0;
1098    }
1099
1100  if (!target_has_execution)
1101    {
1102      lwp = GET_LWP (ptid);
1103      bfd_map_over_sections (core_bfd, fbsd_core_check_lwp, &lwp);
1104      return (lwp == 0);
1105    }
1106
1107  /* check lwp in kernel */
1108  return ptrace (PT_GETREGS, GET_LWP (ptid), (caddr_t)&gregs, 0) == 0;
1109}
1110
1111static void
1112fbsd_thread_files_info (struct target_ops *ignore)
1113{
1114  child_ops.to_files_info (ignore);
1115}
1116
1117static int
1118find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
1119{
1120  td_thrinfo_t ti;
1121  td_err_e err;
1122  ptid_t ptid;
1123
1124  err = td_thr_get_info_p (th_p, &ti);
1125  if (err != TD_OK)
1126    error ("Cannot get thread info: %s", thread_db_err_str (err));
1127
1128  /* Ignore zombie */
1129  if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
1130    return 0;
1131
1132  ptid = BUILD_THREAD (ti.ti_tid, proc_handle.pid);
1133  attach_thread (ptid, th_p, &ti, 1);
1134  return 0;
1135}
1136
1137static void
1138fbsd_thread_find_new_threads (void)
1139{
1140  td_err_e err;
1141
1142  if (!fbsd_thread_active)
1143    return;
1144
1145  /* Iterate over all user-space threads to discover new threads. */
1146  err = td_ta_thr_iter_p (thread_agent, find_new_threads_callback, NULL,
1147          TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
1148          TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
1149  if (err != TD_OK)
1150    error ("Cannot find new threads: %s", thread_db_err_str (err));
1151}
1152
1153static char *
1154fbsd_thread_pid_to_str (ptid_t ptid)
1155{
1156  static char buf[64];
1157
1158  if (IS_THREAD (ptid))
1159    {
1160      td_thrhandle_t th;
1161      td_thrinfo_t ti;
1162      td_err_e err;
1163
1164      err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (ptid), &th);
1165      if (err != TD_OK)
1166        error ("Cannot find thread, Thread ID=%ld, %s",
1167                GET_THREAD (ptid), thread_db_err_str (err));
1168
1169      err = td_thr_get_info_p (&th, &ti);
1170      if (err != TD_OK)
1171        error ("Cannot get thread info, Thread ID=%ld, %s",
1172               GET_THREAD (ptid), thread_db_err_str (err));
1173
1174      if (ti.ti_lid != 0)
1175        {
1176          snprintf (buf, sizeof (buf), "Thread %p (LWP %d)",
1177                    th.th_thread, ti.ti_lid);
1178        }
1179      else
1180        {
1181          snprintf (buf, sizeof (buf), "Thread %p (%s)",
1182                    th.th_thread, thread_db_state_str (ti.ti_state));
1183        }
1184
1185      return buf;
1186    }
1187  else if (IS_LWP (ptid))
1188    {
1189      snprintf (buf, sizeof (buf), "LWP %d", (int) GET_LWP (ptid));
1190      return buf;
1191    }
1192  return normal_pid_to_str (ptid);
1193}
1194
1195CORE_ADDR
1196fbsd_thread_get_local_address(ptid_t ptid, struct objfile *objfile,
1197                              CORE_ADDR offset)
1198{
1199  td_thrhandle_t th;
1200  void *address;
1201  CORE_ADDR lm;
1202  void *lm2;
1203  int ret, is_library = (objfile->flags & OBJF_SHARED);
1204
1205  if (IS_THREAD (ptid))
1206    {
1207      if (!td_thr_tls_get_addr_p)
1208        error ("Cannot find thread-local interface in thread_db library.");
1209
1210      /* Get the address of the link map for this objfile. */
1211      lm = svr4_fetch_objfile_link_map (objfile);
1212
1213      /* Couldn't find link map. Bail out. */
1214      if (!lm)
1215        {
1216          if (is_library)
1217            error ("Cannot find shared library `%s' link_map in dynamic"
1218                   " linker's module list", objfile->name);
1219          else
1220            error ("Cannot find executable file `%s' link_map in dynamic"
1221                   " linker's module list", objfile->name);
1222        }
1223
1224      ret = td_ta_map_id2thr_p (thread_agent, GET_THREAD(ptid), &th);
1225
1226      /* get the address of the variable. */
1227      store_typed_address(&lm2, builtin_type_void_data_ptr, lm);
1228      ret = td_thr_tls_get_addr_p (&th, lm2, offset, &address);
1229
1230      if (ret != TD_OK)
1231        {
1232          if (is_library)
1233            error ("Cannot find thread-local storage for thread %ld, "
1234                   "shared library %s:\n%s",
1235                   (long) GET_THREAD (ptid),
1236                   objfile->name, thread_db_err_str (ret));
1237          else
1238            error ("Cannot find thread-local storage for thread %ld, "
1239                   "executable file %s:\n%s",
1240                   (long) GET_THREAD (ptid),
1241                   objfile->name, thread_db_err_str (ret));
1242        }
1243
1244      /* Cast assuming host == target. */
1245      return extract_typed_address(&address, builtin_type_void_data_ptr);
1246    }
1247  return (0);
1248}
1249
1250static int
1251tsd_cb (thread_key_t key, void (*destructor)(void *), void *ignore)
1252{
1253  struct minimal_symbol *ms;
1254  char *name;
1255
1256  ms = lookup_minimal_symbol_by_pc (
1257	extract_typed_address(&destructor, builtin_type_void_func_ptr));
1258  if (!ms)
1259    name = "???";
1260  else
1261    name = DEPRECATED_SYMBOL_NAME (ms);
1262
1263  printf_filtered ("Destructor %p <%s>\n", destructor, name);
1264  return 0;
1265}
1266
1267static void
1268fbsd_thread_tsd_cmd (char *exp, int from_tty)
1269{
1270  if (fbsd_thread_active)
1271    td_ta_tsd_iter_p (thread_agent, tsd_cb, NULL);
1272}
1273
1274static void
1275fbsd_print_sigset (sigset_t *set)
1276{
1277  int i;
1278
1279  for (i = 1; i <= _SIG_MAXSIG; ++i) {
1280     if (sigismember(set, i)) {
1281       if (i < sizeof(sys_signame)/sizeof(sys_signame[0]))
1282         printf_filtered("%s ", sys_signame[i]);
1283       else
1284         printf_filtered("sig%d ", i);
1285     }
1286  }
1287  printf_filtered("\n");
1288}
1289
1290static void
1291fbsd_thread_signal_cmd (char *exp, int from_tty)
1292{
1293  td_thrhandle_t th;
1294  td_thrinfo_t ti;
1295  td_err_e err;
1296
1297  if (!fbsd_thread_active || !IS_THREAD(inferior_ptid))
1298    return;
1299
1300  err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (inferior_ptid), &th);
1301  if (err != TD_OK)
1302    return;
1303
1304  err = td_thr_get_info_p (&th, &ti);
1305  if (err != TD_OK)
1306    return;
1307
1308  printf_filtered("signal mask:\n");
1309  fbsd_print_sigset(&ti.ti_sigmask);
1310  printf_filtered("signal pending:\n");
1311  fbsd_print_sigset(&ti.ti_pending);
1312}
1313
1314static int
1315ignore (CORE_ADDR addr, char *contents)
1316{
1317  return 0;
1318}
1319
1320static void
1321fbsd_core_open (char *filename, int from_tty)
1322{
1323  int err;
1324
1325  fbsd_thread_core = 1;
1326
1327  orig_core_ops.to_open (filename, from_tty);
1328
1329  if (fbsd_thread_present)
1330    {
1331      err = td_ta_new_p (&proc_handle, &thread_agent);
1332      if (err == TD_OK)
1333        {
1334          proc_handle.pid = elf_tdata (core_bfd)->core_pid;
1335          fbsd_thread_activate ();
1336        }
1337      else
1338        error ("fbsd_core_open: td_ta_new: %s", thread_db_err_str (err));
1339    }
1340}
1341
1342static void
1343fbsd_core_close (int quitting)
1344{
1345  orig_core_ops.to_close (quitting);
1346}
1347
1348static void
1349fbsd_core_detach (char *args, int from_tty)
1350{
1351  if (fbsd_thread_active)
1352    fbsd_thread_deactivate ();
1353  unpush_target (&fbsd_thread_ops);
1354  orig_core_ops.to_detach (args, from_tty);
1355
1356  /* Clear gdb solib information and symbol file
1357     cache, so that after detach and re-attach, new_objfile
1358     hook will be called */
1359  clear_solib();
1360  symbol_file_clear(0);
1361}
1362
1363static void
1364fbsd_core_files_info (struct target_ops *ignore)
1365{
1366  orig_core_ops.to_files_info (ignore);
1367}
1368
1369static void
1370init_fbsd_core_ops (void)
1371{
1372  fbsd_core_ops.to_shortname = "FreeBSD-core";
1373  fbsd_core_ops.to_longname = "FreeBSD core thread.";
1374  fbsd_core_ops.to_doc = "FreeBSD threads support for core files.";
1375  fbsd_core_ops.to_open = fbsd_core_open;
1376  fbsd_core_ops.to_close = fbsd_core_close;
1377  fbsd_core_ops.to_attach = 0;
1378  fbsd_core_ops.to_post_attach = 0;
1379  fbsd_core_ops.to_detach = fbsd_core_detach;
1380  /* fbsd_core_ops.to_resume  = 0; */
1381  /* fbsd_core_ops.to_wait  = 0;  */
1382  fbsd_core_ops.to_fetch_registers = fbsd_thread_fetch_registers;
1383  /* fbsd_core_ops.to_store_registers  = 0; */
1384  /* fbsd_core_ops.to_prepare_to_store  = 0; */
1385  fbsd_core_ops.to_xfer_memory = fbsd_thread_xfer_memory;
1386  fbsd_core_ops.to_files_info = fbsd_core_files_info;
1387  fbsd_core_ops.to_insert_breakpoint = ignore;
1388  fbsd_core_ops.to_remove_breakpoint = ignore;
1389  /* fbsd_core_ops.to_lookup_symbol  = 0; */
1390  fbsd_core_ops.to_create_inferior = fbsd_thread_create_inferior;
1391  fbsd_core_ops.to_stratum = core_stratum;
1392  fbsd_core_ops.to_has_all_memory = 0;
1393  fbsd_core_ops.to_has_memory = 1;
1394  fbsd_core_ops.to_has_stack = 1;
1395  fbsd_core_ops.to_has_registers = 1;
1396  fbsd_core_ops.to_has_execution = 0;
1397  fbsd_core_ops.to_has_thread_control = tc_none;
1398  fbsd_core_ops.to_thread_alive = fbsd_thread_alive;
1399  fbsd_core_ops.to_pid_to_str = fbsd_thread_pid_to_str;
1400  fbsd_core_ops.to_find_new_threads = fbsd_thread_find_new_threads;
1401  fbsd_core_ops.to_sections = 0;
1402  fbsd_core_ops.to_sections_end = 0;
1403  fbsd_core_ops.to_magic = OPS_MAGIC;
1404}
1405
1406static void
1407init_fbsd_thread_ops (void)
1408{
1409  fbsd_thread_ops.to_shortname = "freebsd-threads";
1410  fbsd_thread_ops.to_longname = "FreeBSD multithreaded child process.";
1411  fbsd_thread_ops.to_doc = "FreeBSD threads support.";
1412  fbsd_thread_ops.to_attach = fbsd_thread_attach;
1413  fbsd_thread_ops.to_detach = fbsd_thread_detach;
1414  fbsd_thread_ops.to_post_attach = fbsd_thread_post_attach;
1415  fbsd_thread_ops.to_resume = fbsd_thread_resume;
1416  fbsd_thread_ops.to_wait = fbsd_thread_wait;
1417  fbsd_thread_ops.to_fetch_registers = fbsd_thread_fetch_registers;
1418  fbsd_thread_ops.to_store_registers = fbsd_thread_store_registers;
1419  fbsd_thread_ops.to_xfer_memory = fbsd_thread_xfer_memory;
1420  fbsd_thread_ops.to_files_info = fbsd_thread_files_info;
1421  fbsd_thread_ops.to_kill = fbsd_thread_kill;
1422  fbsd_thread_ops.to_create_inferior = fbsd_thread_create_inferior;
1423  fbsd_thread_ops.to_post_startup_inferior = fbsd_thread_post_startup_inferior;
1424  fbsd_thread_ops.to_mourn_inferior = fbsd_thread_mourn_inferior;
1425  fbsd_thread_ops.to_can_run = fbsd_thread_can_run;
1426  fbsd_thread_ops.to_thread_alive = fbsd_thread_alive;
1427  fbsd_thread_ops.to_find_new_threads = fbsd_thread_find_new_threads;
1428  fbsd_thread_ops.to_pid_to_str = fbsd_thread_pid_to_str;
1429  fbsd_thread_ops.to_stratum = thread_stratum;
1430  fbsd_thread_ops.to_has_thread_control = tc_none;
1431  fbsd_thread_ops.to_has_all_memory = 1;
1432  fbsd_thread_ops.to_has_memory = 1;
1433  fbsd_thread_ops.to_has_stack = 1;
1434  fbsd_thread_ops.to_has_registers = 1;
1435  fbsd_thread_ops.to_has_execution = 1;
1436  fbsd_thread_ops.to_insert_breakpoint = memory_insert_breakpoint;
1437  fbsd_thread_ops.to_remove_breakpoint = memory_remove_breakpoint;
1438  fbsd_thread_ops.to_get_thread_local_address = fbsd_thread_get_local_address;
1439  fbsd_thread_ops.to_magic = OPS_MAGIC;
1440}
1441
1442static int
1443thread_db_load (void)
1444{
1445  void *handle;
1446  td_err_e err;
1447
1448  handle = dlopen (LIBTHREAD_DB_SO, RTLD_NOW);
1449  if (handle == NULL)
1450      return 0;
1451
1452#define resolve(X)			\
1453 if (!(X##_p = dlsym (handle, #X)))	\
1454   return 0;
1455
1456  resolve(td_init);
1457  resolve(td_ta_new);
1458  resolve(td_ta_delete);
1459  resolve(td_ta_map_id2thr);
1460  resolve(td_ta_map_lwp2thr);
1461  resolve(td_ta_thr_iter);
1462  resolve(td_thr_get_info);
1463#ifdef PT_GETXMMREGS
1464  resolve(td_thr_getxmmregs);
1465#endif
1466  resolve(td_thr_getfpregs);
1467  resolve(td_thr_getgregs);
1468#ifdef PT_GETXMMREGS
1469  resolve(td_thr_setxmmregs);
1470#endif
1471  resolve(td_thr_setfpregs);
1472  resolve(td_thr_setgregs);
1473  resolve(td_thr_sstep);
1474  resolve(td_ta_tsd_iter);
1475  resolve(td_thr_dbsuspend);
1476  resolve(td_thr_dbresume);
1477  resolve(td_thr_tls_get_addr);
1478
1479  /* Initialize the library.  */
1480  err = td_init_p ();
1481  if (err != TD_OK)
1482    {
1483      warning ("Cannot initialize libthread_db: %s", thread_db_err_str (err));
1484      return 0;
1485    }
1486
1487  /* These are not essential.  */
1488  td_ta_event_addr_p = dlsym (handle, "td_ta_event_addr");
1489  td_ta_set_event_p = dlsym (handle, "td_ta_set_event");
1490  td_ta_event_getmsg_p = dlsym (handle, "td_ta_event_getmsg");
1491  td_thr_event_enable_p = dlsym (handle, "td_thr_event_enable");
1492  td_thr_tls_get_addr_p = dlsym (handle, "td_thr_tls_get_addr");
1493
1494  return 1;
1495}
1496
1497/* we suppress the call to add_target of core_ops in corelow because
1498   if there are two targets in the stratum core_stratum, find_core_target
1499   won't know which one to return.  see corelow.c for an additonal
1500   comment on coreops_suppress_target. */
1501
1502int coreops_suppress_target = 1;
1503
1504void
1505_initialize_thread_db (void)
1506{
1507  init_fbsd_thread_ops ();
1508  init_fbsd_core_ops ();
1509
1510  if (thread_db_load ())
1511    {
1512      add_target (&fbsd_thread_ops);
1513
1514      /* "thread tsd" command */
1515      add_cmd ("tsd", class_run, fbsd_thread_tsd_cmd,
1516            "Show the thread-specific data keys and destructors "
1517            "for the process.\n",
1518           &thread_cmd_list);
1519
1520      add_cmd ("signal", class_run, fbsd_thread_signal_cmd,
1521            "Show the thread signal info.\n",
1522           &thread_cmd_list);
1523
1524      memcpy (&orig_core_ops, &core_ops, sizeof (struct target_ops));
1525      memcpy (&core_ops, &fbsd_core_ops, sizeof (struct target_ops));
1526      add_target (&core_ops);
1527
1528      /* Add ourselves to objfile event chain. */
1529      target_new_objfile_chain = target_new_objfile_hook;
1530      target_new_objfile_hook = fbsd_thread_new_objfile;
1531
1532      child_suppress_run = 1;
1533    }
1534  else
1535    {
1536      fprintf_unfiltered (gdb_stderr,
1537        "[GDB will not be able to debug user-mode threads: %s]\n", dlerror());
1538
1539      /* allow the user to debug non-threaded core files */
1540      add_target (&core_ops);
1541    }
1542}
1543
1544/* proc service functions */
1545void
1546ps_plog (const char *fmt, ...)
1547{
1548  va_list args;
1549
1550  va_start (args, fmt);
1551  vfprintf_filtered (gdb_stderr, fmt, args);
1552  va_end (args);
1553}
1554
1555ps_err_e
1556ps_pglobal_lookup (struct ps_prochandle *ph, const char *obj,
1557   const char *name, psaddr_t *sym_addr)
1558{
1559  struct minimal_symbol *ms;
1560  CORE_ADDR addr;
1561
1562  ms = lookup_minimal_symbol (name, NULL, NULL);
1563  if (ms == NULL)
1564    return PS_NOSYM;
1565
1566  addr = SYMBOL_VALUE_ADDRESS (ms);
1567  store_typed_address(sym_addr, builtin_type_void_data_ptr, addr);
1568  return PS_OK;
1569}
1570
1571ps_err_e
1572ps_pread (struct ps_prochandle *ph, psaddr_t addr, void *buf, size_t len)
1573{
1574  int err = target_read_memory (
1575    extract_typed_address(&addr, builtin_type_void_data_ptr), buf, len);
1576  return (err == 0 ? PS_OK : PS_ERR);
1577}
1578
1579ps_err_e
1580ps_pwrite (struct ps_prochandle *ph, psaddr_t addr, const void *buf,
1581            size_t len)
1582{
1583  int err = target_write_memory (
1584    extract_typed_address(&addr, builtin_type_void_data_ptr), (void *)buf, len);
1585  return (err == 0 ? PS_OK : PS_ERR);
1586}
1587
1588ps_err_e
1589ps_lgetregs (struct ps_prochandle *ph, lwpid_t lwpid, prgregset_t gregset)
1590{
1591  struct cleanup *old_chain;
1592
1593  old_chain = save_inferior_ptid ();
1594
1595  /* XXX: Target operation isn't lwp aware: replace pid with lwp */
1596  inferior_ptid = BUILD_LWP (0, lwpid);
1597
1598  target_fetch_registers (-1);
1599  fill_gregset (gregset, -1);
1600  do_cleanups (old_chain);
1601  return PS_OK;
1602}
1603
1604ps_err_e
1605ps_lsetregs (struct ps_prochandle *ph, lwpid_t lwpid, const prgregset_t gregset)
1606{
1607  struct cleanup *old_chain;
1608
1609  old_chain = save_inferior_ptid ();
1610  inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1611  supply_gregset (gregset);
1612  target_store_registers (-1);
1613  do_cleanups (old_chain);
1614  return PS_OK;
1615}
1616
1617ps_err_e
1618ps_lgetfpregs (struct ps_prochandle *ph, lwpid_t lwpid, prfpregset_t *fpregset)
1619{
1620  struct cleanup *old_chain;
1621
1622  old_chain = save_inferior_ptid ();
1623  inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1624  target_fetch_registers (-1);
1625  fill_fpregset (fpregset, -1);
1626  do_cleanups (old_chain);
1627  return PS_OK;
1628}
1629
1630ps_err_e
1631ps_lsetfpregs (struct ps_prochandle *ph, lwpid_t lwpid,
1632               const prfpregset_t *fpregset)
1633{
1634  struct cleanup *old_chain;
1635
1636  old_chain = save_inferior_ptid ();
1637  inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1638  supply_fpregset (fpregset);
1639  target_store_registers (-1);
1640  do_cleanups (old_chain);
1641  return PS_OK;
1642}
1643
1644#ifdef PT_GETXMMREGS
1645ps_err_e
1646ps_lgetxmmregs (struct ps_prochandle *ph, lwpid_t lwpid, char *xmmregs)
1647{
1648  struct cleanup *old_chain;
1649
1650  old_chain = save_inferior_ptid ();
1651  inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1652  target_fetch_registers (-1);
1653  i387_fill_fxsave (xmmregs, -1);
1654  do_cleanups (old_chain);
1655  return PS_OK;
1656}
1657
1658ps_err_e
1659ps_lsetxmmregs (struct ps_prochandle *ph, lwpid_t lwpid,
1660		const char *xmmregs)
1661{
1662  struct cleanup *old_chain;
1663
1664  old_chain = save_inferior_ptid ();
1665  inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1666  i387_supply_fxsave (current_regcache, -1, xmmregs);
1667  target_store_registers (-1);
1668  do_cleanups (old_chain);
1669  return PS_OK;
1670}
1671#endif
1672
1673ps_err_e
1674ps_lstop(struct ps_prochandle *ph, lwpid_t lwpid)
1675{
1676  if (ptrace (PT_SUSPEND, lwpid, 0, 0) == -1)
1677    return PS_ERR;
1678  return PS_OK;
1679}
1680
1681ps_err_e
1682ps_lcontinue(struct ps_prochandle *ph, lwpid_t lwpid)
1683{
1684  if (ptrace (PT_RESUME, lwpid, 0, 0) == -1)
1685    return PS_ERR;
1686  return PS_OK;
1687}
1688
1689ps_err_e
1690ps_linfo(struct ps_prochandle *ph, lwpid_t lwpid, void *info)
1691{
1692  if (fbsd_thread_core) {
1693    /* XXX should verify lwpid and make a pseudo lwp info */
1694    memset(info, 0, sizeof(struct ptrace_lwpinfo));
1695    return PS_OK;
1696  }
1697
1698  if (ptrace (PT_LWPINFO, lwpid, info, sizeof(struct ptrace_lwpinfo)) == -1)
1699    return PS_ERR;
1700  return PS_OK;
1701}
1702