OSDN Git Service

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