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