]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - gnu/usr.bin/gdb/libgdb/fbsd-threads.c
Copy stable/8 to releng/8.2 in preparation for FreeBSD-8.2 release.
[FreeBSD/releng/8.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 ((void *)(uintptr_t)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, (void *)(uintptr_t)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 %llx (LWP %d)",
1182                     (unsigned long long)th.th_thread, ti.ti_lid);
1183         }
1184       else
1185         {
1186           snprintf (buf, sizeof (buf), "Thread %llx (%s)",
1187                     (unsigned long long)th.th_thread,
1188                     thread_db_state_str (ti.ti_state));
1189         }
1190
1191       return buf;
1192     }
1193   else if (IS_LWP (ptid))
1194     {
1195       snprintf (buf, sizeof (buf), "LWP %d", (int) GET_LWP (ptid));
1196       return buf;
1197     }
1198   return normal_pid_to_str (ptid);
1199 }
1200
1201 CORE_ADDR
1202 fbsd_thread_get_local_address(ptid_t ptid, struct objfile *objfile,
1203                               CORE_ADDR offset)
1204 {
1205   td_thrhandle_t th;
1206   void *address;
1207   CORE_ADDR lm;
1208   void *lm2;
1209   int ret, is_library = (objfile->flags & OBJF_SHARED);
1210
1211   if (IS_THREAD (ptid))
1212     {
1213       if (!td_thr_tls_get_addr_p)
1214         error ("Cannot find thread-local interface in thread_db library.");
1215
1216       /* Get the address of the link map for this objfile. */
1217       lm = svr4_fetch_objfile_link_map (objfile);
1218
1219       /* Couldn't find link map. Bail out. */
1220       if (!lm)
1221         {
1222           if (is_library)
1223             error ("Cannot find shared library `%s' link_map in dynamic"
1224                    " linker's module list", objfile->name);
1225           else
1226             error ("Cannot find executable file `%s' link_map in dynamic"
1227                    " linker's module list", objfile->name);
1228         }
1229
1230       ret = td_ta_map_id2thr_p (thread_agent, GET_THREAD(ptid), &th);
1231
1232       /* get the address of the variable. */
1233       store_typed_address(&lm2, builtin_type_void_data_ptr, lm);
1234       ret = td_thr_tls_get_addr_p (&th, lm2, offset, &address);
1235
1236       if (ret != TD_OK)
1237         {
1238           if (is_library)
1239             error ("Cannot find thread-local storage for thread %ld, "
1240                    "shared library %s:\n%s",
1241                    (long) GET_THREAD (ptid),
1242                    objfile->name, thread_db_err_str (ret));
1243           else
1244             error ("Cannot find thread-local storage for thread %ld, "
1245                    "executable file %s:\n%s",
1246                    (long) GET_THREAD (ptid),
1247                    objfile->name, thread_db_err_str (ret));
1248         }
1249
1250       /* Cast assuming host == target. */
1251       return extract_typed_address(&address, builtin_type_void_data_ptr);
1252     }
1253   return (0);
1254 }
1255
1256 static int
1257 tsd_cb (thread_key_t key, void (*destructor)(void *), void *ignore)
1258 {
1259   struct minimal_symbol *ms;
1260   char *name;
1261
1262   ms = lookup_minimal_symbol_by_pc (
1263         extract_typed_address(&destructor, builtin_type_void_func_ptr));
1264   if (!ms)
1265     name = "???";
1266   else
1267     name = DEPRECATED_SYMBOL_NAME (ms);
1268
1269   printf_filtered ("Destructor %p <%s>\n", destructor, name);
1270   return 0;
1271 }
1272
1273 static void
1274 fbsd_thread_tsd_cmd (char *exp, int from_tty)
1275 {
1276   if (fbsd_thread_active)
1277     td_ta_tsd_iter_p (thread_agent, tsd_cb, NULL);
1278 }
1279
1280 static void
1281 fbsd_print_sigset (sigset_t *set)
1282 {
1283   int i;
1284
1285   for (i = 1; i <= _SIG_MAXSIG; ++i) {
1286      if (sigismember(set, i)) {
1287        if (i < sizeof(sys_signame)/sizeof(sys_signame[0]))
1288          printf_filtered("%s ", sys_signame[i]);
1289        else
1290          printf_filtered("sig%d ", i);
1291      }
1292   }
1293   printf_filtered("\n");
1294 }
1295
1296 static void
1297 fbsd_thread_signal_cmd (char *exp, int from_tty)
1298 {
1299   td_thrhandle_t th;
1300   td_thrinfo_t ti;
1301   td_err_e err;
1302   const char *code;
1303
1304   if (!fbsd_thread_active || !IS_THREAD(inferior_ptid))
1305     return;
1306
1307   err = td_ta_map_id2thr_p (thread_agent, GET_THREAD (inferior_ptid), &th);
1308   if (err != TD_OK)
1309     return;
1310
1311   err = td_thr_get_info_p (&th, &ti);
1312   if (err != TD_OK)
1313     return;
1314
1315   printf_filtered("signal mask:\n");
1316   fbsd_print_sigset(&ti.ti_sigmask);
1317   printf_filtered("signal pending:\n");
1318   fbsd_print_sigset(&ti.ti_pending);
1319   if (ti.ti_siginfo.si_signo != 0) {
1320    printf_filtered("si_signo %d si_errno %d", ti.ti_siginfo.si_signo,
1321      ti.ti_siginfo.si_errno);
1322    if (ti.ti_siginfo.si_errno != 0)
1323     printf_filtered(" (%s)", strerror(ti.ti_siginfo.si_errno));
1324    printf_filtered("\n");
1325    switch (ti.ti_siginfo.si_code) {
1326    case SI_NOINFO:
1327         code = "NOINFO";
1328         break;
1329     case SI_USER:
1330         code = "USER";
1331         break;
1332     case SI_QUEUE:
1333         code = "QUEUE";
1334         break;
1335     case SI_TIMER:
1336         code = "TIMER";
1337         break;
1338     case SI_ASYNCIO:
1339         code = "ASYNCIO";
1340         break;
1341     case SI_MESGQ:
1342         code = "MESGQ";
1343         break;
1344     case SI_KERNEL:
1345         code = "KERNEL";
1346         break;
1347     default:
1348         code = "UNKNOWN";
1349         break;
1350     }
1351     printf_filtered("si_code %s si_pid %d si_uid %d si_status %x si_addr %p\n",
1352       code, ti.ti_siginfo.si_pid, ti.ti_siginfo.si_uid, ti.ti_siginfo.si_status,
1353       ti.ti_siginfo.si_addr);
1354   }
1355 }
1356
1357 static int
1358 ignore (CORE_ADDR addr, char *contents)
1359 {
1360   return 0;
1361 }
1362
1363 static void
1364 fbsd_core_open (char *filename, int from_tty)
1365 {
1366   int err;
1367
1368   fbsd_thread_core = 1;
1369
1370   orig_core_ops.to_open (filename, from_tty);
1371
1372   if (fbsd_thread_present)
1373     {
1374       err = td_ta_new_p (&proc_handle, &thread_agent);
1375       if (err == TD_OK)
1376         {
1377           proc_handle.pid = elf_tdata (core_bfd)->core_pid;
1378           fbsd_thread_activate ();
1379         }
1380       else
1381         error ("fbsd_core_open: td_ta_new: %s", thread_db_err_str (err));
1382     }
1383 }
1384
1385 static void
1386 fbsd_core_close (int quitting)
1387 {
1388   orig_core_ops.to_close (quitting);
1389 }
1390
1391 static void
1392 fbsd_core_detach (char *args, int from_tty)
1393 {
1394   if (fbsd_thread_active)
1395     fbsd_thread_deactivate ();
1396   unpush_target (&fbsd_thread_ops);
1397   orig_core_ops.to_detach (args, from_tty);
1398  
1399   /* Clear gdb solib information and symbol file
1400      cache, so that after detach and re-attach, new_objfile
1401      hook will be called */
1402   clear_solib();
1403   symbol_file_clear(0);
1404 }
1405
1406 static void
1407 fbsd_core_files_info (struct target_ops *ignore)
1408 {
1409   orig_core_ops.to_files_info (ignore);
1410 }
1411
1412 static void
1413 init_fbsd_core_ops (void)
1414 {
1415   fbsd_core_ops.to_shortname = "FreeBSD-core";
1416   fbsd_core_ops.to_longname = "FreeBSD multithreaded core dump file";
1417   fbsd_core_ops.to_doc =
1418     "Use a core file as a target.  Specify the filename of the core file.";
1419   fbsd_core_ops.to_open = fbsd_core_open;
1420   fbsd_core_ops.to_close = fbsd_core_close;
1421   fbsd_core_ops.to_attach = 0;
1422   fbsd_core_ops.to_post_attach = 0;
1423   fbsd_core_ops.to_detach = fbsd_core_detach;
1424   /* fbsd_core_ops.to_resume  = 0; */
1425   /* fbsd_core_ops.to_wait  = 0;  */
1426   fbsd_core_ops.to_fetch_registers = fbsd_thread_fetch_registers;
1427   /* fbsd_core_ops.to_store_registers  = 0; */
1428   /* fbsd_core_ops.to_prepare_to_store  = 0; */
1429   fbsd_core_ops.to_xfer_memory = fbsd_thread_xfer_memory;
1430   fbsd_core_ops.to_files_info = fbsd_core_files_info;
1431   fbsd_core_ops.to_insert_breakpoint = ignore;
1432   fbsd_core_ops.to_remove_breakpoint = ignore;
1433   /* fbsd_core_ops.to_lookup_symbol  = 0; */
1434   fbsd_core_ops.to_create_inferior = fbsd_thread_create_inferior;
1435   fbsd_core_ops.to_stratum = core_stratum;
1436   fbsd_core_ops.to_has_all_memory = 0;
1437   fbsd_core_ops.to_has_memory = 1;
1438   fbsd_core_ops.to_has_stack = 1;
1439   fbsd_core_ops.to_has_registers = 1;
1440   fbsd_core_ops.to_has_execution = 0;
1441   fbsd_core_ops.to_has_thread_control = tc_none;
1442   fbsd_core_ops.to_thread_alive = fbsd_thread_alive;
1443   fbsd_core_ops.to_pid_to_str = fbsd_thread_pid_to_str;
1444   fbsd_core_ops.to_find_new_threads = fbsd_thread_find_new_threads;
1445   fbsd_core_ops.to_sections = 0;
1446   fbsd_core_ops.to_sections_end = 0;
1447   fbsd_core_ops.to_magic = OPS_MAGIC;
1448 }
1449
1450 static void
1451 init_fbsd_thread_ops (void)
1452 {
1453   fbsd_thread_ops.to_shortname = "freebsd-threads";
1454   fbsd_thread_ops.to_longname = "FreeBSD multithreaded child process.";
1455   fbsd_thread_ops.to_doc = "FreeBSD threads support.";
1456   fbsd_thread_ops.to_attach = fbsd_thread_attach;
1457   fbsd_thread_ops.to_detach = fbsd_thread_detach;
1458   fbsd_thread_ops.to_post_attach = fbsd_thread_post_attach;
1459   fbsd_thread_ops.to_resume = fbsd_thread_resume;
1460   fbsd_thread_ops.to_wait = fbsd_thread_wait;
1461   fbsd_thread_ops.to_fetch_registers = fbsd_thread_fetch_registers;
1462   fbsd_thread_ops.to_store_registers = fbsd_thread_store_registers;
1463   fbsd_thread_ops.to_xfer_memory = fbsd_thread_xfer_memory;
1464   fbsd_thread_ops.to_files_info = fbsd_thread_files_info;
1465   fbsd_thread_ops.to_kill = fbsd_thread_kill;
1466   fbsd_thread_ops.to_create_inferior = fbsd_thread_create_inferior;
1467   fbsd_thread_ops.to_post_startup_inferior = fbsd_thread_post_startup_inferior;
1468   fbsd_thread_ops.to_mourn_inferior = fbsd_thread_mourn_inferior;
1469   fbsd_thread_ops.to_can_run = fbsd_thread_can_run;
1470   fbsd_thread_ops.to_thread_alive = fbsd_thread_alive;
1471   fbsd_thread_ops.to_find_new_threads = fbsd_thread_find_new_threads;
1472   fbsd_thread_ops.to_pid_to_str = fbsd_thread_pid_to_str;
1473   fbsd_thread_ops.to_stratum = thread_stratum;
1474   fbsd_thread_ops.to_has_thread_control = tc_none;
1475   fbsd_thread_ops.to_has_all_memory = 1;
1476   fbsd_thread_ops.to_has_memory = 1;
1477   fbsd_thread_ops.to_has_stack = 1;
1478   fbsd_thread_ops.to_has_registers = 1;
1479   fbsd_thread_ops.to_has_execution = 1;
1480   fbsd_thread_ops.to_insert_breakpoint = memory_insert_breakpoint;
1481   fbsd_thread_ops.to_remove_breakpoint = memory_remove_breakpoint;
1482   fbsd_thread_ops.to_get_thread_local_address = fbsd_thread_get_local_address;
1483   fbsd_thread_ops.to_magic = OPS_MAGIC;
1484 }
1485
1486 static int
1487 thread_db_load (void)
1488 {
1489   void *handle;
1490   td_err_e err;
1491
1492   handle = dlopen (LIBTHREAD_DB_SO, RTLD_NOW);
1493   if (handle == NULL)
1494       return 0;
1495
1496 #define resolve(X)                      \
1497  if (!(X##_p = dlsym (handle, #X)))     \
1498    return 0;
1499
1500   resolve(td_init);
1501   resolve(td_ta_new);
1502   resolve(td_ta_delete);
1503   resolve(td_ta_map_id2thr);
1504   resolve(td_ta_map_lwp2thr);
1505   resolve(td_ta_thr_iter);
1506   resolve(td_thr_get_info);
1507 #ifdef PT_GETXMMREGS
1508   resolve(td_thr_getxmmregs);
1509 #endif
1510   resolve(td_thr_getfpregs);
1511   resolve(td_thr_getgregs);
1512 #ifdef PT_GETXMMREGS
1513   resolve(td_thr_setxmmregs);
1514 #endif
1515   resolve(td_thr_setfpregs);
1516   resolve(td_thr_setgregs);
1517   resolve(td_thr_sstep);
1518   resolve(td_ta_tsd_iter);
1519   resolve(td_thr_dbsuspend);
1520   resolve(td_thr_dbresume);
1521   resolve(td_thr_tls_get_addr);
1522
1523   /* Initialize the library.  */
1524   err = td_init_p ();
1525   if (err != TD_OK)
1526     {
1527       warning ("Cannot initialize libthread_db: %s", thread_db_err_str (err));
1528       return 0;
1529     }
1530
1531   /* These are not essential.  */
1532   td_ta_event_addr_p = dlsym (handle, "td_ta_event_addr");
1533   td_ta_set_event_p = dlsym (handle, "td_ta_set_event");
1534   td_ta_event_getmsg_p = dlsym (handle, "td_ta_event_getmsg");
1535   td_thr_event_enable_p = dlsym (handle, "td_thr_event_enable");
1536   td_thr_tls_get_addr_p = dlsym (handle, "td_thr_tls_get_addr");
1537   
1538   return 1;
1539 }
1540
1541 /* we suppress the call to add_target of core_ops in corelow because
1542    if there are two targets in the stratum core_stratum, find_core_target
1543    won't know which one to return.  see corelow.c for an additonal
1544    comment on coreops_suppress_target. */
1545
1546 int coreops_suppress_target = 1;
1547
1548 /* similarly we allow this target to be completely skipped.  This is used
1549    by kgdb which uses its own core target. */
1550
1551 int fbsdcoreops_suppress_target;
1552
1553 void
1554 _initialize_thread_db (void)
1555 {
1556
1557   if (fbsdcoreops_suppress_target)
1558     return;
1559   init_fbsd_thread_ops ();
1560   init_fbsd_core_ops ();
1561
1562   if (thread_db_load ())
1563     {
1564       add_target (&fbsd_thread_ops);
1565
1566       /* "thread tsd" command */
1567       add_cmd ("tsd", class_run, fbsd_thread_tsd_cmd,
1568             "Show the thread-specific data keys and destructors "
1569             "for the process.\n",
1570            &thread_cmd_list);
1571
1572       add_cmd ("signal", class_run, fbsd_thread_signal_cmd,
1573             "Show the thread signal info.\n",
1574            &thread_cmd_list);
1575
1576       memcpy (&orig_core_ops, &core_ops, sizeof (struct target_ops));
1577       memcpy (&core_ops, &fbsd_core_ops, sizeof (struct target_ops));
1578       add_target (&core_ops);
1579
1580       /* Add ourselves to objfile event chain. */
1581       target_new_objfile_chain = target_new_objfile_hook;
1582       target_new_objfile_hook = fbsd_thread_new_objfile;
1583
1584       child_suppress_run = 1;
1585     }
1586   else
1587     {
1588       fprintf_unfiltered (gdb_stderr,
1589         "[GDB will not be able to debug user-mode threads: %s]\n", dlerror());
1590      
1591       /* allow the user to debug non-threaded core files */
1592       add_target (&core_ops);
1593     }
1594 }
1595
1596 /* proc service functions */
1597 void
1598 ps_plog (const char *fmt, ...)
1599 {
1600   va_list args;
1601
1602   va_start (args, fmt);
1603   vfprintf_filtered (gdb_stderr, fmt, args);
1604   va_end (args);
1605 }
1606
1607 ps_err_e
1608 ps_pglobal_lookup (struct ps_prochandle *ph, const char *obj,
1609    const char *name, psaddr_t *sym_addr)
1610 {
1611   struct minimal_symbol *ms;
1612   CORE_ADDR addr;
1613
1614   ms = lookup_minimal_symbol (name, NULL, NULL);
1615   if (ms == NULL)
1616     return PS_NOSYM;
1617
1618   addr = SYMBOL_VALUE_ADDRESS (ms);
1619   store_typed_address(sym_addr, builtin_type_void_data_ptr, addr);
1620   return PS_OK;
1621 }
1622
1623 ps_err_e
1624 ps_pread (struct ps_prochandle *ph, psaddr_t addr, void *buf, size_t len)
1625 {
1626   int err = target_read_memory (
1627     extract_typed_address(&addr, builtin_type_void_data_ptr), buf, len);
1628   return (err == 0 ? PS_OK : PS_ERR);
1629 }
1630
1631 ps_err_e
1632 ps_pwrite (struct ps_prochandle *ph, psaddr_t addr, const void *buf,
1633             size_t len)
1634 {
1635   int err = target_write_memory (
1636     extract_typed_address(&addr, builtin_type_void_data_ptr), (void *)buf, len);
1637   return (err == 0 ? PS_OK : PS_ERR);
1638 }
1639
1640 ps_err_e
1641 ps_lgetregs (struct ps_prochandle *ph, lwpid_t lwpid, prgregset_t gregset)
1642 {
1643   struct cleanup *old_chain;
1644
1645   old_chain = save_inferior_ptid ();
1646
1647   /* XXX: Target operation isn't lwp aware: replace pid with lwp */
1648   inferior_ptid = BUILD_LWP (0, lwpid);
1649
1650   target_fetch_registers (-1);
1651   fill_gregset (gregset, -1);
1652   do_cleanups (old_chain);
1653   return PS_OK;
1654 }
1655
1656 ps_err_e
1657 ps_lsetregs (struct ps_prochandle *ph, lwpid_t lwpid, const prgregset_t gregset)
1658 {
1659   struct cleanup *old_chain;
1660
1661   old_chain = save_inferior_ptid ();
1662   inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1663   supply_gregset (gregset);
1664   target_store_registers (-1);
1665   do_cleanups (old_chain);
1666   return PS_OK;
1667 }
1668
1669 ps_err_e
1670 ps_lgetfpregs (struct ps_prochandle *ph, lwpid_t lwpid, prfpregset_t *fpregset)
1671 {
1672   struct cleanup *old_chain;
1673
1674   old_chain = save_inferior_ptid ();
1675   inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1676   target_fetch_registers (-1);
1677   fill_fpregset (fpregset, -1);
1678   do_cleanups (old_chain);
1679   return PS_OK;
1680 }
1681
1682 ps_err_e
1683 ps_lsetfpregs (struct ps_prochandle *ph, lwpid_t lwpid,
1684                const prfpregset_t *fpregset)
1685 {
1686   struct cleanup *old_chain;
1687
1688   old_chain = save_inferior_ptid ();
1689   inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1690   supply_fpregset (fpregset);
1691   target_store_registers (-1);
1692   do_cleanups (old_chain);
1693   return PS_OK;
1694 }
1695
1696 #ifdef PT_GETXMMREGS
1697 ps_err_e
1698 ps_lgetxmmregs (struct ps_prochandle *ph, lwpid_t lwpid, char *xmmregs)
1699 {
1700   struct cleanup *old_chain;
1701
1702   old_chain = save_inferior_ptid ();
1703   inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1704   target_fetch_registers (-1);
1705   i387_fill_fxsave (xmmregs, -1);
1706   do_cleanups (old_chain);
1707   return PS_OK;
1708 }
1709
1710 ps_err_e
1711 ps_lsetxmmregs (struct ps_prochandle *ph, lwpid_t lwpid,
1712                 const char *xmmregs)
1713 {
1714   struct cleanup *old_chain;
1715
1716   old_chain = save_inferior_ptid ();
1717   inferior_ptid = BUILD_LWP (lwpid, PIDGET (inferior_ptid));
1718   i387_supply_fxsave (current_regcache, -1, xmmregs);
1719   target_store_registers (-1);
1720   do_cleanups (old_chain);
1721   return PS_OK;
1722 }
1723 #endif
1724
1725 ps_err_e
1726 ps_lstop(struct ps_prochandle *ph, lwpid_t lwpid)
1727 {
1728   if (ptrace (PT_SUSPEND, lwpid, 0, 0) == -1)
1729     return PS_ERR;
1730   return PS_OK;  
1731 }
1732
1733 ps_err_e
1734 ps_lcontinue(struct ps_prochandle *ph, lwpid_t lwpid)
1735 {
1736   if (ptrace (PT_RESUME, lwpid, 0, 0) == -1)
1737     return PS_ERR;
1738   return PS_OK;   
1739 }
1740
1741 ps_err_e
1742 ps_linfo(struct ps_prochandle *ph, lwpid_t lwpid, void *info)
1743 {
1744   if (fbsd_thread_core) {
1745     /* XXX should verify lwpid and make a pseudo lwp info */
1746     memset(info, 0, sizeof(struct ptrace_lwpinfo));
1747     return PS_OK;
1748   }
1749
1750   if (ptrace (PT_LWPINFO, lwpid, info, sizeof(struct ptrace_lwpinfo)) == -1)
1751     return PS_ERR;
1752   return PS_OK;
1753 }