Fix date of last commit.
[external/binutils.git] / gdb / uw-thread.c
1 /* Low level interface for debugging UnixWare user-mode threads for
2    GDB, the GNU debugger.
3
4    Copyright 1999, 2000 Free Software Foundation, Inc.
5    Written by Nick Duffek <nsd@cygnus.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 2 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, write to the Free Software
21    Foundation, Inc., 59 Temple Place - Suite 330,
22    Boston, MA 02111-1307, USA.  */
23
24
25 /* Like many systems, UnixWare implements two classes of threads:
26    kernel-mode threads, which are scheduled by the kernel; and
27    user-mode threads, which are scheduled by a library.  UnixWare
28    calls these two classes lightweight processes (LWPs) and threads,
29    respectively.
30
31    This module deals with user-mode threads.  It calls procfs_ops
32    functions to deal with LWPs and processes and core_ops functions to
33    deal with core files.
34
35    As of this writing, the user-mode thread debugging interface is not
36    documented beyond the comments in <thread.h>.  The following
37    description has been gleaned from experience and from information
38    provided by SCO.
39
40    libthread.so, against which all UnixWare user-mode thread programs
41    link, provides a global thread_debug structure named _thr_debug.
42    It has three fields:
43
44      (1) thr_map is a pointer to a pointer to an element of a
45          thread_map ring.  A thread_map contains a single thread's id
46          number, state, LWP pointer, recent register state, and other
47          useful information.
48
49      (2) thr_brk is a pointer to a stub function that libthread.so
50          calls when it changes a thread's state, e.g. by creating it,
51          switching it to an LWP, or causing it to exit.
52
53      (3) thr_debug_on controls whether libthread.so calls thr_brk().
54
55    Debuggers are able to track thread activity by setting a private
56    breakpoint on thr_brk() and setting thr_debug_on to 1.
57
58    thr_brk() receives two arguments:
59
60      (1) a pointer to a thread_map describing the thread being
61          changed; and
62
63      (2) an enum thread_change specifying one of the following
64          changes:
65
66          invalid                 unknown
67          thread_create           thread has just been created
68          thread_exit             thread has just exited
69          switch_begin            thread will be switched to an LWP
70          switch_complete         thread has been switched to an LWP
71          cancel_complete         thread wasn't switched to an LWP
72          thread_suspend          thread has been thr_suspend()ed
73          thread_suspend_pending  thread will be thr_suspend()ed
74          thread_continue         thread has been thr_continue()d
75
76    The thread_map argument to thr_brk() is NULL under the following
77    circumstances:
78
79      - The main thread is being acted upon.  The main thread always
80        has id 1, so its thread_map is easy to find by scanning through
81        _thr_debug.thr_map.
82
83      - A "switch_complete" change is occurring, which means that the
84        thread specified in the most recent "switch_begin" change has
85        moved to an LWP.
86
87      - A "cancel_complete" change is occurring, which means that the
88        thread specified in the most recent "switch_begin" change has
89        not moved to an LWP after all.
90
91      - A spurious "switch_begin" change is occurring after a
92        "thread_exit" change.
93
94    Between switch_begin and switch_complete or cancel_complete, the
95    affected thread's LWP pointer is not reliable.  It is possible that
96    other parts of the thread's thread_map are also unreliable during
97    that time. */
98
99
100 #include "defs.h"
101 #include "gdbthread.h"
102 #include "target.h"
103 #include "inferior.h"
104 #include <fcntl.h>
105
106 /* <thread.h> includes <sys/priocntl.h>, which requires boolean_t from
107    <sys/types.h>, which doesn't typedef boolean_t with gcc. */
108
109 #define boolean_t int
110 #include <thread.h>
111 #undef boolean_t
112
113 #include <synch.h>              /* for UnixWare 2.x */
114
115 /* Prototypes for supply_gregset etc. */
116 #include "gregset.h"
117
118 /* Whether to emit debugging output. */
119
120 #define DEBUG 0
121
122 /* Default debugging output file, overridden by envvar UWTHR_DEBUG. */
123
124 #define DEBUG_FILE "/dev/tty"
125
126 /* #if DEBUG, write string S to the debugging output channel. */
127
128 #if !DEBUG
129 # define DBG(fmt_and_args)
130 # define DBG2(fmt_and_args)
131 #else
132 # define DBG(fmt_and_args) dbg fmt_and_args
133 # define DBG2(fmt_and_args)
134 #endif
135
136 /* Back end to CALL_BASE() and TRY_BASE(): evaluate CALL, then convert
137    inferior_pid to a composite thread/process id. */
138
139 #define CALL_BASE_1(call)               \
140 do {                                    \
141   DBG2(("CALL_BASE(" #call ")"));       \
142   call;                                 \
143   do_cleanups (infpid_cleanup);         \
144 } while (0)
145
146 /* If inferior_pid can be converted to a composite lwp/process id, do so,
147    evaluate base_ops function CALL, and then convert inferior_pid back to a
148    composite thread/process id.
149
150    Otherwise, issue an error message and return nonlocally. */
151
152 #define CALL_BASE(call)                 \
153 do {                                    \
154   if (!lwp_infpid ())                   \
155     error ("uw-thread: no lwp");        \
156   CALL_BASE_1 (call);                   \
157 } while (0)
158
159 /* Like CALL_BASE(), but instead of returning nonlocally on error, set
160    *CALLED to whether the inferior_pid conversion was successful. */
161
162 #define TRY_BASE(call, called)          \
163 do {                                    \
164   if ((*(called) = lwp_infpid ()))      \
165     CALL_BASE_1 (call);                 \
166 } while (0)
167
168 /* Information passed by thread_iter() to its callback parameter. */
169
170 typedef struct {
171   struct thread_map map;
172   __lwp_desc_t lwp;
173   CORE_ADDR mapp;
174 } iter_t;
175
176 /* Private thread data for the thread_info struct. */
177
178 struct private_thread_info {
179   int stable;           /* 0 if libthread.so is modifying thread map */
180   int thrid;            /* thread id assigned by libthread.so */
181   int lwpid;            /* thread's lwp if .stable, 0 means no lwp */
182   CORE_ADDR mapp;       /* address of thread's map structure */
183 };
184
185
186 /* procfs.c's target-specific operations. */
187 extern struct target_ops procfs_ops;
188
189 /* Flag to prevent procfs.c from starting inferior processes. */
190 extern int procfs_suppress_run;
191
192 /* This module's target-specific operations. */
193 static struct target_ops uw_thread_ops;
194
195 /* Copy of the target over which uw_thread_ops is pushed.  This is
196    more convenient than a pointer to procfs_ops or core_ops, because
197    they lack current_target's default callbacks. */
198 static struct target_ops base_ops;
199
200 /* Saved pointer to previous owner of target_new_objfile_hook. */
201 static void (*target_new_objfile_chain)(struct objfile *);
202
203 /* Whether we are debugging a user-space thread program.  This isn't
204    set until after libthread.so is loaded by the program being
205    debugged.
206
207    Except for module one-time intialization and where otherwise
208    documented, no functions in this module get called when
209    !uw_thread_active. */
210 static int uw_thread_active;
211
212 /* For efficiency, cache the addresses of libthread.so's _thr_debug
213    structure, its thr_brk stub function, and the main thread's map. */
214 static CORE_ADDR thr_debug_addr;
215 static CORE_ADDR thr_brk_addr;
216 static CORE_ADDR thr_map_main;
217
218 /* Remember the thread most recently marked as switching.  Necessary because
219    libthread.so passes null map when calling stub with tc_*_complete. */
220 static struct thread_info *switchto_thread;
221
222 /* Cleanup chain for safely restoring inferior_pid after CALL_BASE. */
223 static struct cleanup *infpid_cleanup;
224
225
226 #if DEBUG
227 /* Helper function for DBG() macro: if printf-style FMT is non-null, format it
228    with args and display the result on the debugging output channel. */
229
230 static void
231 dbg (char *fmt, ...)
232 {
233   static int fd = -1, len;
234   va_list args;
235   char buf[1024];
236   char *path;
237
238   if (!fmt)
239     return;
240
241   if (fd < 0)
242     {
243       path = getenv ("UWTHR_DEBUG");
244       if (!path)
245         path = DEBUG_FILE;
246       if ((fd = open (path, O_WRONLY | O_CREAT | O_TRUNC, 0664)) < 0)
247         error ("can't open %s\n", path);
248     }
249
250   va_start (args, fmt);
251   vsprintf (buf, fmt, args);
252   va_end (args);
253
254   len = strlen (buf);
255   buf[len] = '\n';
256   (void)write (fd, buf, len + 1);
257 }
258
259 #if 0
260 /* Return a string representing composite PID's components. */
261
262 static char *
263 dbgpid (int pid)
264 {
265   static char *buf, buf1[80], buf2[80];
266   if (!buf || buf == buf2)
267     buf = buf1;
268   else
269     buf = buf2;
270
271   if (pid <= 0)
272     sprintf (buf, "%d", pid);
273   else
274     sprintf (buf, "%s %d/%d", ISTID (pid) ? "thr" : "lwp",
275              TIDGET (pid), PIDGET (pid));
276
277   return buf;
278 }
279
280 /* Return a string representing thread state CHANGE. */
281
282 static char *
283 dbgchange (enum thread_change change)
284 {
285   switch (change) {
286   case tc_invalid:                      return "invalid";
287   case tc_thread_create:                return "thread_create";
288   case tc_thread_exit:                  return "thread_exit";
289   case tc_switch_begin:                 return "switch_begin";
290   case tc_switch_complete:              return "switch_complete";
291   case tc_cancel_complete:              return "cancel_complete";
292   case tc_thread_suspend:               return "thread_suspend";
293   case tc_thread_suspend_pending:       return "thread_suspend_pending";
294   case tc_thread_continue:              return "thread_continue";
295   default:                              return "unknown";
296   }
297 }
298
299 /* Return a string representing thread STATE. */
300
301 static char *
302 dbgstate (int state)
303 {
304   switch (state) {
305   case TS_ONPROC:       return "running";
306   case TS_SLEEP:        return "sleeping";
307   case TS_RUNNABLE:     return "runnable";
308   case TS_ZOMBIE:       return "zombie";
309   case TS_SUSPENDED:    return "suspended";
310 #ifdef TS_FORK
311   case TS_FORK:         return "forking";
312 #endif
313   default:              return "confused";
314   }
315 }
316 #endif  /* 0 */
317 #endif  /* DEBUG */
318
319
320 /* Read the contents of _thr_debug into *DEBUGP.  Return success. */
321
322 static int
323 read_thr_debug (struct thread_debug *debugp)
324 {
325   return base_ops.to_xfer_memory (thr_debug_addr, (char *)debugp,
326                                   sizeof (*debugp), 0, &base_ops);
327 }
328
329 /* Read into MAP the contents of the thread map at inferior process address
330    MAPP.  Return success. */
331
332 static int
333 read_map (CORE_ADDR mapp, struct thread_map *map)
334 {
335   return base_ops.to_xfer_memory ((CORE_ADDR)THR_MAP (mapp), (char *)map,
336                                   sizeof (*map), 0, &base_ops);
337 }
338
339 /* Read into LWP the contents of the lwp decriptor at inferior process address
340    LWPP.  Return success. */
341
342 static int
343 read_lwp (CORE_ADDR lwpp, __lwp_desc_t *lwp)
344 {
345   return base_ops.to_xfer_memory (lwpp, (char *)lwp,
346                                   sizeof (*lwp), 0, &base_ops);
347 }
348
349 /* Iterate through all user threads, applying FUNC(<map>, <lwp>, DATA) until
350      (a) FUNC returns nonzero,
351      (b) FUNC has been applied to all threads, or
352      (c) an error occurs,
353    where <map> is the thread's struct thread_map and <lwp> if non-null is the
354    thread's current __lwp_desc_t.
355
356    If a call to FUNC returns nonzero, return that value; otherwise, return 0. */
357
358 static int
359 thread_iter (int (*func)(iter_t *, void *), void *data)
360 {
361   struct thread_debug debug;
362   CORE_ADDR first, mapp;
363   iter_t iter;
364   int ret;
365
366   if (!read_thr_debug (&debug))
367     return 0;
368   if (!base_ops.to_xfer_memory ((CORE_ADDR)debug.thr_map, (char *)&mapp,
369                                 sizeof (mapp), 0, &base_ops))
370     return 0;
371   if (!mapp)
372     return 0;
373
374   for (first = mapp;;)
375     {
376       if (!read_map (mapp, &iter.map))
377         return 0;
378
379       if (iter.map.thr_lwpp)
380         if (!read_lwp ((CORE_ADDR)iter.map.thr_lwpp, &iter.lwp))
381           return 0;
382
383       iter.mapp = mapp;
384       if ((ret = func (&iter, data)))
385         return ret;
386
387       mapp = (CORE_ADDR)iter.map.thr_next;
388       if (mapp == first)
389         return 0;
390     }
391 }
392
393 /* Deactivate user-mode thread support. */
394
395 static void
396 deactivate_uw_thread (void)
397 {
398   remove_thread_event_breakpoints ();
399   uw_thread_active = 0;
400   unpush_target (&uw_thread_ops);
401 }
402
403 /* Return the composite lwp/process id corresponding to composite
404    id PID.  If PID is a thread with no lwp, return 0. */
405
406 static int
407 thr_to_lwp (int pid)
408 {
409   struct thread_info *info;
410   int lid;
411
412   if (!ISTID (pid))
413     lid = pid;
414   else if (!(info = find_thread_pid (pid)))
415     lid = 0;
416   else if (!info->private->lwpid)
417     lid = 0;
418   else
419     lid = MKLID (pid, info->private->lwpid);
420
421   DBG2(("  thr_to_lwp(%s) = %s", dbgpid (pid), dbgpid (lid)));
422   return lid;
423 }
424
425 /* find_thread_lwp() callback: return whether TP describes a thread
426    associated with lwp id DATA. */
427
428 static int
429 find_thread_lwp_callback (struct thread_info *tp, void *data)
430 {
431   int lwpid = (int)data;
432
433   if (!ISTID (tp->pid))
434     return 0;
435   if (!tp->private->stable)
436     return 0;
437   if (lwpid != tp->private->lwpid)
438     return 0;
439
440   /* match */
441   return 1;
442 }
443
444 /* If a thread is associated with lwp id LWPID, return the corresponding
445    member of the global thread list; otherwise, return null. */
446
447 static struct thread_info *
448 find_thread_lwp (int lwpid)
449 {
450   return iterate_over_threads (find_thread_lwp_callback, (void *)lwpid);
451 }
452
453 /* Return the composite thread/process id corresponding to composite
454    id PID.  If PID is an lwp with no thread, return PID. */
455
456 static int
457 lwp_to_thr (int pid)
458 {
459   struct thread_info *info;
460   int tid = pid, lwpid;
461
462   if (ISTID (pid))
463     goto done;
464   if (!(lwpid = LIDGET (pid)))
465     goto done;
466   if (!(info = find_thread_lwp (lwpid)))
467     goto done;
468   tid = MKTID (pid, info->private->thrid);
469
470  done:
471   DBG2((ISTID (tid) ? NULL : "lwp_to_thr: no thr for %s", dbgpid (pid)));
472   return tid;
473 }
474
475 /* do_cleanups() callback: convert inferior_pid to a composite
476    thread/process id after having made a procfs call. */
477
478 static void
479 thr_infpid (void *unused)
480 {
481   int pid = lwp_to_thr (inferior_pid);
482   DBG2((" inferior_pid from procfs: %s => %s",
483         dbgpid (inferior_pid), dbgpid (pid)));
484   inferior_pid = pid;
485 }
486
487 /* If possible, convert inferior_pid to a composite lwp/process id in
488    preparation for making a procfs call.  Return success. */
489
490 static int
491 lwp_infpid (void)
492 {
493   int pid = thr_to_lwp (inferior_pid);
494   DBG2((" inferior_pid to procfs: %s => %s",
495         dbgpid (inferior_pid), dbgpid (pid)));
496
497   if (!pid)
498     return 0;
499
500   inferior_pid = pid;
501   infpid_cleanup = make_cleanup (thr_infpid, NULL);
502   return 1;
503 }
504
505 /* Add to the global thread list a new user-mode thread with system id THRID,
506    lwp id LWPID, map address MAPP, and composite thread/process PID. */
507
508 static void
509 add_thread_uw (int thrid, int lwpid, CORE_ADDR mapp, int pid)
510 {
511   struct thread_info *newthread;
512
513   if ((newthread = add_thread (pid)) == NULL)
514     error ("failed to create new thread structure");
515
516   newthread->private = xmalloc (sizeof (struct private_thread_info));
517   newthread->private->stable = 1;
518   newthread->private->thrid = thrid;
519   newthread->private->lwpid = lwpid;
520   newthread->private->mapp = mapp;
521
522   if (target_has_execution)
523     printf_unfiltered ("[New %s]\n", target_pid_to_str (pid));
524 }
525
526 /* notice_threads() and find_main() callback: if the thread list doesn't
527    already contain the thread described by ITER, add it if it's the main
528    thread or if !DATA. */
529
530 static int
531 notice_thread (iter_t *iter, void *data)
532 {
533   int thrid = iter->map.thr_tid;
534   int lwpid = !iter->map.thr_lwpp ? 0 : iter->lwp.lwp_id;
535   int pid = MKTID (inferior_pid, thrid);
536
537   if (!find_thread_pid (pid) && (!data || thrid == 1))
538     add_thread_uw (thrid, lwpid, iter->mapp, pid);
539
540   return 0;
541 }
542
543 /* Add to the thread list any threads it doesn't already contain. */
544
545 static void
546 notice_threads (void)
547 {
548   thread_iter (notice_thread, NULL);
549 }
550
551 /* Return the address of the main thread's map.  On error, return 0. */
552
553 static CORE_ADDR
554 find_main (void)
555 {
556   if (!thr_map_main)
557     {
558       struct thread_info *info;
559       thread_iter (notice_thread, (void *)1);
560       if ((info = find_thread_pid (MKTID (inferior_pid, 1))))
561         thr_map_main = info->private->mapp;
562     }
563   return thr_map_main;
564 }
565
566 /* Attach to process specified by ARGS, then initialize for debugging it
567    and wait for the trace-trap that results from attaching.
568
569    This function only gets called with uw_thread_active == 0. */
570
571 static void
572 uw_thread_attach (char *args, int from_tty)
573 {
574   procfs_ops.to_attach (args, from_tty);
575   if (uw_thread_active)
576     thr_infpid (NULL);
577 }
578
579 /* Detach from the process attached to by uw_thread_attach(). */
580
581 static void
582 uw_thread_detach (char *args, int from_tty)
583 {
584   deactivate_uw_thread ();
585   base_ops.to_detach (args, from_tty);
586 }
587
588 /* Tell the inferior process to continue running thread PID if >= 0
589    and all threads otherwise. */
590
591 static void
592 uw_thread_resume (int pid, int step, enum target_signal signo)
593 {
594   if (pid > 0 && !(pid = thr_to_lwp (pid)))
595     pid = -1;
596
597   CALL_BASE (base_ops.to_resume (pid, step, signo));
598 }
599
600 /* If the trap we just received from lwp PID was due to a breakpoint
601    on the libthread.so debugging stub, update this module's state
602    accordingly. */
603
604 static void
605 libthread_stub (int pid)
606 {
607   CORE_ADDR sp, mapp, mapp_main;
608   enum thread_change change;
609   struct thread_map map;
610   __lwp_desc_t lwp;
611   int tid = 0, lwpid;
612   struct thread_info *info;
613
614   /* Check for stub breakpoint. */
615   if (read_pc_pid (pid) - DECR_PC_AFTER_BREAK != thr_brk_addr)
616     return;
617
618   /* Retrieve stub args. */
619   sp = read_register_pid (SP_REGNUM, pid);
620   if (!base_ops.to_xfer_memory (sp + SP_ARG0, (char *)&mapp,
621                                 sizeof (mapp), 0, &base_ops))
622     goto err;
623   if (!base_ops.to_xfer_memory (sp + SP_ARG0 + sizeof (mapp), (char *)&change,
624                                 sizeof (change), 0, &base_ops))
625     goto err;
626
627   /* create_inferior() may not have finished yet, so notice the main
628      thread to ensure that it's displayed first by add_thread(). */
629   mapp_main = find_main ();
630
631   /* Notice thread creation, deletion, or stability change. */
632   switch (change) {
633   case tc_switch_begin:
634     if (!mapp)                          /* usually means main thread */
635       mapp = mapp_main;
636     /* fall through */
637
638   case tc_thread_create:
639   case tc_thread_exit:
640     if (!mapp)
641       break;
642     if (!read_map (mapp, &map))
643       goto err;
644     tid = MKTID (pid, map.thr_tid);
645
646     switch (change) {
647     case tc_thread_create:              /* new thread */
648       if (!map.thr_lwpp)
649         lwpid = 0;
650       else if (!read_lwp ((CORE_ADDR)map.thr_lwpp, &lwp))
651         goto err;
652       else
653         lwpid = lwp.lwp_id;
654       add_thread_uw (map.thr_tid, lwpid, mapp, tid);
655       break;
656
657     case tc_thread_exit:                /* thread has exited */
658       printf_unfiltered ("[Exited %s]\n", target_pid_to_str (tid));
659       delete_thread (tid);
660       if (tid == inferior_pid)
661         inferior_pid = pid;
662       break;
663
664     case tc_switch_begin:               /* lwp is switching threads */
665       if (switchto_thread)
666         goto err;
667       if (!(switchto_thread = find_thread_pid (tid)))
668         goto err;
669       switchto_thread->private->stable = 0;
670       break;
671
672     default:
673       break;
674     }
675     break;
676
677   case tc_switch_complete:              /* lwp has switched threads */
678   case tc_cancel_complete:              /* lwp didn't switch threads */
679     if (!switchto_thread)
680       goto err;
681
682     if (change == tc_switch_complete)
683       {
684         /* If switchto_thread is the main thread, then (a) the corresponding
685            tc_switch_begin probably received a null map argument and therefore
686            (b) it may have been a spurious switch following a tc_thread_exit.
687
688            Therefore, explicitly query the thread's lwp before caching it in
689            its thread list entry. */
690
691         if (!read_map (switchto_thread->private->mapp, &map))
692           goto err;
693         if (map.thr_lwpp)
694           {
695             if (!read_lwp ((CORE_ADDR)map.thr_lwpp, &lwp))
696               goto err;
697             if ((info = find_thread_lwp (lwp.lwp_id)))
698               info->private->lwpid = 0;
699             switchto_thread->private->lwpid = lwp.lwp_id;
700           }
701       }
702
703     switchto_thread->private->stable = 1;
704     switchto_thread = NULL;
705     break;
706
707   case tc_invalid:
708   case tc_thread_suspend:
709   case tc_thread_suspend_pending:
710   case tc_thread_continue:
711   err:
712     DBG(("unexpected condition in libthread_stub()"));
713     break;
714   }
715
716   DBG2(("libthread_stub(%s): %s %s %s", dbgpid (pid), dbgpid (tid),
717         dbgchange (change), tid ? dbgstate (map.thr_state) : ""));
718 }
719
720 /* Wait for thread/lwp/process ID if >= 0 or for any thread otherwise. */
721
722 static int
723 uw_thread_wait (int pid, struct target_waitstatus *status)
724 {
725   if (pid > 0)
726     pid = thr_to_lwp (pid);
727   CALL_BASE (pid = base_ops.to_wait (pid > 0 ? pid : -1, status));
728
729   if (status->kind == TARGET_WAITKIND_STOPPED &&
730       status->value.sig == TARGET_SIGNAL_TRAP)
731     libthread_stub (pid);
732
733   return lwp_to_thr (pid);
734 }
735
736 /* Tell gdb about the registers in the thread/lwp/process specified by
737    inferior_pid. */
738
739 static void
740 uw_thread_fetch_registers (int regno)
741 {
742   int called;
743   struct thread_info *info;
744   struct thread_map map;
745
746   TRY_BASE (base_ops.to_fetch_registers (regno), &called);
747   if (called)
748     return;
749
750   if (!(info = find_thread_pid (inferior_pid)))
751     return;
752   if (!read_map (info->private->mapp, &map))
753     return;
754
755   supply_gregset (&map.thr_ucontext.uc_mcontext.gregs);
756   supply_fpregset (&map.thr_ucontext.uc_mcontext.fpregs);
757 }
758
759 /* Store gdb's current view of the register set into the thread/lwp/process
760    specified by inferior_pid. */
761
762 static void
763 uw_thread_store_registers (int regno)
764 {
765   CALL_BASE (base_ops.to_store_registers (regno));
766 }
767
768 /* Prepare to modify the registers array. */
769
770 static void
771 uw_thread_prepare_to_store (void)
772 {
773   CALL_BASE (base_ops.to_prepare_to_store ());
774 }
775
776 /* Fork an inferior process and start debugging it.
777
778    This function only gets called with uw_thread_active == 0. */
779
780 static void
781 uw_thread_create_inferior (char *exec_file, char *allargs, char **env)
782 {
783   if (uw_thread_active)
784     deactivate_uw_thread ();
785
786   procfs_ops.to_create_inferior (exec_file, allargs, env);
787   if (uw_thread_active)
788     {
789       find_main ();
790       thr_infpid (NULL);
791     }
792 }
793
794 /* Kill and forget about the inferior process. */
795
796 static void
797 uw_thread_kill (void)
798 {
799   base_ops.to_kill ();
800 }
801
802 /* Clean up after the inferior exits. */
803
804 static void
805 uw_thread_mourn_inferior (void)
806 {
807   deactivate_uw_thread ();
808   base_ops.to_mourn_inferior ();
809 }
810
811 /* Return whether this module can attach to and run processes.
812
813    This function only gets called with uw_thread_active == 0. */
814
815 static int
816 uw_thread_can_run (void)
817 {
818   return procfs_suppress_run;
819 }
820
821 /* Return whether thread PID is still valid. */
822
823 static int
824 uw_thread_alive (int pid)
825 {
826   if (!ISTID (pid))
827     return base_ops.to_thread_alive (pid);
828
829   /* If it's in the thread list, it's valid, because otherwise
830      libthread_stub() would have deleted it. */
831   return in_thread_list (pid);
832 }
833
834 /* Add to the thread list any threads and lwps it doesn't already contain. */
835
836 static void
837 uw_thread_find_new_threads (void)
838 {
839   CALL_BASE (if (base_ops.to_find_new_threads)
840                base_ops.to_find_new_threads ());
841   notice_threads ();
842 }
843
844 /* Return a string for pretty-printing PID in "info threads" output.
845    This may be called by either procfs.c or by generic gdb. */
846
847 static char *
848 uw_thread_pid_to_str (int pid)
849 {
850 #define FMT "Thread %d"
851   static char buf[sizeof (FMT) + 3 * sizeof (pid)];
852
853   if (!ISTID (pid))
854     /* core_ops says "process foo", so call procfs_ops explicitly. */
855     return procfs_ops.to_pid_to_str (pid);
856
857   sprintf (buf, FMT, TIDGET (pid));
858 #undef FMT
859   return buf;
860 }
861
862 /* Return a string displaying INFO state information in "info threads"
863    output. */
864
865 static char *
866 uw_extra_thread_info (struct thread_info *info)
867 {
868   static char buf[80];
869   struct thread_map map;
870   __lwp_desc_t lwp;
871   int lwpid;
872   char *name;
873
874   if (!ISTID (info->pid))
875     return NULL;
876
877   if (!info->private->stable)
878     return "switching";
879
880   if (!read_map (info->private->mapp, &map))
881     return NULL;
882
883   if (!map.thr_lwpp || !read_lwp ((CORE_ADDR)map.thr_lwpp, &lwp))
884     lwpid = 0;
885   else
886     lwpid = lwp.lwp_id;
887
888   switch (map.thr_state) {
889   case TS_ONPROC:       name = "running";       break;
890   case TS_SLEEP:        name = "sleeping";      break;
891   case TS_RUNNABLE:     name = "runnable";      break;
892   case TS_ZOMBIE:       name = "zombie";        break;
893   case TS_SUSPENDED:    name = "suspended";     break;
894 #ifdef TS_FORK
895   case TS_FORK:         name = "forking";       break;
896 #endif
897   default:              name = "confused";      break;
898   }
899
900   if (!lwpid)
901     return name;
902
903   sprintf (buf, "%s, LWP %d", name, lwpid);
904   return buf;
905 }
906
907 /* Check whether libthread.so has just been loaded, and if so, try to
908    initialize user-space thread debugging support.
909
910    libthread.so loading happens while (a) an inferior process is being
911    started by procfs and (b) a core image is being loaded.
912
913    This function often gets called with uw_thread_active == 0. */
914
915 static void
916 libthread_init (void)
917 {
918   struct minimal_symbol *ms;
919   struct thread_debug debug;
920   CORE_ADDR onp;
921   struct breakpoint *b;
922   int one = 1;
923
924   /* Don't initialize twice. */
925   if (uw_thread_active)
926     return;
927
928   /* Check whether libthread.so has been loaded. */
929   if (!(ms = lookup_minimal_symbol ("_thr_debug", NULL, NULL)))
930     return;
931
932   /* Cache _thr_debug's address. */
933   if (!(thr_debug_addr = SYMBOL_VALUE_ADDRESS (ms)))
934     return;
935
936   /* Initialize base_ops.to_xfer_memory(). */
937   base_ops = current_target;
938
939   /* Load _thr_debug's current contents. */
940   if (!read_thr_debug (&debug))
941     return;
942
943   /* User code (e.g. my test programs) may dereference _thr_debug,
944      making it availble to GDB before shared libs are loaded. */
945   if (!debug.thr_map)
946     return;
947
948   /* libthread.so has been loaded, and the current_target should now
949      reflect core_ops or procfs_ops. */
950   push_target (&uw_thread_ops);         /* must precede notice_threads() */
951   uw_thread_active = 1;
952
953   if (!target_has_execution)
954
955     /* Locate threads in core file. */
956     notice_threads ();
957
958   else
959     {
960       /* Set a breakpoint on the stub function provided by libthread.so. */
961       thr_brk_addr = (CORE_ADDR)debug.thr_brk;
962       if (!(b = create_thread_event_breakpoint (thr_brk_addr)))
963         goto err;
964
965       /* Activate the stub function. */
966       onp = (CORE_ADDR)&((struct thread_debug *)thr_debug_addr)->thr_debug_on;
967       if (!base_ops.to_xfer_memory ((CORE_ADDR)onp, (char *)&one,
968                                     sizeof (one), 1, &base_ops))
969         {
970           delete_breakpoint (b);
971           goto err;
972         }
973
974       /* Prepare for finding the main thread, which doesn't yet exist. */
975       thr_map_main = 0;
976     }
977
978   return;
979
980  err:
981   warning ("uw-thread: unable to initialize user-mode thread debugging\n");
982   deactivate_uw_thread ();
983 }
984
985 /* target_new_objfile_hook callback.
986
987    If OBJFILE is non-null, check whether libthread.so was just loaded,
988    and if so, prepare for user-mode thread debugging.
989
990    If OBJFILE is null, libthread.so has gone away, so stop debugging
991    user-mode threads.
992
993    This function often gets called with uw_thread_active == 0. */
994
995 static void
996 uw_thread_new_objfile (struct objfile *objfile)
997 {
998   if (objfile)
999     libthread_init ();
1000
1001   else if (uw_thread_active)
1002     deactivate_uw_thread ();
1003
1004   if (target_new_objfile_chain)
1005     target_new_objfile_chain (objfile);
1006 }
1007
1008 /* Initialize uw_thread_ops. */
1009
1010 static void
1011 init_uw_thread_ops (void)
1012 {
1013   uw_thread_ops.to_shortname          = "unixware-threads";
1014   uw_thread_ops.to_longname           = "UnixWare threads and pthread.";
1015   uw_thread_ops.to_doc        = "UnixWare threads and pthread support.";
1016   uw_thread_ops.to_attach             = uw_thread_attach;
1017   uw_thread_ops.to_detach             = uw_thread_detach;
1018   uw_thread_ops.to_resume             = uw_thread_resume;
1019   uw_thread_ops.to_wait               = uw_thread_wait;
1020   uw_thread_ops.to_fetch_registers    = uw_thread_fetch_registers;
1021   uw_thread_ops.to_store_registers    = uw_thread_store_registers;
1022   uw_thread_ops.to_prepare_to_store   = uw_thread_prepare_to_store;
1023   uw_thread_ops.to_create_inferior    = uw_thread_create_inferior;
1024   uw_thread_ops.to_kill               = uw_thread_kill;
1025   uw_thread_ops.to_mourn_inferior     = uw_thread_mourn_inferior;
1026   uw_thread_ops.to_can_run            = uw_thread_can_run;
1027   uw_thread_ops.to_thread_alive       = uw_thread_alive;
1028   uw_thread_ops.to_find_new_threads   = uw_thread_find_new_threads;
1029   uw_thread_ops.to_pid_to_str         = uw_thread_pid_to_str;
1030   uw_thread_ops.to_extra_thread_info  = uw_extra_thread_info;
1031   uw_thread_ops.to_stratum            = thread_stratum;
1032   uw_thread_ops.to_magic              = OPS_MAGIC;
1033 }
1034
1035 /* Module startup initialization function, automagically called by
1036    init.c. */
1037
1038 void
1039 _initialize_uw_thread (void)
1040 {
1041   init_uw_thread_ops ();
1042   add_target (&uw_thread_ops);
1043
1044   procfs_suppress_run = 1;
1045
1046   /* Notice when libthread.so gets loaded. */
1047   target_new_objfile_chain = target_new_objfile_hook;
1048   target_new_objfile_hook = uw_thread_new_objfile;
1049 }