OSDN Git Service

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