OSDN Git Service

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