OSDN Git Service

2002-07-17 Michael Snyder <msnyder@redhat.com>
[pf3gnuchains/pf3gnuchains3x.git] / gdb / aix-thread.c
1 /* Low level interface for debugging AIX 4.3+ pthreads.
2
3    Copyright 1999, 2000, 2002 Free Software Foundation, Inc.
4    Written by Nick Duffek <nsd@redhat.com>.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 59 Temple Place - Suite 330,
21    Boston, MA 02111-1307, USA.  */
22
23
24 /* This module uses the libpthdebug.a library provided by AIX 4.3+ for
25    debugging pthread applications.
26
27    Some name prefix conventions:
28      pthdb_     provided by libpthdebug.a
29      pdc_       callbacks that this module provides to libpthdebug.a
30      pd_        variables or functions interfacing with libpthdebug.a
31
32    libpthdebug peculiarities:
33
34      - pthdb_ptid_pthread() is prototyped in <sys/pthdebug.h>, but
35        it's not documented, and after several calls it stops working
36        and causes other libpthdebug functions to fail.
37
38      - pthdb_tid_pthread() doesn't always work after
39        pthdb_session_update(), but it does work after cycling through
40        all threads using pthdb_pthread().
41
42      */
43
44 #include "defs.h"
45 #include "gdbthread.h"
46 #include "target.h"
47 #include "inferior.h"
48 #include "regcache.h"
49 #include "gdbcmd.h"
50
51 #if 0
52 #include "coff/internal.h"      /* for libcoff.h */
53 #include "bfd/libcoff.h"        /* for xcoff_data */
54 #endif
55
56 #include <procinfo.h>
57 #include <sys/types.h>
58 #include <sys/ptrace.h>
59 #include <sys/reg.h>
60 #if 0
61 #include <pthread.h>
62 #endif
63 #include <sched.h>
64 #include <sys/pthdebug.h>
65
66 /* Whether to emit debugging output.  */
67 static int debug_aix_thread;
68
69 /* In AIX 5.1, functions use pthdb_tid_t instead of tid_t.  */
70 #ifndef PTHDB_VERSION_3
71 #define pthdb_tid_t     tid_t
72 #endif
73
74 /* Return whether to treat PID as a debuggable thread id.  */
75
76 #define PD_TID(ptid)    (pd_active && ptid_get_tid (ptid) != 0)
77
78 /* Build a thread ptid.  */
79 #define BUILD_THREAD(TID, PID) ptid_build (PID, 0, TID)
80
81 /* Build and lwp ptid.  */
82 #define BUILD_LWP(LWP, PID) MERGEPID (PID, LWP)
83
84 /* pthdb_user_t value that we pass to pthdb functions.  0 causes
85    PTHDB_BAD_USER errors, so use 1.  */
86
87 #define PD_USER 1
88
89 /* Success and failure values returned by pthdb callbacks.  */
90
91 #define PDC_SUCCESS     PTHDB_SUCCESS
92 #define PDC_FAILURE     PTHDB_CALLBACK
93
94 /* Private data attached to each element in GDB's thread list.  */
95
96 struct private_thread_info {
97   pthdb_pthread_t pdtid;         /* thread's libpthdebug id */
98   pthdb_tid_t tid;                      /* kernel thread id */
99 };
100
101 /* Information about a thread of which libpthdebug is aware.  */
102
103 struct pd_thread {
104   pthdb_pthread_t pdtid;
105   pthread_t pthid;
106   pthdb_tid_t tid;
107 };
108
109 /* This module's target-specific operations, active while pd_able is true.  */
110
111 static struct target_ops ops;
112
113 /* Copy of the target over which ops is pushed.  
114    This is more convenient than a pointer to child_ops or core_ops,
115    because they lack current_target's default callbacks.  */
116
117 static struct target_ops base_ops;
118
119 /* Address of the function that libpthread will call when libpthdebug
120    is ready to be initialized.  */
121
122 static CORE_ADDR pd_brk_addr;
123
124 /* Whether the current application is debuggable by pthdb.  */
125
126 static int pd_able = 0;
127
128 /* Whether a threaded application is being debugged.  */
129
130 static int pd_active = 0;
131
132 /* Whether the current architecture is 64-bit.  
133    Only valid when pd_able is true.  */
134
135 static int arch64;
136
137 /* Saved pointer to previous owner of target_new_objfile_hook.  */
138
139 static void (*target_new_objfile_chain)(struct objfile *);
140
141 /* Forward declarations for pthdb callbacks.  */
142
143 static int pdc_symbol_addrs (pthdb_user_t, pthdb_symbol_t *, int);
144 static int pdc_read_data (pthdb_user_t, void *, pthdb_addr_t, size_t);
145 static int pdc_write_data (pthdb_user_t, void *, pthdb_addr_t, size_t);
146 static int pdc_read_regs (pthdb_user_t user, pthdb_tid_t tid,
147                           unsigned long long flags, 
148                           pthdb_context_t *context);
149 static int pdc_write_regs (pthdb_user_t user, pthdb_tid_t tid,
150                            unsigned long long flags, 
151                            pthdb_context_t *context);
152 static int pdc_alloc (pthdb_user_t, size_t, void **);
153 static int pdc_realloc (pthdb_user_t, void *, size_t, void **);
154 static int pdc_dealloc (pthdb_user_t, void *);
155
156 /* pthdb callbacks.  */
157
158 static pthdb_callbacks_t pd_callbacks = {
159   pdc_symbol_addrs,
160   pdc_read_data,
161   pdc_write_data,
162   pdc_read_regs,
163   pdc_write_regs,
164   pdc_alloc,
165   pdc_realloc,
166   pdc_dealloc,
167   NULL
168 };
169
170 /* Current pthdb session.  */
171
172 static pthdb_session_t pd_session;
173
174 /* Return a printable representation of pthdebug function return
175    STATUS.  */
176
177 static char *
178 pd_status2str (int status)
179 {
180   switch (status)
181     {
182     case PTHDB_SUCCESS:         return "SUCCESS";
183     case PTHDB_NOSYS:           return "NOSYS";
184     case PTHDB_NOTSUP:          return "NOTSUP";
185     case PTHDB_BAD_VERSION:     return "BAD_VERSION";
186     case PTHDB_BAD_USER:        return "BAD_USER";
187     case PTHDB_BAD_SESSION:     return "BAD_SESSION";
188     case PTHDB_BAD_MODE:        return "BAD_MODE";
189     case PTHDB_BAD_FLAGS:       return "BAD_FLAGS";
190     case PTHDB_BAD_CALLBACK:    return "BAD_CALLBACK";
191     case PTHDB_BAD_POINTER:     return "BAD_POINTER";
192     case PTHDB_BAD_CMD:         return "BAD_CMD";
193     case PTHDB_BAD_PTHREAD:     return "BAD_PTHREAD";
194     case PTHDB_BAD_ATTR:        return "BAD_ATTR";
195     case PTHDB_BAD_MUTEX:       return "BAD_MUTEX";
196     case PTHDB_BAD_MUTEXATTR:   return "BAD_MUTEXATTR";
197     case PTHDB_BAD_COND:        return "BAD_COND";
198     case PTHDB_BAD_CONDATTR:    return "BAD_CONDATTR";
199     case PTHDB_BAD_RWLOCK:      return "BAD_RWLOCK";
200     case PTHDB_BAD_RWLOCKATTR:  return "BAD_RWLOCKATTR";
201     case PTHDB_BAD_KEY:         return "BAD_KEY";
202     case PTHDB_BAD_PTID:        return "BAD_PTID";
203     case PTHDB_BAD_TID:         return "BAD_TID";
204     case PTHDB_CALLBACK:        return "CALLBACK";
205     case PTHDB_CONTEXT:         return "CONTEXT";
206     case PTHDB_HELD:            return "HELD";
207     case PTHDB_NOT_HELD:        return "NOT_HELD";
208     case PTHDB_MEMORY:          return "MEMORY";
209     case PTHDB_NOT_PTHREADED:   return "NOT_PTHREADED";
210     case PTHDB_SYMBOL:          return "SYMBOL";
211     case PTHDB_NOT_AVAIL:       return "NOT_AVAIL";
212     case PTHDB_INTERNAL:        return "INTERNAL";
213     default:                    return "UNKNOWN";
214     }
215 }
216
217 /* A call to ptrace(REQ, ID, ...) just returned RET.  Check for
218    exceptional conditions and either return nonlocally or else return
219    1 for success and 0 for failure.  */
220
221 static int
222 ptrace_check (int req, int id, int ret)
223 {
224   if (ret == 0 && !errno)
225     return 1;
226
227   /* According to ptrace(2), ptrace may fail with EPERM if "the
228      Identifier parameter corresponds to a kernel thread which is
229      stopped in kernel mode and whose computational state cannot be
230      read or written."  This happens quite often with register reads.  */
231
232   switch (req)
233     {
234     case PTT_READ_GPRS:
235     case PTT_READ_FPRS:
236     case PTT_READ_SPRS:
237       if (ret == -1 && errno == EPERM)
238         {
239           if (debug_aix_thread)
240             fprintf_unfiltered (gdb_stdlog, 
241                                 "ptrace (%d, %d) = %d (errno = %d)",
242                                 req, id, ret, errno);
243           return ret == -1 ? 0 : 1;
244         }
245       break;
246     }
247   error ("aix-thread: ptrace (%d, %d) returned %d (errno = %d %s)",
248          req, id, ret, errno, safe_strerror (errno));
249   return 0;  /* Not reached.  */
250 }
251
252 /* Call ptracex (REQ, ID, ADDR, DATA, BUF).  Return success.  */
253
254 static int
255 ptrace64aix (int req, int id, long long addr, int data, int *buf)
256 {
257   errno = 0;
258   return ptrace_check (req, id, ptracex (req, id, addr, data, buf));
259 }
260
261 /* Call ptrace (REQ, ID, ADDR, DATA, BUF).  Return success.  */
262
263 static int
264 ptrace32 (int req, int id, int *addr, int data, int *buf)
265 {
266   errno = 0;
267   return ptrace_check (req, id, 
268                        ptrace (req, id, (int *)addr, data, buf));
269 }
270
271 /* If *PIDP is a composite process/thread id, convert it to a
272    process id.  */
273
274 static void
275 pid_to_prc (ptid_t *ptidp)
276 {
277   ptid_t ptid;
278
279   ptid = *ptidp;
280   if (PD_TID (ptid))
281     *ptidp = pid_to_ptid (PIDGET (ptid));
282 }
283
284 /* pthdb callback: for <i> from 0 to COUNT, set SYMBOLS[<i>].addr to
285    the address of SYMBOLS[<i>].name.  */
286
287 static int
288 pdc_symbol_addrs (pthdb_user_t user, pthdb_symbol_t *symbols, int count)
289 {
290   struct minimal_symbol *ms;
291   int i;
292   char *name;
293
294   if (debug_aix_thread)
295     fprintf_unfiltered (gdb_stdlog,
296       "pdc_symbol_addrs (user = %ld, symbols = 0x%lx, count = %d)",
297       user, (long) symbols, count);
298
299   for (i = 0; i < count; i++)
300     {
301       name = symbols[i].name;
302       if (debug_aix_thread)
303         fprintf_unfiltered (gdb_stdlog, 
304                             "  symbols[%d].name = \"%s\"", i, name);
305
306       if (!*name)
307         symbols[i].addr = 0;
308       else
309         {
310           if (!(ms = lookup_minimal_symbol (name, NULL, NULL)))
311             {
312               if (debug_aix_thread)
313                 fprintf_unfiltered (gdb_stdlog, " returning PDC_FAILURE");
314               return PDC_FAILURE;
315             }
316           symbols[i].addr = SYMBOL_VALUE_ADDRESS (ms);
317         }
318       if (debug_aix_thread)
319         fprintf_unfiltered (gdb_stdlog, "  symbols[%d].addr = 0x%llx",
320                             i, symbols[i].addr);
321     }
322   if (debug_aix_thread)
323     fprintf_unfiltered (gdb_stdlog, " returning PDC_SUCCESS");
324   return PDC_SUCCESS;
325 }
326
327 /* Read registers call back function should be able to read the
328    context information of a debuggee kernel thread from an active
329    process or from a core file.  The information should be formatted
330    in context64 form for both 32-bit and 64-bit process.  
331    If successful return 0, else non-zero is returned.  */
332
333 static int
334 pdc_read_regs (pthdb_user_t user, 
335                pthdb_tid_t tid,
336                unsigned long long flags,
337                pthdb_context_t *context)
338 {
339   /* This function doesn't appear to be used, so we could probably
340    just return 0 here.  HOWEVER, if it is not defined, the OS will
341    complain and several thread debug functions will fail.  In case
342    this is needed, I have implemented what I think it should do,
343    however this code is untested.  */
344
345   uint64_t gprs64[32];
346   uint32_t gprs32[32];
347   double fprs[32];
348   struct ptxsprs sprs64;
349   struct ptsprs sprs32;
350   
351   if (debug_aix_thread)
352     fprintf_unfiltered (gdb_stdlog, "pdc_read_regs tid=%d flags=%llx\n",
353                         (int)tid, flags);
354
355   /* General-purpose registers.  */
356   if (flags & PTHDB_FLAG_GPRS)
357     {
358       if (arch64)
359         {
360           if (!ptrace64aix (PTT_READ_GPRS, tid, 
361                             (unsigned long) gprs64, 0, NULL))
362             memset (gprs64, 0, sizeof (gprs64));
363           memcpy (context->gpr, gprs64, sizeof(gprs64));
364         }
365       else
366         {
367           if (!ptrace32 (PTT_READ_GPRS, tid, gprs32, 0, NULL))
368             memset (gprs32, 0, sizeof (gprs32));
369           memcpy (context->gpr, gprs32, sizeof(gprs32));
370         }
371     }
372
373   /* Floating-point registers.  */
374   if (flags & PTHDB_FLAG_FPRS)
375     {
376       if (!ptrace32 (PTT_READ_FPRS, tid, (int *) fprs, 0, NULL))
377         memset (fprs, 0, sizeof (fprs));
378           memcpy (context->fpr, fprs, sizeof(fprs));
379     }
380
381   /* Special-purpose registers.  */
382   if (flags & PTHDB_FLAG_SPRS)
383     {
384       if (arch64)
385         {
386           if (!ptrace64aix (PTT_READ_SPRS, tid, 
387                             (unsigned long) &sprs64, 0, NULL))
388             memset (&sprs64, 0, sizeof (sprs64));
389           memcpy (&context->msr, &sprs64, sizeof(sprs64));
390         }
391       else
392         {
393           if (!ptrace32 (PTT_READ_SPRS, tid, (int *) &sprs32, 0, NULL))
394             memset (&sprs32, 0, sizeof (sprs32));
395           memcpy (&context->msr, &sprs32, sizeof(sprs32));
396         }
397     }  
398   return 0;
399 }
400
401 /* Write register function should be able to write requested context
402    information to specified debuggee's kernel thread id. 
403    If successful return 0, else non-zero is returned.  */
404
405 static int
406 pdc_write_regs (pthdb_user_t user,
407                 pthdb_tid_t tid,
408                 unsigned long long flags,
409                 pthdb_context_t *context)
410
411   /* This function doesn't appear to be used, so we could probably
412      just return 0 here.  HOWEVER, if it is not defined, the OS will
413      complain and several thread debug functions will fail.  In case
414      this is needed, I have implemented what I think it should do,
415      however this code is untested.  */
416
417   if (debug_aix_thread)
418     fprintf_unfiltered (gdb_stdlog, "pdc_write_regs tid=%d flags=%llx\n",
419                         (int)tid, flags);
420
421   /* General-purpose registers.  */
422   if (flags & PTHDB_FLAG_GPRS)
423     {
424       if (arch64)
425         ptrace64aix (PTT_WRITE_GPRS, tid, 
426                      (unsigned long)context->gpr, 0, NULL);
427       else
428         ptrace32 (PTT_WRITE_GPRS, tid, (int *)context->gpr, 0, NULL);
429     }
430
431  /* Floating-point registers.  */
432   if (flags & PTHDB_FLAG_FPRS)
433     {
434       ptrace32 (PTT_WRITE_FPRS, tid, (int *)context->fpr, 0, NULL);
435     }
436
437   /* Special-purpose registers.  */
438   if (flags & PTHDB_FLAG_SPRS)
439     {
440       if (arch64)
441         {
442           ptrace64aix (PTT_WRITE_SPRS, tid, 
443                        (unsigned long) &context->msr, 0, NULL);
444         }
445       else
446         {
447           ptrace32 (PTT_WRITE_SPRS, tid, (int *)&context->msr, 0, NULL);
448         }
449     }
450   return 0;
451 }
452
453 /* pthdb callback: read LEN bytes from process ADDR into BUF.  */
454
455 static int
456 pdc_read_data (pthdb_user_t user, void *buf, 
457                pthdb_addr_t addr, size_t len)
458 {
459   int status, ret;
460
461   if (debug_aix_thread)
462     fprintf_unfiltered (gdb_stdlog,
463       "pdc_read_data (user = %ld, buf = 0x%lx, addr = 0x%llx, len = %ld)",
464       user, (long) buf, addr, len);
465
466   status = target_read_memory (addr, buf, len);
467   ret = status == 0 ? PDC_SUCCESS : PDC_FAILURE;
468
469   if (debug_aix_thread)
470     fprintf_unfiltered (gdb_stdlog, "  status=%d, returning %s",
471                         status, pd_status2str (ret));
472   return ret;
473 }
474
475 /* pthdb callback: write LEN bytes from BUF to process ADDR.  */
476
477 static int
478 pdc_write_data (pthdb_user_t user, void *buf, 
479                 pthdb_addr_t addr, size_t len)
480 {
481   int status, ret;
482
483   if (debug_aix_thread)
484     fprintf_unfiltered (gdb_stdlog,
485       "pdc_write_data (user = %ld, buf = 0x%lx, addr = 0x%llx, len = %ld)",
486       user, (long) buf, addr, len);
487
488   status = target_write_memory (addr, buf, len);
489   ret = status == 0 ? PDC_SUCCESS : PDC_FAILURE;
490
491   if (debug_aix_thread)
492     fprintf_unfiltered (gdb_stdlog, "  status=%d, returning %s", status,
493                         pd_status2str (ret));
494   return ret;
495 }
496
497 /* pthdb callback: allocate a LEN-byte buffer and store a pointer to it
498    in BUFP.  */
499
500 static int
501 pdc_alloc (pthdb_user_t user, size_t len, void **bufp)
502 {
503   if (debug_aix_thread)
504     fprintf_unfiltered (gdb_stdlog,
505                         "pdc_alloc (user = %ld, len = %ld, bufp = 0x%lx)",
506                         user, len, (long) bufp);
507   *bufp = xmalloc (len);
508   if (debug_aix_thread)
509     fprintf_unfiltered (gdb_stdlog, 
510                         "  malloc returned 0x%lx", (long) *bufp);
511
512   /* Note: xmalloc() can't return 0; therefore PDC_FAILURE will never
513      be returned.  */
514
515   return *bufp ? PDC_SUCCESS : PDC_FAILURE;
516 }
517
518 /* pthdb callback: reallocate BUF, which was allocated by the alloc or
519    realloc callback, so that it contains LEN bytes, and store a
520    pointer to the result in BUFP.  */
521
522 static int
523 pdc_realloc (pthdb_user_t user, void *buf, size_t len, void **bufp)
524 {
525   if (debug_aix_thread)
526     fprintf_unfiltered (gdb_stdlog,
527       "pdc_realloc (user = %ld, buf = 0x%lx, len = %ld, bufp = 0x%lx)",
528       user, (long) buf, len, (long) bufp);
529   *bufp = xrealloc (buf, len);
530   if (debug_aix_thread)
531     fprintf_unfiltered (gdb_stdlog, 
532                         "  realloc returned 0x%lx", (long) *bufp);
533   return *bufp ? PDC_SUCCESS : PDC_FAILURE;
534 }
535
536 /* pthdb callback: free BUF, which was allocated by the alloc or
537    realloc callback.  */
538
539 static int
540 pdc_dealloc (pthdb_user_t user, void *buf)
541 {
542   if (debug_aix_thread)
543     fprintf_unfiltered (gdb_stdlog, 
544                         "pdc_free (user = %ld, buf = 0x%lx)", user,
545                         (long) buf);
546   xfree (buf);
547   return PDC_SUCCESS;
548 }
549
550 /* Return a printable representation of pthread STATE.  */
551
552 static char *
553 state2str (pthdb_state_t state)
554 {
555   switch (state)
556     {
557     case PST_IDLE:      return "idle";          /* being created */
558     case PST_RUN:       return "running";       /* running */
559     case PST_SLEEP:     return "sleeping";      /* awaiting an event */
560     case PST_READY:     return "ready";         /* runnable */
561     case PST_TERM:      return "finished";      /* awaiting a join/detach */
562     default:            return "unknown";
563     }
564 }
565
566 /* qsort() comparison function for sorting pd_thread structs by pthid.  */
567
568 static int
569 pcmp (const void *p1v, const void *p2v)
570 {
571   struct pd_thread *p1 = (struct pd_thread *) p1v;
572   struct pd_thread *p2 = (struct pd_thread *) p2v;
573   return p1->pthid < p2->pthid ? -1 : p1->pthid > p2->pthid;
574 }
575
576 /* iterate_over_threads() callback for counting GDB threads.  */
577
578 static int
579 giter_count (struct thread_info *thread, void *countp)
580 {
581   (*(int *) countp)++;
582   return 0;
583 }
584
585 /* iterate_over_threads() callback for accumulating GDB thread pids.  */
586
587 static int
588 giter_accum (struct thread_info *thread, void *bufp)
589 {
590   **(struct thread_info ***) bufp = thread;
591   (*(struct thread_info ***) bufp)++;
592   return 0;
593 }
594
595 /* ptid comparison function */
596
597 static int
598 ptid_cmp (ptid_t ptid1, ptid_t ptid2)
599 {
600   int pid1, pid2;
601
602   if (ptid_get_pid (ptid1) < ptid_get_pid (ptid2))
603     return -1;
604   else if (ptid_get_pid (ptid1) > ptid_get_pid (ptid2))
605     return 1;
606   else if (ptid_get_tid (ptid1) < ptid_get_tid (ptid2))
607     return -1;
608   else if (ptid_get_tid (ptid1) > ptid_get_tid (ptid2))
609     return 1;
610   else if (ptid_get_lwp (ptid1) < ptid_get_lwp (ptid2))
611     return -1;
612   else if (ptid_get_lwp (ptid1) > ptid_get_lwp (ptid2))
613     return 1;
614   else
615     return 0;
616 }
617
618 /* qsort() comparison function for sorting thread_info structs by pid.  */
619
620 static int
621 gcmp (const void *t1v, const void *t2v)
622 {
623   struct thread_info *t1 = *(struct thread_info **) t1v;
624   struct thread_info *t2 = *(struct thread_info **) t2v;
625   return ptid_cmp (t1->ptid, t2->ptid);
626 }
627
628 /* Synchronize GDB's thread list with libpthdebug's.
629
630    There are some benefits of doing this every time the inferior stops:
631
632      - allows users to run thread-specific commands without needing to
633        run "info threads" first
634
635      - helps pthdb_tid_pthread() work properly (see "libpthdebug
636        peculiarities" at the top of this module)
637
638      - simplifies the demands placed on libpthdebug, which seems to
639        have difficulty with certain call patterns */
640
641 static void
642 sync_threadlists (void)
643 {
644   int cmd, status, infpid;
645   int pcount, psize, pi, gcount, gi;
646   struct pd_thread *pbuf;
647   struct thread_info **gbuf, **g, *thread;
648   pthdb_pthread_t pdtid;
649   pthread_t pthid;
650   pthdb_tid_t tid;
651
652   /* Accumulate an array of libpthdebug threads sorted by pthread id.  */
653
654   pcount = 0;
655   psize = 1;
656   pbuf = (struct pd_thread *) xmalloc (psize * sizeof *pbuf);
657
658   for (cmd = PTHDB_LIST_FIRST;; cmd = PTHDB_LIST_NEXT)
659     {
660       status = pthdb_pthread (pd_session, &pdtid, cmd);
661       if (status != PTHDB_SUCCESS || pdtid == PTHDB_INVALID_PTHREAD)
662         break;
663
664       status = pthdb_pthread_ptid (pd_session, pdtid, &pthid);
665       if (status != PTHDB_SUCCESS || pthid == PTHDB_INVALID_PTID)
666         continue;
667
668       if (pcount == psize)
669         {
670           psize *= 2;
671           pbuf = (struct pd_thread *) xrealloc (pbuf, 
672                                                 psize * sizeof *pbuf);
673         }
674       pbuf[pcount].pdtid = pdtid;
675       pbuf[pcount].pthid = pthid;
676       pcount++;
677     }
678
679   for (pi = 0; pi < pcount; pi++)
680     {
681       status = pthdb_pthread_tid (pd_session, pbuf[pi].pdtid, &tid);
682       if (status != PTHDB_SUCCESS)
683         tid = PTHDB_INVALID_TID;
684       pbuf[pi].tid = tid;
685     }
686
687   qsort (pbuf, pcount, sizeof *pbuf, pcmp);
688
689   /* Accumulate an array of GDB threads sorted by pid.  */
690
691   gcount = 0;
692   iterate_over_threads (giter_count, &gcount);
693   g = gbuf = (struct thread_info **) xmalloc (gcount * sizeof *gbuf);
694   iterate_over_threads (giter_accum, &g);
695   qsort (gbuf, gcount, sizeof *gbuf, gcmp);
696
697   /* Apply differences between the two arrays to GDB's thread list.  */
698
699   infpid = PIDGET (inferior_ptid);
700   for (pi = gi = 0; pi < pcount || gi < gcount;)
701     {
702       if (pi == pcount)
703         {
704           delete_thread (gbuf[gi]->ptid);
705           gi++;
706         }
707       else if (gi == gcount)
708         {
709           thread = add_thread (BUILD_THREAD (pbuf[pi].pthid, infpid));
710           thread->private = xmalloc (sizeof (struct private_thread_info));
711           thread->private->pdtid = pbuf[pi].pdtid;
712           thread->private->tid = pbuf[pi].tid;
713           pi++;
714         }
715       else
716         {
717           ptid_t pptid, gptid;
718           int cmp_result;
719
720           pptid = BUILD_THREAD (pbuf[pi].pthid, infpid);
721           gptid = gbuf[gi]->ptid;
722           pdtid = pbuf[pi].pdtid;
723           tid = pbuf[pi].tid;
724
725           cmp_result = ptid_cmp (pptid, gptid);
726
727           if (cmp_result == 0)
728             {
729               gbuf[gi]->private->pdtid = pdtid;
730               gbuf[gi]->private->tid = tid;
731               pi++;
732               gi++;
733             }
734           else if (cmp_result > 0)
735             {
736               delete_thread (gptid);
737               gi++;
738             }
739           else
740             {
741               thread = add_thread (pptid);
742               thread->private = xmalloc (sizeof (struct private_thread_info));
743               thread->private->pdtid = pdtid;
744               thread->private->tid = tid;
745               pi++;
746             }
747         }
748     }
749
750   xfree (pbuf);
751   xfree (gbuf);
752 }
753
754 /* Iterate_over_threads() callback for locating a thread whose kernel
755    thread just received a trap signal.  */
756
757 static int
758 iter_trap (struct thread_info *thread, void *unused)
759 {
760   struct thrdsinfo64 thrinf;
761   pthdb_tid_t tid;
762
763   /* getthrds(3) isn't prototyped in any AIX 4.3.3 #include file.  */
764   extern int getthrds (pid_t, struct thrdsinfo64 *, 
765                        int, pthdb_tid_t *, int);
766
767   tid = thread->private->tid;
768   if (tid == PTHDB_INVALID_TID)
769     return 0;
770
771   if (getthrds (PIDGET (inferior_ptid), &thrinf, 
772                 sizeof (thrinf), &tid, 1) != 1)
773     return 0;
774
775   return thrinf.ti_cursig == SIGTRAP;
776 }
777
778 /* Synchronize libpthdebug's state with the inferior and with GDB,
779    generate a composite process/thread <pid> for the current thread,
780    set inferior_ptid to <pid> if SET_INFPID, and return <pid>.  */
781
782 static ptid_t
783 pd_update (int set_infpid)
784 {
785   int status;
786   ptid_t ptid;
787   struct thread_info *thread;
788
789   if (!pd_active)
790     return inferior_ptid;
791
792   status = pthdb_session_update (pd_session);
793   if (status != PTHDB_SUCCESS)
794     return inferior_ptid;
795
796   sync_threadlists ();
797
798   /* Define "current thread" as one that just received a trap signal.  */
799
800   thread = iterate_over_threads (iter_trap, NULL);
801   if (!thread)
802     ptid = inferior_ptid;
803   else
804     {
805       ptid = thread->ptid;
806       if (set_infpid)
807         inferior_ptid = ptid;
808     }
809   return ptid;
810 }
811
812 /* Try to start debugging threads in the current process. 
813    If successful and SET_INFPID, set inferior_ptid to reflect the
814    current thread.  */
815
816 static ptid_t
817 pd_activate (int set_infpid)
818 {
819   int status;
820                 
821   status = pthdb_session_init (PD_USER, arch64 ? PEM_64BIT : PEM_32BIT,
822                                PTHDB_FLAG_REGS, &pd_callbacks, 
823                                &pd_session);
824   if (status != PTHDB_SUCCESS)
825     {
826       return inferior_ptid;
827     }
828   pd_active = 1;
829   return pd_update (set_infpid);
830 }
831
832 /* Undo the effects of pd_activate().  */
833
834 static void
835 pd_deactivate (void)
836 {
837   if (!pd_active)
838     return;
839   pthdb_session_destroy (pd_session);
840   
841   pid_to_prc (&inferior_ptid);
842   pd_active = 0;
843 }
844
845 /* An object file has just been loaded.  Check whether the current
846    application is pthreaded, and if so, prepare for thread debugging.  */
847
848 static void
849 pd_enable (void)
850 {
851   int status;
852   char *stub_name;
853   struct minimal_symbol *ms;
854
855   /* Don't initialize twice.  */
856   if (pd_able)
857     return;
858
859   /* Check application word size.  */
860   arch64 = REGISTER_RAW_SIZE (0) == 8;
861
862   /* Check whether the application is pthreaded.  */
863   stub_name = NULL;
864   status = pthdb_session_pthreaded (PD_USER, PTHDB_FLAG_REGS,
865                                     &pd_callbacks, &stub_name);
866   if ((status != PTHDB_SUCCESS && 
867        status != PTHDB_NOT_PTHREADED) || !stub_name)
868     return;
869
870   /* Set a breakpoint on the returned stub function.  */
871   if (!(ms = lookup_minimal_symbol (stub_name, NULL, NULL)))
872     return;
873   pd_brk_addr = SYMBOL_VALUE_ADDRESS (ms);
874   if (!create_thread_event_breakpoint (pd_brk_addr))
875     return;
876
877   /* Prepare for thread debugging.  */
878   base_ops = current_target;
879   push_target (&ops);
880   pd_able = 1;
881
882   /* If we're debugging a core file or an attached inferior, the
883      pthread library may already have been initialized, so try to
884      activate thread debugging.  */
885   pd_activate (1);
886 }
887
888 /* Undo the effects of pd_enable().  */
889
890 static void
891 pd_disable (void)
892 {
893   if (!pd_able)
894     return;
895   if (pd_active)
896     pd_deactivate ();
897   pd_able = 0;
898   unpush_target (&ops);
899 }
900
901 /* target_new_objfile_hook callback.
902
903    If OBJFILE is non-null, check whether a threaded application is
904    being debugged, and if so, prepare for thread debugging.
905
906    If OBJFILE is null, stop debugging threads.  */
907
908 static void
909 new_objfile (struct objfile *objfile)
910 {
911   if (objfile)
912     pd_enable ();
913   else
914     pd_disable ();
915
916   if (target_new_objfile_chain)
917     target_new_objfile_chain (objfile);
918 }
919
920 /* Attach to process specified by ARGS.  */
921
922 static void
923 ops_attach (char *args, int from_tty)
924 {
925   base_ops.to_attach (args, from_tty);
926   pd_activate (1);
927 }
928
929 /* Detach from the process attached to by ops_attach().  */
930
931 static void
932 ops_detach (char *args, int from_tty)
933 {
934   pd_deactivate ();
935   base_ops.to_detach (args, from_tty);
936 }
937
938 /* Tell the inferior process to continue running thread PID if != -1
939    and all threads otherwise.  */
940
941 static void
942 ops_resume (ptid_t ptid, int step, enum target_signal sig)
943 {
944   struct thread_info *thread;
945   pthdb_tid_t tid[2];
946
947   if (!PD_TID (ptid))
948     {
949       struct cleanup *cleanup = save_inferior_ptid ();
950       inferior_ptid = pid_to_ptid (PIDGET (inferior_ptid));
951       base_ops.to_resume (ptid, step, sig);
952       do_cleanups (cleanup);
953     }
954   else
955     {
956       thread = find_thread_pid (ptid);
957       if (!thread)
958         error ("aix-thread resume: unknown pthread %ld", 
959                TIDGET (ptid));
960
961       tid[0] = thread->private->tid;
962       if (tid[0] == PTHDB_INVALID_TID)
963         error ("aix-thread resume: no tid for pthread %ld", 
964                TIDGET (ptid));
965       tid[1] = 0;
966
967       if (arch64)
968         ptrace64aix (PTT_CONTINUE, tid[0], 1, 
969                      target_signal_to_host (sig), (int *)tid);
970       else
971         ptrace32 (PTT_CONTINUE, tid[0], (int *) 1,
972                   target_signal_to_host (sig), (int *)tid);
973     }
974 }
975
976 /* Wait for thread/process ID if != -1 or for any thread otherwise.
977    If an error occurs, return -1, else return the pid of the stopped
978    thread.  */
979
980 static ptid_t
981 ops_wait (ptid_t ptid, struct target_waitstatus *status)
982 {
983   struct cleanup *cleanup = save_inferior_ptid ();
984
985   pid_to_prc (&ptid);
986
987   inferior_ptid = pid_to_ptid (PIDGET (inferior_ptid));
988   ptid = base_ops.to_wait (ptid, status);
989   do_cleanups (cleanup);
990
991   if (PIDGET (ptid) == -1)
992     return pid_to_ptid (-1);
993
994   /* Check whether libpthdebug might be ready to be initialized.  */
995   if (!pd_active && status->kind == TARGET_WAITKIND_STOPPED &&
996       status->value.sig == TARGET_SIGNAL_TRAP &&
997       read_pc_pid (ptid) - DECR_PC_AFTER_BREAK == pd_brk_addr)
998     return pd_activate (0);
999
1000   return pd_update (0);
1001 }
1002
1003 /* Record that the 64-bit general-purpose registers contain VALS.  */
1004
1005 static void
1006 supply_gprs64 (uint64_t *vals)
1007 {
1008   int regno;
1009
1010   for (regno = 0; regno < 32; regno++)
1011     supply_register (regno, (char *) (vals + regno));
1012 }
1013
1014 /* Record that 32-bit register REGNO contains VAL.  */
1015
1016 static void
1017 supply_reg32 (int regno, uint32_t val)
1018 {
1019   supply_register (regno, (char *) &val);
1020 }
1021
1022 /* Record that the floating-point registers contain VALS.  */
1023
1024 static void
1025 supply_fprs (double *vals)
1026 {
1027   int regno;
1028
1029   for (regno = 0; regno < 32; regno++)
1030     supply_register (regno + FP0_REGNUM, (char *) (vals + regno));
1031 }
1032
1033 /* Record that the special registers contain the specified 64-bit and
1034    32-bit values.  */
1035
1036 static void
1037 supply_sprs64 (uint64_t iar, uint64_t msr, uint32_t cr,
1038                uint64_t lr, uint64_t ctr, uint32_t xer)
1039 {
1040   int regno = FIRST_UISA_SP_REGNUM;
1041   supply_register (regno, (char *) &iar);
1042   supply_register (regno + 1, (char *) &msr);
1043   supply_register (regno + 2, (char *) &cr);
1044   supply_register (regno + 3, (char *) &lr);
1045   supply_register (regno + 4, (char *) &ctr);
1046   supply_register (regno + 5, (char *) &xer);
1047 }
1048
1049 /* Record that the special registers contain the specified 32-bit
1050    values.  */
1051
1052 static void
1053 supply_sprs32 (uint32_t iar, uint32_t msr, uint32_t cr,
1054                uint32_t lr, uint32_t ctr, uint32_t xer)
1055 {
1056   int regno = FIRST_UISA_SP_REGNUM;
1057   supply_register (regno, (char *) &iar);
1058   supply_register (regno + 1, (char *) &msr);
1059   supply_register (regno + 2, (char *) &cr);
1060   supply_register (regno + 3, (char *) &lr);
1061   supply_register (regno + 4, (char *) &ctr);
1062   supply_register (regno + 5, (char *) &xer);
1063 }
1064
1065 /* Fetch all registers from pthread PDTID, which doesn't have a kernel
1066    thread.
1067
1068    There's no way to query a single register from a non-kernel
1069    pthread, so there's no need for a single-register version of this
1070    function.  */
1071
1072 static void
1073 fetch_regs_lib (pthdb_pthread_t pdtid)
1074 {
1075   int status, i;
1076   pthdb_context_t ctx;
1077
1078   if (debug_aix_thread)
1079     fprintf_unfiltered (gdb_stdlog, "fetch_regs_lib %lx\n", (long)pdtid);
1080   status = pthdb_pthread_context (pd_session, pdtid, &ctx);
1081   if (status != PTHDB_SUCCESS)
1082     error ("aix-thread: fetch_registers: pthdb_pthread_context returned %s",
1083            pd_status2str (status));
1084
1085   /* General-purpose registers.  */
1086
1087   if (arch64)
1088     supply_gprs64 (ctx.gpr);
1089   else
1090     for (i = 0; i < 32; i++)
1091       supply_reg32 (i, ctx.gpr[i]);
1092
1093   /* Floating-point registers.  */
1094
1095   supply_fprs (ctx.fpr);
1096
1097   /* Special registers.  */
1098
1099   if (arch64)
1100     supply_sprs64 (ctx.iar, ctx.msr, ctx.cr, ctx.lr, ctx.ctr, ctx.xer);
1101   else
1102     supply_sprs32 (ctx.iar, ctx.msr, ctx.cr, ctx.lr, ctx.ctr, ctx.xer);
1103 }
1104
1105 /* Fetch register REGNO if != -1 or all registers otherwise from
1106    kernel thread TID.
1107
1108    AIX provides a way to query all of a kernel thread's GPRs, FPRs, or
1109    SPRs, but there's no way to query individual registers within those
1110    groups.  Therefore, if REGNO != -1, this function fetches an entire
1111    group.
1112
1113    Unfortunately, kernel thread register queries often fail with
1114    EPERM, indicating that the thread is in kernel space.  This breaks
1115    backtraces of threads other than the current one.  To make that
1116    breakage obvious without throwing an error to top level (which is
1117    bad e.g. during "info threads" output), zero registers that can't
1118    be retrieved.  */
1119
1120 static void
1121 fetch_regs_kern (int regno, pthdb_tid_t tid)
1122 {
1123   uint64_t gprs64[32];
1124   uint32_t gprs32[32];
1125   double fprs[32];
1126   struct ptxsprs sprs64;
1127   struct ptsprs sprs32;
1128   int i;
1129
1130   if (debug_aix_thread)
1131     fprintf_unfiltered (gdb_stdlog,
1132                         "fetch_regs_kern tid=%lx regno=%d arch64=%d\n",
1133                         (long)tid, regno, arch64);
1134
1135   /* General-purpose registers.  */
1136   if (regno == -1 || regno < FP0_REGNUM)
1137     {
1138       if (arch64)
1139         {
1140           if (!ptrace64aix (PTT_READ_GPRS, tid, 
1141                             (unsigned long) gprs64, 0, NULL))
1142             memset (gprs64, 0, sizeof (gprs64));
1143           supply_gprs64 (gprs64);
1144         }
1145       else
1146         {
1147           if (!ptrace32 (PTT_READ_GPRS, tid, gprs32, 0, NULL))
1148             memset (gprs32, 0, sizeof (gprs32));
1149           for (i = 0; i < 32; i++)
1150             supply_reg32 (i, gprs32[i]);
1151         }
1152     }
1153
1154   /* Floating-point registers.  */
1155
1156   if (regno == -1 || (regno >= FP0_REGNUM && regno <= FPLAST_REGNUM))
1157     {
1158       if (!ptrace32 (PTT_READ_FPRS, tid, (int *) fprs, 0, NULL))
1159         memset (fprs, 0, sizeof (fprs));
1160       supply_fprs (fprs);
1161     }
1162
1163   /* Special-purpose registers.  */
1164
1165   if (regno == -1 || 
1166       (regno > FPLAST_REGNUM && regno <= LAST_UISA_SP_REGNUM))
1167     {
1168       if (arch64)
1169         {
1170           if (!ptrace64aix (PTT_READ_SPRS, tid, 
1171                             (unsigned long) &sprs64, 0, NULL))
1172             memset (&sprs64, 0, sizeof (sprs64));
1173           supply_sprs64 (sprs64.pt_iar, sprs64.pt_msr, sprs64.pt_cr,
1174                          sprs64.pt_lr, sprs64.pt_ctr, sprs64.pt_xer);
1175         }
1176       else
1177         {
1178           if (!ptrace32 (PTT_READ_SPRS, tid, (int *) &sprs32, 0, NULL))
1179             memset (&sprs32, 0, sizeof (sprs32));
1180           supply_sprs32 (sprs32.pt_iar, sprs32.pt_msr, sprs32.pt_cr,
1181                          sprs32.pt_lr, sprs32.pt_ctr, sprs32.pt_xer);
1182
1183           if (REGISTER_RAW_SIZE (LAST_UISA_SP_REGNUM))
1184             supply_register (LAST_UISA_SP_REGNUM, (char *) &sprs32.pt_mq);
1185         }
1186     }
1187 }
1188
1189 /* Fetch register REGNO if != -1 or all registers otherwise in the
1190    thread/process specified by inferior_ptid.  */
1191
1192 static void
1193 ops_fetch_registers (int regno)
1194 {
1195   struct thread_info *thread;
1196   pthdb_tid_t tid;
1197
1198   if (!PD_TID (inferior_ptid))
1199     base_ops.to_fetch_registers (regno);
1200   else
1201     {
1202       thread = find_thread_pid (inferior_ptid);
1203       tid = thread->private->tid;
1204
1205       if (tid == PTHDB_INVALID_TID)
1206         fetch_regs_lib (thread->private->pdtid);
1207       else
1208         fetch_regs_kern (regno, tid);
1209     }
1210 }
1211
1212 /* Store the special registers into the specified 64-bit and 32-bit
1213    locations.  */
1214
1215 static void
1216 fill_sprs64 (uint64_t *iar, uint64_t *msr, uint32_t *cr,
1217              uint64_t *lr, uint64_t *ctr, uint32_t *xer)
1218 {
1219   int regno = FIRST_UISA_SP_REGNUM;
1220   *iar = read_register (regno);
1221   *msr = read_register (regno + 1);
1222   *cr = read_register (regno + 2);
1223   *lr = read_register (regno + 3);
1224   *ctr = read_register (regno + 4);
1225   *xer = read_register (regno + 5);
1226 }
1227
1228 /* Store all registers into pthread PDTID, which doesn't have a kernel
1229    thread.
1230
1231    It's possible to store a single register into a non-kernel pthread,
1232    but I doubt it's worth the effort.  */
1233
1234 static void
1235 store_regs_lib (pthdb_pthread_t pdtid)
1236 {
1237   int status, i;
1238   pthdb_context_t ctx;
1239
1240   if (debug_aix_thread)
1241     fprintf_unfiltered (gdb_stdlog, 
1242                         "store_regs_lib %lx\n", (long)pdtid);
1243
1244   /* Retrieve the thread's current context for its non-register
1245      values.  */
1246   status = pthdb_pthread_context (pd_session, pdtid, &ctx);
1247   if (status != PTHDB_SUCCESS)
1248     error ("aix-thread: store_registers: pthdb_pthread_context returned %s",
1249            pd_status2str (status));
1250
1251   /* General-purpose registers.  */
1252
1253   for (i = 0; i < 32; i++)
1254     ctx.gpr[i] = read_register (i);
1255
1256   /* Floating-point registers.  */
1257
1258   for (i = 0; i < 32; i++)
1259     ctx.fpr[i] = *(double *) &registers[REGISTER_BYTE (FP0_REGNUM + i)];
1260
1261   /* Special registers.  */
1262
1263   fill_sprs64 (&ctx.iar, &ctx.msr, &ctx.cr, &ctx.lr, &ctx.ctr, &ctx.xer);
1264
1265   status = pthdb_pthread_setcontext (pd_session, pdtid, &ctx);
1266   if (status != PTHDB_SUCCESS)
1267     error ("aix-thread: store_registers: pthdb_pthread_setcontext returned %s",
1268            pd_status2str (status));
1269 }
1270
1271 /* Store register REGNO if != -1 or all registers otherwise into
1272    kernel thread TID.
1273
1274    AIX provides a way to set all of a kernel thread's GPRs, FPRs, or
1275    SPRs, but there's no way to set individual registers within those
1276    groups.  Therefore, if REGNO != -1, this function stores an entire
1277    group.  */
1278
1279 static void
1280 store_regs_kern (int regno, pthdb_tid_t tid)
1281 {
1282   struct ptxsprs sprs64;
1283   struct ptsprs sprs32;
1284   char *regp;
1285
1286   if (debug_aix_thread)
1287     fprintf_unfiltered (gdb_stdlog, "store_regs_kern tid=%lx regno=%d\n",
1288                         (long)tid, regno);
1289
1290   /* General-purpose registers.  */
1291   if (regno == -1 || regno < FP0_REGNUM)
1292     {
1293       regp = &registers[REGISTER_BYTE (0)];
1294       if (arch64)
1295         ptrace64aix (PTT_WRITE_GPRS, tid, (unsigned long) regp, 0, NULL);
1296       else
1297         ptrace32 (PTT_WRITE_GPRS, tid, (int *) regp, 0, NULL);
1298     }
1299
1300   /* Floating-point registers.  */
1301
1302   if (regno == -1 || (regno >= FP0_REGNUM && regno <= FPLAST_REGNUM))
1303     {
1304       regp = &registers[REGISTER_BYTE (FP0_REGNUM)];
1305       ptrace32 (PTT_WRITE_FPRS, tid, (int *) regp, 0, NULL);
1306     }
1307
1308   /* Special-purpose registers.  */
1309
1310   if (regno == -1 || 
1311       (regno > FPLAST_REGNUM && regno <= LAST_UISA_SP_REGNUM))
1312     {
1313       if (arch64)
1314         {
1315           ptrace64aix (PTT_READ_SPRS, tid, 
1316                        (unsigned long) &sprs64, 0, NULL);
1317           fill_sprs64 (&sprs64.pt_iar, &sprs64.pt_msr, &sprs64.pt_cr,
1318                        &sprs64.pt_lr, &sprs64.pt_ctr, &sprs64.pt_xer);
1319           ptrace64aix (PTT_WRITE_SPRS, tid, 
1320                        (unsigned long) &sprs64, 0, NULL);
1321         }
1322       else
1323         {
1324           ptrace32 (PTT_READ_SPRS, tid, (int *) &sprs32, 0, NULL);
1325
1326           regno = FIRST_UISA_SP_REGNUM;
1327           sprs32.pt_iar = read_register (regno);
1328           sprs32.pt_msr = read_register (regno + 1);
1329           sprs32.pt_cr = read_register (regno + 2);
1330           sprs32.pt_lr = read_register (regno + 3);
1331           sprs32.pt_ctr = read_register (regno + 4);
1332           sprs32.pt_xer = read_register (regno + 5);
1333
1334           if (REGISTER_RAW_SIZE (LAST_UISA_SP_REGNUM))
1335             sprs32.pt_mq = read_register (LAST_UISA_SP_REGNUM);
1336
1337           ptrace32 (PTT_WRITE_SPRS, tid, (int *) &sprs32, 0, NULL);
1338         }
1339     }
1340 }
1341
1342 /* Store gdb's current view of the register set into the
1343    thread/process specified by inferior_ptid.  */
1344
1345 static void
1346 ops_store_registers (int regno)
1347 {
1348   struct thread_info *thread;
1349   pthdb_tid_t tid;
1350
1351   if (!PD_TID (inferior_ptid))
1352     base_ops.to_store_registers (regno);
1353   else
1354     {
1355       thread = find_thread_pid (inferior_ptid);
1356       tid = thread->private->tid;
1357
1358       if (tid == PTHDB_INVALID_TID)
1359         store_regs_lib (thread->private->pdtid);
1360       else
1361         store_regs_kern (regno, tid);
1362     }
1363 }
1364
1365 /* Prepare to modify the registers array.  */
1366
1367 static void
1368 ops_prepare_to_store (void)
1369 {
1370   if (!PD_TID (inferior_ptid))
1371     base_ops.to_prepare_to_store ();
1372   else
1373     read_register_bytes (0, NULL, REGISTER_BYTES);
1374 }
1375
1376 /* Transfer LEN bytes of memory from GDB address MYADDR to target
1377    address MEMADDR if WRITE and vice versa otherwise.  */
1378
1379 static int
1380 ops_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len, int write,
1381                  struct mem_attrib *attrib,
1382                  struct target_ops *target)
1383 {
1384   int n;
1385   struct cleanup *cleanup = save_inferior_ptid ();
1386
1387   inferior_ptid = pid_to_ptid (PIDGET (inferior_ptid));
1388   n = base_ops.to_xfer_memory (memaddr, myaddr, len, 
1389                                write, attrib, &base_ops);
1390   do_cleanups (cleanup);
1391
1392   return n;
1393 }
1394
1395 /* Kill and forget about the inferior process.  */
1396
1397 static void
1398 ops_kill (void)
1399 {
1400   struct cleanup *cleanup = save_inferior_ptid ();
1401
1402   inferior_ptid = pid_to_ptid (PIDGET (inferior_ptid));
1403   base_ops.to_kill ();
1404   do_cleanups (cleanup);
1405 }
1406
1407 /* Clean up after the inferior exits.  */
1408
1409 static void
1410 ops_mourn_inferior (void)
1411 {
1412   pd_deactivate ();
1413   base_ops.to_mourn_inferior ();
1414 }
1415
1416 /* Return whether thread PID is still valid.  */
1417
1418 static int
1419 ops_thread_alive (ptid_t ptid)
1420 {
1421   if (!PD_TID (ptid))
1422     return base_ops.to_thread_alive (ptid);
1423
1424   /* We update the thread list every time the child stops, so all
1425      valid threads should be in the thread list.  */
1426   return in_thread_list (ptid);
1427 }
1428
1429 /* Return a printable representation of composite PID for use in
1430    "info threads" output.  */
1431
1432 static char *
1433 ops_pid_to_str (ptid_t ptid)
1434 {
1435   static char *ret = NULL;
1436
1437   if (!PD_TID (ptid))
1438     return base_ops.to_pid_to_str (ptid);
1439
1440   /* Free previous return value; a new one will be allocated by
1441      xasprintf().  */
1442   xfree (ret);
1443
1444   xasprintf (&ret, "Thread %ld", ptid_get_tid (ptid));
1445   return ret;
1446 }
1447
1448 /* Return a printable representation of extra information about
1449    THREAD, for use in "info threads" output.  */
1450
1451 static char *
1452 ops_extra_thread_info (struct thread_info *thread)
1453 {
1454   struct ui_file *buf;
1455   int status;
1456   pthdb_pthread_t pdtid;
1457   pthdb_tid_t tid;
1458   pthdb_state_t state;
1459   pthdb_suspendstate_t suspendstate;
1460   pthdb_detachstate_t detachstate;
1461   int cancelpend;
1462   long length;
1463   static char *ret = NULL;
1464
1465   if (!PD_TID (thread->ptid))
1466     return NULL;
1467
1468   buf = mem_fileopen ();
1469
1470   pdtid = thread->private->pdtid;
1471   tid = thread->private->tid;
1472
1473   if (tid != PTHDB_INVALID_TID)
1474     fprintf_unfiltered (buf, "tid %d", tid);
1475
1476   status = pthdb_pthread_state (pd_session, pdtid, &state);
1477   if (status != PTHDB_SUCCESS)
1478     state = PST_NOTSUP;
1479   fprintf_unfiltered (buf, ", %s", state2str (state));
1480
1481   status = pthdb_pthread_suspendstate (pd_session, pdtid, 
1482                                        &suspendstate);
1483   if (status == PTHDB_SUCCESS && suspendstate == PSS_SUSPENDED)
1484     fprintf_unfiltered (buf, ", suspended");
1485
1486   status = pthdb_pthread_detachstate (pd_session, pdtid, 
1487                                       &detachstate);
1488   if (status == PTHDB_SUCCESS && detachstate == PDS_DETACHED)
1489     fprintf_unfiltered (buf, ", detached");
1490
1491   pthdb_pthread_cancelpend (pd_session, pdtid, &cancelpend);
1492   if (status == PTHDB_SUCCESS && cancelpend)
1493     fprintf_unfiltered (buf, ", cancel pending");
1494
1495   ui_file_write (buf, "", 1);
1496
1497   xfree (ret);                  /* Free old buffer.  */
1498
1499   ret = ui_file_xstrdup (buf, &length);
1500   ui_file_delete (buf);
1501
1502   return ret;
1503 }
1504
1505 /* Initialize target ops.  */
1506
1507 static void
1508 init_ops (void)
1509 {
1510   ops.to_shortname          = "aix-threads";
1511   ops.to_longname           = "AIX pthread support";
1512   ops.to_doc                = "AIX pthread support";
1513
1514   ops.to_attach             = ops_attach;
1515   ops.to_detach             = ops_detach;
1516   ops.to_resume             = ops_resume;
1517   ops.to_wait               = ops_wait;
1518   ops.to_fetch_registers    = ops_fetch_registers;
1519   ops.to_store_registers    = ops_store_registers;
1520   ops.to_prepare_to_store   = ops_prepare_to_store;
1521   ops.to_xfer_memory        = ops_xfer_memory;
1522   /* No need for ops.to_create_inferior, because we activate thread
1523      debugging when the inferior reaches pd_brk_addr.  */
1524   ops.to_kill               = ops_kill;
1525   ops.to_mourn_inferior     = ops_mourn_inferior;
1526   ops.to_thread_alive       = ops_thread_alive;
1527   ops.to_pid_to_str         = ops_pid_to_str;
1528   ops.to_extra_thread_info  = ops_extra_thread_info;
1529   ops.to_stratum            = thread_stratum;
1530   ops.to_magic              = OPS_MAGIC;
1531 }
1532
1533 /* Module startup initialization function, automagically called by
1534    init.c.  */
1535
1536 void
1537 _initialize_aix_thread (void)
1538 {
1539   init_ops ();
1540   add_target (&ops);
1541
1542   /* Notice when object files get loaded and unloaded.  */
1543   target_new_objfile_chain = target_new_objfile_hook;
1544   target_new_objfile_hook = new_objfile;
1545
1546   add_show_from_set (add_set_cmd ("aix-thread", no_class, var_zinteger,
1547                                   (char *) &debug_aix_thread, 
1548                                   "Set debugging of AIX thread module.\n"
1549                                   "Enables printf debugging output.\n",
1550                                   &setdebuglist),
1551                                   &showdebuglist);
1552 }