]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - gnu/usr.bin/gdb/libgdb/fbsd-threads.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / gnu / usr.bin / gdb / libgdb / fbsd-threads.c
1 /* $FreeBSD$ */
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
48 struct ps_prochandle
49 {
50   pid_t pid;
51 };
52
53 extern int child_suppress_run;
54
55 extern struct target_ops child_ops;
56
57 /* This module's target vectors.  */
58 static struct target_ops fbsd_thread_ops;
59 static struct target_ops fbsd_core_ops;
60
61 /* Saved copy of orignal core_ops. */
62 static struct target_ops orig_core_ops;
63 extern struct target_ops core_ops;
64
65 /* Pointer to the next function on the objfile event chain.  */
66 static void (*target_new_objfile_chain) (struct objfile *objfile);
67
68 /* Non-zero if there is a thread module */
69 static int fbsd_thread_present;
70
71 /* Non-zero if we're using this module's target vector.  */
72 static int fbsd_thread_active;
73
74 /* Non-zero if core_open is called */
75 static int fbsd_thread_core = 0;
76
77 /* Non-zero if we have to keep this module's target vector active
78    across re-runs.  */
79 static int keep_thread_db;
80
81 /* Structure that identifies the child process for the
82    <proc_service.h> interface.  */
83 static struct ps_prochandle proc_handle;
84
85 /* Connection to the libthread_db library.  */
86 static td_thragent_t *thread_agent;
87
88 /* The last thread we are single stepping */
89 static ptid_t last_single_step_thread;
90
91 /* Pointers to the libthread_db functions.  */
92
93 static td_err_e (*td_init_p) (void);
94
95 static td_err_e (*td_ta_new_p) (struct ps_prochandle *ps, td_thragent_t **ta);
96 static td_err_e (*td_ta_delete_p) (td_thragent_t *);
97 static td_err_e (*td_ta_map_id2thr_p) (const td_thragent_t *ta, thread_t pt,
98                                        td_thrhandle_t *__th);
99 static td_err_e (*td_ta_map_lwp2thr_p) (const td_thragent_t *ta, lwpid_t lwpid,
100                                         td_thrhandle_t *th);
101 static 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);
106 static td_err_e (*td_ta_event_addr_p) (const td_thragent_t *ta,
107                                        td_event_e event, td_notify_t *ptr);
108 static td_err_e (*td_ta_set_event_p) (const td_thragent_t *ta,
109                                       td_thr_events_t *event);
110 static td_err_e (*td_ta_event_getmsg_p) (const td_thragent_t *ta,
111                                          td_event_msg_t *msg);
112 static td_err_e (*td_thr_get_info_p) (const td_thrhandle_t *th,
113                                       td_thrinfo_t *infop);
114 #ifdef PT_GETXMMREGS
115 static td_err_e (*td_thr_getxmmregs_p) (const td_thrhandle_t *th,
116                                         char *regset);
117 #endif
118 static td_err_e (*td_thr_getfpregs_p) (const td_thrhandle_t *th,
119                                        prfpregset_t *regset);
120 static td_err_e (*td_thr_getgregs_p) (const td_thrhandle_t *th,
121                                       prgregset_t gregs);
122 #ifdef PT_GETXMMREGS
123 static td_err_e (*td_thr_setxmmregs_p) (const td_thrhandle_t *th,
124                                         const char *fpregs);
125 #endif
126 static td_err_e (*td_thr_setfpregs_p) (const td_thrhandle_t *th,
127                                        const prfpregset_t *fpregs);
128 static td_err_e (*td_thr_setgregs_p) (const td_thrhandle_t *th,
129                                       prgregset_t gregs);
130 static td_err_e (*td_thr_event_enable_p) (const td_thrhandle_t *th, int event);
131
132 static td_err_e (*td_thr_sstep_p) (td_thrhandle_t *th, int step);
133
134 static td_err_e (*td_ta_tsd_iter_p) (const td_thragent_t *ta,
135                                  td_key_iter_f *func, void *data);
136 static td_err_e (*td_thr_tls_get_addr_p) (const td_thrhandle_t *th,
137                                           void *map_address,
138                                           size_t offset, void **address);
139 static td_err_e (*td_thr_dbsuspend_p) (const td_thrhandle_t *);
140 static td_err_e (*td_thr_dbresume_p) (const td_thrhandle_t *);
141
142 static CORE_ADDR td_create_bp_addr;
143
144 /* Location of the thread death event breakpoint.  */
145 static CORE_ADDR td_death_bp_addr;
146
147 /* Prototypes for local functions.  */
148 static void fbsd_thread_find_new_threads (void);
149 static int fbsd_thread_alive (ptid_t ptid);
150 static void attach_thread (ptid_t ptid, const td_thrhandle_t *th_p,
151                const td_thrinfo_t *ti_p, int verbose);
152 static 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
166 static char *
167 thread_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
221 static char *
222 thread_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. */
247 static ptid_t
248 thread_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
270 static void
271 fbsd_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
282 static long
283 get_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
300 static void
301 get_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
318 static td_err_e
319 enable_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
338 static void
339 enable_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
388 static void
389 disable_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
404 static void
405 fbsd_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
415 static void
416 fbsd_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
429 static void
430 fbsd_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
498 static void
499 fbsd_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
512 static void
513 fbsd_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
524 static void
525 fbsd_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
540 static int
541 suspend_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
549 static int
550 resume_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
558 static void
559 fbsd_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
654 static void
655 attach_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
681 static void
682 detach_thread (ptid_t ptid, int verbose)
683 {
684   if (verbose)
685     printf_unfiltered ("[%s exited]\n", target_pid_to_str (ptid));
686 }
687
688 static void
689 check_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
737 static ptid_t
738 fbsd_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
776 static int
777 fbsd_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
792 static void
793 fbsd_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
831 static void
832 fbsd_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
881 static void
882 fbsd_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
918 noxmm:
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
932 static void
933 fbsd_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 #ifdef PT_GETXMMREGS
965       err = td_thr_getxmmregs_p (&th, xmmregs);
966       if (err != TD_OK)
967         {
968 #endif
969           err = td_thr_getfpregs_p (&th, &fpregset);
970           if (err != TD_OK)
971             error ("%s: td_thr_getfpgregs %s", __func__, thread_db_err_str (err));
972 #ifdef PT_GETXMMREGS
973         }
974 #endif
975       supply_register (regno, old_value);
976     }
977
978   fill_gregset (gregset, regno);
979   err = td_thr_setgregs_p (&th, gregset);
980   if (err != TD_OK)
981     error ("Cannot store general-purpose registers for thread %d: Thread ID=%d, %s",
982            pid_to_thread_id (inferior_ptid), GET_THREAD (inferior_ptid),
983            thread_db_err_str (err));
984
985 #ifdef PT_GETXMMREGS
986   i387_fill_fxsave (xmmregs, regno);
987   err = td_thr_setxmmregs_p (&th, xmmregs);
988   if (err == TD_OK)
989     return;
990 #endif
991
992   fill_fpregset (&fpregset, regno);
993   err = td_thr_setfpregs_p (&th, &fpregset);
994   if (err != TD_OK)
995     error ("Cannot store floating-point registers for thread %d: Thread ID=%d, %s",
996            pid_to_thread_id (inferior_ptid), GET_THREAD (inferior_ptid),
997            thread_db_err_str (err));
998 }
999
1000 static void
1001 fbsd_thread_kill (void)
1002 {
1003   child_ops.to_kill();
1004 }
1005
1006 static int
1007 fbsd_thread_can_run (void)
1008 {
1009   return child_suppress_run;
1010 }
1011
1012 static void
1013 fbsd_thread_create_inferior (char *exec_file, char *allargs, char **env)
1014 {
1015   if (fbsd_thread_present && !fbsd_thread_active)
1016     push_target(&fbsd_thread_ops);
1017
1018   child_ops.to_create_inferior (exec_file, allargs, env);
1019 }
1020
1021 static void
1022 fbsd_thread_post_startup_inferior (ptid_t ptid)
1023 {
1024   if (fbsd_thread_present && !fbsd_thread_active)
1025     {
1026       /* The child process is now the actual multi-threaded
1027          program.  Snatch its process ID... */
1028       proc_handle.pid = GET_PID (ptid);
1029       td_ta_new_p (&proc_handle, &thread_agent);
1030       fbsd_thread_activate();
1031     }
1032 }
1033
1034 static void
1035 fbsd_thread_mourn_inferior (void)
1036 {
1037   if (fbsd_thread_active)
1038     fbsd_thread_deactivate ();
1039
1040   unpush_target (&fbsd_thread_ops);
1041
1042   child_ops.to_mourn_inferior ();
1043 }
1044
1045 static void
1046 fbsd_core_check_lwp (bfd *abfd, asection *asect, void *obj)
1047 {
1048   lwpid_t lwp;
1049
1050   if (strncmp (bfd_section_name (abfd, asect), ".reg/", 5) != 0)
1051     return;
1052
1053   /* already found */
1054   if (*(lwpid_t *)obj == 0)
1055     return;
1056
1057   lwp = atoi (bfd_section_name (abfd, asect) + 5);
1058   if (*(lwpid_t *)obj == lwp)
1059     *(lwpid_t *)obj = 0;
1060 }
1061
1062 static int
1063 fbsd_thread_alive (ptid_t ptid)
1064 {
1065   td_thrhandle_t th;
1066   td_thrinfo_t ti;
1067   td_err_e err;
1068   gregset_t gregs;
1069   lwpid_t lwp;
1070
1071   if (IS_THREAD (ptid))
1072     {
1073       err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (ptid), &th);
1074       if (err != TD_OK)
1075         return 0;
1076
1077       err = td_thr_get_info_p (&th, &ti);
1078       if (err != TD_OK)
1079         return 0;
1080
1081       /* A zombie thread. */
1082       if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
1083         return 0;
1084
1085       return 1;
1086     }
1087   else if (GET_LWP (ptid) == 0)
1088     {
1089       /* we sometimes are called with lwp == 0 */
1090       return 1;
1091     }
1092
1093   if (fbsd_thread_active)
1094     {
1095       err = td_ta_map_lwp2thr_p (thread_agent, GET_LWP (ptid), &th);
1096
1097       /*
1098        * if the lwp was already mapped to user thread, don't use it
1099        * directly, please use user thread id instead.
1100        */
1101       if (err == TD_OK)
1102         return 0;
1103     }
1104
1105   if (!target_has_execution)
1106     {
1107       lwp = GET_LWP (ptid);
1108       bfd_map_over_sections (core_bfd, fbsd_core_check_lwp, &lwp);
1109       return (lwp == 0); 
1110     }
1111
1112   /* check lwp in kernel */
1113   return ptrace (PT_GETREGS, GET_LWP (ptid), (caddr_t)&gregs, 0) == 0;
1114 }
1115
1116 static void
1117 fbsd_thread_files_info (struct target_ops *ignore)
1118 {
1119   child_ops.to_files_info (ignore);
1120 }
1121
1122 static int
1123 find_new_threads_callback (const td_thrhandle_t *th_p, void *data)
1124 {
1125   td_thrinfo_t ti;
1126   td_err_e err;
1127   ptid_t ptid;
1128
1129   err = td_thr_get_info_p (th_p, &ti);
1130   if (err != TD_OK)
1131     error ("Cannot get thread info: %s", thread_db_err_str (err));
1132
1133   /* Ignore zombie */
1134   if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE)
1135     return 0;
1136
1137   ptid = BUILD_THREAD (ti.ti_tid, proc_handle.pid);
1138   attach_thread (ptid, th_p, &ti, 1);
1139   return 0;
1140 }
1141
1142 static void
1143 fbsd_thread_find_new_threads (void)
1144 {
1145   td_err_e err;
1146
1147   if (!fbsd_thread_active)
1148     return;
1149
1150   /* Iterate over all user-space threads to discover new threads. */
1151   err = td_ta_thr_iter_p (thread_agent, find_new_threads_callback, NULL,
1152           TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
1153           TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS);
1154   if (err != TD_OK)
1155     error ("Cannot find new threads: %s", thread_db_err_str (err));
1156 }
1157
1158 static char *
1159 fbsd_thread_pid_to_str (ptid_t ptid)
1160 {
1161   static char buf[64];
1162
1163   if (IS_THREAD (ptid))
1164     {
1165       td_thrhandle_t th;
1166       td_thrinfo_t ti;
1167       td_err_e err;
1168
1169       err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (ptid), &th);
1170       if (err != TD_OK)
1171         error ("Cannot find thread, Thread ID=%ld, %s",
1172                 GET_THREAD (ptid), thread_db_err_str (err));
1173
1174       err = td_thr_get_info_p (&th, &ti);
1175       if (err != TD_OK)
1176         error ("Cannot get thread info, Thread ID=%ld, %s",
1177                GET_THREAD (ptid), thread_db_err_str (err));
1178
1179       if (ti.ti_lid != 0)
1180         {
1181           snprintf (buf, sizeof (buf), "Thread %p (LWP %d)",
1182                     th.th_thread, ti.ti_lid);
1183         }
1184       else
1185         {
1186           snprintf (buf, sizeof (buf), "Thread %p (%s)",
1187                     th.th_thread, thread_db_state_str (ti.ti_state));
1188         }
1189
1190       return buf;
1191     }
1192   else if (IS_LWP (ptid))
1193     {
1194       snprintf (buf, sizeof (buf), "LWP %d", (int) GET_LWP (ptid));
1195       return buf;
1196     }
1197   return normal_pid_to_str (ptid);
1198 }
1199
1200 CORE_ADDR
1201 fbsd_thread_get_local_address(ptid_t ptid, struct objfile *objfile,
1202                               CORE_ADDR offset)
1203 {
1204   td_thrhandle_t th;
1205   void *address;
1206   CORE_ADDR lm;
1207   void *lm2;
1208   int ret, is_library = (objfile->flags & OBJF_SHARED);
1209
1210   if (IS_THREAD (ptid))
1211     {
1212       if (!td_thr_tls_get_addr_p)
1213         error ("Cannot find thread-local interface in thread_db library.");
1214
1215       /* Get the address of the link map for this objfile. */
1216       lm = svr4_fetch_objfile_link_map (objfile);
1217
1218       /* Couldn't find link map. Bail out. */
1219       if (!lm)
1220         {
1221           if (is_library)
1222             error ("Cannot find shared library `%s' link_map in dynamic"
1223                    " linker's module list", objfile->name);
1224           else
1225             error ("Cannot find executable file `%s' link_map in dynamic"
1226                    " linker's module list", objfile->name);
1227         }
1228
1229       ret = td_ta_map_id2thr_p (thread_agent, GET_THREAD(ptid), &th);
1230
1231       /* get the address of the variable. */
1232       store_typed_address(&lm2, builtin_type_void_data_ptr, lm);
1233       ret = td_thr_tls_get_addr_p (&th, lm2, offset, &address);
1234
1235       if (ret != TD_OK)
1236         {
1237           if (is_library)
1238             error ("Cannot find thread-local storage for thread %ld, "
1239                    "shared library %s:\n%s",
1240                    (long) GET_THREAD (ptid),
1241                    objfile->name, thread_db_err_str (ret));
1242           else
1243             error ("Cannot find thread-local storage for thread %ld, "
1244                    "executable file %s:\n%s",
1245                    (long) GET_THREAD (ptid),
1246                    objfile->name, thread_db_err_str (ret));
1247         }
1248
1249       /* Cast assuming host == target. */
1250       return extract_typed_address(&address, builtin_type_void_data_ptr);
1251     }
1252   return (0);
1253 }
1254
1255 static int
1256 tsd_cb (thread_key_t key, void (*destructor)(void *), void *ignore)
1257 {
1258   struct minimal_symbol *ms;
1259   char *name;
1260
1261   ms = lookup_minimal_symbol_by_pc (
1262         extract_typed_address(&destructor, builtin_type_void_func_ptr));
1263   if (!ms)
1264     name = "???";
1265   else
1266     name = DEPRECATED_SYMBOL_NAME (ms);
1267
1268   printf_filtered ("Destructor %p <%s>\n", destructor, name);
1269   return 0;
1270 }
1271
1272 static void
1273 fbsd_thread_tsd_cmd (char *exp, int from_tty)
1274 {
1275   if (fbsd_thread_active)
1276     td_ta_tsd_iter_p (thread_agent, tsd_cb, NULL);
1277 }
1278
1279 static void
1280 fbsd_print_sigset (sigset_t *set)
1281 {
1282   int i;
1283
1284   for (i = 1; i <= _SIG_MAXSIG; ++i) {
1285      if (sigismember(set, i)) {
1286        if (i < sizeof(sys_signame)/sizeof(sys_signame[0]))
1287          printf_filtered("%s ", sys_signame[i]);
1288        else
1289          printf_filtered("sig%d ", i);
1290      }
1291   }
1292   printf_filtered("\n");
1293 }
1294
1295 static void
1296 fbsd_thread_signal_cmd (char *exp, int from_tty)
1297 {
1298   td_thrhandle_t th;
1299   td_thrinfo_t ti;
1300   td_err_e err;
1301
1302   if (!fbsd_thread_active || !IS_THREAD(inferior_ptid))
1303     return;
1304
1305   err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (inferior_ptid), &th);
1306   if (err != TD_OK)
1307     return;
1308
1309   err = td_thr_get_info_p (&th, &ti);
1310   if (err != TD_OK)
1311     return;
1312
1313   printf_filtered("signal mask:\n");
1314   fbsd_print_sigset(&ti.ti_sigmask);
1315   printf_filtered("signal pending:\n");
1316   fbsd_print_sigset(&ti.ti_pending);
1317 }
1318
1319 static int
1320 ignore (CORE_ADDR addr, char *contents)
1321 {
1322   return 0;
1323 }
1324
1325 static void
1326 fbsd_core_open (char *filename, int from_tty)
1327 {
1328   int err;
1329
1330   fbsd_thread_core = 1;
1331
1332   orig_core_ops.to_open (filename, from_tty);
1333
1334   if (fbsd_thread_present)
1335     {
1336       err = td_ta_new_p (&proc_handle, &thread_agent);
1337       if (err == TD_OK)
1338         {
1339           proc_handle.pid = elf_tdata (core_bfd)->core_pid;
1340           fbsd_thread_activate ();
1341         }
1342       else
1343         error ("fbsd_core_open: td_ta_new: %s", thread_db_err_str (err));
1344     }
1345 }
1346
1347 static void
1348 fbsd_core_close (int quitting)
1349 {
1350   orig_core_ops.to_close (quitting);
1351 }
1352
1353 static void
1354 fbsd_core_detach (char *args, int from_tty)
1355 {
1356   if (fbsd_thread_active)
1357     fbsd_thread_deactivate ();
1358   unpush_target (&fbsd_thread_ops);
1359   orig_core_ops.to_detach (args, from_tty);
1360  
1361   /* Clear gdb solib information and symbol file
1362      cache, so that after detach and re-attach, new_objfile
1363      hook will be called */
1364   clear_solib();
1365   symbol_file_clear(0);
1366 }
1367
1368 static void
1369 fbsd_core_files_info (struct target_ops *ignore)
1370 {
1371   orig_core_ops.to_files_info (ignore);
1372 }
1373
1374 static void
1375 init_fbsd_core_ops (void)
1376 {
1377   fbsd_core_ops.to_shortname = "FreeBSD-core";
1378   fbsd_core_ops.to_longname = "FreeBSD multithreaded core dump file";
1379   fbsd_core_ops.to_doc =
1380     "Use a core file as a target.  Specify the filename of the core file.";
1381   fbsd_core_ops.to_open = fbsd_core_open;
1382   fbsd_core_ops.to_close = fbsd_core_close;
1383   fbsd_core_ops.to_attach = 0;
1384   fbsd_core_ops.to_post_attach = 0;
1385   fbsd_core_ops.to_detach = fbsd_core_detach;
1386   /* fbsd_core_ops.to_resume  = 0; */
1387   /* fbsd_core_ops.to_wait  = 0;  */
1388   fbsd_core_ops.to_fetch_registers = fbsd_thread_fetch_registers;
1389   /* fbsd_core_ops.to_store_registers  = 0; */
1390   /* fbsd_core_ops.to_prepare_to_store  = 0; */
1391   fbsd_core_ops.to_xfer_memory = fbsd_thread_xfer_memory;
1392   fbsd_core_ops.to_files_info = fbsd_core_files_info;
1393   fbsd_core_ops.to_insert_breakpoint = ignore;
1394   fbsd_core_ops.to_remove_breakpoint = ignore;
1395   /* fbsd_core_ops.to_lookup_symbol  = 0; */
1396   fbsd_core_ops.to_create_inferior = fbsd_thread_create_inferior;
1397   fbsd_core_ops.to_stratum = core_stratum;
1398   fbsd_core_ops.to_has_all_memory = 0;
1399   fbsd_core_ops.to_has_memory = 1;
1400   fbsd_core_ops.to_has_stack = 1;
1401   fbsd_core_ops.to_has_registers = 1;
1402   fbsd_core_ops.to_has_execution = 0;
1403   fbsd_core_ops.to_has_thread_control = tc_none;
1404   fbsd_core_ops.to_thread_alive = fbsd_thread_alive;
1405   fbsd_core_ops.to_pid_to_str = fbsd_thread_pid_to_str;
1406   fbsd_core_ops.to_find_new_threads = fbsd_thread_find_new_threads;
1407   fbsd_core_ops.to_sections = 0;
1408   fbsd_core_ops.to_sections_end = 0;
1409   fbsd_core_ops.to_magic = OPS_MAGIC;
1410 }
1411
1412 static void
1413 init_fbsd_thread_ops (void)
1414 {
1415   fbsd_thread_ops.to_shortname = "freebsd-threads";
1416   fbsd_thread_ops.to_longname = "FreeBSD multithreaded child process.";
1417   fbsd_thread_ops.to_doc = "FreeBSD threads support.";
1418   fbsd_thread_ops.to_attach = fbsd_thread_attach;
1419   fbsd_thread_ops.to_detach = fbsd_thread_detach;
1420   fbsd_thread_ops.to_post_attach = fbsd_thread_post_attach;
1421   fbsd_thread_ops.to_resume = fbsd_thread_resume;
1422   fbsd_thread_ops.to_wait = fbsd_thread_wait;
1423   fbsd_thread_ops.to_fetch_registers = fbsd_thread_fetch_registers;
1424   fbsd_thread_ops.to_store_registers = fbsd_thread_store_registers;
1425   fbsd_thread_ops.to_xfer_memory = fbsd_thread_xfer_memory;
1426   fbsd_thread_ops.to_files_info = fbsd_thread_files_info;
1427   fbsd_thread_ops.to_kill = fbsd_thread_kill;
1428   fbsd_thread_ops.to_create_inferior = fbsd_thread_create_inferior;
1429   fbsd_thread_ops.to_post_startup_inferior = fbsd_thread_post_startup_inferior;
1430   fbsd_thread_ops.to_mourn_inferior = fbsd_thread_mourn_inferior;
1431   fbsd_thread_ops.to_can_run = fbsd_thread_can_run;
1432   fbsd_thread_ops.to_thread_alive = fbsd_thread_alive;
1433   fbsd_thread_ops.to_find_new_threads = fbsd_thread_find_new_threads;
1434   fbsd_thread_ops.to_pid_to_str = fbsd_thread_pid_to_str;
1435   fbsd_thread_ops.to_stratum = thread_stratum;
1436   fbsd_thread_ops.to_has_thread_control = tc_none;
1437   fbsd_thread_ops.to_has_all_memory = 1;
1438   fbsd_thread_ops.to_has_memory = 1;
1439   fbsd_thread_ops.to_has_stack = 1;
1440   fbsd_thread_ops.to_has_registers = 1;
1441   fbsd_thread_ops.to_has_execution = 1;
1442   fbsd_thread_ops.to_insert_breakpoint = memory_insert_breakpoint;
1443   fbsd_thread_ops.to_remove_breakpoint = memory_remove_breakpoint;
1444   fbsd_thread_ops.to_get_thread_local_address = fbsd_thread_get_local_address;
1445   fbsd_thread_ops.to_magic = OPS_MAGIC;
1446 }
1447
1448 static int
1449 thread_db_load (void)
1450 {
1451   void *handle;
1452   td_err_e err;
1453
1454   handle = dlopen (LIBTHREAD_DB_SO, RTLD_NOW);
1455   if (handle == NULL)
1456       return 0;
1457
1458 #define resolve(X)                      \
1459  if (!(X##_p = dlsym (handle, #X)))     \
1460    return 0;
1461
1462   resolve(td_init);
1463   resolve(td_ta_new);
1464   resolve(td_ta_delete);
1465   resolve(td_ta_map_id2thr);
1466   resolve(td_ta_map_lwp2thr);
1467   resolve(td_ta_thr_iter);
1468   resolve(td_thr_get_info);
1469 #ifdef PT_GETXMMREGS
1470   resolve(td_thr_getxmmregs);
1471 #endif
1472   resolve(td_thr_getfpregs);
1473   resolve(td_thr_getgregs);
1474 #ifdef PT_GETXMMREGS
1475   resolve(td_thr_setxmmregs);
1476 #endif
1477   resolve(td_thr_setfpregs);
1478   resolve(td_thr_setgregs);
1479   resolve(td_thr_sstep);
1480   resolve(td_ta_tsd_iter);
1481   resolve(td_thr_dbsuspend);
1482   resolve(td_thr_dbresume);
1483   resolve(td_thr_tls_get_addr);
1484
1485   /* Initialize the library.  */
1486   err = td_init_p ();
1487   if (err != TD_OK)
1488     {
1489       warning ("Cannot initialize libthread_db: %s", thread_db_err_str (err));
1490       return 0;
1491     }
1492
1493   /* These are not essential.  */
1494   td_ta_event_addr_p = dlsym (handle, "td_ta_event_addr");
1495   td_ta_set_event_p = dlsym (handle, "td_ta_set_event");
1496   td_ta_event_getmsg_p = dlsym (handle, "td_ta_event_getmsg");
1497   td_thr_event_enable_p = dlsym (handle, "td_thr_event_enable");
1498   td_thr_tls_get_addr_p = dlsym (handle, "td_thr_tls_get_addr");
1499   
1500   return 1;
1501 }
1502
1503 /* we suppress the call to add_target of core_ops in corelow because
1504    if there are two targets in the stratum core_stratum, find_core_target
1505    won't know which one to return.  see corelow.c for an additonal
1506    comment on coreops_suppress_target. */
1507
1508 int coreops_suppress_target = 1;
1509
1510 /* similarly we allow this target to be completely skipped.  This is used
1511    by kgdb which uses its own core target. */
1512
1513 int fbsdcoreops_suppress_target;
1514
1515 void
1516 _initialize_thread_db (void)
1517 {
1518
1519   if (fbsdcoreops_suppress_target)
1520     return;
1521   init_fbsd_thread_ops ();
1522   init_fbsd_core_ops ();
1523
1524   if (thread_db_load ())
1525     {
1526       add_target (&fbsd_thread_ops);
1527
1528       /* "thread tsd" command */
1529       add_cmd ("tsd", class_run, fbsd_thread_tsd_cmd,
1530             "Show the thread-specific data keys and destructors "
1531             "for the process.\n",
1532            &thread_cmd_list);
1533
1534       add_cmd ("signal", class_run, fbsd_thread_signal_cmd,
1535             "Show the thread signal info.\n",
1536            &thread_cmd_list);
1537
1538       memcpy (&orig_core_ops, &core_ops, sizeof (struct target_ops));
1539       memcpy (&core_ops, &fbsd_core_ops, sizeof (struct target_ops));
1540       add_target (&core_ops);
1541
1542       /* Add ourselves to objfile event chain. */
1543       target_new_objfile_chain = target_new_objfile_hook;
1544       target_new_objfile_hook = fbsd_thread_new_objfile;
1545
1546       child_suppress_run = 1;
1547     }
1548   else
1549     {
1550       fprintf_unfiltered (gdb_stderr,
1551         "[GDB will not be able to debug user-mode threads: %s]\n", dlerror());
1552      
1553       /* allow the user to debug non-threaded core files */
1554       add_target (&core_ops);
1555     }
1556 }
1557
1558 /* proc service functions */
1559 void
1560 ps_plog (const char *fmt, ...)
1561 {
1562   va_list args;
1563
1564   va_start (args, fmt);
1565   vfprintf_filtered (gdb_stderr, fmt, args);
1566   va_end (args);
1567 }
1568
1569 ps_err_e
1570 ps_pglobal_lookup (struct ps_prochandle *ph, const char *obj,
1571    const char *name, psaddr_t *sym_addr)
1572 {
1573   struct minimal_symbol *ms;
1574   CORE_ADDR addr;
1575
1576   ms = lookup_minimal_symbol (name, NULL, NULL);
1577   if (ms == NULL)
1578     return PS_NOSYM;
1579
1580   addr = SYMBOL_VALUE_ADDRESS (ms);
1581   store_typed_address(sym_addr, builtin_type_void_data_ptr, addr);
1582   return PS_OK;
1583 }
1584
1585 ps_err_e
1586 ps_pread (struct ps_prochandle *ph, psaddr_t addr, void *buf, size_t len)
1587 {
1588   int err = target_read_memory (
1589     extract_typed_address(&addr, builtin_type_void_data_ptr), buf, len);
1590   return (err == 0 ? PS_OK : PS_ERR);
1591 }
1592
1593 ps_err_e
1594 ps_pwrite (struct ps_prochandle *ph, psaddr_t addr, const void *buf,
1595             size_t len)
1596 {
1597   int err = target_write_memory (
1598     extract_typed_address(&addr, builtin_type_void_data_ptr), (void *)buf, len);
1599   return (err == 0 ? PS_OK : PS_ERR);
1600 }
1601
1602 ps_err_e
1603 ps_lgetregs (struct ps_prochandle *ph, lwpid_t lwpid, prgregset_t gregset)
1604 {
1605   struct cleanup *old_chain;
1606
1607   old_chain = save_inferior_ptid ();
1608
1609   /* XXX: Target operation isn't lwp aware: replace pid with lwp */
1610   inferior_ptid = BUILD_LWP (0, lwpid);
1611
1612   target_fetch_registers (-1);
1613   fill_gregset (gregset, -1);
1614   do_cleanups (old_chain);
1615   return PS_OK;
1616 }
1617
1618 ps_err_e
1619 ps_lsetregs (struct ps_prochandle *ph, lwpid_t lwpid, const prgregset_t gregset)
1620 {
1621   struct cleanup *old_chain;
1622
1623   old_chain = save_inferior_ptid ();
1624   inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1625   supply_gregset (gregset);
1626   target_store_registers (-1);
1627   do_cleanups (old_chain);
1628   return PS_OK;
1629 }
1630
1631 ps_err_e
1632 ps_lgetfpregs (struct ps_prochandle *ph, lwpid_t lwpid, 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   target_fetch_registers (-1);
1639   fill_fpregset (fpregset, -1);
1640   do_cleanups (old_chain);
1641   return PS_OK;
1642 }
1643
1644 ps_err_e
1645 ps_lsetfpregs (struct ps_prochandle *ph, lwpid_t lwpid,
1646                const prfpregset_t *fpregset)
1647 {
1648   struct cleanup *old_chain;
1649
1650   old_chain = save_inferior_ptid ();
1651   inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1652   supply_fpregset (fpregset);
1653   target_store_registers (-1);
1654   do_cleanups (old_chain);
1655   return PS_OK;
1656 }
1657
1658 #ifdef PT_GETXMMREGS
1659 ps_err_e
1660 ps_lgetxmmregs (struct ps_prochandle *ph, lwpid_t lwpid, 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   target_fetch_registers (-1);
1667   i387_fill_fxsave (xmmregs, -1);
1668   do_cleanups (old_chain);
1669   return PS_OK;
1670 }
1671
1672 ps_err_e
1673 ps_lsetxmmregs (struct ps_prochandle *ph, lwpid_t lwpid,
1674                 const char *xmmregs)
1675 {
1676   struct cleanup *old_chain;
1677
1678   old_chain = save_inferior_ptid ();
1679   inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1680   i387_supply_fxsave (current_regcache, -1, xmmregs);
1681   target_store_registers (-1);
1682   do_cleanups (old_chain);
1683   return PS_OK;
1684 }
1685 #endif
1686
1687 ps_err_e
1688 ps_lstop(struct ps_prochandle *ph, lwpid_t lwpid)
1689 {
1690   if (ptrace (PT_SUSPEND, lwpid, 0, 0) == -1)
1691     return PS_ERR;
1692   return PS_OK;  
1693 }
1694
1695 ps_err_e
1696 ps_lcontinue(struct ps_prochandle *ph, lwpid_t lwpid)
1697 {
1698   if (ptrace (PT_RESUME, lwpid, 0, 0) == -1)
1699     return PS_ERR;
1700   return PS_OK;   
1701 }
1702
1703 ps_err_e
1704 ps_linfo(struct ps_prochandle *ph, lwpid_t lwpid, void *info)
1705 {
1706   if (fbsd_thread_core) {
1707     /* XXX should verify lwpid and make a pseudo lwp info */
1708     memset(info, 0, sizeof(struct ptrace_lwpinfo));
1709     return PS_OK;
1710   }
1711
1712   if (ptrace (PT_LWPINFO, lwpid, info, sizeof(struct ptrace_lwpinfo)) == -1)
1713     return PS_ERR;
1714   return PS_OK;
1715 }