OSDN Git Service

* thread-db.c (get_thread_signals): Doc fix.
[pf3gnuchains/sourceware.git] / rda / unix / thread-db.c
1 /* thread-db.c
2
3    Copyright 2001, 2002 Red Hat, Inc.
4
5    This file is part of RDA, the Red Hat Debug Agent (and library).
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    Alternative licenses for RDA may be arranged by contacting Red Hat,
23    Inc.  */
24
25 #include "config.h"
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <dlfcn.h>
30 #include <thread_db.h>
31 #include <signal.h>
32 #include <errno.h>
33 #include <sys/wait.h>
34
35 #include "gdbserv.h"
36 #include "gdbserv-target.h"
37 #include "server.h"
38 #include "gdb_proc_service.h"
39 #include "gdbserv-thread-db.h"
40
41 /* Make lots of noise (debugging output). */
42 int thread_db_noisy = 0;
43 int proc_service_noisy = 0;
44
45 /*
46  * A tiny local symbol table.
47  *
48  * This is used by ps_pglobal_lookup, and is really just a 
49  * local cache of symbols whose values we have obtained from gdb.
50  *
51  * Since the cache is expected to be small, and infrequently used,
52  * there is no effort to sort or hash it.  Symbols may be added 
53  * in an "undefined" state, and then defined later.
54  */
55
56 /* The "defined_p" field may have one of the following three values. */
57 enum symbol_cache_defined { UNDEFINED, REQUESTED, DEFINED };
58
59 struct symbol_cache {
60   char *name;
61   paddr_t value;
62   enum symbol_cache_defined  defined_p;
63   struct symbol_cache *next;
64 } *symbol_list;
65
66 /* Function: add_symbol_to_list
67    Add a symbol to the symbol cache.  First checks to see if 
68    an entry is already in there, and re-uses it if so.  This way
69    the cache may be used for symbols awaiting lookup as well as
70    for those that have already been defined by the debugger. */
71
72 static void
73 add_symbol_to_list (char *name, paddr_t value, int defined_p)
74 {
75   struct symbol_cache *tmp;
76
77   for (tmp = symbol_list; tmp; tmp = tmp->next)
78     {
79       if (strcmp (name, tmp->name) == 0)
80         {
81           /* Symbol is already in cache -- set its value and definedness. */
82           tmp->value = value;
83           if (defined_p == DEFINED)
84             tmp->defined_p = defined_p;
85           return;
86         }
87     }
88
89   /* Symbol is not in cache -- add it. */
90   tmp = malloc (sizeof (struct symbol_cache));
91
92   tmp->value = value;
93   tmp->defined_p = defined_p;
94   tmp->name = malloc (strlen (name) + 1);
95   strcpy (tmp->name, name);
96   /* LIFO */
97   tmp->next = symbol_list;
98   symbol_list = tmp;
99 }
100
101 /* Function: free_symbol_list
102    Empty the symbol cache. */
103
104 static void
105 free_symbol_list (void)
106 {
107   struct symbol_cache *tmp;
108
109   for (tmp = symbol_list; tmp; tmp = symbol_list)
110     {
111       symbol_list = tmp->next;
112       free (tmp->name);
113       free (tmp);
114     }
115 }
116
117 /* Function: sync_symbol_list
118    Return all "requested" symbols to the "undefined" state
119    (so they can be "requested" again).  Called when a new
120    source of symbols becomes available (eg. a new shared object). */
121
122 static void
123 sync_symbol_list (void)
124 {
125   struct symbol_cache *tmp;
126
127   for (tmp = symbol_list; tmp; tmp = tmp->next)
128     if (tmp->defined_p == REQUESTED)
129       tmp->defined_p = UNDEFINED;
130 }
131
132 /* Function: lookup_cached_symbol
133    If symbol is defined and cached, return its value in VALUE.
134    Return:  0 if not found, 1 if found.  */
135
136 static int 
137 lookup_cached_symbol (char *name, paddr_t *value)
138 {
139   struct symbol_cache *tmp;
140
141   for (tmp = symbol_list; tmp; tmp = tmp->next)
142     if (strcmp (name, tmp->name) == 0 && tmp->defined_p == DEFINED)
143       {
144         *value = tmp->value;    /* known and defined */
145         return 1;
146       }
147
148   return 0;     /* not found */
149 }
150
151 /* Function: next_undefined_symbol
152    Find a symbol in the cache that needs lookup by GDB.
153    On returning a symbol, mark it REQUESTED, so that it won't
154    be requested again until a new source of symbols opens up
155    (eg. a new shared object). */
156
157 static char *
158 next_undefined_symbol (void)
159 {
160   struct symbol_cache *tmp;
161   /* Make a pass thru the list, and return the first symbol that
162      hasn't been either requested or defined. */
163   for (tmp = symbol_list; tmp; tmp = tmp->next)
164     if (tmp->defined_p == UNDEFINED)
165       {
166         tmp->defined_p = REQUESTED;
167         return tmp->name;
168       }
169   return NULL;
170 }
171
172 /*
173  * A tiny local thread list.
174  *
175  * This local list of threads is used for gdbserv operations that
176  * require a struct gdbserv_thread.  Its first use will be to 
177  * implement "info threads" for gdb.
178  */
179
180 /* Define the struct gdbserv_thread object. */
181
182 struct gdbserv_thread {
183   td_thrinfo_t ti;
184   int attached : 1;
185   int stopped : 1;
186   int waited : 1;
187   int stepping : 1;
188   struct gdbserv_thread *next;
189 } *thread_list;
190
191 /* Function: add_thread_to_list 
192    Add a thread (provided by libthread_db) to the local list. */
193
194 static struct gdbserv_thread *
195 add_thread_to_list (td_thrinfo_t *ti)
196 {
197   struct gdbserv_thread *new = malloc (sizeof (struct gdbserv_thread));
198
199   /* First cut -- add to start of list. */
200   memcpy (&new->ti, ti, sizeof (td_thrinfo_t));
201   new->next = thread_list;
202   thread_list = new;
203   return new;
204 }
205
206 static struct gdbserv_thread *
207 first_thread_in_list (void)
208 {
209   return thread_list;
210 }
211
212 static struct gdbserv_thread *
213 next_thread_in_list (struct gdbserv_thread *thread)
214 {
215   if (thread == NULL)
216     return thread_list;
217   else
218     return thread->next;
219 }
220
221 static void
222 delete_thread_from_list (struct gdbserv_thread *thread)
223 {
224   struct gdbserv_thread *tmp;
225
226   for (tmp = thread_list; tmp; tmp = tmp->next)
227     {
228       if (tmp->next == thread)
229         {
230           tmp->next = tmp->next->next;          /* unlink */
231           free (thread);                        /* discard */
232           return;                               /* finished */
233         }
234     }
235   /* Special case -- delete first element of list. */
236   if (thread == thread_list)
237     {
238       thread_list = thread->next;               /* unlink */
239       free (thread);                            /* discard */
240       return;                                   /* finished */
241     }
242   /* If we reach this point, the thread wasn't in the list. */
243 }
244
245 static void
246 free_thread_list (void)
247 {
248   struct gdbserv_thread *tmp;
249
250   for (tmp = thread_list; tmp; tmp = thread_list)
251     {
252       thread_list = tmp->next;
253       free (tmp);
254     }
255 }
256
257 static struct gdbserv_thread *
258 thread_list_lookup_by_tid (thread_t tid)
259 {
260   struct gdbserv_thread *tmp;
261
262   for (tmp = thread_list; tmp; tmp = tmp->next)
263     if (tmp->ti.ti_tid == tid)
264       break;
265
266   return tmp;
267 }
268
269 static struct gdbserv_thread *
270 thread_list_lookup_by_lid (lwpid_t pid)
271 {
272   struct gdbserv_thread *tmp;
273
274   for (tmp = thread_list; tmp; tmp = tmp->next)
275     if (tmp->ti.ti_lid == pid)
276       break;
277
278   return tmp;
279 }
280
281 /* A copy of the next lower layer's target vector, before we modify it. */
282 static struct gdbserv_target parentvec;
283
284 /* A pointer to the current target vector. */
285 static struct gdbserv_target *currentvec;
286
287 /* 
288  * proc_service callback functions, called by thread_db.
289  */
290
291 void
292 ps_plog (const char *fmt, ...)
293 {
294   fprintf (stderr, "<ps_plog: %s>\n", fmt);
295   return;
296 }
297
298 /* Look up a symbol in GDB's global symbol table.
299    Return the symbol's address.
300    FIXME: it would be more correct to look up the symbol in the context 
301    of the LD_OBJECT_NAME provided.  However we're probably fairly safe 
302    as long as there aren't name conflicts with other libraries.  */
303
304 ps_err_e
305 ps_pglobal_lookup (gdb_ps_prochandle_t ph,
306                    const char *ld_object_name,  /* the library name */
307                    const char *ld_symbol_name,  /* the symbol name */
308                    paddr_t    *ld_symbol_addr)  /* return the symbol addr */
309 {
310   paddr_t value;
311
312   if (lookup_cached_symbol ((char *) ld_symbol_name, &value) == 0)
313     {
314       /* Symbol not in cache -- ask GDB to look it up. 
315          Add the symbol to the cache as undefined. */
316       add_symbol_to_list ((char *) ld_symbol_name, 0, UNDEFINED);
317       return PS_NOSYM;
318     }
319   else
320     {
321       /* Symbol is in the cache and defined -- return its value. */
322       *ld_symbol_addr = value;
323       return PS_OK;
324     }
325 }
326
327
328 /* Connection to the libthread_db library.  */
329 static struct ps_prochandle  proc_handle;
330 static td_thragent_t *thread_agent = NULL;
331
332 /* Pointers to the libthread_db functions.  */
333 static td_err_e (*td_init_p) (void);
334
335 static td_err_e (*td_ta_new_p)           (struct ps_prochandle *ps, 
336                                           td_thragent_t **ta);
337 static td_err_e (*td_ta_delete_p)        (td_thragent_t *ta);
338 static td_err_e (*td_ta_map_id2thr_p)    (const td_thragent_t *ta, 
339                                           thread_t pt, 
340                                           td_thrhandle_t *__th);
341 static td_err_e (*td_ta_map_lwp2thr_p)   (const td_thragent_t *ta, 
342                                           lwpid_t lwpid, 
343                                           td_thrhandle_t *th);
344 static td_err_e (*td_ta_thr_iter_p)      (const td_thragent_t *ta, 
345                                           td_thr_iter_f *callback, 
346                                           void *cbdata, 
347                                           td_thr_state_e state, 
348                                           int ti_pri, 
349                                           sigset_t *ti_sigmask, 
350                                           unsigned int ti_user_flags);
351 static td_err_e (*td_ta_event_addr_p)    (const td_thragent_t *ta, 
352                                           td_event_e event, 
353                                           td_notify_t *ptr);
354 static td_err_e (*td_ta_set_event_p)     (const td_thragent_t *ta, 
355                                           td_thr_events_t *event);
356 static td_err_e (*td_ta_event_getmsg_p)  (const td_thragent_t *ta, 
357                                           td_event_msg_t *msg);
358 static td_err_e (*td_thr_validate_p)     (const td_thrhandle_t *th);
359 static td_err_e (*td_thr_get_info_p)     (const td_thrhandle_t *th, 
360                                           td_thrinfo_t *infop);
361 static td_err_e (*td_thr_getfpregs_p)    (const td_thrhandle_t *th, 
362                                           FPREGSET_T *regset);
363 static td_err_e (*td_thr_getgregs_p)     (const td_thrhandle_t *th, 
364                                           GREGSET_T gregs);
365 static td_err_e (*td_thr_setfpregs_p)    (const td_thrhandle_t *th, 
366                                           const FPREGSET_T *fpregs);
367 static td_err_e (*td_thr_setgregs_p)     (const td_thrhandle_t *th, 
368                                           GREGSET_T gregs);
369 static td_err_e (*td_thr_getxregsize_p)  (const td_thrhandle_t *th,
370                                           int *sizep);
371 static td_err_e (*td_thr_getxregs_p)     (const td_thrhandle_t *th, 
372                                           void *xregs);
373 static td_err_e (*td_thr_setxregs_p)     (const td_thrhandle_t *th, 
374                                           void *xregs);
375 static td_err_e (*td_thr_event_enable_p) (const td_thrhandle_t *th, 
376                                           int event);
377
378 /* Function: thread_db_state_str
379    Convert a thread_db state code to a string.
380    If state code is unknown, return an <unknown> message. */
381
382 static char *
383 thread_db_state_str (td_thr_state_e statecode)
384 {
385   static char buf[64];
386
387   switch (statecode) {
388   case TD_THR_ANY_STATE:        return "<any state>";
389   case TD_THR_UNKNOWN:          return "<officially unknown>";
390   case TD_THR_STOPPED:          return "<stopped>";
391   case TD_THR_RUN:              return "<running>";
392   case TD_THR_ACTIVE:           return "<active> ";
393   case TD_THR_ZOMBIE:           return "<zombie> ";
394   case TD_THR_SLEEP:            return "<sleep>  ";
395   case TD_THR_STOPPED_ASLEEP:   return "<stopped asleep>";
396   default:
397     sprintf (buf, "<unknown state code %d>", statecode);
398     return buf;
399   }
400 }
401
402 static char *
403 thread_db_type_str (td_thr_type_e type)
404 {
405   switch (type) {
406   case TD_THR_USER:             return "<user>  ";
407   case TD_THR_SYSTEM:           return "<system>";
408   default:                      return "<unknown>";
409   }
410 }
411
412 /* Function: thread_db_err_string
413    Convert a thread_db error code to a string.
414    If errcode is unknown, then return an <unknown> message. */
415
416 static char *
417 thread_db_err_str (td_err_e errcode)
418 {
419   static char buf[64];
420
421   switch (errcode) {
422   case TD_OK:           return "generic 'call succeeded'";
423   case TD_ERR:          return "generic error";
424   case TD_NOTHR:        return "no thread to satisfy query";
425   case TD_NOSV:         return "no sync handle to satisfy query";
426   case TD_NOLWP:        return "no lwp to satisfy query";
427   case TD_BADPH:        return "invalid process handle";
428   case TD_BADTH:        return "invalid thread handle";
429   case TD_BADSH:        return "invalid synchronization handle";
430   case TD_BADTA:        return "invalid thread agent";
431   case TD_BADKEY:       return "invalid key";
432   case TD_NOMSG:        return "no event message for getmsg";
433   case TD_NOFPREGS:     return "FPU register set not available";
434   case TD_NOLIBTHREAD:  return "application not linked with libthread";
435   case TD_NOEVENT:      return "requested event is not supported";
436   case TD_NOCAPAB:      return "capability not available";
437   case TD_DBERR:        return "debugger service failed";
438   case TD_NOAPLIC:      return "operation not applicable to";
439   case TD_NOTSD:        return "no thread-specific data for this thread";
440   case TD_MALLOC:       return "malloc failed";
441   case TD_PARTIALREG:   return "only part of register set was written/read";
442   case TD_NOXREGS:      return "X register set not available for this thread";
443   default:
444     sprintf (buf, "unknown thread_db error '%d'", errcode);
445     return buf;
446   }
447 }
448
449 /* flag which indicates if the map_id2thr cache is valid.  See below.  */
450 static int thread_db_map_id2thr_cache_valid;
451
452 /* Function: thread_db_map_id2thr
453    Calling td_ta_map_id2thr() is expensive.  This function invokes
454    td_ta_map_id2thr() and caches the value for future reference.  The
455    cache may be invalidated by calling thread_db_invalidate_cache().
456    Returns: TD_OK on success, an appropriate error code otherwise.  */
457
458 static td_err_e
459 thread_db_map_id2thr (const td_thragent_t *ta, thread_t pt,
460                       td_thrhandle_t *th)
461 {
462   static td_thrhandle_t cached_handle;
463   static thread_t input_pt;
464
465   if (pt == input_pt && thread_db_map_id2thr_cache_valid)
466     {
467       *th = cached_handle;
468       return TD_OK;
469     }
470   else
471     {
472       td_err_e status;
473
474       status = td_ta_map_id2thr_p (ta, pt, th);
475       if (status == TD_OK)
476         {
477           thread_db_map_id2thr_cache_valid = 1;
478           input_pt = pt;
479           cached_handle = *th;
480         }
481       else
482         thread_db_map_id2thr_cache_valid = 0;
483       return status;
484     }
485 }
486
487 /* Invalidate the map_id2thr cache.  */
488 static void
489 thread_db_invalidate_map_id2thr_cache (void)
490 {
491   thread_db_map_id2thr_cache_valid = 0;
492 }
493
494 /* The regset cache object.  This object keeps track of the most
495    recently fetched or set gregset (of a particular type) and whether
496    or not it needs to still needs to be synchronized with the target.  */
497 struct regset_cache
498 {
499   /* Are the cache contents valid?  */
500   int valid;
501
502   /* Does cache need to be flushed?  */
503   int needs_flush;
504
505   /* Handle corresponding to cached regset.  */
506   td_thrhandle_t handle;
507
508   /* Size of memory area used to hold regset.  */
509   int regset_size;
510
511   /* Memory area used to hold regset.  */
512   void *regset_buffer;
513
514   /* Functions used to get/set regset.  */
515   td_err_e (*getregset) (const td_thrhandle_t *th, void *regset);
516   td_err_e (*setregset) (const td_thrhandle_t *th, const void *regset);
517 };
518
519 /* Declare fpregset and gregset cache objects.  */
520 static struct regset_cache fpregset_cache;
521 static struct regset_cache gregset_cache;
522
523 /* Wrappers for td_thr_getfpregs_p, td_thr_setfpregs_p, td_thr_getgregs_p,
524    and td_thr_setgregs_p.  These simply allow us to pass a void * for the
525    regset parameter.  */
526
527 static td_err_e
528 td_thr_getfpregs_wrapper (const td_thrhandle_t *th, void *fpregs)
529 {
530   return td_thr_getfpregs_p (th, fpregs);
531 }
532
533 static td_err_e td_thr_getgregs_wrapper (const td_thrhandle_t *th, void *gregs)
534 {
535   return td_thr_getgregs_p (th, gregs);
536 }
537
538 static td_err_e td_thr_setfpregs_wrapper (const td_thrhandle_t *th,
539                                           const void *fpregs)
540 {
541   return td_thr_setfpregs_p (th, fpregs);
542 }
543
544 static td_err_e td_thr_setgregs_wrapper (const td_thrhandle_t *th,
545                                          const void *gregs)
546 {
547   void * gregs_nonconst = (void *) gregs;
548
549   return td_thr_setgregs_p (th, gregs_nonconst);
550 }
551
552 /* Initialize a regset cache object.  */
553 static void
554 initialize_regset_cache (struct regset_cache *regset_cache,
555                          const int regset_size,
556                          void * const regset_buffer,
557                          td_err_e (* const getregset) (const td_thrhandle_t *th,
558                                                        void *regset),
559                          td_err_e (* const setregset) (const td_thrhandle_t *th,
560                                                        const void *regset))
561 {
562   regset_cache->valid = 0;
563   regset_cache->needs_flush = 0;
564   regset_cache->regset_size = regset_size;
565   regset_cache->regset_buffer = regset_buffer;
566   regset_cache->getregset = getregset;
567   regset_cache->setregset = setregset;
568 }
569
570 /* Initialize the fpregset and gregset cache objects.  Space for
571    the regset buffer is statically allocated to avoid calls to malloc().  */
572 static void
573 initialize_regset_caches (void)
574 {
575   static FPREGSET_T fpregset;
576   static GREGSET_T gregset;
577
578   initialize_regset_cache (&fpregset_cache, sizeof fpregset, &fpregset,
579                            td_thr_getfpregs_wrapper, td_thr_setfpregs_wrapper);
580   initialize_regset_cache (&gregset_cache, sizeof gregset, gregset,
581                            td_thr_getgregs_wrapper, td_thr_setgregs_wrapper);
582 }
583
584 /* Synchronize a cached regset with the target.  */
585 static td_err_e
586 thread_db_flush_regset_cache (struct regset_cache *regset_cache)
587 {
588   td_err_e status = TD_OK;
589   if (regset_cache->valid && regset_cache->needs_flush)
590     {
591       status = regset_cache->setregset (&regset_cache->handle,
592                                         regset_cache->regset_buffer);
593       if (status != TD_OK)
594         regset_cache->valid = 0;
595       regset_cache->needs_flush = 0;
596     }
597   return status;
598 }
599
600 /* Synchronize the gregset and fpregset caches with the target.  */
601 static td_err_e
602 thread_db_flush_regset_caches (void)
603 {
604   td_err_e status;
605   td_err_e ret_status = TD_OK;
606
607   status = thread_db_flush_regset_cache (&fpregset_cache);
608   if (status != TD_OK)
609     ret_status = status;
610
611   status = thread_db_flush_regset_cache (&gregset_cache);
612   if (status != TD_OK)
613     ret_status = status;
614
615   return status;
616 }
617
618 /* Fetch a regset, using a previously cached copy if possible.  */
619 static td_err_e
620 thread_db_get_regset (struct regset_cache *regset_cache,
621                      const td_thrhandle_t *th,
622                      void *regset)
623 {
624   if (regset_cache->valid
625       && memcmp (&regset_cache->handle, th, sizeof *th) == 0)
626     {
627       /* Cache is valid and handles match.  Copy the cached regset.  */
628       memcpy (regset, regset_cache->regset_buffer, regset_cache->regset_size);
629       return TD_OK;
630     }
631   else
632     {
633       td_err_e status;
634
635       /* Handles don't match.  Write out old cache contents before
636          fetching contents w/ new handle if necessary.  */
637       if (regset_cache->valid && regset_cache->needs_flush)
638         {
639           status = regset_cache->setregset (&regset_cache->handle,
640                                             regset_cache->regset_buffer);
641           if (status != TD_OK)
642             {
643               regset_cache->needs_flush = 0;
644               regset_cache->valid = 0;
645               return status;
646             }
647         }
648       
649
650       /* Fetch the regset.  */
651       status = regset_cache->getregset (th, regset);
652       if (status == TD_OK)
653         {
654           /* Preserve it in the cache.  */
655           regset_cache->needs_flush = 0;
656           regset_cache->valid = 1;
657           memcpy (&regset_cache->handle, th, sizeof (*th));
658           memcpy (regset_cache->regset_buffer, regset,
659                   regset_cache->regset_size);
660         }
661       else
662         regset_cache->valid = 0;
663       return status;
664     }
665 }
666
667 /* Set a regset deferring synchronization with the target until
668    later.  */
669 static td_err_e
670 thread_db_set_regset (struct regset_cache *regset_cache,
671                      const td_thrhandle_t *th,
672                      const void *regset)
673 {
674   td_err_e ret_status = TD_OK;
675
676   if (regset_cache->valid && regset_cache->needs_flush
677       && memcmp (&regset_cache->handle, th, sizeof *th) != 0)
678     {
679       /* Cached regset needs to be flushed because handles don't
680          match.  */
681       ret_status = thread_db_flush_regset_cache (regset_cache);
682     }
683
684   memcpy (&regset_cache->handle, th, sizeof *th);
685   memcpy (regset_cache->regset_buffer, regset, regset_cache->regset_size);
686   regset_cache->valid = 1;
687   regset_cache->needs_flush = 1;
688
689   return ret_status;
690 }
691
692 /* Mark a regset cache as invalid.  */
693 static void
694 thread_db_invalidate_regset_cache (struct regset_cache *regset_cache)
695 {
696   regset_cache->valid = 0;
697 }
698
699 /* Mark the gregset and fpregset caches as invalid.  */
700 static void
701 thread_db_invalidate_regset_caches (void)
702 {
703   thread_db_invalidate_regset_cache (&fpregset_cache);
704   thread_db_invalidate_regset_cache (&gregset_cache);
705 }
706
707 /* Invalidate all caches.  */
708 static void
709 thread_db_invalidate_caches (void)
710 {
711   thread_db_invalidate_regset_caches ();
712   thread_db_invalidate_map_id2thr_cache ();
713 }
714
715 /* Fetch the floating point registers via the fpregset cache.  */
716 static td_err_e
717 thread_db_getfpregs (const td_thrhandle_t *th, FPREGSET_T *fpregset)
718 {
719   return thread_db_get_regset (&fpregset_cache, th, fpregset);
720 }
721
722 /* Set the floating point registers via the fpregset cache.  */
723 static td_err_e
724 thread_db_setfpregs (const td_thrhandle_t *th, const FPREGSET_T *fpregset)
725 {
726   return thread_db_set_regset (&fpregset_cache, th, fpregset);
727 }
728
729 /* Fetch the general purpose registers via the gregset cache.  */
730 static td_err_e
731 thread_db_getgregs (const td_thrhandle_t *th, GREGSET_T gregset)
732 {
733   return thread_db_get_regset (&gregset_cache, th, gregset);
734 }
735
736 /* Set the general purpose registers via the gregset cache.  */
737 static td_err_e
738 thread_db_setgregs (const td_thrhandle_t *th, const GREGSET_T gregset)
739 {
740   return thread_db_set_regset (&gregset_cache, th, gregset);
741 }
742
743 /* Call dlsym() to find the address of a symbol.  If symbol lookup fails,
744    print the reason to stderr.  */
745
746 static void *
747 lookup_sym (void *dlhandle, char *symbol)
748 {
749   void *addr;
750
751   addr = dlsym (dlhandle, symbol);
752
753   if (addr == NULL)
754     fprintf (stderr, "Symbol lookup of %s failed: %s\n",
755              symbol, dlerror ());
756
757   return addr;
758 }
759
760 /* Function: thread_db_dlopen
761    Attach to the libthread_db library.  
762    This function does all the dynamic library stuff (dlopen, dlsym).
763    Return: -1 for failure, zero for success.  */
764
765 static int
766 thread_db_dlopen (void)
767 {
768   void *dlhandle;
769
770 #ifndef LIBTHREAD_DB_SO
771 #define LIBTHREAD_DB_SO "libthread_db.so.1"
772 #endif
773
774   if ((dlhandle = dlopen (LIBTHREAD_DB_SO, RTLD_NOW)) == NULL)
775     {
776       fprintf (stderr, "Unable to open %s: %s\n",
777                LIBTHREAD_DB_SO, dlerror ());
778       return -1;                /* fail */
779     }
780
781   /* Initialize pointers to the dynamic library functions we will use.
782    */
783
784   if ((td_init_p = lookup_sym (dlhandle, "td_init")) == NULL)
785     return -1;          /* fail */
786
787   if ((td_ta_new_p = lookup_sym (dlhandle, "td_ta_new")) == NULL)
788     return -1;          /* fail */
789
790   if ((td_ta_delete_p = lookup_sym (dlhandle, "td_ta_delete")) == NULL)
791     return -1;          /* fail */
792
793   if ((td_ta_map_id2thr_p = lookup_sym (dlhandle, "td_ta_map_id2thr")) == NULL)
794     return -1;          /* fail */
795
796   if ((td_ta_map_lwp2thr_p = lookup_sym (dlhandle, "td_ta_map_lwp2thr")) == NULL)
797     return -1;          /* fail */
798
799   if ((td_ta_thr_iter_p = lookup_sym (dlhandle, "td_ta_thr_iter")) == NULL)
800     return -1;          /* fail */
801
802   if ((td_thr_validate_p = lookup_sym (dlhandle, "td_thr_validate")) == NULL)
803     return -1;          /* fail */
804
805   if ((td_thr_get_info_p = lookup_sym (dlhandle, "td_thr_get_info")) == NULL)
806     return -1;          /* fail */
807
808   if ((td_thr_getfpregs_p = lookup_sym (dlhandle, "td_thr_getfpregs")) == NULL)
809     return -1;          /* fail */
810
811   if ((td_thr_getgregs_p = lookup_sym (dlhandle, "td_thr_getgregs")) == NULL)
812     return -1;          /* fail */
813
814   if ((td_thr_setfpregs_p = lookup_sym (dlhandle, "td_thr_setfpregs")) == NULL)
815     return -1;          /* fail */
816
817   if ((td_thr_setgregs_p = lookup_sym (dlhandle, "td_thr_setgregs")) == NULL)
818     return -1;          /* fail */
819
820   /* These are not essential.  */
821   td_ta_event_addr_p    = dlsym (dlhandle, "td_ta_event_addr");
822   td_ta_set_event_p     = dlsym (dlhandle, "td_ta_set_event");
823   td_ta_event_getmsg_p  = dlsym (dlhandle, "td_ta_event_getmsg");
824   td_thr_event_enable_p = dlsym (dlhandle, "td_thr_event_enable");
825   td_thr_getxregsize_p  = dlsym (dlhandle, "td_thr_getxregsize");
826   td_thr_getxregs_p     = dlsym (dlhandle, "td_thr_getxregs");
827   td_thr_setxregs_p     = dlsym (dlhandle, "td_thr_setxregs");
828
829   return 0;             /* success */
830 }
831
832 /* Function: thread_db_open
833    Open a channel to the child's thread library.
834    Returns: -1 for success, 0 for failure
835    FIXME: closure.
836    FIXME: where should we be called from?  We will not succeed
837    until the thread shlib is loaded.  The call from attach will not
838    succeed even if the target is statically linked, 'cause there's 
839    no symbol lookup handshake on attach.  Therefore I can't handle
840    a statically linked threaded process.  */
841
842 static int
843 thread_db_open (struct gdbserv *serv, int pid)
844 { /* FIXME: once we have the serv, we can derive the pid. 
845      No, not true -- not when we're called from attach. 
846      But then, there isn't much use in the call from attach unles
847      I make GDB respond to symbol callbacks from there somehow. */
848   td_err_e ret;
849
850   if (thread_agent == NULL)
851     {
852       proc_handle.pid = pid;
853       proc_handle.serv = serv;
854       
855       ret = td_ta_new_p (&proc_handle, &thread_agent);
856       if (ret == TD_OK)
857         {
858           return -1;    /* success */
859         }
860       else if (thread_db_noisy)
861         {
862           fprintf (stderr, "< -- failed, thread_agent = 0x%08x>\n", 
863                    (long) thread_agent);
864         }
865       return 0;         /* failure */
866     }
867   return -1;            /* success */
868 }
869
870 /* Function: thread_db_detach
871    FIXME: gdbserv kills the inferior and exits when gdb detaches.
872    This is the best place I have from which to shut down the 
873    thread_db interface, but it's not really where this should
874    be done. */
875
876 static void
877 thread_db_detach (struct gdbserv *serv, struct gdbserv_target *target)
878 {
879   struct child_process *process = gdbserv_target_data (serv);
880
881   /* FIXME: this isn't really enough, and detach isn't really the
882      right place for this anyway.  Do this in exit_program. */
883   td_ta_delete_p (thread_agent);
884   thread_agent = NULL;
885   currentvec = NULL;
886
887   if (process->debug_informational)
888     fprintf (stderr, "<thread_db_detach>\n");
889   if (parentvec.detach)
890     parentvec.detach (serv, target);
891 }
892
893 static void
894 attach_thread (struct gdbserv_thread *thread)
895 {
896   if (thread->ti.ti_lid   != 0 &&
897       thread->ti.ti_state != TD_THR_ZOMBIE)     /* Don't attach a zombie. */
898     {
899       if (attach_lwp (thread->ti.ti_lid) == 0)
900         thread->attached = 1;
901       else
902         thread->attached = 0;
903     }
904 }
905
906 /* Function: find_new_threads_callback
907    Enter threads into a local thread database. */
908
909 static int
910 find_new_threads_callback (const td_thrhandle_t *thandle, void *data)
911 {
912   struct gdbserv_thread *thread;
913   td_thrinfo_t ti;
914   td_err_e     ret;
915
916   if ((ret = td_thr_get_info_p (thandle, &ti)) != TD_OK)
917     {
918       fprintf (stderr, "<find_new_threads_callback: get_info failed! %s>\n", 
919                thread_db_err_str (ret));
920       return -1;
921     }
922
923   /* Enter the thread into a local list
924      (unless it is TD_THR_UNKNOWN, which means its defunct). */
925   if ((thread = thread_list_lookup_by_tid (ti.ti_tid)) == NULL)
926     {
927       if (ti.ti_state != TD_THR_UNKNOWN)
928         {
929           thread = add_thread_to_list (&ti);
930           /* Now make sure we've attached to it.  
931              Skip the main pid (already attached). */
932           if (thread->ti.ti_lid != proc_handle.pid)
933             {
934               attach_thread (thread);
935             }
936         }
937     }
938   else
939     {
940       /* Already in list -- cache new thread info */
941       memcpy (&thread->ti, &ti, sizeof (ti));
942     }
943
944   return 0;
945 }
946
947 /* Function: update_thread_list
948
949    First run td_ta_thr_iter to find all threads.
950    Then walk the list and validate that each thread is still running.
951    If not, prune it from the list. */
952
953 static void
954 update_thread_list (void)
955 {
956   struct gdbserv_thread *thread, *next;
957   td_thrhandle_t handle;
958
959   /* First make sure all libthread threads are in the list. */
960   td_ta_thr_iter_p (thread_agent, find_new_threads_callback, 
961                     (void *) 0, 
962                     TD_THR_ANY_STATE, 
963                     TD_THR_LOWEST_PRIORITY,
964                     TD_SIGNO_MASK,
965                     TD_THR_ANY_USER_FLAGS);
966
967   /* Next, remove any defunct threads from the list. */
968   for (thread = first_thread_in_list ();
969        thread;
970        thread = next)
971     {
972       /* Thread may be deleted, so find its successor first! */
973       next = next_thread_in_list (thread);
974
975       /* Now ask if thread is still valid, and if not, delete it. */
976       if (thread_db_map_id2thr (thread_agent, 
977                                 thread->ti.ti_tid, 
978                                 &handle) != TD_OK
979           || td_thr_validate_p (&handle) != TD_OK)
980         {
981           if (thread->ti.ti_state == TD_THR_UNKNOWN)
982             {
983               /* Thread is no longer "valid".
984                  By the time this happens, it's too late for us to 
985                  detach from it.  Just delete it from the list.  */
986               
987               delete_thread_from_list (thread);
988             }
989         }
990     }
991 }
992
993 /* Function: thread_db_thread_next
994    Exported to gdbserv to implement "info threads" request from GDB. */
995
996 static struct gdbserv_thread *
997 thread_db_thread_next (struct gdbserv *serv, struct gdbserv_thread *thread)
998 {
999   if (thread == NULL)
1000     {
1001       /* First request -- build up thread list using td_ta_thr_iter. */
1002       /* NOTE: this should be unnecessary, once we begin to keep the
1003          list up to date all the time. */
1004       update_thread_list ();
1005     }
1006   return next_thread_in_list (thread);
1007 }
1008
1009
1010 /* Function: thread_db_get_gen
1011    Handle 'q' requests:
1012      qSymbol
1013 */
1014
1015 static void
1016 thread_db_get_gen (struct gdbserv *serv)
1017 {
1018   struct child_process *process = gdbserv_target_data (serv);
1019   char tempname[1024], *symbol_query;
1020   unsigned long tempval;
1021   int len;
1022
1023   if (gdbserv_input_string_match (serv, "Symbol:") >= 0)
1024     {
1025       /* Message: qSymbol:<optional value>:<optional name hexified>
1026          Reply:   OK
1027          Reply:   qSymbol:<name hexified>
1028
1029          This message from GDB has three possible forms:
1030
1031          1) "qSymbol::" (no value, no name).
1032          This means the start of a symbol query session.
1033          GDB is offering to serve up symbols.
1034          The target should reply with the FIRST symbol whose value 
1035          it wants (or "OK" if it doesn't want any).
1036
1037          2) "qSymbol:<value>:<name hexified>
1038          This means "here is the value of the symbol you requested".
1039          The target should reply with the NEXT symbol whose value
1040          it wants (or "OK" if it doesn't want any more).
1041
1042          3) "qSymbol::<name hexified>" (no value)
1043          This means "I have no value for the symbol you requested".
1044          The target should reply with the NEXT symbol whose value
1045          it wants (or "OK" if it doesn't want any more).
1046       */
1047          
1048       if (gdbserv_input_string_match (serv, ":") >= 0)
1049         {
1050           /* So far we've matched "qSymbol::".  We're looking at either 
1051              form #1 ("qSymbol::", open a symbol lookup session), or
1052              form #3 ("qSymbol::<name>", a reply that "this symbol is
1053              not defined".  */
1054
1055           len = gdbserv_input_bytes (serv, tempname, sizeof (tempname));
1056
1057           if (len == 0)
1058             {
1059               /* Form #1, open a new symbol lookup session.
1060                  Prepare to request the first symbol in the list. */
1061               sync_symbol_list ();
1062             }
1063           else
1064             {
1065               /* Form #3, this symbol not currently defined.  Nothing
1066                  to do, since we marked it REQUESTED when we sent it,
1067                  and lookup_cached_symbol treats REQUESTED like
1068                  UNDEFINED. */
1069             }
1070         }
1071       else if (gdbserv_input_hex_ulong (serv, &tempval) >= 0 &&
1072                gdbserv_input_string_match (serv, ":") >= 0 &&
1073                (len = gdbserv_input_bytes (serv, tempname, sizeof (tempname))) 
1074                > 0)
1075         {
1076           /* Message contains a symbol and a value (form #2). */
1077
1078           tempname[len] = '\0';
1079           add_symbol_to_list (tempname, (paddr_t) tempval, DEFINED);
1080           if (thread_agent != NULL)
1081             {
1082               /* We now have a new symbol in the cache, which was
1083                  requested by the last td_ta_new call.  Delete the
1084                  current (not-completely-valid) thread agent, so that
1085                  a new one will have to be opened.  */
1086               td_ta_delete_p (thread_agent);
1087               thread_agent = NULL;
1088             }
1089         }
1090
1091       /* Now the reply depends on whether there is another 
1092          symbol in need of lookup.  */
1093       thread_db_open (serv, process->pid);
1094       if ((symbol_query = next_undefined_symbol ()) == NULL)
1095         {
1096           gdbserv_output_string (serv, "OK");
1097         }
1098       else
1099         {
1100           gdbserv_output_string (serv, "qSymbol:");
1101           gdbserv_output_bytes (serv, symbol_query, strlen (symbol_query));
1102         }
1103     }
1104   else if (parentvec.process_get_gen)
1105     parentvec.process_get_gen (serv);
1106 }
1107
1108 /* Function: thread_db_set_gen
1109    Handle 'Q' requests:
1110 */
1111
1112 static void
1113 thread_db_set_gen (struct gdbserv *serv)
1114 {
1115     if (parentvec.process_set_gen)
1116       parentvec.process_set_gen (serv);
1117 }
1118
1119 static void
1120 thread_db_thread_id (struct gdbserv *serv, 
1121                      struct gdbserv_thread *thread,
1122                      struct gdbserv_reg *id)
1123 {
1124   gdbserv_ulonglong_to_reg (serv, 
1125                             (unsigned long long) thread->ti.ti_tid, 
1126                             id);
1127 }
1128
1129 static int
1130 thread_db_thread_lookup_by_id (struct gdbserv *serv,
1131                                const struct gdbserv_reg *thread_id,
1132                                struct gdbserv_thread **thread)
1133 {
1134   unsigned long id;
1135
1136   gdbserv_reg_to_ulong (serv, thread_id, &id);
1137   if (id == 0)                  /* any thread */
1138     {
1139       *thread = next_thread_in_list (NULL);     /* FIXME curthread? */
1140       return 0;
1141     }
1142   else
1143     {
1144       *thread = thread_list_lookup_by_tid ((thread_t) id);
1145       if (*thread == NULL)      /* bad thread id */
1146         {
1147           *thread = next_thread_in_list (NULL); /* FIXME curthread? */
1148           return -1;
1149         }
1150       else
1151         {
1152           return 1;             /* success */
1153         }
1154     }
1155 }
1156
1157 static char *
1158 thread_db_thread_info (struct gdbserv *serv, struct gdbserv_thread *thread)
1159 {
1160   char *info = malloc (128);
1161
1162   sprintf (info, "PID %d Type %s State %s",
1163            thread->ti.ti_lid, 
1164            thread_db_type_str (thread->ti.ti_type),
1165            thread_db_state_str (thread->ti.ti_state));
1166   return info;
1167 }
1168
1169 /* Function: get_target_int_by_name
1170    Read the value of a target integer, given its name and size.
1171    Returns -1 for failure, zero for success. */
1172
1173 static int
1174 get_target_int_by_name (char *name, void *value, int size)
1175 {
1176   paddr_t addr;
1177
1178   if (ps_pglobal_lookup (&proc_handle, NULL, name, &addr) == PS_OK)
1179     {
1180       if (ps_pdread (&proc_handle, addr,
1181                      (gdb_ps_read_buf_t) value,
1182                      (gdb_ps_size_t) size) == PS_OK)
1183         return 0;
1184     }
1185   return -1;            /* fail */
1186 }
1187
1188 /* Function: set_target_int_by_name
1189    Read the value of a target integer, given its name and size.
1190    Returns -1 for failure, zero for success. */
1191
1192 static int
1193 set_target_int_by_name (char *name, void *value, int size)
1194 {
1195   paddr_t addr;
1196
1197   if (ps_pglobal_lookup (&proc_handle, NULL, name, &addr) == PS_OK)
1198     {
1199       if (ps_pdwrite (&proc_handle, addr,
1200                       (gdb_ps_write_buf_t) value,
1201                       (gdb_ps_size_t) size) == PS_OK)
1202         return 0;
1203     }
1204   return -1;            /* fail */
1205 }
1206
1207 /* Function: get_thread_signals
1208
1209    Obtain the values of the "cancel", "restart" and "debug" signals
1210    used by LinuxThreads, and store them in a set of global variables
1211    for use by check_child_state and friends.
1212
1213    Recent versions of NPTL don't define these symbols at all; you must
1214    use the libthread_db event functions instead (td_ta_event_addr,
1215    ...) to find out about thread creation, thread exits, and so on.
1216
1217    Older versions of LinuxThreads provide both interfaces.  To avoid
1218    changing RDA's behavior on any system it supports, we use the older
1219    signal-based interface if present, and use the event-based
1220    interface as a fall-back.  */
1221
1222 static int cancel_signal;
1223 static int restart_signal;
1224 static int debug_signal;
1225 static int got_thread_signals;
1226
1227 static void
1228 get_thread_signals (void)
1229 {
1230   int cancel, restart, debug, debug_flag;
1231
1232   if (!got_thread_signals)
1233     {
1234       if (get_target_int_by_name ("__pthread_sig_cancel", 
1235                                   &cancel, sizeof (cancel)) == 0 &&
1236           get_target_int_by_name ("__pthread_sig_restart",
1237                                   &restart, sizeof (restart)) == 0 &&
1238           get_target_int_by_name ("__pthread_sig_debug", 
1239                                   &debug, sizeof (debug)) == 0)
1240         {
1241           restart_signal = restart;
1242           cancel_signal  = cancel;
1243           debug_signal   = debug;
1244           got_thread_signals = 1;
1245         }
1246       debug_flag = 1;
1247       set_target_int_by_name ("__pthread_threads_debug", 
1248                               &debug_flag, sizeof (debug_flag));
1249     }
1250 }
1251
1252 /* Function: stop_thread 
1253    Use SIGSTOP to force a thread to stop. */
1254
1255 static void
1256 stop_thread (struct gdbserv_thread *thread)
1257 {
1258   if (thread->ti.ti_lid != 0)
1259     {
1260       if (stop_lwp (thread->ti.ti_lid) == 0)
1261         thread->stopped = 1;
1262       else
1263         thread->stopped = 0;
1264     }
1265 }
1266
1267 /* Function: stop_all_threads
1268    Use SIGSTOP to make sure all child threads are stopped.
1269    Do not send SIGSTOP to the event thread, or to any 
1270    new threads that have just been attached. */
1271
1272 static void
1273 stop_all_threads (struct child_process *process)
1274 {
1275   struct gdbserv_thread *thread;
1276
1277   for (thread = first_thread_in_list ();
1278        thread;
1279        thread = next_thread_in_list (thread))
1280     {
1281       if (thread->ti.ti_lid == process->pid)
1282         {
1283           /* HACK mark him signalled. */
1284           thread->stopped = 1;
1285           continue;     /* This thread is already stopped. */
1286         }
1287       /* All threads must be stopped, unles
1288          a) they have only just been attached, or 
1289          b) they're already stopped. */
1290       if (!thread->attached && !thread->stopped &&
1291           thread->ti.ti_state != TD_THR_ZOMBIE &&
1292           thread->ti.ti_state != TD_THR_UNKNOWN)
1293         {
1294           stop_thread (thread);
1295         }
1296     }
1297 }
1298
1299 /* A list of signals that have been prematurely sucked out of the threads.
1300    Because of the complexities of linux threads, we must send SIGSTOP to
1301    every thread, and then call waitpid on the thread to retrieve the 
1302    SIGSTOP event.  Sometimes another signal is pending on the thread,
1303    and we get that one by mistake.  Throw all such signals into this
1304    list, and send them back to their respective threads once we're
1305    finished calling waitpid. */
1306
1307 static struct event_list {
1308   struct gdbserv_thread *thread;
1309   union wait waited;
1310   int selected;
1311 } *pending_events;
1312 static int pending_events_listsize;
1313 static int pending_events_top;
1314
1315 /* Function: add_pending_event
1316    Helper function for wait_all_threads.
1317
1318    When we call waitpid for each thread (trying to consume the SIGSTOP
1319    events that we sent from stop_all_threads), we sometimes inadvertantly
1320    get other events that we didn't send.  We pend these to a list, and 
1321    then resend them to the child threads after our own SIGSTOP events
1322    have been consumed.  
1323
1324    This list will be used to choose which of the possible events 
1325    will be returned to the debugger by check_child_status. */
1326
1327 static void
1328 add_pending_event (struct gdbserv_thread *thread, union wait waited)
1329 {
1330   if (pending_events_top >= pending_events_listsize)
1331     {
1332       pending_events_listsize += 64;
1333       pending_events = 
1334         realloc (pending_events, 
1335                  pending_events_listsize * sizeof (*pending_events));
1336     }
1337   pending_events [pending_events_top].thread = thread;
1338   pending_events [pending_events_top].waited = waited;
1339   pending_events [pending_events_top].selected = 0;
1340   pending_events_top ++;
1341 }
1342
1343 /* Function: select_pending_event
1344    Helper function for wait_all_threads.
1345
1346    Having collected a list of events from various threads, 
1347    choose one "favored event" to be returned to the debugger. */
1348
1349
1350 static void
1351 select_pending_event (struct child_process *process)
1352 {
1353   int i = 0;
1354   int num_wifstopped_events = 0;
1355   int random_key;
1356
1357   /* Select the event that will be returned to the debugger. */
1358
1359   /* Selection criterion #0:
1360      If there are no events, don't do anything!  (paranoia) */
1361   if (pending_events_top == 0)
1362     return;
1363
1364   /* Selection criterion #1: 
1365      If the thread pointer is null, then the thread library is
1366      not in play yet, so this is the only thread and the only event. */
1367   if (pending_events[0].thread == NULL)
1368     {
1369       i = 0;
1370       goto selected;
1371     }
1372
1373   /* Selection criterion #2:
1374      Exit and terminate events take priority. */
1375   for (i = 0; i < pending_events_top; i++)
1376     if (WIFEXITED (pending_events[i].waited) ||
1377         WIFSIGNALED (pending_events[i].waited))
1378       {
1379         goto selected;
1380       }
1381
1382   /* Selection criterion #3: 
1383      Give priority to a stepping SIGTRAP. */
1384   for (i = 0; i < pending_events_top; i++)
1385     if (pending_events[i].thread->stepping &&
1386         WIFSTOPPED (pending_events[i].waited) &&
1387         WSTOPSIG (pending_events[i].waited) == SIGTRAP)
1388       {
1389         /* We don't actually know whether this sigtrap was the result
1390            of a singlestep, or of executing a trap instruction.  But
1391            GDB has a better chance of figuring it out than we do. */
1392         goto selected;
1393       }
1394
1395   /* Selection criterion #4:
1396      Count the WIFSTOPPED events and choose one at random. */
1397   for (i = 0; i < pending_events_top; i++)
1398     if (WIFSTOPPED (pending_events[i].waited))
1399       num_wifstopped_events ++;
1400
1401   random_key = (int) 
1402     ((num_wifstopped_events * (double) rand ()) / (RAND_MAX + 1.0));
1403
1404   for (i = pending_events_top - 1; i >= 0; i--)
1405     if (WIFSTOPPED (pending_events[i].waited))
1406       {
1407         if (random_key == --num_wifstopped_events)
1408           {
1409             goto selected;
1410           }
1411         else if (WSTOPSIG (pending_events[i].waited) == SIGINT)
1412           {
1413             goto selected;      /* Give preference to SIGINT. */
1414           }
1415       }
1416
1417   /* Selection criterion #4 (should never get here):
1418      If all else fails, take the first event in the list. */
1419   i = 0;
1420
1421  selected:      /* Got our favored event. */
1422   pending_events[i].selected = 1;
1423   process->event_thread = pending_events[i].thread;
1424   if (pending_events[i].thread)
1425     process->pid = pending_events[i].thread->ti.ti_lid;
1426
1427   handle_waitstatus (process, pending_events[i].waited);
1428   if (thread_db_noisy)
1429     fprintf (stderr, "<select_pending_event: pid %d '%c' %d>\n",
1430             process->pid, process->stop_status, process->stop_signal);
1431   return;
1432 }
1433
1434 /* Function: send_pending_signals
1435    Helper function for wait_all_threads.
1436
1437    When we call waitpid for each thread (trying to consume the SIGSTOP
1438    events that we sent from stop_all_threads), we sometimes inadvertantly
1439    get other events that we didn't send.  We pend these to a list, and 
1440    then resend them to the child threads after our own SIGSTOP events
1441    have been consumed. 
1442
1443    Some events in the list require special treatment:
1444     * One event is "selected" to be returned to the debugger. 
1445       Skip that one.
1446     * Trap events may represent breakpoints.  We can't just resend
1447       the signal.  Instead we must arrange for the breakpoint to be
1448       hit again when the thread resumes.  */
1449
1450 static void
1451 send_pending_signals (struct child_process *process)
1452 {
1453   int i;
1454   int signum;
1455
1456   for (i = 0; i < pending_events_top; i++)
1457     {
1458       if (WIFSTOPPED (pending_events[i].waited) &&
1459           ! pending_events[i].selected)
1460         {
1461           signum = WSTOPSIG (pending_events[i].waited);
1462           if (signum == SIGTRAP &&
1463               pending_events[i].thread->stepping == 0)
1464             {
1465               /* Breakpoint.  Push it back.  */
1466               if (thread_db_noisy)
1467                 fprintf (stderr, "<send_pending_events: pushing back SIGTRAP for %d>\n",
1468                         pending_events[i].thread->ti.ti_lid);
1469               decr_pc_after_break (process->serv,
1470                                    pending_events[i].thread->ti.ti_lid);
1471             }
1472           else /* FIXME we're letting SIGINT go thru as normal */
1473             {
1474               /* Put the signal back into the child's queue. */
1475               kill (pending_events[i].thread->ti.ti_lid, 
1476                     WSTOPSIG (pending_events[i].waited));
1477             }
1478         }
1479     }
1480   pending_events_top = 0;
1481 }
1482
1483 /* Function: wait_all_threads
1484    Use waitpid to close the loop on all threads that have been
1485    attached or SIGSTOP'd.  Skip the eventpid -- it's already been waited. 
1486
1487    Special considerations:
1488      The debug signal does not go into the event queue, 
1489      does not get forwarded to the thread etc. */
1490
1491 static void
1492 wait_all_threads (struct child_process *process)
1493 {
1494   struct gdbserv_thread *thread;
1495   union  wait w;
1496   int    ret, stopsig;
1497
1498   for (thread = first_thread_in_list ();
1499        thread;
1500        thread = next_thread_in_list (thread))
1501     {
1502       /* Special handling for the thread that has already been waited. */
1503       if (thread->ti.ti_lid == process->pid)
1504         {
1505           /* HACK mark him waited. */
1506           thread->waited = 1;
1507           continue;
1508         }
1509
1510       while ((thread->stopped || thread->attached) &&
1511              !thread->waited)
1512         {
1513           errno = 0;
1514           ret = waitpid (thread->ti.ti_lid, (int *) &w, 
1515                          thread->ti.ti_lid == proc_handle.pid ? 0 : __WCLONE);
1516           if (ret == -1)
1517             {
1518               if (errno == ECHILD)
1519                 fprintf (stderr, "<wait_all_threads: %d has disappeared>\n", 
1520                         thread->ti.ti_lid);
1521               else
1522                 fprintf (stderr, "<wait_all_threads: waitpid %d failed, '%s'>\n", 
1523                         thread->ti.ti_lid, strerror (errno));
1524               break;
1525             }
1526           if (WIFEXITED (w))
1527             {
1528               add_pending_event (thread, w);
1529               fprintf (stderr, "<wait_all_threads: %d has exited>\n", 
1530                       thread->ti.ti_lid);
1531               break;
1532             }
1533           if (WIFSIGNALED (w))
1534             {
1535               add_pending_event (thread, w);
1536               fprintf (stderr, "<wait_all_threads: %d died with signal %d>\n", 
1537                       thread->ti.ti_lid, WTERMSIG (w));
1538               break;
1539             }
1540           stopsig = WSTOPSIG (w);
1541           switch (stopsig) {
1542           case SIGSTOP:
1543             /* This is the one we're looking for.
1544                Mark the thread as 'waited' and move on to the next thread. */
1545 #if 0 /* too noisy! */
1546             if (thread_db_noisy)
1547               fprintf (stderr, "<waitpid (%d, SIGSTOP)>\n", thread->ti.ti_lid);
1548 #endif
1549             thread->waited = 1;
1550             break;
1551           default:
1552             if (stopsig == debug_signal)
1553               {
1554                 /* This signal does not need to be forwarded. */
1555                 if (thread_db_noisy)
1556                   fprintf (stderr, "<wait_all_threads: ignoring SIGDEBUG (%d) for %d>\n",
1557                           debug_signal,
1558                           thread->ti.ti_lid);
1559               }
1560             else
1561               {
1562                 if (thread_db_noisy)
1563                   fprintf (stderr, "<wait_all_threads: stash sig %d for %d at 0x%08x>\n",
1564                            stopsig, thread->ti.ti_lid,
1565                           (unsigned long) debug_get_pc (process->serv,
1566                                                         thread->ti.ti_lid));
1567                 add_pending_event (thread, w);
1568               }
1569           }
1570
1571           if (!thread->waited)  /* Signal was something other than STOP. */
1572             {
1573               /* Continue the thread so it can stop on the next signal. */
1574               continue_lwp (thread->ti.ti_lid, 0);
1575             }
1576         }
1577     }
1578   select_pending_event (process);
1579   send_pending_signals (process);
1580 }
1581
1582 /* Function: continue_thread
1583    Send continue to a struct gdbserv_thread. */
1584
1585 static void
1586 continue_thread (struct gdbserv_thread *thread, int signal)
1587 {
1588   thread_db_flush_regset_caches();
1589
1590   /* Continue thread only if (a) it was just attached, or 
1591      (b) we stopped it and waited for it. */
1592   if (thread->ti.ti_lid != 0)
1593     if (thread->attached || (thread->stopped && thread->waited))
1594       {
1595         continue_lwp (thread->ti.ti_lid, signal);
1596         thread->stopped = thread->attached = thread->waited = 0;
1597       }
1598   thread_db_invalidate_caches ();
1599 }
1600
1601 /* Function: continue_all_threads 
1602    Send continue to all stopped or attached threads
1603    except the event thread (which will be continued separately). */
1604
1605 static void
1606 continue_all_threads (struct gdbserv *serv)
1607 {
1608   struct child_process *process = gdbserv_target_data (serv);
1609   struct gdbserv_thread *thread;
1610   int signal;
1611
1612   for (thread = first_thread_in_list ();
1613        thread;
1614        thread = next_thread_in_list (thread))
1615     {
1616       /* Send any newly attached thread the restart signal. */
1617       if (thread->attached)
1618         continue_thread (thread, restart_signal);
1619       else
1620         continue_thread (thread, 0);
1621     }
1622 }
1623
1624 /* Function: continue_program
1625    Make sure every thread is running, starting with the event thread. */
1626
1627 static void
1628 thread_db_continue_program (struct gdbserv *serv)
1629 {
1630   struct child_process *process = gdbserv_target_data (serv);
1631
1632   /* Synchronize the regset caches.  */
1633   thread_db_flush_regset_caches();
1634
1635   /* First resume the event thread. */
1636   if (process->event_thread)
1637     continue_thread (process->event_thread, process->signal_to_send);
1638   else
1639     continue_lwp (process->pid, process->signal_to_send);
1640
1641   process->stop_signal = process->stop_status = 
1642     process->signal_to_send = 0;
1643
1644   /* Then resume everyone else. */
1645   continue_all_threads (serv);
1646   process->running = 1;
1647   thread_db_invalidate_caches ();
1648 }
1649
1650 /* Function: singlestep_thread
1651    Send SINGLESTEP to a struct gdbserv_thread. */
1652
1653 static void
1654 singlestep_thread (struct gdbserv *serv,
1655                    struct gdbserv_thread *thread,
1656                    int signal)
1657 {
1658   singlestep_lwp (serv, thread->ti.ti_lid, signal);
1659   thread->stopped = thread->attached = thread->waited = 0;
1660   thread->stepping = 1;
1661 }
1662
1663 /* Function: singlestep_program
1664    Make sure every thread is runnable, while the event thread gets to 
1665    do a singlestep. */
1666
1667 static void
1668 thread_db_singlestep_program (struct gdbserv *serv)
1669 {
1670   struct child_process *process = gdbserv_target_data (serv);
1671
1672   /* Synchronize the regset caches.  */
1673   thread_db_flush_regset_caches();
1674
1675   /* First singlestep the event thread. */
1676   if (process->event_thread)
1677     singlestep_thread (serv, process->event_thread, process->signal_to_send);
1678   else
1679     singlestep_lwp (serv, process->pid, process->signal_to_send);
1680
1681   process->stop_status = process->stop_signal =
1682     process->signal_to_send = 0;
1683
1684   /* Then resume everyone else. */
1685   continue_all_threads (serv);          /* All but the event thread. */
1686   process->running = 1;
1687   thread_db_invalidate_caches ();
1688 }
1689
1690 /* Function: thread_db_continue_thread
1691    Let a single thread continue, while everyone else waits. */
1692
1693 static void
1694 thread_db_continue_thread (struct gdbserv *serv,
1695                            struct gdbserv_thread *thread,
1696                            const struct gdbserv_reg *signum)
1697 {
1698   struct child_process *process = gdbserv_target_data (serv);
1699   unsigned long sig;
1700
1701   /* Synchronize the regset caches.  */
1702   thread_db_flush_regset_caches();
1703
1704   /* Handle the signal value. */
1705   if (parentvec.process_signal && signum)
1706     {
1707       gdbserv_reg_to_ulong (serv, signum, &sig);
1708       parentvec.process_signal (serv, (int) sig);
1709     }
1710
1711   /* A null thread argument is to be taken as a continue for all. */
1712   if (thread == NULL)
1713     thread_db_continue_program (serv);
1714   else
1715     {
1716       process->pid = thread->ti.ti_lid;         /* thread to be continued */
1717       continue_thread (thread, process->signal_to_send);
1718       process->stop_status = process->stop_signal =
1719         process->signal_to_send = 0;
1720       process->running = 1;
1721     }
1722   thread_db_invalidate_caches ();
1723 }
1724
1725 /* Function: singlestep_thread
1726    Let a single thread step, while everyone else waits. */
1727
1728 static void
1729 thread_db_singlestep_thread (struct gdbserv *serv,
1730                              struct gdbserv_thread *thread,
1731                              const struct gdbserv_reg *signum)
1732 {
1733   struct child_process *process = gdbserv_target_data (serv);
1734   unsigned long sig;
1735
1736   /* Synchronize the regset caches.  */
1737   thread_db_flush_regset_caches();
1738
1739   /* Handle the signal value. */
1740   if (parentvec.process_signal && signum)
1741     {
1742       gdbserv_reg_to_ulong (serv, signum, &sig);
1743       parentvec.process_signal (serv, (int) sig);
1744     }
1745
1746   /* A null thread argument is to be taken as a singlestep for all. */
1747   if (thread == NULL)
1748     thread_db_singlestep_program (serv);
1749   else
1750     {
1751       singlestep_thread (serv, thread, process->signal_to_send);
1752       process->stop_status = process->stop_signal =
1753         process->signal_to_send = 0;
1754       process->running = 1;
1755     }
1756   thread_db_invalidate_caches ();
1757 }
1758
1759 /* Function: exit_program
1760    Called by main loop when child exits. */
1761
1762 static void
1763 thread_db_exit_program (struct gdbserv *serv)
1764 {
1765   /* FIXME: stop and kill all threads. */
1766
1767   /* Shut down the thread_db library interface. */
1768   td_ta_delete_p (thread_agent);
1769   thread_agent = NULL;
1770   currentvec = NULL;
1771   /* Discard all cached symbol lookups. */
1772   free_symbol_list ();
1773   /* Discard all cached threads. */
1774   free_thread_list ();
1775   /* Call underlying exit_program method. */
1776   parentvec.exit_program (serv);
1777 }
1778
1779 /* Function: check_child_state
1780
1781    This function checks for signal events in the running child processes.
1782    It does not block if there is no event in any child, but if there is
1783    an event, it selectively calls other functions that will, if appropriate,
1784    make sure that all the other children are stopped as well. 
1785
1786    This is a polling (non-blocking) function, and may be called when 
1787    the child is already stopped. */
1788
1789 static int
1790 thread_db_check_child_state (struct child_process *process)
1791 {
1792   struct gdbserv *serv = process->serv;
1793   int eventpid;
1794   union wait w;
1795
1796   /* The "process" is likely to be the parent thread.
1797      We will have to manage a list of threads/pids. */
1798
1799   /* Since this is a polling call, and threads don't all stop at once, 
1800      it is possible for a subsequent call to intercept a new wait event
1801      before we've resumed from the previous wait event.  Prevent this
1802      with a resume flag. */
1803
1804   if (process->running)
1805     {
1806       eventpid = waitpid (-1, (int *) &w, WNOHANG);
1807       /* If no event on main thread, check clone threads. 
1808          It doesn't matter what event we find first, since we now have
1809          a fair algorithm for choosing which event to handle next. */
1810       if (eventpid <= 0)
1811         eventpid = waitpid (-1, (int *) &w, WNOHANG | __WCLONE);
1812
1813       if (eventpid > 0) /* found an event */
1814         {
1815           /* Allow underlying target to use the event process by default,
1816              since it is stopped and the others are still running. */
1817           process->pid = eventpid;
1818
1819           handle_waitstatus (process, w);
1820
1821           /* Look for thread exit. 
1822              This has to be done now -- if the eventpid has exited, I can't
1823              run update_thread_list because there is no stopped process 
1824              thru which I can read memory.  I could find another one to 
1825              stop, but it's not really worth it. */
1826           if (process->stop_status == 'W')
1827             {
1828               if (eventpid == proc_handle.pid)
1829                 return 1;       /* Main thread exited! */
1830               else
1831                 return 0;       /* Just a thread exit, don't tell GDB. */
1832             }
1833
1834           /* FIXME: this debugging output will be removed soon, but 
1835              putting it here before the update_thread_list etc. is
1836              bad from the point of view of synchronization. */
1837           handle_waitstatus (process, w);
1838           if (thread_db_noisy)
1839             fprintf (stderr, "<check_child_state: %d got '%c' - %d at 0x%08x>\n", 
1840                      process->pid, process->stop_status, process->stop_signal,
1841                      (unsigned long) debug_get_pc (process->serv, process->pid));
1842
1843           /* Update the thread list. */
1844           update_thread_list ();
1845
1846           /* For now, call get_thread_signals from here (FIXME:) */
1847           get_thread_signals ();
1848
1849           /* Put this child's event into the pending list. */
1850           add_pending_event (thread_list_lookup_by_lid ((lwpid_t) eventpid), 
1851                              w);
1852
1853           stop_all_threads (process);
1854           wait_all_threads (process);
1855           /* Note: if more than one thread has an event ready to be
1856              handled, wait_all_threads will have chosen one at random. */
1857
1858           if (got_thread_signals && process->stop_status == 'T')
1859             {
1860               /* Child stopped with a signal.  
1861                  See if it was one of our special signals. */
1862
1863               if (process->stop_signal == cancel_signal  ||     /* ignore */
1864                   process->stop_signal == restart_signal ||     /* ignore */
1865                   process->stop_signal == debug_signal   ||     /* ignore */
1866                   process->stop_signal == SIGCHLD)              /* ignore */
1867                 {
1868                   /* Ignore this signal, restart the child. */
1869                   if (thread_db_noisy)
1870                     fprintf (stderr, "<check_child_state: ignoring signal %d for %d>\n",
1871                              process->stop_signal, process->pid);
1872                   if (process->stop_signal == debug_signal)
1873                     {
1874                       /* The debug signal arrives under two circumstances:
1875                          1) The main thread raises it once, upon the first call
1876                          to pthread_create.  This lets us detect the manager
1877                          thread.  The main thread MUST be given the restart
1878                          signal when this occurs. 
1879                          2) The manager thread raises it each time a new
1880                          child thread is created.  The child thread will be
1881                          in sigsuspend, and MUST be sent the restart signal.
1882                          However, the manager thread, which raised the debug
1883                          signal, does not need to be restarted.  
1884
1885                          Sending the restart signal to the newly attached
1886                          child thread (which is not the event thread) is
1887                          handled in continue_all_threads.  */
1888
1889                       if (process->pid == proc_handle.pid)  /* main thread */
1890                         process->stop_signal = restart_signal;
1891                       else                              /* not main thread */
1892                         process->stop_signal = 0;
1893                     }
1894                   process->signal_to_send = process->stop_signal;
1895                   currentvec->continue_program (serv);
1896                   return 0;
1897                 }
1898             }
1899           if (process->stop_status == 'W')
1900             {
1901               if (process->pid == proc_handle.pid)
1902                 return 1;       /* Main thread exited! */
1903               else
1904                 {
1905                   currentvec->continue_program (serv);
1906                   return 0;     /* Just a thread exit, don't tell GDB. */
1907                 }
1908             }
1909
1910           process->running = 0;
1911
1912           /* This is the place to cancel its 'stepping' flag. */
1913           if (process && process->event_thread)
1914             process->event_thread->stepping = 0;
1915
1916           /* Pass this event back to GDB. */
1917           if (process->debug_backend)
1918             fprintf (stderr, "wait returned '%c' (%d) for %d.\n", 
1919                      process->stop_status, process->stop_signal, eventpid);
1920           return 1;
1921         }
1922     }
1923
1924   /* NOTE: this function is called in a polling loop, so it
1925      probably (?) should not block.  Return when there's no event. */
1926   return 0;
1927 }
1928
1929 /* Function: fromtarget_thread_break
1930    Called from the main loop when one of the child processes stops.
1931    Notifies the RDA library and lets it know which thread took the event. */
1932
1933 static void
1934 thread_db_fromtarget_thread_break (struct child_process *process)
1935 {
1936   int gdb_signal = parentvec.compute_signal (process->serv,
1937                                              process->stop_signal);
1938
1939   gdbserv_fromtarget_thread_break (process->serv, 
1940                                    process->event_thread,
1941                                    gdb_signal);
1942 }
1943
1944 /* Function: get_thread_reg
1945    Get a register value for a specific thread. */
1946
1947 static int
1948 thread_db_get_thread_reg (struct gdbserv *serv, 
1949                           struct gdbserv_thread *thread, 
1950                           int regnum, 
1951                           struct gdbserv_reg *reg)
1952 {
1953   struct child_process *process = gdbserv_target_data (serv);
1954   td_thrhandle_t thread_handle;
1955   td_thrinfo_t   ti;
1956   FPREGSET_T fpregset;
1957   GREGSET_T gregset;
1958   td_err_e ret;
1959
1960   if (thread == NULL)
1961     thread = process->event_thread;     /* Default to the event thread. */
1962
1963   if (thread_agent == NULL ||           /* Thread layer not alive yet? */
1964       thread       == NULL)             /* No thread specified? */
1965     {
1966       /* Fall back on parentvec non-threaded method. */
1967       if (parentvec.get_reg)
1968         return parentvec.get_reg (serv, regnum, reg);
1969       else
1970         return -1;      /* give up. */
1971     }
1972
1973   /* Thread_db active, thread_agent valid.
1974      The request goes to the thread_db library. 
1975      From there it will be dispatched to ps_lgetregs,
1976      and from there it will be kicked back to the parent. */
1977
1978   if (thread->ti.ti_state == TD_THR_ZOMBIE ||
1979       thread->ti.ti_state == TD_THR_UNKNOWN)
1980     {
1981       /* This thread is dead!  Can't get its registers. */
1982       return -1;
1983     }
1984
1985   ret = thread_db_map_id2thr (thread_agent, 
1986                               thread->ti.ti_tid,
1987                               &thread_handle);
1988   if (ret == TD_NOTHR)
1989     {
1990       /* Thread has exited, no registers. */
1991       return -1;
1992     }
1993   else if (ret != TD_OK)
1994     {
1995       fprintf (stderr, "<<< ERROR get_thread_reg map_id2thr %d >>>\n",
1996                thread->ti.ti_tid);
1997       return -1;        /* fail */
1998     }
1999
2000   if (is_fp_reg (regnum))
2001     {
2002       if (thread_db_getfpregs (&thread_handle, &fpregset) != TD_OK)
2003         {
2004           /* Failure to get the fpregs isn't necessarily an error.
2005              Assume that the target just doesn't support fpregs. */
2006           return 0;
2007         }
2008       /* Now extract the register from the fpregset. */
2009       if (reg_from_fpregset (serv, reg, regnum, &fpregset) < 0)
2010         {
2011           fprintf (stderr, "<<< ERROR reg_from_fpregset %d %d>>>\n",
2012                    thread->ti.ti_tid, regnum);
2013           return -1;
2014         }
2015     }
2016   else if (td_thr_getxregsize_p != NULL
2017            && td_thr_getxregs_p != NULL
2018            && is_extended_reg (regnum))
2019     {
2020       int xregsize;
2021       void *xregset;
2022
2023       if (td_thr_getxregsize_p (&thread_handle, &xregsize) != TD_OK)
2024         {
2025           /* Failure to get the size of the extended regs isn't
2026              necessarily an error.  Assume that the target just
2027              doesn't support them.  */
2028           return 0;
2029         }
2030
2031       if (xregsize <= 0)
2032         {
2033           /* Another form of not being supported...  */
2034           return 0;
2035         }
2036
2037       /* Allocate space for the extended registers.  */
2038       xregset = alloca (xregsize);
2039       
2040       /* Fetch the extended registers.  */
2041       if (td_thr_getxregs_p (&thread_handle, xregset) != TD_OK)
2042         {
2043           /* Failure to get the extended regs isn't necessarily an error.
2044              Assume that the target just doesn't support them.  */
2045           return 0;
2046         }
2047
2048       /* Now extract the register from the extended regset.  */
2049       if (reg_from_xregset (serv, reg, regnum, xregset) < 0)
2050         {
2051           fprintf (stderr, "<<< ERROR reg_from_xregset %d %d>>>\n",
2052                    thread->ti.ti_tid, regnum);
2053           return -1;
2054         }
2055     }
2056   else if (is_gp_reg (regnum)) /* GP reg */
2057     {
2058       if (thread_db_getgregs (&thread_handle, gregset) != TD_OK)
2059         {
2060           fprintf (stderr, "<<< ERROR get_thread_reg td_thr_getgregs %d >>>\n",
2061                    thread->ti.ti_tid);
2062           return -1;    /* fail */
2063         }
2064       /* Now extract the requested register from the gregset. */
2065       if (reg_from_gregset (serv, reg, regnum, gregset) < 0)
2066         {
2067           fprintf (stderr, "<<< ERROR reg_from_gregset %d %d>>>\n", 
2068                    thread->ti.ti_tid, regnum);
2069           return -1;    /* fail */
2070         }
2071     }
2072   else
2073     {
2074       /* Register not supported by this target.  This shouldn't be
2075          construed as an error though.  */
2076       return 0;
2077     }
2078
2079   return 0;             /* success */
2080 }
2081
2082 /* Function: set_thread_reg
2083    Set a register value for a specific thread. */
2084
2085 static int
2086 thread_db_set_thread_reg (struct gdbserv *serv, 
2087                           struct gdbserv_thread *thread, 
2088                           int regnum, 
2089                           const struct gdbserv_reg *reg)
2090 {
2091   struct child_process *process = gdbserv_target_data (serv);
2092   td_thrhandle_t thread_handle;
2093   FPREGSET_T fpregset;
2094   GREGSET_T gregset;
2095   td_err_e ret;
2096
2097   if (thread == NULL)
2098     thread = process->event_thread;     /* Default to the event thread. */
2099
2100   if (thread_agent == NULL ||           /* Thread layer not alive yet? */
2101       thread       == NULL)             /* No thread specified? */
2102     {
2103       /* Fall back on parentvec non-threaded method. */
2104       if (parentvec.set_reg)
2105         return parentvec.set_reg (serv, regnum, (struct gdbserv_reg *) reg);
2106       else
2107         return -1;      /* give up. */
2108     }
2109
2110   /* Thread_db active, thread_agent valid.
2111      The request goes to the thread_db library. 
2112      From there it will be dispatched to ps_lsetregs,
2113      and from there it will be kicked back to the parent. */
2114
2115   if (thread->ti.ti_state == TD_THR_ZOMBIE ||
2116       thread->ti.ti_state == TD_THR_UNKNOWN)
2117     {
2118       /* This thread is dead!  Can't get its registers. */
2119       return -1;
2120     }
2121
2122   ret = thread_db_map_id2thr (thread_agent, 
2123                               thread->ti.ti_tid,
2124                               &thread_handle);
2125   if (ret == TD_NOTHR)
2126     {
2127       /* Thread has exited, no registers. */
2128       return -1;
2129     }
2130   else if (ret != TD_OK)
2131     {
2132       fprintf (stderr, "<<< ERROR set_thread_reg map_id2thr %d >>>\n",
2133                thread->ti.ti_tid);
2134       return -1;        /* fail */
2135     }
2136
2137   if (is_fp_reg (regnum))
2138     {
2139       /* Get the current fpregset.  */
2140       if (thread_db_getfpregs (&thread_handle, &fpregset) != TD_OK)
2141         {
2142           /* Failing to get the fpregs is not necessarily an error.
2143              Assume it simply means that this target doesn't support
2144              fpregs. */
2145           return 0;
2146         }
2147       /* Now write the new reg value into the fpregset. */
2148       if (reg_to_fpregset (serv, reg, regnum, &fpregset) < 0)
2149         {
2150           fprintf (stderr, "<<< ERROR reg_to_fpregset %d %d >>>\n",
2151                    thread->ti.ti_tid, regnum);
2152           return -1;    /* fail */
2153         }
2154       /* Now write the fpregset back to the child. */
2155       if (thread_db_setfpregs (&thread_handle, &fpregset) != TD_OK)
2156         {
2157           fprintf (stderr, "<<< ERROR set_thread_reg td_thr_setfpregs %d>>>\n",
2158                    thread->ti.ti_tid);
2159           return -1;    /* fail */
2160         }
2161     }
2162   else if (td_thr_getxregsize_p != NULL
2163            && td_thr_getxregs_p != NULL
2164            && td_thr_setxregs_p != NULL
2165            && is_extended_reg (regnum))
2166     {
2167       int xregsize;
2168       void *xregset;
2169
2170       if (td_thr_getxregsize_p (&thread_handle, &xregsize) != TD_OK)
2171         {
2172           /* Failure to get the size of the extended regs isn't
2173              necessarily an error.  Assume that the target just
2174              doesn't support them.  */
2175           return 0;
2176         }
2177
2178       if (xregsize <= 0)
2179         {
2180           /* Another form of not being supported...  */
2181           return 0;
2182         }
2183
2184       /* Allocate space for the extended registers.  */
2185       xregset = alloca (xregsize);
2186
2187       /* Fetch the extended registers.  */
2188       if (td_thr_getxregs_p (&thread_handle, xregset) != TD_OK)
2189         {
2190           /* Failure to get the extended regs isn't necessarily an error.
2191              Assume that the target just doesn't support them.  */
2192           return 0;
2193         }
2194       /* Now write the new reg value into the extended regset. */
2195       if (reg_to_xregset (serv, reg, regnum, xregset) < 0)
2196         {
2197           fprintf (stderr, "<<< ERROR reg_to_xregset %d %d >>>\n", 
2198                    thread->ti.ti_tid, regnum);
2199           return -1;    /* fail */
2200         }
2201       /* Now write the extended regset back to the child. */
2202       if (td_thr_setxregs_p (&thread_handle, gregset) != TD_OK)
2203         {
2204           fprintf (stderr, "<<< ERROR set_thread_reg td_thr_setxregs %d >>>\n",
2205                    thread->ti.ti_tid);
2206           return -1;    /* fail */
2207         }
2208     }
2209   else if (is_gp_reg (regnum))
2210     {
2211       /* First get the current gregset.  */
2212       if (thread_db_getgregs (&thread_handle, gregset) != TD_OK)
2213         {
2214           fprintf (stderr, "<<< ERROR set_thread_reg td_thr_getgregs %d >>>\n",
2215                    thread->ti.ti_tid);
2216           return -1;    /* fail */
2217         }
2218       /* Now write the new reg value into the gregset. */
2219       if (reg_to_gregset (serv, reg, regnum, gregset) < 0)
2220         {
2221           fprintf (stderr, "<<< ERROR reg_to_gregset %d %d >>>\n", 
2222                    thread->ti.ti_tid, regnum);
2223           return -1;    /* fail */
2224         }
2225       /* Now write the gregset back to the child. */
2226       if (thread_db_setgregs (&thread_handle, gregset) != TD_OK)
2227         {
2228           fprintf (stderr, "<<< ERROR set_thread_reg td_thr_setgregs %d >>>\n",
2229                    thread->ti.ti_tid);
2230           return -1;    /* fail */
2231         }
2232     }
2233
2234   return 0;     /* success */
2235 }
2236
2237 /* Function: thread_db_attach
2238    gdbserv target function called upon attaching to gdb. 
2239    Return -1 for failure, zero for success. 
2240    Note that this has nothing to do with attaching to a running process
2241    (which in fact we don't even know how to do), or a running thread. */
2242
2243 int
2244 thread_db_attach (struct gdbserv *serv, struct gdbserv_target *target)
2245 {
2246   td_err_e ret;
2247   struct child_process *process = target->data;
2248   extern struct server_vector gdbserver;
2249   paddr_t dummy;
2250
2251   if ((thread_db_dlopen ()) < 0)
2252     return -1;                  /* fail */
2253
2254   /* Save a copy of the existing target vector before we modify it. */
2255   memcpy (&parentvec, target, sizeof (parentvec));
2256   /* Save a pointer to the actual target vector. */
2257   currentvec = target;
2258
2259   /* Initialize the library.  */
2260   if ((ret = td_init_p ()) != TD_OK)
2261     {
2262       fprintf (stderr, 
2263                "Cannot initialize libthread_db: %s", thread_db_err_str (ret));
2264       currentvec = NULL;
2265       return -1;                /* fail */
2266     }
2267
2268   /* Initialize threadish target methods. */
2269   target->thread_info         = thread_db_thread_info;
2270   target->thread_next         = thread_db_thread_next;
2271   target->thread_id           = thread_db_thread_id;
2272   target->thread_lookup_by_id = thread_db_thread_lookup_by_id;
2273   target->process_set_gen     = thread_db_set_gen;
2274   target->process_get_gen     = thread_db_get_gen;
2275   target->detach              = thread_db_detach;
2276
2277   /* Take over selected target methods. */
2278   target->exit_program        = thread_db_exit_program;
2279   target->continue_program    = thread_db_continue_program;
2280   target->singlestep_program  = thread_db_singlestep_program;
2281
2282   target->continue_thread     = thread_db_continue_thread;
2283   target->singlestep_thread   = thread_db_singlestep_thread;
2284
2285   /* Take over get_reg / set_reg methods with threaded versions. */
2286   if (target->next_gg_reg != NULL &&
2287       target->reg_format  != NULL &&
2288       target->output_reg  != NULL &&
2289       target->input_reg   != NULL)
2290     {
2291       target->get_thread_reg      = thread_db_get_thread_reg;
2292       target->set_thread_reg      = thread_db_set_thread_reg;
2293     }
2294   else
2295     fprintf (stderr, "< ERROR attach: GDB will not read thread regs. >>>\n");
2296
2297   /* KLUDGE: Insert some magic symbols into the cached symbol list,
2298      to be looked up later.  This is badly wrong -- we should be 
2299      obtaining these values thru the thread_db interface.  Their names
2300      should not be hard-coded here <sob>. */
2301   add_symbol_to_list ("__pthread_sig_restart",   0, UNDEFINED);
2302   add_symbol_to_list ("__pthread_sig_cancel",    0, UNDEFINED);
2303   add_symbol_to_list ("__pthread_sig_debug",     0, UNDEFINED);
2304   add_symbol_to_list ("__pthread_threads_debug", 0, UNDEFINED);
2305
2306   /* Attempt to open the thread_db interface.  This attempt will 
2307      most likely fail (unles the child is statically linked). */
2308   thread_db_open (serv, process->pid);  /* Don't test return value */
2309
2310   /* Take over the "wait" vector. FIXME global object */
2311   gdbserver.check_child_state = thread_db_check_child_state;
2312   /* Take over the "fromtarget_break" vector. FIXME global object */
2313   gdbserver.fromtarget_break = thread_db_fromtarget_thread_break;
2314   /* FIXME what about terminate and exit? */
2315
2316   /* Set up the regset caches.  */
2317   initialize_regset_caches ();
2318   return 0;             /* success */
2319 }