Implement CLOCK_MONOTONIC using getnanouptime(), which in DragonFly is
[dragonfly.git] / contrib / gdb / gdb / infttrace.c
1 /* Low level Unix child interface to ttrace, for GDB when running under HP-UX.
2    Copyright 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996
3    Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21 #include "defs.h"
22 #include "frame.h"
23 #include "inferior.h"
24 #include "target.h"
25 #include "gdb_string.h"
26 #include "wait.h"
27 #include "command.h"
28
29 /* Some hackery to work around a use of the #define name NO_FLAGS
30  * in both gdb and HPUX (bfd.h and /usr/include/machine/vmparam.h).
31  */
32 #ifdef  NO_FLAGS
33 #define INFTTRACE_TEMP_HACK NO_FLAGS
34 #undef  NO_FLAGS
35 #endif
36
37 #ifdef USG
38 #include <sys/types.h>
39 #endif
40
41 #include <sys/param.h>
42 #include <sys/dir.h>
43 #include <signal.h>
44 #include <sys/ioctl.h>
45
46 #include <sys/ttrace.h>
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50 #include <sys/mman.h>
51
52 #ifndef NO_PTRACE_H
53 #ifdef PTRACE_IN_WRONG_PLACE
54 #include <ptrace.h>
55 #else
56 #include <sys/ptrace.h>
57 #endif
58 #endif /* NO_PTRACE_H */
59
60 /* Second half of the hackery above.  Non-ANSI C, so
61  * we can't use "#error", alas.
62  */
63 #ifdef NO_FLAGS
64 #if (NO_FLAGS != INFTTRACE_TEMP_HACK )
65   /* #error "Hackery to remove warning didn't work right" */
66 #else
67   /* Ok, new def'n of NO_FLAGS is same as old one; no action needed. */
68 #endif
69 #else
70   /* #error "Didn't get expected re-definition of NO_FLAGS" */
71 #define NO_FLAGS INFTTRACE_TEMP_HACK
72 #endif
73
74 #if !defined (PT_SETTRC)
75 #define PT_SETTRC       0       /* Make process traceable by parent */
76 #endif
77 #if !defined (PT_READ_I)
78 #define PT_READ_I       1       /* Read word from text space */
79 #endif
80 #if !defined (PT_READ_D)
81 #define PT_READ_D       2       /* Read word from data space */
82 #endif
83 #if !defined (PT_READ_U)
84 #define PT_READ_U       3       /* Read word from kernel user struct */
85 #endif
86 #if !defined (PT_WRITE_I)
87 #define PT_WRITE_I      4       /* Write word to text space */
88 #endif
89 #if !defined (PT_WRITE_D)
90 #define PT_WRITE_D      5       /* Write word to data space */
91 #endif
92 #if !defined (PT_WRITE_U)
93 #define PT_WRITE_U      6       /* Write word to kernel user struct */
94 #endif
95 #if !defined (PT_CONTINUE)
96 #define PT_CONTINUE     7       /* Continue after signal */
97 #endif
98 #if !defined (PT_STEP)
99 #define PT_STEP         9       /* Set flag for single stepping */
100 #endif
101 #if !defined (PT_KILL)
102 #define PT_KILL         8       /* Send child a SIGKILL signal */
103 #endif
104
105 #ifndef PT_ATTACH
106 #define PT_ATTACH PTRACE_ATTACH
107 #endif
108 #ifndef PT_DETACH
109 #define PT_DETACH PTRACE_DETACH
110 #endif
111
112 #include "gdbcore.h"
113 #ifndef NO_SYS_FILE
114 #include <sys/file.h>
115 #endif
116
117 /* This semaphore is used to coordinate the child and parent processes
118    after a fork(), and before an exec() by the child.  See parent_attach_all
119    for details.
120    */
121 typedef struct {
122     int  parent_channel[2];  /* Parent "talks" to [1], child "listens" to [0] */
123     int  child_channel[2];   /* Child "talks" to [1], parent "listens" to [0] */
124 } startup_semaphore_t;
125
126 #define SEM_TALK (1)
127 #define SEM_LISTEN (0)
128
129 static startup_semaphore_t  startup_semaphore;
130
131 /* See can_touch_threads_of_process for details. */
132 static int  vforking_child_pid = 0;
133 static int  vfork_in_flight = 0;
134
135 /* To support PREPARE_TO_PROCEED (hppa_prepare_to_proceed).
136  */
137 static pid_t old_gdb_pid  = 0;
138 static pid_t reported_pid = 0;
139 static int reported_bpt = 0;
140
141 /* 1 if ok as results of a ttrace or ttrace_wait call, 0 otherwise.
142  */
143 #define TT_OK( _status, _errno ) \
144     (((_status) == 1) && ((_errno) == 0))
145
146 #define TTRACE_ARG_TYPE uint64_t
147
148 /* When supplied as the "addr" operand, ttrace interprets this
149    to mean, "from the current address".
150    */
151 #define TT_USE_CURRENT_PC ((TTRACE_ARG_TYPE) TT_NOPC)
152
153 /* When supplied as the "addr", "data" or "addr2" operand for most
154    requests, ttrace interprets this to mean, "pay no heed to this
155    argument".
156    */
157 #define TT_NIL ((TTRACE_ARG_TYPE) TT_NULLARG)
158
159 /* This is capable of holding the value of a 32-bit register.  The
160    value is always left-aligned in the buffer; i.e., [0] contains
161    the most-significant byte of the register's value, and [sizeof(reg)]
162    contains the least-significant value.
163
164    ??rehrauer: Yes, this assumes that an int is 32-bits on HP-UX, and
165    that registers are 32-bits on HP-UX.  The latter assumption changes
166    with PA2.0.
167    */
168 typedef int  register_value_t;
169
170 /********************************************************************
171
172                  How this works:
173
174    1.  Thread numbers
175
176    The rest of GDB sees threads as being things with different
177    "pid" (process id) values.  See "thread.c" for details.  The
178    separate threads will be seen and reacted to if infttrace passes
179    back different pid values (for _events_).  See wait_for_inferior
180    in inftarg.c.
181
182    So infttrace is going to use thread ids externally, pretending
183    they are process ids, and keep track internally so that it can
184    use the real process id (and thread id) when calling ttrace.
185
186    The data structure that supports this is a linked list of the
187    current threads.  Since at some date infttrace will have to
188    deal with multiple processes, each list element records its
189    corresponding pid, rather than having a single global.
190
191    Note that the list is only approximately current; that's ok, as
192    it's up to date when we need it (we hope!).  Also, it can contain
193    dead threads, as there's no harm if it does.
194
195    The approach taken here is to bury the translation from external
196    to internal inside "call_ttrace" and a few other places.
197
198    There are some wrinkles:
199
200    o  When GDB forks itself to create the debug target process,
201       there's only a pid of 0 around in the child, so the
202       TT_PROC_SETTRC operation uses a more direct call to ttrace;
203       Similiarly, the initial setting of the event mask happens
204       early as  well, and so is also special-cased, and an attach
205       uses a real pid;
206
207    o  We define an unthreaded application as having a "pseudo"
208       thread;
209
210    o  To keep from confusing the rest of GDB, we don't switch
211       the PID for the pseudo thread to a TID.  A table will help:
212
213       Rest of GDB sees these PIDs:     pid   tid1  tid2  tid3 ...
214                                         
215       Our thread list stores:          pid   pid   pid   pid  ...
216                                        tid0  tid1  tid2  tid3
217       
218       Ttrace sees these TIDS:          tid0  tid1  tid2  tid3 ...
219
220       Both pid and tid0 will map to tid0, as there are infttrace.c-internal
221       calls to ttrace using tid0.
222
223    2. Step and Continue
224
225    Since we're implementing the "stop the world" model, sub-model
226    "other threads run during step", we have some stuff to do:
227
228    o  User steps require continuing all threads other than the
229       one the user is stepping;
230
231    o  Internal debugger steps (such as over a breakpoint or watchpoint,
232       but not out of a library load thunk) require stepping only
233       the selected thread; this means that we have to report the
234       step finish on that thread, which can lead to complications;
235
236    o  When a thread is created, it is created running, rather
237       than stopped--so we have to stop it.
238
239    The OS doesn't guarantee the stopped thread list will be stable,
240    no does it guarantee where on the stopped thread list a thread
241    that is single-stepped will wind up: it's possible that it will
242    be off the list for a while, it's possible the step will complete
243    and it will be re-posted to the end...
244
245    This means we have to scan the stopped thread list, build up
246    a work-list, and then run down the work list; we can't do the
247    step/continue during the scan.
248
249    3. Buffering events
250
251    Then there's the issue of waiting for an event.  We do this by
252    noticing how many events are reported at the end of each wait.
253    From then on, we "fake" all resumes and steps, returning instantly,
254    and don't do another wait.  Once all pending events are reported,
255    we can really resume again.
256
257    To keep this hidden, all the routines which know about tids and
258    pids or real events and simulated ones are static (file-local).
259
260    This code can make lots of calls to ttrace, in particular it
261    can spin down the list of thread states more than once.  If this
262    becomes a performance hit, the spin could be done once and the
263    various "tsp" blocks saved, keeping all later spins in this
264    process.
265
266    The O/S doesn't promise to keep the list straight, and so we must
267    re-scan a lot.  By observation, it looks like a single-step/wait
268    puts the stepped thread at the end of the list but doesn't change
269    it otherwise.
270
271 ****************************************************************
272 */
273
274 /* Uncomment these to turn on various debugging output */
275 /* #define THREAD_DEBUG */
276 /* #define WAIT_BUFFER_DEBUG */
277 /* #define PARANOIA */
278
279
280 #define INFTTRACE_ALL_THREADS (-1)
281 #define INFTTRACE_STEP        (1)
282 #define INFTTRACE_CONTINUE    (0)
283
284 /* FIX: this is used in inftarg.c/child_wait, in a hack.
285  */
286 extern int not_same_real_pid;
287
288 /* This is used to count buffered events.
289  */
290 static unsigned int more_events_left = 0;
291
292 /* Process state.
293  */
294 typedef enum process_state_enum {
295     STOPPED,
296     FAKE_STEPPING,
297     FAKE_CONTINUE,   /* For later use */
298     RUNNING,
299     FORKING,
300     VFORKING
301 } process_state_t;
302
303 static process_state_t process_state = STOPPED;
304
305 /* User-specified stepping modality.
306  */
307 typedef enum stepping_mode_enum {
308     DO_DEFAULT,  /* ...which is a continue! */
309     DO_STEP,
310     DO_CONTINUE
311 } stepping_mode_t;
312  
313 /* Action to take on an attach, depends on
314  * what kind (user command, fork, vfork).
315  *
316  * At the moment, this is either:
317  *
318  * o  continue with a SIGTRAP signal, or
319  *
320  * o  leave stopped.
321  */
322 typedef enum attach_continue_enum {
323    DO_ATTACH_CONTINUE,
324    DONT_ATTACH_CONTINUE
325 } attach_continue_t;
326
327 /* This flag is true if we are doing a step-over-bpt
328  * with buffered events.  We will have to be sure to
329  * report the right thread, as otherwise the spaghetti
330  * code in "infrun.c/wait_for_inferior" will get
331  * confused.
332  */
333 static int doing_fake_step  = 0;
334 static lwpid_t  fake_step_tid    = 0;
335
336 \f
337 /****************************************************
338  * Thread information structure routines and types. *
339  ****************************************************
340  */
341 typedef 
342 struct thread_info_struct
343 {
344     int                 am_pseudo;      /* This is a pseudo-thread for the process. */
345     int                 pid;            /* Process ID */
346     lwpid_t             tid;            /* Thread  ID */
347     int                 handled;        /* 1 if a buffered event was handled. */
348     int                 seen;           /* 1 if this thread was seen on a traverse. */
349     int                 terminated;     /* 1 if thread has terminated. */
350     int                 have_signal;    /* 1 if signal to be sent */
351     enum target_signal  signal_value;   /* Signal to send */
352     int                 have_start;     /* 1 if alternate starting address */
353     stepping_mode_t     stepping_mode;  /* Whether to step or continue */
354     CORE_ADDR           start;          /* Where to start */
355     int                 have_state;     /* 1 if the event state has been set */
356     ttstate_t           last_stop_state;/* The most recently-waited event for this thread. */
357     struct thread_info_struct
358                        *next;           /* All threads are linked via this field. */
359     struct thread_info_struct
360                        *next_pseudo;    /* All pseudo-threads are linked via this field. */
361 } thread_info;
362
363 typedef
364 struct thread_info_header_struct
365 {
366     int          count;
367     thread_info *head;
368     thread_info *head_pseudo;
369     
370 } thread_info_header;
371
372 static thread_info_header thread_head     = { 0, NULL, NULL };
373 static thread_info_header deleted_threads = { 0, NULL, NULL };
374
375 static saved_real_pid = 0;
376
377 \f
378 /*************************************************
379  *          Debugging support functions          *
380  *************************************************
381  */
382 CORE_ADDR
383 get_raw_pc( ttid )
384     lwpid_t ttid;
385 {
386     unsigned long pc_val;
387     int      offset;
388     int      res;
389  
390     offset = register_addr( PC_REGNUM, U_REGS_OFFSET );
391     res    = read_from_register_save_state(
392                        ttid,
393                        (TTRACE_ARG_TYPE) offset,
394                        (char *) &pc_val,
395                        sizeof( pc_val ));
396     if( res <= 0 ) {
397         return (CORE_ADDR) pc_val;
398     }
399     else {
400         return (CORE_ADDR) 0;
401     }
402 }                   
403
404 static char *
405 get_printable_name_of_stepping_mode( mode )
406     stepping_mode_t mode;
407 {
408   switch( mode ) {
409     case DO_DEFAULT:  return "DO_DEFAULT";
410     case DO_STEP:     return "DO_STEP";
411     case DO_CONTINUE: return "DO_CONTINUE";
412     default:          return "?unknown mode?";
413   }
414 }
415
416 /* This function returns a pointer to a string describing the
417  * ttrace event being reported.
418  */
419 char *
420 get_printable_name_of_ttrace_event (event)
421   ttevents_t event;
422 {
423   /* This enumeration is "gappy", so don't use a table. */
424   switch (event) {
425
426     case TTEVT_NONE:
427        return "TTEVT_NONE";
428     case TTEVT_SIGNAL:
429        return "TTEVT_SIGNAL";
430     case TTEVT_FORK:
431        return "TTEVT_FORK";
432     case TTEVT_EXEC:
433        return "TTEVT_EXEC";
434     case TTEVT_EXIT:
435        return "TTEVT_EXIT";
436     case TTEVT_VFORK:
437        return "TTEVT_VFORK";
438     case TTEVT_SYSCALL_RETURN:
439        return "TTEVT_SYSCALL_RETURN";
440     case TTEVT_LWP_CREATE:
441        return "TTEVT_LWP_CREATE";
442     case TTEVT_LWP_TERMINATE:
443        return "TTEVT_LWP_TERMINATE";
444     case TTEVT_LWP_EXIT:
445        return "TTEVT_LWP_EXIT";
446     case TTEVT_LWP_ABORT_SYSCALL:
447        return "TTEVT_LWP_ABORT_SYSCALL";
448     case TTEVT_SYSCALL_ENTRY:
449        return "TTEVT_SYSCALL_ENTRY";
450     case TTEVT_SYSCALL_RESTART: 
451        return "TTEVT_SYSCALL_RESTART";
452     default :
453       return "?new event?";
454   }
455 }
456
457 \f
458 /* This function translates the ttrace request enumeration into
459  * a character string that is its printable (aka "human readable")
460  * name.
461  */
462 char *
463 get_printable_name_of_ttrace_request (request)
464   ttreq_t  request;
465 {
466   if (!IS_TTRACE_REQ (request))
467     return "?bad req?";
468
469   /* This enumeration is "gappy", so don't use a table. */
470   switch (request) {
471     case TT_PROC_SETTRC :
472       return "TT_PROC_SETTRC";
473     case TT_PROC_ATTACH :
474       return "TT_PROC_ATTACH";
475     case TT_PROC_DETACH :
476       return "TT_PROC_DETACH";
477     case TT_PROC_RDTEXT :
478       return "TT_PROC_RDTEXT";
479     case TT_PROC_WRTEXT :
480       return "TT_PROC_WRTEXT";
481     case TT_PROC_RDDATA :
482       return "TT_PROC_RDDATA";
483     case TT_PROC_WRDATA :
484       return "TT_PROC_WRDATA";
485     case TT_PROC_STOP :
486       return "TT_PROC_STOP";
487     case TT_PROC_CONTINUE :
488       return "TT_PROC_CONTINUE";
489     case TT_PROC_GET_PATHNAME :
490       return "TT_PROC_GET_PATHNAME";
491     case TT_PROC_GET_EVENT_MASK :
492       return "TT_PROC_GET_EVENT_MASK";
493     case TT_PROC_SET_EVENT_MASK :
494       return "TT_PROC_SET_EVENT_MASK";
495     case TT_PROC_GET_FIRST_LWP_STATE :
496       return "TT_PROC_GET_FIRST_LWP_STATE";
497     case TT_PROC_GET_NEXT_LWP_STATE :
498       return "TT_PROC_GET_NEXT_LWP_STATE";
499     case TT_PROC_EXIT :
500       return "TT_PROC_EXIT";
501     case TT_PROC_GET_MPROTECT :
502       return "TT_PROC_GET_MPROTECT";
503     case TT_PROC_SET_MPROTECT :
504       return "TT_PROC_SET_MPROTECT";
505     case TT_PROC_SET_SCBM :
506       return "TT_PROC_SET_SCBM";
507     case TT_LWP_STOP :
508       return "TT_LWP_STOP";
509     case TT_LWP_CONTINUE :
510       return "TT_LWP_CONTINUE";
511     case TT_LWP_SINGLE :
512       return "TT_LWP_SINGLE";
513     case TT_LWP_RUREGS :
514       return "TT_LWP_RUREGS";
515     case TT_LWP_WUREGS :
516       return "TT_LWP_WUREGS";
517     case TT_LWP_GET_EVENT_MASK :
518       return "TT_LWP_GET_EVENT_MASK";
519     case TT_LWP_SET_EVENT_MASK :
520       return "TT_LWP_SET_EVENT_MASK";
521     case TT_LWP_GET_STATE       :
522       return "TT_LWP_GET_STATE";
523     default :
524       return "?new req?";
525   }
526 }
527
528 \f
529 /* This function translates the process state enumeration into
530  * a character string that is its printable (aka "human readable")
531  * name.
532  */
533 static char *
534 get_printable_name_of_process_state (process_state)
535   process_state_t  process_state;
536 {
537   switch (process_state) {
538     case STOPPED:
539       return "STOPPED";
540     case FAKE_STEPPING:
541       return "FAKE_STEPPING";
542     case RUNNING:
543       return "RUNNING";
544     case FORKING:
545       return "FORKING";
546     case VFORKING:
547       return "VFORKING";
548     default:
549       return "?some unknown state?";
550   }
551 }
552
553 /* Set a ttrace thread state to a safe, initial state.
554  */
555 static void
556 clear_ttstate_t (tts)
557     ttstate_t *  tts;
558 {
559     tts->tts_pid = 0;
560     tts->tts_lwpid = 0;
561     tts->tts_user_tid = 0;
562     tts->tts_event = TTEVT_NONE;
563 }
564
565 /* Copy ttrace thread state TTS_FROM into TTS_TO.
566  */
567 static void
568 copy_ttstate_t (tts_to, tts_from)
569     ttstate_t *  tts_to;
570     ttstate_t *  tts_from;
571 {
572     memcpy ((char *) tts_to, (char *) tts_from, sizeof (*tts_to));
573 }
574
575 /* Are there any live threads we know about?
576  */
577 static int 
578 any_thread_records()
579 {
580     return( thread_head.count > 0 );
581 }
582
583 /* Create, fill in and link in a thread descriptor.
584  */
585 static thread_info *
586 create_thread_info (pid, tid)
587     int     pid;
588     lwpid_t tid;
589 {
590     thread_info *  new_p;
591     thread_info *  p;
592     int  thread_count_of_pid;
593
594     new_p = malloc( sizeof( thread_info ));
595     new_p->pid = pid;
596     new_p->tid = tid;
597     new_p->have_signal = 0;
598     new_p->have_start  = 0;
599     new_p->have_state  = 0;
600     clear_ttstate_t( &new_p->last_stop_state );
601     new_p->am_pseudo   = 0;
602     new_p->handled     = 0;
603     new_p->seen        = 0;
604     new_p->terminated  = 0;
605     new_p->next        = NULL;
606     new_p->next_pseudo = NULL;
607     new_p->stepping_mode = DO_DEFAULT;
608
609     if( 0 == thread_head.count ) {
610 #ifdef THREAD_DEBUG
611         if( debug_on )
612             printf( "First thread, pid %d tid %d!\n", pid, tid );
613 #endif
614         saved_real_pid = inferior_pid;
615     }
616     else {
617 #ifdef THREAD_DEBUG
618         if( debug_on )
619             printf( "Subsequent thread, pid %d tid %d\n", pid, tid );
620 #endif
621     }
622
623     /* Another day, another thread...
624      */
625     thread_head.count++;
626
627     /* The new thread always goes at the head of the list.
628      */
629     new_p->next       = thread_head.head;
630     thread_head.head  = new_p;
631
632     /* Is this the "pseudo" thread of a process?  It is if there's
633      * no other thread for this process on the list.  (Note that this
634      * accomodates multiple processes, such as we see even for simple
635      * cases like forking "non-threaded" programs.)
636      */
637     p = thread_head.head;
638     thread_count_of_pid = 0;
639     while (p)
640       {
641         if (p->pid == new_p->pid)
642           thread_count_of_pid++;
643         p = p->next;
644       }
645
646     /* Did we see any other threads for this pid?  (Recall that we just
647      * added this thread to the list...)
648      */
649     if (thread_count_of_pid == 1)
650       {
651         new_p->am_pseudo        = 1;
652         new_p->next_pseudo      = thread_head.head_pseudo;
653         thread_head.head_pseudo = new_p;
654       }
655     
656     return new_p;
657 }
658
659 /* Get rid of our thread info.
660  */
661 static void
662 clear_thread_info ()
663 {
664     thread_info *p;
665     thread_info *q;
666
667 #ifdef THREAD_DEBUG
668     if( debug_on )
669         printf( "Clearing all thread info\n" );
670 #endif
671
672     p = thread_head.head;
673     while( p ) {
674         q = p;
675         p = p->next;
676         free( q );
677     }
678
679     thread_head.head        = NULL;
680     thread_head.head_pseudo = NULL;
681     thread_head.count       = 0;
682
683     p = deleted_threads.head;
684     while( p ) {
685         q = p;
686         p = p->next;
687         free( q );
688     }
689
690     deleted_threads.head        = NULL;
691     deleted_threads.head_pseudo = NULL;
692     deleted_threads.count       = 0;
693
694     /* No threads, so can't have pending events.
695      */
696     more_events_left = 0;   
697 }
698
699 /* Given a tid, find the thread block for it.
700  */
701 static thread_info *
702 find_thread_info (tid)
703     lwpid_t tid;
704 {
705     thread_info *p;
706
707     for( p = thread_head.head; p; p = p->next )  {
708        if( p->tid == tid ) {
709            return p;
710        }
711     }
712
713     for( p = deleted_threads.head; p; p = p->next )  {
714        if( p->tid == tid ) {
715            return p;
716        }
717     }
718     
719     return NULL;  
720 }
721
722 /* For any but the pseudo thread, this maps to the
723  * thread ID.  For the pseudo thread, if you pass either
724  * the thread id or the PID, you get the pseudo thread ID.
725  *
726  * We have to be prepared for core gdb to ask about
727  * deleted threads.  We do the map, but we don't like it.
728  */
729 static lwpid_t
730 map_from_gdb_tid( gdb_tid )
731     lwpid_t gdb_tid;
732 {
733     thread_info *p;
734
735     /* First assume gdb_tid really is a tid, and try to find a
736      * matching entry on the threads list.
737      */
738     for( p = thread_head.head; p; p = p->next )  {
739         if( p->tid == gdb_tid )
740             return gdb_tid;
741     }
742
743     /* It doesn't appear to be a tid; perhaps it's really a pid?
744      * Try to find a "pseudo" thread entry on the threads list.
745      */
746     for (p = thread_head.head_pseudo; p != NULL; p = p->next_pseudo)
747       {
748         if (p->pid == gdb_tid)
749           return p->tid;
750       }
751
752     /* Perhaps it's the tid of a deleted thread we may still
753      * have some knowledge of?
754      */
755     for( p = deleted_threads.head; p; p = p-> next ) {
756         if( p->tid == gdb_tid )
757             return gdb_tid;
758     }
759
760     /* Or perhaps it's the pid of a deleted process we may still
761      * have knowledge of?
762      */
763     for (p = deleted_threads.head_pseudo; p != NULL; p = p->next_pseudo)
764       {
765         if (p->pid == gdb_tid)
766           return p->tid;
767       }
768
769     return 0;  /* Error? */
770 }
771
772 /* Map the other way: from a real tid to the
773  * "pid" known by core gdb.  This tid may be
774  * for a thread that just got deleted, so we
775  * also need to consider deleted threads.
776  */
777 static lwpid_t
778 map_to_gdb_tid( real_tid )
779     lwpid_t real_tid;
780 {
781     thread_info *p;
782
783     for( p = thread_head.head; p; p = p->next )  {
784         if( p->tid == real_tid ) {
785             if( p->am_pseudo )
786                 return p->pid;
787             else 
788                 return real_tid;
789        }
790     }
791
792     for( p = deleted_threads.head; p; p = p-> next ) {
793         if( p->tid == real_tid )
794             if( p->am_pseudo )
795                 return p->pid;  /* Error? */
796             else 
797                 return real_tid;
798     }
799
800     return 0;  /* Error?  Never heard of this thread! */
801 }
802
803 /* Do any threads have saved signals?
804  */
805 static int 
806 saved_signals_exist ()
807 {
808     thread_info *p;
809    
810     for( p = thread_head.head; p; p = p->next )  {
811        if( p->have_signal ) {
812            return 1;
813        }
814     }
815
816     return 0;
817 }
818
819 /* Is this the tid for the zero-th thread?
820  */
821 static int 
822 is_pseudo_thread (tid)
823     lwpid_t tid;
824 {
825     thread_info *p = find_thread_info( tid );
826     if( NULL == p || p->terminated )
827         return 0;
828     else
829         return p->am_pseudo;
830 }
831
832 /* Is this thread terminated?
833  */
834 static int 
835 is_terminated (tid)
836     lwpid_t tid;
837 {
838     thread_info *p = find_thread_info( tid );
839
840     if( NULL != p )
841         return p->terminated;
842
843     return 0;
844 }
845
846 /* Is this pid a real PID or a TID?
847  */
848 static int 
849 is_process_id (pid)
850   int  pid;
851 {
852   lwpid_t  tid;
853   thread_info *  tinfo;
854   pid_t  this_pid;
855   int  this_pid_count;
856
857   /* What does PID really represent?
858    */
859   tid = map_from_gdb_tid (pid);
860   if (tid <= 0)
861     return 0; /* Actually, is probably an error... */
862
863   tinfo = find_thread_info (tid);
864
865   /* Does it appear to be a true thread?
866    */
867   if (! tinfo->am_pseudo)
868     return 0;
869
870   /* Else, it looks like it may be a process.  See if there's any other
871    * threads with the same process ID, though.  If there are, then TID
872    * just happens to be the first thread of several for this process.
873    */
874   this_pid = tinfo->pid;
875   this_pid_count = 0;
876   for (tinfo = thread_head.head; tinfo; tinfo = tinfo->next)
877     {
878       if (tinfo->pid == this_pid)
879         this_pid_count++;
880     }
881
882   return (this_pid_count == 1);
883 }
884
885
886 /* Add a thread to our info.  Prevent duplicate entries.
887  */
888 static thread_info *
889 add_tthread (pid, tid)
890     int     pid;
891     lwpid_t tid;
892 {
893     thread_info *p;
894
895     p = find_thread_info( tid );
896     if( NULL == p )
897         p = create_thread_info( pid, tid );
898
899     return p;
900 }
901
902 /* Notice that a thread was deleted.
903  */
904 static void
905 del_tthread (tid)
906     lwpid_t tid;
907 {
908     thread_info *p;
909     thread_info *chase;
910
911     if( thread_head.count <= 0 ) {
912         error( "Internal error in thread database." );
913         return;
914     }
915
916     chase = NULL;
917     for( p = thread_head.head; p; p = p->next )  {
918        if( p->tid == tid ) {
919
920 #ifdef THREAD_DEBUG
921            if( debug_on )
922                printf( "Delete here: %d \n", tid );
923 #endif
924
925            if( p->am_pseudo ) {
926                /*
927                 * Deleting a main thread is ok if we're doing
928                 * a parent-follow on a child; this is odd but
929                 * not wrong.  It apparently _doesn't_ happen
930                 * on the child-follow, as we don't just delete
931                 * the pseudo while keeping the rest of the
932                 * threads around--instead, we clear out the whole
933                 * thread list at once.
934                 */
935                thread_info *q;
936                thread_info *q_chase;
937                
938                q_chase = NULL;
939                for( q = thread_head.head_pseudo; q; q = q -> next ) {
940                     if( q == p ) {
941                         /* Remove from pseudo list.
942                          */
943                         if( q_chase == NULL )
944                             thread_head.head_pseudo = p->next_pseudo;
945                         else
946                             q_chase-> next = p->next_pseudo;
947                     }
948                     else
949                         q_chase = q;
950                }
951            }
952            
953            /* Remove from live list.
954             */
955            thread_head.count--;
956
957            if( NULL == chase )
958                thread_head.head = p->next;
959            else
960                chase->next      = p->next;
961
962            /* Add to deleted thread list.
963             */
964            p->next = deleted_threads.head;
965            deleted_threads.head = p;
966            deleted_threads.count++;
967            if( p->am_pseudo ) {
968                p->next_pseudo              = deleted_threads.head_pseudo;
969                deleted_threads.head_pseudo = p;
970            }
971            p->terminated = 1;
972            
973            return;
974        }
975
976        else
977            chase = p;
978     }
979 }
980
981 /* Get the pid for this tid. (Has to be a real TID!).
982  */
983 static int
984 get_pid_for (tid)
985     lwpid_t tid;
986 {
987     thread_info *p;
988
989     for( p = thread_head.head; p; p = p->next ) {
990         if( p->tid == tid ) {
991             return p->pid;
992         }
993     }
994
995     for( p = deleted_threads.head; p; p = p->next ) {
996         if( p->tid == tid ) {
997             return p->pid;
998         }
999     }
1000     
1001     return 0;
1002 }
1003
1004 /* Note that this thread's current event has been handled.
1005  */
1006 static void
1007 set_handled( pid, tid )
1008     int     pid;
1009     lwpid_t tid;
1010 {
1011     thread_info *p;
1012     
1013     p = find_thread_info( tid );
1014     if( NULL == p )
1015         p = add_tthread( pid, tid );
1016
1017     p->handled = 1;
1018 }
1019
1020 /* Was this thread's current event handled?
1021  */
1022 static int 
1023 was_handled( tid )
1024     lwpid_t tid;
1025 {
1026     thread_info *p;
1027     
1028     p = find_thread_info( tid );
1029     if( NULL != p )
1030         return p->handled;
1031
1032     return 0;  /* New threads have not been handled */
1033 }
1034
1035 /* Set this thread to unhandled.
1036  */
1037 static void
1038 clear_handled( tid )
1039   lwpid_t  tid;
1040 {
1041   thread_info *  p;
1042     
1043 #ifdef WAIT_BUFFER_DEBUG
1044     if( debug_on )
1045         printf( "clear_handled %d\n", (int) tid );
1046 #endif
1047
1048   p = find_thread_info (tid);
1049   if (p == NULL)
1050     error ("Internal error: No thread state to clear?");
1051
1052   p->handled = 0;
1053 }
1054
1055 /* Set all threads to unhandled.
1056  */
1057 static void
1058 clear_all_handled ()
1059 {
1060     thread_info *p;
1061
1062 #ifdef WAIT_BUFFER_DEBUG
1063     if( debug_on )
1064         printf( "clear_all_handled\n" );
1065 #endif
1066
1067     for( p = thread_head.head; p; p = p->next ) {
1068         p->handled = 0;
1069     }
1070
1071     for( p = deleted_threads.head; p; p = p->next ) {
1072         p->handled = 0;
1073     }
1074 }
1075
1076 /* Set this thread to default stepping mode.
1077  */
1078 static void
1079 clear_stepping_mode( tid )
1080   lwpid_t  tid;
1081 {
1082   thread_info *  p;
1083     
1084 #ifdef WAIT_BUFFER_DEBUG
1085   if( debug_on )
1086        printf( "clear_stepping_mode %d\n", (int) tid );
1087 #endif
1088
1089   p = find_thread_info (tid);
1090   if (p == NULL)
1091     error ("Internal error: No thread state to clear?");
1092
1093   p->stepping_mode = DO_DEFAULT;
1094 }
1095
1096 /* Set all threads to do default continue on resume.
1097  */
1098 static void
1099 clear_all_stepping_mode ()
1100 {
1101     thread_info *p;
1102
1103 #ifdef WAIT_BUFFER_DEBUG
1104     if( debug_on )
1105         printf( "clear_all_stepping_mode\n" );
1106 #endif
1107
1108     for( p = thread_head.head; p; p = p->next ) {
1109         p->stepping_mode = DO_DEFAULT;
1110     }
1111
1112     for( p = deleted_threads.head; p; p = p->next ) {
1113         p->stepping_mode = DO_DEFAULT;
1114     }
1115 }
1116
1117 /* Set all threads to unseen on this pass.
1118  */    
1119 static void
1120 set_all_unseen ()
1121 {
1122     thread_info *p;
1123
1124     for( p = thread_head.head; p; p = p->next ) {
1125         p->seen = 0;
1126     }
1127 }
1128
1129 #if (defined( THREAD_DEBUG ) || defined( PARANOIA ))
1130 /* debugging routine.
1131  */
1132 static void
1133 print_tthread (p)
1134     thread_info *  p;
1135 {
1136     printf( " Thread pid %d, tid %d", p->pid, p->tid );
1137     if( p->have_state ) 
1138         printf( ", event is %s",
1139             get_printable_name_of_ttrace_event( p->last_stop_state.tts_event ));
1140             
1141     if( p->am_pseudo )
1142         printf( ", pseudo thread" );
1143         
1144     if( p->have_signal )
1145         printf( ", have signal 0x%x", p->signal_value );
1146         
1147     if( p->have_start )
1148         printf( ", have start at 0x%x", p->start );
1149         
1150     printf( ", step is %s", get_printable_name_of_stepping_mode( p->stepping_mode ));
1151         
1152     if( p->handled )
1153         printf( ", handled" );
1154     else
1155         printf( ", not handled" );
1156         
1157     if( p->seen )
1158         printf( ", seen" );
1159     else
1160         printf( ", not seen" );
1161
1162     printf( "\n" );
1163 }
1164
1165 static void
1166 print_tthreads ()
1167 {
1168     thread_info *p;
1169
1170     if( thread_head.count == 0 )
1171         printf( "Thread list is empty\n" );
1172     else {
1173         printf( "Thread list has " );
1174         if( thread_head.count == 1 )
1175             printf( "1 entry:\n" );
1176         else
1177             printf( "%d entries:\n", thread_head.count );
1178         for( p = thread_head.head; p; p = p->next ) {
1179             print_tthread (p);
1180         }
1181     }
1182
1183     if( deleted_threads.count == 0 )
1184         printf( "Deleted thread list is empty\n" );
1185     else {
1186         printf( "Deleted thread list has " );
1187         if( deleted_threads.count == 1 )
1188             printf( "1 entry:\n" );
1189         else
1190             printf( "%d entries:\n", deleted_threads.count );
1191
1192         for( p = deleted_threads.head; p; p = p->next ) {
1193             print_tthread (p);
1194         }
1195     }
1196 }
1197 #endif
1198
1199 /* Update the thread list based on the "seen" bits.
1200  */
1201 static void
1202 update_thread_list ()
1203 {
1204     thread_info *p;
1205     thread_info *chase;
1206
1207     chase = NULL;
1208     for( p = thread_head.head; p; p = p->next ) {
1209       /* Is this an "unseen" thread which really happens to be a process?
1210          If so, is it inferior_pid and is a vfork in flight?  If yes to
1211          all, then DON'T REMOVE IT!  We're in the midst of moving a vfork
1212          operation, which is a multiple step thing, to the point where we
1213          can touch the parent again.  We've most likely stopped to examine
1214          the child at a late stage in the vfork, and if we're not following
1215          the child, we'd best not treat the parent as a dead "thread"...
1216          */
1217         if( (!p->seen) && p->am_pseudo && vfork_in_flight
1218          && (p->pid != vforking_child_pid))
1219             p->seen = 1;
1220
1221         if( !p->seen ) {
1222             /* Remove this one
1223              */
1224
1225 #ifdef THREAD_DEBUG
1226            if( debug_on )
1227                printf( "Delete unseen thread: %d \n", p->tid );
1228 #endif
1229            del_tthread( p->tid );
1230        }
1231     }
1232 }
1233
1234     
1235 \f
1236 /************************************************
1237  *            O/S call wrappers                 *
1238  ************************************************
1239  */
1240
1241 /* This function simply calls ttrace with the given arguments.  
1242  * It exists so that all calls to ttrace are isolated.  All
1243  * parameters should be as specified by "man 2 ttrace".
1244  *
1245  * No other "raw" calls to ttrace should exist in this module.
1246  */
1247 static int
1248 call_real_ttrace( request, pid, tid, addr, data, addr2 )
1249   ttreq_t          request;
1250   pid_t            pid;
1251   lwpid_t          tid;
1252   TTRACE_ARG_TYPE  addr, data, addr2;
1253 {
1254   int  tt_status;
1255
1256   errno = 0;
1257   tt_status = ttrace( request, pid, tid, addr, data, addr2 );
1258
1259 #ifdef THREAD_DEBUG
1260   if (errno) {
1261     /* Don't bother for a known benign error: if you ask for the
1262      * first thread state, but there is only one thread and it's
1263      * not stopped, ttrace complains.
1264      *
1265      * We have this inside the #ifdef because our caller will do
1266      * this check for real.
1267      */
1268     if( request != TT_PROC_GET_FIRST_LWP_STATE
1269     ||  errno   != EPROTO ) {
1270         if( debug_on )
1271             printf( "TT fail for %s, with pid %d, tid %d, status %d \n",
1272                     get_printable_name_of_ttrace_request (request),
1273                     pid, tid, tt_status );
1274     }
1275   }
1276 #endif
1277
1278 #if 0
1279   /* ??rehrauer: It would probably be most robust to catch and report
1280    * failed requests here.  However, some clients of this interface
1281    * seem to expect to catch & deal with them, so we'd best not.
1282    */
1283   if (errno) {
1284     strcpy (reason_for_failure, "ttrace (");
1285     strcat (reason_for_failure, get_printable_name_of_ttrace_request (request));
1286     strcat (reason_for_failure, ")");
1287     printf( "ttrace error, errno = %d\n", errno );
1288     perror_with_name (reason_for_failure);
1289   }
1290 #endif
1291
1292   return tt_status;
1293 }
1294
1295 \f
1296 /* This function simply calls ttrace_wait with the given arguments.  
1297  * It exists so that all calls to ttrace_wait are isolated.
1298  *
1299  * No "raw" calls to ttrace_wait should exist elsewhere.
1300  */
1301 static int
1302 call_real_ttrace_wait( pid, tid, option, tsp, tsp_size )
1303   int        pid;
1304   lwpid_t    tid;
1305   ttwopt_t   option;
1306   ttstate_t *tsp;
1307   size_t     tsp_size;
1308 {
1309   int        ttw_status;
1310   thread_info *  tinfo = NULL;
1311
1312   errno = 0;
1313   ttw_status = ttrace_wait (pid, tid, option, tsp, tsp_size);
1314   
1315   if (errno) {
1316 #ifdef THREAD_DEBUG
1317       if( debug_on )
1318           printf( "TW fail with pid %d, tid %d \n", pid, tid );
1319 #endif
1320
1321       perror_with_name ("ttrace wait");
1322   }
1323
1324   return ttw_status;
1325 }
1326
1327 \f
1328 /* A process may have one or more kernel threads, of which all or
1329    none may be stopped.  This function returns the ID of the first
1330    kernel thread in a stopped state, or 0 if none are stopped.
1331
1332    This function can be used with get_process_next_stopped_thread_id
1333    to iterate over the IDs of all stopped threads of this process.
1334  */
1335 static lwpid_t
1336 get_process_first_stopped_thread_id (pid, thread_state)
1337   int  pid;
1338   ttstate_t *  thread_state;
1339 {
1340   int  tt_status;
1341
1342   tt_status = call_real_ttrace (
1343                       TT_PROC_GET_FIRST_LWP_STATE,
1344                       (pid_t) pid,
1345                       (lwpid_t) TT_NIL,
1346                       (TTRACE_ARG_TYPE) thread_state,
1347                       (TTRACE_ARG_TYPE) sizeof (*thread_state),
1348                       TT_NIL);
1349                       
1350   if (errno) {
1351     if( errno == EPROTO) {
1352         /* This is an error we can handle: there isn't any stopped
1353          * thread.  This happens when we're re-starting the application
1354          * and it has only one thread.  GET_NEXT handles the case of
1355          * no more stopped threads well; GET_FIRST doesn't.  (A ttrace
1356          * "feature".)
1357          */
1358         tt_status = 1;
1359         errno     = 0;
1360         return 0;
1361     }
1362     else
1363         perror_with_name ("ttrace");
1364   }
1365   
1366   if( tt_status < 0 )
1367     /* Failed somehow.
1368      */
1369     return 0;
1370
1371   return thread_state->tts_lwpid;
1372 }
1373
1374 \f
1375 /* This function returns the ID of the "next" kernel thread in a
1376    stopped state, or 0 if there are none.  "Next" refers to the
1377    thread following that of the last successful call to this
1378    function or to get_process_first_stopped_thread_id, using
1379    the value of thread_state returned by that call.
1380
1381    This function can be used with get_process_first_stopped_thread_id
1382    to iterate over the IDs of all stopped threads of this process.
1383  */
1384 static lwpid_t
1385 get_process_next_stopped_thread_id (pid, thread_state)
1386   int  pid;
1387   ttstate_t *  thread_state;
1388 {
1389   int  tt_status;
1390
1391   tt_status = call_real_ttrace (
1392                       TT_PROC_GET_NEXT_LWP_STATE,
1393                       (pid_t) pid,
1394                       (lwpid_t) TT_NIL,
1395                       (TTRACE_ARG_TYPE) thread_state,
1396                       (TTRACE_ARG_TYPE) sizeof (*thread_state),
1397                       TT_NIL);
1398   if (errno)
1399     perror_with_name ("ttrace");
1400
1401   if (tt_status < 0)
1402     /* Failed
1403      */
1404     return 0;
1405
1406   else if( tt_status == 0 ) {
1407     /* End of list, no next state.  Don't return the
1408      * tts_lwpid, as it's a meaningless "240".
1409      *
1410      * This is an HPUX "feature".
1411      */
1412     return 0;
1413   }
1414   
1415   return thread_state->tts_lwpid;
1416 }
1417
1418 /* ??rehrauer: Eventually this function perhaps should be calling
1419    pid_to_thread_id.  However, that function currently does nothing
1420    for HP-UX.  Even then, I'm not clear whether that function
1421    will return a "kernel" thread ID, or a "user" thread ID.  If
1422    the former, we can just call it here.  If the latter, we must
1423    map from the "user" tid to a "kernel" tid.
1424
1425    NOTE: currently not called.
1426  */
1427 static lwpid_t
1428 get_active_tid_of_pid (pid)
1429   int  pid;
1430 {
1431   ttstate_t  thread_state;
1432
1433   return get_process_first_stopped_thread_id (pid, &thread_state);
1434 }
1435
1436 /* This function returns 1 if tt_request is a ttrace request that
1437  * operates upon all threads of a (i.e., the entire) process.
1438  */
1439 int
1440 is_process_ttrace_request (tt_request)
1441   ttreq_t  tt_request;
1442 {
1443   return IS_TTRACE_PROCREQ (tt_request);
1444 }
1445
1446 \f
1447 /* This function translates a thread ttrace request into
1448  * the equivalent process request for a one-thread process.
1449  */
1450 static ttreq_t
1451 make_process_version( request )
1452   ttreq_t request;
1453 {
1454   if (!IS_TTRACE_REQ (request)) {
1455     error( "Internal error, bad ttrace request made\n" );
1456     return -1;
1457   }
1458
1459   switch (request) {
1460     case TT_LWP_STOP :
1461       return TT_PROC_STOP;
1462
1463     case TT_LWP_CONTINUE :
1464       return TT_PROC_CONTINUE;
1465
1466     case TT_LWP_GET_EVENT_MASK :
1467       return TT_PROC_GET_EVENT_MASK;
1468
1469     case TT_LWP_SET_EVENT_MASK :
1470       return TT_PROC_SET_EVENT_MASK;
1471
1472     case TT_LWP_SINGLE :
1473     case TT_LWP_RUREGS :
1474     case TT_LWP_WUREGS :
1475     case TT_LWP_GET_STATE       :
1476       return -1;       /* No equivalent */
1477
1478     default :
1479       return request;
1480   }
1481 }
1482
1483 \f
1484 /* This function translates the "pid" used by the rest of
1485  * gdb to a real pid and a tid.  It then calls "call_real_ttrace"
1486  * with the given arguments.
1487  *
1488  * In general, other parts of this module should call this
1489  * function when they are dealing with external users, who only
1490  * have tids to pass (but they call it "pid" for historical
1491  * reasons).
1492  */
1493 static int
1494 call_ttrace( request, gdb_tid, addr, data, addr2 )
1495   ttreq_t  request;
1496   int      gdb_tid;
1497   TTRACE_ARG_TYPE  addr, data, addr2;
1498 {
1499   lwpid_t  real_tid;
1500   int      real_pid;
1501   ttreq_t  new_request;
1502   int      tt_status;
1503   char     reason_for_failure [100];  /* Arbitrary size, should be big enough. */
1504   
1505 #ifdef THREAD_DEBUG
1506   int   is_interesting = 0;
1507
1508   if( TT_LWP_RUREGS == request ) {
1509      is_interesting = 1;          /* Adjust code here as desired */
1510   }
1511   
1512   if( is_interesting && 0 && debug_on ) {
1513       if( !is_process_ttrace_request( request )) {
1514           printf( "TT: Thread request, tid is %d", gdb_tid );
1515           printf( "== SINGLE at %x", addr );
1516       }
1517       else {
1518           printf( "TT: Process request, tid is %d\n", gdb_tid );
1519           printf( "==! SINGLE at %x", addr );
1520       }
1521   }
1522 #endif
1523
1524   /* The initial SETTRC and SET_EVENT_MASK calls (and all others
1525    * which happen before any threads get set up) should go
1526    * directly to "call_real_ttrace", so they don't happen here.
1527    *
1528    * But hardware watchpoints do a SET_EVENT_MASK, so we can't
1529    * rule them out....
1530    */
1531 #ifdef THREAD_DEBUG
1532   if( request == TT_PROC_SETTRC && debug_on )
1533       printf( "Unexpected call for TT_PROC_SETTRC\n" );
1534 #endif
1535
1536   /* Sometimes we get called with a bogus tid (e.g., if a
1537    * thread has terminated, we return 0; inftarg later asks
1538    * whether the thread has exited/forked/vforked).
1539    */
1540   if( gdb_tid == 0 )
1541     {
1542       errno = ESRCH;  /* ttrace's response would probably be "No such process". */
1543       return -1;
1544     }
1545
1546   /* All other cases should be able to expect that there are
1547    * thread records.
1548    */
1549   if( !any_thread_records()) {
1550 #ifdef THREAD_DEBUG
1551       if( debug_on )
1552           warning ("No thread records for ttrace call");
1553 #endif
1554       errno = ESRCH;  /* ttrace's response would be "No such process". */
1555       return -1;
1556   }
1557
1558   /* OK, now the task is to translate the incoming tid into
1559    * a pid/tid pair.
1560    */
1561   real_tid = map_from_gdb_tid( gdb_tid );
1562   real_pid = get_pid_for( real_tid );
1563
1564   /* Now check the result.  "Real_pid" is NULL if our list
1565    * didn't find it.  We have some tricks we can play to fix
1566    * this, however.
1567    */
1568   if( 0 == real_pid ) {
1569     ttstate_t  thread_state;
1570
1571 #ifdef THREAD_DEBUG
1572     if( debug_on )
1573         printf( "No saved pid for tid %d\n", gdb_tid );
1574 #endif
1575
1576     if( is_process_ttrace_request( request )) {
1577      
1578         /* Ok, we couldn't get a tid.  Try to translate to
1579          * the equivalent process operation.  We expect this
1580          * NOT to happen, so this is a desparation-type
1581          * move.  It can happen if there is an internal
1582          * error and so no "wait()" call is ever done.
1583          */
1584         new_request = make_process_version( request );
1585         if( new_request == -1 ) {
1586         
1587 #ifdef THREAD_DEBUG
1588             if( debug_on )
1589                 printf( "...and couldn't make process version of thread operation\n" );
1590 #endif
1591
1592             /* Use hacky saved pid, which won't always be correct
1593              * in the multi-process future.  Use tid as thread,
1594              * probably dooming this to failure.  FIX!
1595              */
1596             if( saved_real_pid != 0 ) {
1597 #ifdef THREAD_DEBUG
1598                 if( debug_on )
1599                     printf( "...using saved pid %d\n", saved_real_pid );
1600 #endif
1601
1602                 real_pid = saved_real_pid;
1603                 real_tid = gdb_tid;
1604             }
1605
1606             else
1607                 error( "Unable to perform thread operation" );
1608         } 
1609
1610         else {
1611             /* Sucessfully translated this to a process request,
1612              * which needs no thread value.
1613              */
1614             real_pid = gdb_tid;
1615             real_tid = 0;
1616             request  = new_request;
1617
1618 #ifdef THREAD_DEBUG
1619             if( debug_on ) {
1620                 printf( "Translated thread request to process request\n" );
1621                 if( saved_real_pid == 0 )
1622                     printf( "...but there's no saved pid\n" );
1623                 
1624                 else {
1625                     if( gdb_tid != saved_real_pid )
1626                         printf( "...but have the wrong pid (%d rather than %d)\n",
1627                                 gdb_tid, saved_real_pid );
1628                 }
1629             }
1630 #endif
1631         } /* Translated to a process request */
1632     }     /* Is a process request */
1633
1634     else {
1635         /* We have to have a thread.  Ooops.
1636          */
1637        error( "Thread request with no threads (%s)",
1638                get_printable_name_of_ttrace_request( request ));
1639     }
1640   }
1641
1642   /* Ttrace doesn't like to see tid values on process requests,
1643    * even if we have the right one.
1644    */
1645   if (is_process_ttrace_request (request)) {
1646       real_tid = 0;
1647   }
1648   
1649 #ifdef THREAD_DEBUG
1650   if( is_interesting && 0 && debug_on ) {
1651     printf( "    now tid %d, pid %d\n", real_tid, real_pid );
1652     printf( "    request is %s\n", get_printable_name_of_ttrace_request (request));
1653   }
1654 #endif
1655
1656   /* Finally, the (almost) real call.
1657    */
1658   tt_status = call_real_ttrace (request, real_pid, real_tid, addr, data, addr2);
1659
1660 #ifdef THREAD_DEBUG
1661   if(is_interesting && debug_on ) {
1662     if( !TT_OK( tt_status, errno )
1663     &&  !(tt_status == 0 & errno == 0))
1664       printf( " got error (errno==%d, status==%d)\n", errno, tt_status );
1665   }
1666 #endif
1667
1668   return tt_status;
1669 }
1670
1671
1672 /* Stop all the threads of a process.
1673  *
1674  * NOTE: use of TT_PROC_STOP can cause a thread with a real event
1675  *       to get a TTEVT_NONE event, discarding the old event.  Be
1676  *       very careful, and only call TT_PROC_STOP when you mean it!
1677  */
1678 static void
1679 stop_all_threads_of_process( real_pid )
1680   pid_t  real_pid;
1681 {
1682   int  ttw_status;
1683
1684   ttw_status = call_real_ttrace (TT_PROC_STOP,
1685                                  (pid_t) real_pid,
1686                                  (lwpid_t) TT_NIL,
1687                                  (TTRACE_ARG_TYPE) TT_NIL,
1688                                  (TTRACE_ARG_TYPE) TT_NIL,
1689                                  TT_NIL );
1690   if (errno)
1691     perror_with_name ("ttrace stop of other threads");
1692 }
1693
1694
1695 /* Under some circumstances, it's unsafe to attempt to stop, or even
1696    query the state of, a process' threads.
1697
1698    In ttrace-based HP-UX, an example is a vforking child process.  The
1699    vforking parent and child are somewhat fragile, w/r/t what we can do
1700    what we can do to them with ttrace, until after the child exits or
1701    execs, or until the parent's vfork event is delivered.  Until that
1702    time, we must not try to stop the process' threads, or inquire how
1703    many there are, or even alter its data segments, or it typically dies
1704    with a SIGILL.  Sigh.
1705
1706    This function returns 1 if this stopped process, and the event that
1707    we're told was responsible for its current stopped state, cannot safely
1708    have its threads examined.
1709    */
1710 #define CHILD_VFORKED(evt,pid) \
1711   (((evt) == TTEVT_VFORK) && ((pid) != inferior_pid))
1712 #define CHILD_URPED(evt,pid) \
1713   ((((evt) == TTEVT_EXEC) || ((evt) == TTEVT_EXIT)) && ((pid) != vforking_child_pid))
1714 #define PARENT_VFORKED(evt,pid) \
1715   (((evt) == TTEVT_VFORK) && ((pid) == inferior_pid))
1716
1717 static int
1718 can_touch_threads_of_process (pid, stopping_event)
1719   int  pid;
1720   ttevents_t  stopping_event;
1721 {
1722   if (CHILD_VFORKED (stopping_event, pid))
1723     {
1724       vforking_child_pid = pid;
1725       vfork_in_flight = 1;
1726     }
1727
1728   else if (vfork_in_flight &&
1729            (PARENT_VFORKED (stopping_event, pid) ||
1730             CHILD_URPED (stopping_event, pid)))
1731     {
1732       vfork_in_flight = 0;
1733       vforking_child_pid = 0;
1734     }
1735
1736   return ! vfork_in_flight;
1737 }
1738
1739
1740 /* If we can find an as-yet-unhandled thread state of a
1741  * stopped thread of this process return 1 and set "tsp".
1742  * Return 0 if we can't.
1743  *
1744  * If this function is used when the threads of PIS haven't
1745  * been stopped, undefined behaviour is guaranteed!
1746  */
1747 static int 
1748 select_stopped_thread_of_process (pid, tsp)
1749   int  pid;
1750   ttstate_t *  tsp;
1751 {
1752   lwpid_t    candidate_tid,    tid;
1753   ttstate_t  candidate_tstate, tstate;
1754
1755   /* If we're not allowed to touch the process now, then just
1756    * return the current value of *TSP.
1757    *
1758    * This supports "vfork".  It's ok, really, to double the
1759    * current event (the child EXEC, we hope!).
1760    */
1761   if (! can_touch_threads_of_process (pid, tsp->tts_event))
1762     return 1;
1763
1764   /* Decide which of (possibly more than one) events to
1765    * return as the first one.  We scan them all so that
1766    * we always return the result of a fake-step first.
1767    */
1768   candidate_tid = 0;
1769   for (tid = get_process_first_stopped_thread_id (pid, &tstate);
1770        tid != 0;
1771        tid = get_process_next_stopped_thread_id (pid, &tstate))
1772     {
1773       /* TTEVT_NONE events are uninteresting to our clients.  They're
1774        * an artifact of our "stop the world" model--the thread is
1775        * stopped because we stopped it.
1776        */
1777       if (tstate.tts_event == TTEVT_NONE) {
1778           set_handled( pid, tstate.tts_lwpid );
1779       }
1780
1781       /* Did we just single-step a single thread, without letting any
1782        * of the others run?  Is this an event for that thread?
1783        *
1784        * If so, we believe our client would prefer to see this event
1785        * over any others.  (Typically the client wants to just push
1786        * one thread a little farther forward, and then go around
1787        * checking for what all threads are doing.)
1788        */
1789       else if (doing_fake_step && (tstate.tts_lwpid == fake_step_tid))
1790         {
1791 #ifdef WAIT_BUFFER_DEBUG
1792           /* It's possible here to see either a SIGTRAP (due to
1793            * successful completion of a step) or a SYSCALL_ENTRY
1794            * (due to a step completion with active hardware
1795            * watchpoints).
1796            */
1797            if( debug_on )
1798                printf( "Ending fake step with tid %d, state %s\n",
1799                        tstate.tts_lwpid,
1800                        get_printable_name_of_ttrace_event( tstate.tts_event ));
1801 #endif 
1802
1803           /* Remember this one, and throw away any previous
1804            * candidate.
1805            */
1806           candidate_tid    = tstate.tts_lwpid;
1807           candidate_tstate = tstate;
1808       }
1809
1810 #ifdef FORGET_DELETED_BPTS
1811
1812       /* We can't just do this, as if we do, and then wind
1813        * up the loop with no unhandled events, we need to
1814        * handle that case--the appropriate reaction is to
1815        * just continue, but there's no easy way to do that.
1816        *
1817        * Better to put this in the ttrace_wait call--if, when
1818        * we fake a wait, we update our events based on the
1819        * breakpoint_here_pc call and find there are no more events,
1820        * then we better continue and so on.
1821        *
1822        * Or we could put it in the next/continue fake.
1823        * But it has to go in the buffering code, not in the
1824        * real go/wait code.
1825        */
1826       else if( (TTEVT_SIGNAL == tstate.tts_event)
1827             && (5 == tstate.tts_u.tts_signal.tts_signo)
1828             && (0 != get_raw_pc( tstate.tts_lwpid ))
1829             && ! breakpoint_here_p( get_raw_pc( tstate.tts_lwpid )) ) {
1830           /*
1831            * If the user deleted a breakpoint while this
1832            * breakpoint-hit event was buffered, we can forget
1833            * it now.
1834            */
1835 #ifdef WAIT_BUFFER_DEBUG
1836            if( debug_on )
1837                printf( "Forgetting deleted bp hit for thread %d\n",
1838                        tstate.tts_lwpid );
1839 #endif 
1840
1841           set_handled( pid, tstate.tts_lwpid );
1842       }
1843 #endif
1844
1845       /* Else, is this the first "unhandled" event?  If so,
1846        * we believe our client wants to see it (if we don't
1847        * see a fake-step later on in the scan).
1848        */
1849       else if( !was_handled( tstate.tts_lwpid ) && candidate_tid == 0 ) {
1850           candidate_tid    = tstate.tts_lwpid;
1851           candidate_tstate = tstate;
1852       }
1853
1854       /* This is either an event that has already been "handled",
1855        * and thus we believe is uninteresting to our client, or we
1856        * already have a candidate event.  Ignore it...
1857        */
1858     }
1859
1860   /* What do we report?
1861    */
1862   if( doing_fake_step ) {
1863       if( candidate_tid == fake_step_tid ) {
1864           /* Fake step.
1865            */
1866           tstate = candidate_tstate;
1867       }
1868       else {
1869           warning( "Internal error: fake-step failed to complete." );
1870           return 0;
1871       }
1872   }
1873   else if( candidate_tid != 0 ) {
1874       /* Found a candidate unhandled event.
1875        */
1876       tstate = candidate_tstate;
1877   }
1878   else if( tid != 0 ) {
1879       warning( "Internal error in call of ttrace_wait." );
1880       return 0;
1881   }
1882   else {
1883       warning ("Internal error: no unhandled thread event to select");
1884       return 0;
1885   }
1886
1887   copy_ttstate_t (tsp, &tstate);
1888   return 1;
1889 } /* End of select_stopped_thread_of_process */
1890
1891 #ifdef PARANOIA
1892 /* Check our internal thread data against the real thing.
1893  */
1894 static void
1895 check_thread_consistency( real_pid )
1896     pid_t real_pid;
1897 {
1898     int          tid;       /* really lwpid_t */
1899     ttstate_t    tstate;
1900     thread_info *p;
1901
1902     /* Spin down the O/S list of threads, checking that they
1903      * match what we've got.
1904      */
1905     for (tid = get_process_first_stopped_thread_id( real_pid, &tstate );
1906          tid != 0;
1907          tid = get_process_next_stopped_thread_id(  real_pid, &tstate )) {
1908        
1909         p = find_thread_info( tid );
1910       
1911         if( NULL == p ) {
1912             warning( "No internal thread data for thread %d.", tid );
1913             continue;
1914         }
1915
1916         if( !p->seen ) {
1917             warning( "Inconsistent internal thread data for thread %d.", tid );
1918         }
1919
1920         if( p->terminated ) {
1921             warning( "Thread %d is not terminated, internal error.", tid );
1922             continue;
1923         }
1924
1925
1926 #define TT_COMPARE( fld ) \
1927             tstate.fld != p->last_stop_state.fld
1928             
1929         if( p->have_state ) {
1930             if( TT_COMPARE( tts_pid      )
1931              || TT_COMPARE( tts_lwpid    )
1932              || TT_COMPARE( tts_user_tid )
1933              || TT_COMPARE( tts_event    )
1934              || TT_COMPARE( tts_flags    )
1935              || TT_COMPARE( tts_scno     )
1936              || TT_COMPARE( tts_scnargs  )) {
1937                 warning( "Internal thread data for thread %d is wrong.", tid );
1938                 continue;
1939             }
1940         }
1941     }
1942 }
1943 #endif  /* PARANOIA */
1944
1945 \f
1946 /* This function wraps calls to "call_real_ttrace_wait" so
1947  * that a actual wait is only done when all pending events
1948  * have been reported.
1949  *
1950  * Note that typically it is called with a pid of "0", i.e. 
1951  * the "don't care" value.
1952  *
1953  * Return value is the status of the pseudo wait.
1954  */
1955 static int
1956 call_ttrace_wait( pid, option, tsp, tsp_size )
1957   int        pid;
1958   ttwopt_t   option;
1959   ttstate_t *tsp;
1960   size_t     tsp_size;
1961 {
1962   /* This holds the actual, for-real, true process ID.
1963    */
1964   static int real_pid;
1965
1966   /* As an argument to ttrace_wait, zero pid
1967    * means "Any process", and zero tid means
1968    * "Any thread of the specified process".
1969    */
1970   int      wait_pid = 0;
1971   lwpid_t  wait_tid = 0;
1972   lwpid_t  real_tid;
1973
1974   int       ttw_status = 0;   /* To be returned */
1975
1976   thread_info *  tinfo = NULL;
1977
1978   if( pid != 0 ) {
1979       /* Unexpected case.
1980        */
1981 #ifdef THREAD_DEBUG
1982       if( debug_on )
1983           printf( "TW: Pid to wait on is %d\n", pid );
1984 #endif
1985
1986       if( !any_thread_records())
1987           error( "No thread records for ttrace call w. specific pid" );
1988
1989       /* OK, now the task is to translate the incoming tid into
1990        * a pid/tid pair.
1991        */
1992       real_tid = map_from_gdb_tid( pid );
1993       real_pid = get_pid_for( real_tid );
1994 #ifdef THREAD_DEBUG
1995       if( debug_on )
1996           printf( "==TW: real pid %d, real tid %d\n", real_pid, real_tid );
1997 #endif
1998   }
1999
2000
2001   /* Sanity checks and set-up.
2002    *                             Process State
2003    *
2004    *                        Stopped   Running    Fake-step  (v)Fork
2005    *                      \________________________________________
2006    *                      |
2007    *  No buffered events  |  error     wait       wait      wait
2008    *                      |
2009    *  Buffered events     |  debuffer  error      wait      debuffer (?)
2010    *
2011    */
2012   if( more_events_left == 0 ) {
2013
2014       if( process_state == RUNNING ) {
2015           /* OK--normal call of ttrace_wait with no buffered events.
2016            */
2017           ;
2018       }
2019       else if( process_state == FAKE_STEPPING ) {
2020           /* Ok--call of ttrace_wait to support
2021            * fake stepping with no buffered events.
2022            *
2023            * But we better be fake-stepping!
2024            */
2025           if( !doing_fake_step ) {
2026               warning( "Inconsistent thread state." );
2027           }
2028       }
2029       else if( (process_state == FORKING)
2030             || (process_state == VFORKING)) {
2031           /* Ok--there are two processes, so waiting
2032            * for the second while the first is stopped
2033            * is ok.  Handled bits stay as they were.
2034            */
2035            ;
2036       }
2037       else if( process_state == STOPPED ) {
2038           warning( "Process not running at wait call." );
2039       }
2040       else
2041           /* No known state.
2042            */
2043           warning( "Inconsistent process state." );
2044   }
2045   
2046   else {
2047       /* More events left
2048        */
2049       if( process_state == STOPPED ) {
2050           /* OK--buffered events being unbuffered.
2051            */
2052           ;
2053       }
2054       else if( process_state == RUNNING ) {
2055           /* An error--shouldn't have buffered events
2056            * when running.
2057            */
2058           warning( "Trying to continue with buffered events:" );
2059       }
2060       else if( process_state == FAKE_STEPPING ) {
2061           /*
2062            * Better be fake-stepping!
2063            */
2064           if( !doing_fake_step ) {
2065               warning( "Losing buffered thread events!\n" );
2066           }
2067       }
2068       else if( (process_state == FORKING)
2069             || (process_state == VFORKING)) {
2070           /* Ok--there are two processes, so waiting
2071            * for the second while the first is stopped
2072            * is ok.  Handled bits stay as they were.
2073            */
2074            ;
2075       }
2076       else
2077           warning( "Process in unknown state with buffered events." );
2078   }
2079
2080   /* Sometimes we have to wait for a particular thread
2081    * (if we're stepping over a bpt).  In that case, we
2082    * _know_ it's going to complete the single-step we
2083    * asked for (because we're only doing the step under
2084    * certain very well-understood circumstances), so it
2085    * can't block.
2086    */
2087   if( doing_fake_step ) {
2088       wait_tid = fake_step_tid;
2089       wait_pid = get_pid_for( fake_step_tid );
2090
2091 #ifdef WAIT_BUFFER_DEBUG
2092       if( debug_on )
2093           printf( "Doing a wait after a fake-step for %d, pid %d\n",
2094                   wait_tid, wait_pid );
2095 #endif
2096   }
2097
2098   if( more_events_left == 0         /* No buffered events, need real ones. */
2099   ||  process_state != STOPPED ) {
2100       /* If there are no buffered events, and so we need
2101        * real ones, or if we are FORKING, VFORKING, 
2102        * FAKE_STEPPING or RUNNING, and thus have to do
2103        * a real wait, then do a real wait.
2104        */
2105
2106 #ifdef WAIT_BUFFER_DEBUG
2107       /* Normal case... */
2108       if( debug_on )
2109           printf( "TW: do it for real; pid %d, tid %d\n", wait_pid, wait_tid );
2110 #endif
2111
2112       /* The actual wait call.
2113        */
2114       ttw_status = call_real_ttrace_wait( wait_pid, wait_tid, option, tsp, tsp_size);
2115
2116       /* Note that the routines we'll call will be using "call_real_ttrace",
2117        * not "call_ttrace", and thus need the real pid rather than the pseudo-tid
2118        * the rest of the world uses (which is actually the tid).
2119        */
2120       real_pid = tsp->tts_pid;
2121
2122       /* For most events: Stop the world!
2123        *
2124        * It's sometimes not safe to stop all threads of a process.
2125        * Sometimes it's not even safe to ask for the thread state
2126        * of a process!
2127        */
2128       if (can_touch_threads_of_process (real_pid, tsp->tts_event))
2129         {
2130           /* If we're really only stepping a single thread, then don't
2131            * try to stop all the others -- we only do this single-stepping
2132            * business when all others were already stopped...and the stop
2133            * would mess up other threads' events.
2134            *
2135            * Similiarly, if there are other threads with events,
2136            * don't do the stop.
2137            */
2138           if( !doing_fake_step ) {
2139             if( more_events_left > 0 )
2140                 warning( "Internal error in stopping process" );
2141                 
2142             stop_all_threads_of_process (real_pid);
2143
2144             /* At this point, we could scan and update_thread_list(),
2145              * and only use the local list for the rest of the
2146              * module! We'd get rid of the scans in the various
2147              * continue routines (adding one in attach).  It'd
2148              * be great--UPGRADE ME!
2149              */
2150             }
2151         }
2152         
2153 #ifdef PARANOIA
2154       else if( debug_on ) {
2155           if( more_events_left > 0 )
2156               printf( "== Can't stop process; more events!\n" );
2157           else
2158               printf( "== Can't stop process!\n" );
2159       }
2160 #endif
2161
2162       process_state   = STOPPED;
2163
2164 #ifdef WAIT_BUFFER_DEBUG
2165       if( debug_on )
2166           printf( "Process set to STOPPED\n" );
2167 #endif
2168   }
2169   
2170   else {
2171       /* Fake a call to ttrace_wait.  The process must be
2172        * STOPPED, as we aren't going to do any wait.
2173        */
2174 #ifdef WAIT_BUFFER_DEBUG
2175       if( debug_on )
2176           printf( "TW: fake it\n" );
2177 #endif
2178
2179       if( process_state != STOPPED ) {
2180           warning( "Process not stopped at wait call, in state '%s'.\n",
2181                    get_printable_name_of_process_state( process_state ));
2182       }
2183     
2184       if( doing_fake_step )
2185           error( "Internal error in stepping over breakpoint" );
2186
2187       ttw_status = 0;  /* Faking it is always successful! */
2188   }   /* End of fake or not? if */
2189
2190   /* Pick an event to pass to our caller.  Be paranoid.
2191    */
2192   if( !select_stopped_thread_of_process( real_pid, tsp ))
2193       warning( "Can't find event, using previous event." );
2194
2195   else if( tsp->tts_event == TTEVT_NONE )
2196       warning( "Internal error: no thread has a real event." );
2197
2198   else if( doing_fake_step ) {
2199       if( fake_step_tid != tsp->tts_lwpid )
2200           warning( "Internal error in stepping over breakpoint." );
2201           
2202       /* This wait clears the (current) fake-step if there was one.
2203        */
2204       doing_fake_step = 0;
2205       fake_step_tid   = 0;
2206   }
2207
2208   /* We now have a correct tsp and ttw_status for the thread
2209    * which we want to report.  So it's "handled"!  This call
2210    * will add it to our list if it's not there already.
2211    */
2212   set_handled( real_pid, tsp->tts_lwpid );
2213
2214   /* Save a copy of the ttrace state of this thread, in our local
2215      thread descriptor.
2216
2217      This caches the state.  The implementation of queries like
2218      target_has_execd can then use this cached state, rather than
2219      be forced to make an explicit ttrace call to get it.
2220
2221      (Guard against the condition that this is the first time we've
2222      waited on, i.e., seen this thread, and so haven't yet entered
2223      it into our list of threads.)
2224    */
2225   tinfo = find_thread_info (tsp->tts_lwpid);
2226   if (tinfo != NULL) {
2227     copy_ttstate_t (&tinfo->last_stop_state, tsp);
2228     tinfo->have_state = 1;
2229   }
2230   
2231   return ttw_status;
2232 } /* call_ttrace_wait */
2233
2234 #if defined(CHILD_REPORTED_EXEC_EVENTS_PER_EXEC_CALL)
2235 int
2236 child_reported_exec_events_per_exec_call ()
2237 {
2238   return 1;  /* ttrace reports the event once per call. */
2239 }
2240 #endif
2241
2242
2243 \f
2244 /* Our implementation of hardware watchpoints involves making memory
2245    pages write-protected.  We must remember a page's original permissions,
2246    and we must also know when it is appropriate to restore a page's
2247    permissions to its original state.
2248
2249    We use a "dictionary" of hardware-watched pages to do this.  Each
2250    hardware-watched page is recorded in the dictionary.  Each page's
2251    dictionary entry contains the original permissions and a reference
2252    count.  Pages are hashed into the dictionary by their start address.
2253
2254    When hardware watchpoint is set on page X for the first time, page X
2255    is added to the dictionary with a reference count of 1.  If other
2256    hardware watchpoints are subsequently set on page X, its reference
2257    count is incremented.  When hardware watchpoints are removed from
2258    page X, its reference count is decremented.  If a page's reference
2259    count drops to 0, it's permissions are restored and the page's entry
2260    is thrown out of the dictionary.
2261    */
2262 typedef struct memory_page {
2263   CORE_ADDR  page_start;
2264   int  reference_count;
2265   int  original_permissions;
2266   struct memory_page *  next;
2267   struct memory_page *  previous;
2268 } memory_page_t;
2269
2270 #define MEMORY_PAGE_DICTIONARY_BUCKET_COUNT  128
2271
2272 static struct {
2273   LONGEST  page_count;
2274   int  page_size;
2275   int  page_protections_allowed;
2276   /* These are just the heads of chains of actual page descriptors. */
2277   memory_page_t  buckets [MEMORY_PAGE_DICTIONARY_BUCKET_COUNT];
2278 } memory_page_dictionary;
2279
2280
2281 static void
2282 require_memory_page_dictionary ()
2283 {
2284   int  i;
2285
2286   /* Is the memory page dictionary ready for use?  If so, we're done. */
2287   if (memory_page_dictionary.page_count >= (LONGEST) 0)
2288     return;
2289
2290   /* Else, initialize it. */
2291   memory_page_dictionary.page_count = (LONGEST) 0;
2292
2293   for (i=0; i<MEMORY_PAGE_DICTIONARY_BUCKET_COUNT; i++)
2294     {
2295       memory_page_dictionary.buckets[i].page_start = (CORE_ADDR) 0;
2296       memory_page_dictionary.buckets[i].reference_count = 0;
2297       memory_page_dictionary.buckets[i].next = NULL;
2298       memory_page_dictionary.buckets[i].previous = NULL;
2299     }
2300 }
2301
2302
2303 static void
2304 retire_memory_page_dictionary ()
2305 {
2306   memory_page_dictionary.page_count = (LONGEST) -1;
2307 }
2308
2309
2310 /* Write-protect the memory page that starts at this address.
2311
2312    Returns the original permissions of the page.
2313  */
2314 static int
2315 write_protect_page (pid, page_start)
2316   int       pid;
2317   CORE_ADDR page_start;
2318 {
2319   int  tt_status;
2320   int  original_permissions;
2321   int  new_permissions;
2322
2323   tt_status = call_ttrace (TT_PROC_GET_MPROTECT,
2324                            pid,
2325                            (TTRACE_ARG_TYPE) page_start,
2326                            TT_NIL,
2327                            (TTRACE_ARG_TYPE) &original_permissions);
2328   if (errno || (tt_status < 0))
2329     {
2330       return 0;  /* What else can we do? */
2331     }
2332
2333   /* We'll also write-protect the page now, if that's allowed. */
2334   if (memory_page_dictionary.page_protections_allowed)
2335     {
2336       new_permissions = original_permissions & ~PROT_WRITE;
2337       tt_status = call_ttrace (TT_PROC_SET_MPROTECT,
2338                                pid,
2339                                (TTRACE_ARG_TYPE) page_start,
2340                                (TTRACE_ARG_TYPE) memory_page_dictionary.page_size,
2341                                (TTRACE_ARG_TYPE) new_permissions);
2342       if (errno || (tt_status < 0))
2343         {
2344           return 0;  /* What else can we do? */
2345         }
2346     }
2347
2348   return original_permissions;
2349 }
2350
2351
2352 /* Unwrite-protect the memory page that starts at this address, restoring
2353    (what we must assume are) its original permissions.
2354    */
2355 static void
2356 unwrite_protect_page (pid, page_start, original_permissions)
2357   int  pid;
2358   CORE_ADDR  page_start;
2359   int  original_permissions;
2360 {
2361   int  tt_status;
2362
2363   tt_status = call_ttrace (TT_PROC_SET_MPROTECT,
2364                            pid,
2365                            (TTRACE_ARG_TYPE) page_start,
2366                            (TTRACE_ARG_TYPE) memory_page_dictionary.page_size,
2367                            (TTRACE_ARG_TYPE) original_permissions);
2368   if (errno || (tt_status < 0))
2369     {
2370       return;  /* What else can we do? */
2371     }
2372 }
2373
2374
2375 /* Memory page-protections are used to implement "hardware" watchpoints
2376    on HP-UX.
2377
2378    For every memory page that is currently being watched (i.e., that
2379    presently should be write-protected), write-protect it.
2380    */
2381 void
2382 hppa_enable_page_protection_events (pid)
2383   int  pid;
2384 {
2385   int  bucket;
2386
2387   memory_page_dictionary.page_protections_allowed = 1;
2388
2389   for (bucket=0; bucket<MEMORY_PAGE_DICTIONARY_BUCKET_COUNT; bucket++)
2390     {
2391       memory_page_t *  page;
2392
2393       page = memory_page_dictionary.buckets[bucket].next;
2394       while (page != NULL)
2395         {
2396           page->original_permissions = write_protect_page (pid, page->page_start);
2397           page = page->next;
2398         }
2399     }
2400 }
2401
2402
2403 /* Memory page-protections are used to implement "hardware" watchpoints
2404    on HP-UX.
2405
2406    For every memory page that is currently being watched (i.e., that
2407    presently is or should be write-protected), un-write-protect it.
2408    */
2409 void
2410 hppa_disable_page_protection_events (pid)
2411   int  pid;
2412 {
2413   int  bucket;
2414
2415   for (bucket=0; bucket<MEMORY_PAGE_DICTIONARY_BUCKET_COUNT; bucket++)
2416     {
2417       memory_page_t *  page;
2418
2419       page = memory_page_dictionary.buckets[bucket].next;
2420       while (page != NULL)
2421         {
2422           unwrite_protect_page (pid, page->page_start, page->original_permissions);
2423           page = page->next;
2424         }
2425     }
2426
2427   memory_page_dictionary.page_protections_allowed = 0;
2428 }
2429
2430 /* Count the number of outstanding events.  At this
2431  * point, we have selected one thread and its event
2432  * as the one to be "reported" upwards to core gdb.
2433  * That thread is already marked as "handled".
2434  *
2435  * Note: we could just scan our own thread list.  FIXME!
2436  */
2437 static int
2438 count_unhandled_events( real_pid, real_tid )
2439   int     real_pid;
2440   lwpid_t real_tid;
2441 {
2442   ttstate_t  tstate;
2443   lwpid_t    ttid;
2444   int        events_left;
2445   
2446   /* Ok, find out how many threads have real events to report.
2447    */
2448   events_left = 0;
2449   ttid = get_process_first_stopped_thread_id( real_pid, &tstate );
2450
2451 #ifdef THREAD_DEBUG
2452   if( debug_on ) {
2453       if( ttid == 0 )
2454           printf( "Process %d has no threads\n", real_pid );
2455       else
2456           printf( "Process %d has these threads:\n", real_pid );
2457   }
2458 #endif
2459
2460   while (ttid > 0 ) {
2461       if( tstate.tts_event != TTEVT_NONE
2462       &&  !was_handled( ttid )) {
2463           /* TTEVT_NONE implies we just stopped it ourselves
2464            * because we're the stop-the-world guys, so it's
2465            * not an event from our point of view.
2466            *
2467            * If "was_handled" is true, this is an event we
2468            * already handled, so don't count it.
2469            *
2470            * Note that we don't count the thread with the
2471            * currently-reported event, as it's already marked
2472            * as handled.
2473            */
2474           events_left++;
2475       }
2476          
2477 #if defined( THREAD_DEBUG ) || defined( WAIT_BUFFER_DEBUG )
2478   if( debug_on ) {
2479       if( ttid == real_tid )
2480           printf( "*" );         /* Thread we're reporting */
2481       else
2482           printf( " " );
2483          
2484       if( tstate.tts_event != TTEVT_NONE )
2485           printf( "+" );         /* Thread with a real event */
2486       else
2487           printf( " " );
2488
2489       if( was_handled( ttid ))
2490           printf( "h" );         /* Thread has been handled */
2491       else
2492           printf( " " );
2493          
2494       printf( " %d, with event %s", ttid,
2495               get_printable_name_of_ttrace_event( tstate.tts_event ));
2496               
2497       if( tstate.tts_event == TTEVT_SIGNAL
2498        && 5 == tstate.tts_u.tts_signal.tts_signo ) {
2499           CORE_ADDR pc_val;
2500
2501           pc_val = get_raw_pc( ttid );
2502
2503           if( pc_val > 0 )
2504               printf( " breakpoint at 0x%x\n", pc_val );
2505           else
2506               printf( " bpt, can't fetch pc.\n" );
2507       }
2508       else
2509           printf( "\n" );
2510   }
2511 #endif
2512
2513       ttid = get_process_next_stopped_thread_id (real_pid, &tstate);
2514   }
2515
2516 #if defined( THREAD_DEBUG ) || defined( WAIT_BUFFER_DEBUG )
2517   if( debug_on )
2518       if( events_left > 0 )
2519           printf( "There are thus %d pending events\n", events_left );
2520 #endif
2521
2522   return events_left;
2523 }
2524
2525 /* This function is provided as a sop to clients that are calling
2526  * ptrace_wait to wait for a process to stop.  (see the
2527  * implementation of child_wait.)  Return value is the pid for
2528  * the event that ended the wait.
2529  *
2530  * Note: used by core gdb and so uses the pseudo-pid (really tid).
2531  */
2532 int
2533 ptrace_wait (pid, status)
2534     int pid;
2535     int *status;
2536 {
2537   ttstate_t  tsp;
2538   int        ttwait_return;
2539   int        real_pid;
2540   ttstate_t  state;
2541   lwpid_t    real_tid;
2542   int  return_pid;
2543
2544   /* The ptrace implementation of this also ignores pid.
2545    */
2546   *status = 0;
2547
2548   ttwait_return = call_ttrace_wait( 0, TTRACE_WAITOK, &tsp, sizeof (tsp) );
2549   if (ttwait_return < 0)
2550     {
2551       /* ??rehrauer: It appears that if our inferior exits and we
2552          haven't asked for exit events, that we're not getting any
2553          indication save a negative return from ttrace_wait and an
2554          errno set to ESRCH?
2555          */
2556       if (errno == ESRCH)
2557         {
2558           *status = 0;  /* WIFEXITED */
2559           return inferior_pid;
2560         }
2561
2562       warning( "Call of ttrace_wait returned with errno %d.",
2563                errno );
2564       *status = ttwait_return;
2565       return inferior_pid;
2566     }
2567
2568   real_pid = tsp.tts_pid;
2569   real_tid = tsp.tts_lwpid;
2570
2571   /* One complication is that the "tts_event" structure has
2572    * a set of flags, and more than one can be set.  So we
2573    * either have to force an order (as we do here), or handle
2574    * more than one flag at a time.
2575    */
2576   if (tsp.tts_event & TTEVT_LWP_CREATE) {
2577
2578      /* Unlike what you might expect, this event is reported in
2579       * the _creating_ thread, and the _created_ thread (whose tid
2580       * we have) is still running.  So we have to stop it.  This
2581       * has already been done in "call_ttrace_wait", but should we
2582       * ever abandon the "stop-the-world" model, here's the command
2583       * to use:
2584       *
2585       *    call_ttrace( TT_LWP_STOP, real_tid, TT_NIL, TT_NIL, TT_NIL );
2586       *
2587       * Note that this would depend on being called _after_ "add_tthread"
2588       * below for the tid-to-pid translation to be done in "call_ttrace".
2589       */
2590
2591 #ifdef THREAD_DEBUG
2592      if( debug_on )
2593          printf( "New thread: pid %d, tid %d, creator tid %d\n",
2594                  real_pid, tsp.tts_u.tts_thread.tts_target_lwpid,
2595                  real_tid );
2596 #endif
2597
2598      /* Now we have to return the tid of the created thread, not
2599       * the creating thread, or "wait_for_inferior" won't know we
2600       * have a new "process" (thread).  Plus we should record it
2601       * right, too.
2602       */
2603       real_tid = tsp.tts_u.tts_thread.tts_target_lwpid;
2604
2605       add_tthread( real_pid, real_tid );
2606   }
2607
2608   else if( (tsp.tts_event & TTEVT_LWP_TERMINATE )
2609         || (tsp.tts_event & TTEVT_LWP_EXIT) ) {
2610
2611 #ifdef THREAD_DEBUG
2612      if( debug_on )
2613          printf( "Thread dies: %d\n", real_tid );
2614 #endif
2615
2616      del_tthread( real_tid );
2617   }
2618
2619   else if (tsp.tts_event & TTEVT_EXEC) {
2620
2621 #ifdef THREAD_DEBUG 
2622       if( debug_on )
2623           printf( "Pid %d has zero'th thread %d; inferior pid is %d\n",
2624                   real_pid, real_tid, inferior_pid );
2625 #endif
2626
2627      add_tthread( real_pid, real_tid );
2628   }
2629
2630 #ifdef THREAD_DEBUG
2631   else if( debug_on ) {
2632      printf( "Process-level event %s, using tid %d\n",
2633              get_printable_name_of_ttrace_event( tsp.tts_event ),
2634              real_tid );
2635
2636      /* OK to do this, as "add_tthread" won't add
2637       * duplicate entries.  Also OK not to do it,
2638       * as this event isn't one which can change the
2639       * thread state.
2640       */
2641      add_tthread( real_pid, real_tid );
2642   }
2643 #endif
2644
2645
2646   /* How many events are left to report later?
2647    * In a non-stop-the-world model, this isn't needed.
2648    *
2649    * Note that it's not always safe to query the thread state of a process,
2650    * which is what count_unhandled_events does.  (If unsafe, we're left with
2651    * no other resort than to assume that no more events remain...)
2652    */
2653   if (can_touch_threads_of_process (real_pid, tsp.tts_event))
2654       more_events_left = count_unhandled_events( real_pid, real_tid );
2655       
2656   else {
2657       if( more_events_left > 0 )
2658           warning( "Vfork or fork causing loss of %d buffered events.",
2659                    more_events_left );
2660           
2661       more_events_left = 0;
2662   }
2663
2664   /* Attempt to translate the ttrace_wait-returned status into the
2665      ptrace equivalent.
2666
2667      ??rehrauer: This is somewhat fragile.  We really ought to rewrite
2668      clients that expect to pick apart a ptrace wait status, to use
2669      something a little more abstract.
2670      */
2671   if (   (tsp.tts_event & TTEVT_EXEC)
2672       || (tsp.tts_event & TTEVT_FORK)
2673       || (tsp.tts_event & TTEVT_VFORK))
2674     {
2675       /* Forks come in pairs (parent and child), so core gdb
2676        * will do two waits.  Be ready to notice this.
2677        */
2678       if (tsp.tts_event & TTEVT_FORK)
2679         {
2680           process_state = FORKING;
2681           
2682 #ifdef WAIT_BUFFER_DEBUG
2683           if( debug_on )
2684               printf( "Process set to FORKING\n" );
2685 #endif
2686         }
2687       else if (tsp.tts_event & TTEVT_VFORK)
2688         {
2689           process_state = VFORKING;
2690           
2691 #ifdef WAIT_BUFFER_DEBUG
2692           if( debug_on )
2693               printf( "Process set to VFORKING\n" );
2694 #endif
2695         }
2696
2697       /* Make an exec or fork look like a breakpoint.  Definitely a hack,
2698          but I don't think non HP-UX-specific clients really carefully
2699          inspect the first events they get after inferior startup, so
2700          it probably almost doesn't matter what we claim this is.
2701          */
2702
2703 #ifdef THREAD_DEBUG
2704       if( debug_on )
2705           printf( "..a process 'event'\n" );
2706 #endif
2707
2708       /* Also make fork and exec events look like bpts, so they can be caught.
2709       */
2710       *status = 0177 | (_SIGTRAP << 8);
2711     }
2712
2713   /* Special-cases: We ask for syscall entry and exit events to implement
2714      "fast" (aka "hardware") watchpoints.
2715
2716      When we get a syscall entry, we want to disable page-protections,
2717      and resume the inferior; this isn't an event we wish for
2718      wait_for_inferior to see.  Note that we must resume ONLY the
2719      thread that reported the syscall entry; we don't want to allow
2720      other threads to run with the page protections off, as they might
2721      then be able to write to watch memory without it being caught.
2722
2723      When we get a syscall exit, we want to reenable page-protections,
2724      but we don't want to resume the inferior; this is an event we wish
2725      wait_for_inferior to see.  Make it look like the signal we normally
2726      get for a single-step completion.  This should cause wait_for_inferior
2727      to evaluate whether any watchpoint triggered.
2728
2729      Or rather, that's what we'd LIKE to do for syscall exit; we can't,
2730      due to some HP-UX "features".  Some syscalls have problems with
2731      write-protections on some pages, and some syscalls seem to have
2732      pending writes to those pages at the time we're getting the return
2733      event.  So, we'll single-step the inferior to get out of the syscall,
2734      and then reenable protections.
2735
2736      Note that we're intentionally allowing the syscall exit case to
2737      fall through into the succeeding cases, as sometimes we single-
2738      step out of one syscall only to immediately enter another...
2739    */
2740   else if ((tsp.tts_event & TTEVT_SYSCALL_ENTRY)
2741         || (tsp.tts_event & TTEVT_SYSCALL_RETURN))
2742     {
2743       /* Make a syscall event look like a breakpoint.  Same comments
2744          as for exec & fork events.
2745          */
2746 #ifdef THREAD_DEBUG
2747       if( debug_on )
2748           printf( "..a syscall 'event'\n" );
2749 #endif
2750
2751       /* Also make syscall events look like bpts, so they can be caught.
2752       */
2753       *status = 0177 | (_SIGTRAP << 8);
2754     }
2755
2756   else if ((tsp.tts_event & TTEVT_LWP_CREATE)
2757         || (tsp.tts_event & TTEVT_LWP_TERMINATE)
2758         || (tsp.tts_event & TTEVT_LWP_EXIT))
2759     {
2760       /* Make a thread event look like a breakpoint.  Same comments
2761        * as for exec & fork events.
2762        */
2763 #ifdef THREAD_DEBUG
2764       if( debug_on )
2765           printf( "..a thread 'event'\n" );
2766 #endif
2767
2768       /* Also make thread events look like bpts, so they can be caught.
2769       */
2770       *status = 0177 | (_SIGTRAP << 8);
2771     }
2772     
2773   else if ((tsp.tts_event & TTEVT_EXIT))
2774     {  /* WIFEXITED */
2775     
2776 #ifdef THREAD_DEBUG
2777        if( debug_on )
2778            printf( "..an exit\n" );
2779 #endif
2780
2781       /* Prevent rest of gdb from thinking this is
2782        * a new thread if for some reason it's never
2783        * seen the main thread before.
2784        */
2785       inferior_pid = map_to_gdb_tid( real_tid ); /* HACK, FIX */
2786       
2787       *status = 0 | (tsp.tts_u.tts_exit.tts_exitcode);
2788     }
2789     
2790   else if (tsp.tts_event & TTEVT_SIGNAL)
2791     {  /* WIFSTOPPED */
2792 #ifdef THREAD_DEBUG
2793        if( debug_on )
2794            printf( "..a signal, %d\n", tsp.tts_u.tts_signal.tts_signo );
2795 #endif
2796
2797       *status = 0177 | (tsp.tts_u.tts_signal.tts_signo << 8);
2798     }
2799
2800   else
2801     {  /* !WIFSTOPPED */
2802
2803       /* This means the process or thread terminated.  But we should've
2804          caught an explicit exit/termination above.  So warn (this is
2805          really an internal error) and claim the process or thread
2806          terminated with a SIGTRAP.
2807        */
2808
2809       warning ("process_wait: unknown process state");
2810
2811 #ifdef THREAD_DEBUG
2812       if( debug_on )
2813           printf( "Process-level event %s, using tid %d\n",
2814                   get_printable_name_of_ttrace_event( tsp.tts_event ),
2815                   real_tid );
2816 #endif
2817
2818       *status = _SIGTRAP;
2819     }
2820
2821   target_post_wait (tsp.tts_pid, *status);
2822
2823
2824 #ifdef THREAD_DEBUG
2825   if( debug_on )
2826       printf( "Done waiting, pid is %d, tid %d\n", real_pid, real_tid );
2827 #endif
2828
2829   /* All code external to this module uses the tid, but calls
2830    * it "pid".  There's some tweaking so that the outside sees
2831    * the first thread as having the same number as the starting
2832    * pid.
2833    */
2834   return_pid = map_to_gdb_tid( real_tid );
2835
2836   /* Remember this for later use in "hppa_prepare_to_proceed".
2837    */
2838   old_gdb_pid  = inferior_pid;
2839   reported_pid = return_pid;
2840   reported_bpt = ((tsp.tts_event & TTEVT_SIGNAL) && (5 == tsp.tts_u.tts_signal.tts_signo));
2841
2842   if( real_tid == 0 || return_pid == 0 ) {
2843       warning( "Internal error: process-wait failed." );
2844   }
2845         
2846   return return_pid;
2847 }
2848
2849 \f
2850 /* This function causes the caller's process to be traced by its
2851    parent.  This is intended to be called after GDB forks itself,
2852    and before the child execs the target.  Despite the name, it
2853    is called by the child.
2854
2855    Note that HP-UX ttrace is rather funky in how this is done.
2856    If the parent wants to get the initial exec event of a child,
2857    it must set the ttrace event mask of the child to include execs.
2858    (The child cannot do this itself.)  This must be done after the
2859    child is forked, but before it execs.
2860
2861    To coordinate the parent and child, we implement a semaphore using
2862    pipes.  After SETTRC'ing itself, the child tells the parent that
2863    it is now traceable by the parent, and waits for the parent's
2864    acknowledgement.  The parent can then set the child's event mask,
2865    and notify the child that it can now exec.
2866
2867    (The acknowledgement by parent happens as a result of a call to
2868    child_acknowledge_created_inferior.)
2869  */
2870 int
2871 parent_attach_all ()
2872 {
2873   int  tt_status;
2874
2875   /* We need a memory home for a constant, to pass it to ttrace.
2876      The value of the constant is arbitrary, so long as both
2877      parent and child use the same value.  Might as well use the
2878      "magic" constant provided by ttrace...
2879    */
2880   uint64_t  tc_magic_child = TT_VERSION;
2881   uint64_t  tc_magic_parent = 0;
2882
2883   tt_status = call_real_ttrace (
2884                             TT_PROC_SETTRC,
2885                             (int)     TT_NIL,
2886                             (lwpid_t) TT_NIL,
2887                             TT_NIL,
2888                             (TTRACE_ARG_TYPE) TT_VERSION,
2889                             TT_NIL );
2890
2891   if (tt_status < 0)
2892     return tt_status;
2893
2894   /* Notify the parent that we're potentially ready to exec(). */
2895   write (startup_semaphore.child_channel[SEM_TALK],
2896          &tc_magic_child,
2897          sizeof (tc_magic_child));
2898
2899   /* Wait for acknowledgement from the parent. */
2900   read (startup_semaphore.parent_channel[SEM_LISTEN],
2901         &tc_magic_parent,
2902         sizeof (tc_magic_parent));
2903         
2904   if (tc_magic_child != tc_magic_parent)
2905     warning ("mismatched semaphore magic");
2906
2907   /* Discard our copy of the semaphore. */
2908   (void) close (startup_semaphore.parent_channel[SEM_LISTEN]);
2909   (void) close (startup_semaphore.parent_channel[SEM_TALK]);
2910   (void) close (startup_semaphore.child_channel[SEM_LISTEN]);
2911   (void) close (startup_semaphore.child_channel[SEM_TALK]);
2912   
2913   return tt_status;
2914 }
2915
2916 /* Despite being file-local, this routine is dealing with
2917  * actual process IDs, not thread ids.  That's because it's
2918  * called before the first "wait" call, and there's no map
2919  * yet from tids to pids.
2920  *
2921  * When it is called, a forked child is running, but waiting on
2922  * the semaphore.  If you stop the child and re-start it,
2923  * things get confused, so don't do that!  An attached child is
2924  * stopped.
2925  *
2926  * Since this is called after either attach or run, we
2927  * have to be the common part of both.
2928  */
2929 static void
2930 require_notification_of_events ( real_pid )
2931   int  real_pid;
2932 {
2933   int  tt_status;
2934   ttevent_t  notifiable_events;
2935
2936   lwpid_t    tid;
2937   ttstate_t  thread_state;
2938
2939 #ifdef THREAD_DEBUG
2940   if( debug_on )
2941       printf( "Require notif, pid is %d\n", real_pid );
2942 #endif
2943
2944   /* Temporary HACK: tell inftarg.c/child_wait to not
2945    * loop until pids are the same.
2946    */
2947   not_same_real_pid = 0;
2948
2949   sigemptyset (&notifiable_events.tte_signals);
2950   notifiable_events.tte_opts = TTEO_NONE;
2951
2952   /* This ensures that forked children inherit their parent's
2953    * event mask, which we're setting here.
2954    *
2955    * NOTE: if you debug gdb with itself, then the ultimate
2956    *       debuggee gets flags set by the outermost gdb, as
2957    *       a child of a child will still inherit.
2958    */
2959   notifiable_events.tte_opts |= TTEO_PROC_INHERIT;
2960
2961   notifiable_events.tte_events  = TTEVT_DEFAULT;
2962   notifiable_events.tte_events |= TTEVT_SIGNAL;
2963   notifiable_events.tte_events |= TTEVT_EXEC;
2964   notifiable_events.tte_events |= TTEVT_EXIT;
2965   notifiable_events.tte_events |= TTEVT_FORK;
2966   notifiable_events.tte_events |= TTEVT_VFORK;
2967   notifiable_events.tte_events |= TTEVT_LWP_CREATE;
2968   notifiable_events.tte_events |= TTEVT_LWP_EXIT;
2969   notifiable_events.tte_events |= TTEVT_LWP_TERMINATE;
2970
2971   tt_status = call_real_ttrace (
2972                            TT_PROC_SET_EVENT_MASK,
2973                            real_pid,
2974                            (lwpid_t) TT_NIL,
2975                            (TTRACE_ARG_TYPE) &notifiable_events,
2976                            (TTRACE_ARG_TYPE) sizeof (notifiable_events),
2977                            TT_NIL);
2978 }
2979
2980 static void
2981 require_notification_of_exec_events ( real_pid )
2982   int  real_pid;
2983 {
2984   int  tt_status;
2985   ttevent_t  notifiable_events;
2986
2987   lwpid_t    tid;
2988   ttstate_t  thread_state;
2989
2990 #ifdef THREAD_DEBUG
2991   if( debug_on )
2992       printf( "Require notif, pid is %d\n", real_pid );
2993 #endif
2994
2995   /* Temporary HACK: tell inftarg.c/child_wait to not
2996    * loop until pids are the same.
2997    */
2998   not_same_real_pid = 0;
2999
3000   sigemptyset (&notifiable_events.tte_signals);
3001   notifiable_events.tte_opts = TTEO_NOSTRCCHLD;
3002
3003   /* This ensures that forked children don't inherit their parent's
3004    * event mask, which we're setting here.
3005    */
3006   notifiable_events.tte_opts &= ~TTEO_PROC_INHERIT;
3007
3008   notifiable_events.tte_events  = TTEVT_DEFAULT;
3009   notifiable_events.tte_events |= TTEVT_EXEC;
3010   notifiable_events.tte_events |= TTEVT_EXIT;
3011
3012   tt_status = call_real_ttrace (
3013                            TT_PROC_SET_EVENT_MASK,
3014                            real_pid,
3015                            (lwpid_t) TT_NIL,
3016                            (TTRACE_ARG_TYPE) &notifiable_events,
3017                            (TTRACE_ARG_TYPE) sizeof (notifiable_events),
3018                            TT_NIL);
3019 }
3020
3021 \f
3022 /* This function is called by the parent process, with pid being the
3023  * ID of the child process, after the debugger has forked.
3024  */
3025 void
3026 child_acknowledge_created_inferior (pid)
3027     int  pid;
3028 {
3029   /* We need a memory home for a constant, to pass it to ttrace.
3030      The value of the constant is arbitrary, so long as both
3031      parent and child use the same value.  Might as well use the
3032      "magic" constant provided by ttrace...
3033      */
3034   uint64_t  tc_magic_parent = TT_VERSION;
3035   uint64_t  tc_magic_child = 0;
3036
3037   /* Wait for the child to tell us that it has forked. */
3038   read (startup_semaphore.child_channel[SEM_LISTEN],
3039         &tc_magic_child,
3040         sizeof(tc_magic_child));
3041
3042   /* Clear thread info now.  We'd like to do this in
3043    * "require...", but that messes up attach.
3044    */
3045   clear_thread_info();
3046
3047   /* Tell the "rest of gdb" that the initial thread exists.
3048    * This isn't really a hack.  Other thread-based versions
3049    * of gdb (e.g. gnu-nat.c) seem to do the same thing.
3050    *
3051    * Q: Why don't we also add this thread to the local
3052    *    list via "add_tthread"?
3053    *
3054    * A: Because we don't know the tid, and can't stop the
3055    *    the process safely to ask what it is.  Anyway, we'll
3056    *    add it when it gets the EXEC event.
3057    */
3058   add_thread( pid );       /* in thread.c */
3059
3060   /* We can now set the child's ttrace event mask.
3061    */
3062   require_notification_of_exec_events (pid);
3063
3064   /* Tell ourselves that the process is running.
3065    */
3066   process_state = RUNNING;
3067
3068   /* Notify the child that it can exec. */
3069   write (startup_semaphore.parent_channel[SEM_TALK],
3070          &tc_magic_parent,
3071          sizeof (tc_magic_parent));
3072
3073   /* Discard our copy of the semaphore. */
3074   (void) close (startup_semaphore.parent_channel[SEM_LISTEN]);
3075   (void) close (startup_semaphore.parent_channel[SEM_TALK]);
3076   (void) close (startup_semaphore.child_channel[SEM_LISTEN]);
3077   (void) close (startup_semaphore.child_channel[SEM_TALK]);
3078 }
3079
3080
3081 /*
3082  * arrange for notification of all events by
3083  * calling require_notification_of_events.
3084  */
3085 void
3086 child_post_startup_inferior ( real_pid)
3087   int  real_pid;
3088 {
3089   require_notification_of_events (real_pid);
3090 }
3091
3092 /* From here on, we should expect tids rather than pids.
3093  */
3094 static void
3095 hppa_enable_catch_fork (tid)
3096   int  tid;
3097 {
3098   int        tt_status;
3099   ttevent_t  ttrace_events;
3100
3101   /* Get the set of events that are currently enabled.
3102    */
3103   tt_status = call_ttrace (TT_PROC_GET_EVENT_MASK,
3104                            tid,
3105                            (TTRACE_ARG_TYPE) &ttrace_events,
3106                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
3107                            TT_NIL );
3108   if (errno)
3109     perror_with_name ("ttrace");
3110
3111   /* Add forks to that set. */
3112   ttrace_events.tte_events |= TTEVT_FORK;
3113
3114 #ifdef THREAD_DEBUG
3115   if( debug_on )
3116       printf( "enable fork, tid is %d\n", tid );
3117 #endif
3118
3119   tt_status = call_ttrace (TT_PROC_SET_EVENT_MASK,
3120                            tid,
3121                            (TTRACE_ARG_TYPE) &ttrace_events,
3122                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
3123                            TT_NIL);
3124   if (errno)
3125     perror_with_name ("ttrace");
3126 }
3127
3128
3129 static void
3130 hppa_disable_catch_fork (tid)
3131   int  tid;
3132 {
3133   int        tt_status;
3134   ttevent_t  ttrace_events;
3135
3136   /* Get the set of events that are currently enabled.
3137    */
3138   tt_status = call_ttrace (TT_PROC_GET_EVENT_MASK,
3139                            tid,
3140                            (TTRACE_ARG_TYPE) &ttrace_events,
3141                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
3142                            TT_NIL);
3143
3144   if (errno)
3145     perror_with_name ("ttrace");
3146
3147   /* Remove forks from that set. */
3148   ttrace_events.tte_events &= ~TTEVT_FORK;
3149
3150 #ifdef THREAD_DEBUG
3151   if( debug_on )
3152       printf("disable fork, tid is %d\n", tid );
3153 #endif
3154
3155   tt_status = call_ttrace (TT_PROC_SET_EVENT_MASK,
3156                            tid,
3157                            (TTRACE_ARG_TYPE) &ttrace_events,
3158                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
3159                            TT_NIL);
3160
3161   if (errno)
3162     perror_with_name ("ttrace");
3163 }
3164
3165
3166 #if defined(CHILD_INSERT_FORK_CATCHPOINT)
3167 int
3168 child_insert_fork_catchpoint (tid)
3169   int  tid;
3170 {
3171   /* Enable reporting of fork events from the kernel. */
3172   /* ??rehrauer: For the moment, we're always enabling these events,
3173      and just ignoring them if there's no catchpoint to catch them.
3174      */
3175   return 0;
3176 }
3177 #endif
3178
3179
3180 #if defined(CHILD_REMOVE_FORK_CATCHPOINT)
3181 int
3182 child_remove_fork_catchpoint (tid)
3183   int  tid;
3184 {
3185   /* Disable reporting of fork events from the kernel. */
3186   /* ??rehrauer: For the moment, we're always enabling these events,
3187      and just ignoring them if there's no catchpoint to catch them.
3188      */
3189   return 0;
3190 }
3191 #endif
3192
3193
3194 static void
3195 hppa_enable_catch_vfork (tid)
3196   int  tid;
3197 {
3198   int  tt_status;
3199   ttevent_t  ttrace_events;
3200
3201   /* Get the set of events that are currently enabled.
3202    */
3203   tt_status = call_ttrace (TT_PROC_GET_EVENT_MASK,
3204                            tid,
3205                            (TTRACE_ARG_TYPE) &ttrace_events,
3206                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
3207                            TT_NIL);
3208
3209   if (errno)
3210     perror_with_name ("ttrace");
3211
3212   /* Add vforks to that set. */
3213   ttrace_events.tte_events |= TTEVT_VFORK;
3214
3215 #ifdef THREAD_DEBUG
3216   if( debug_on )
3217       printf("enable vfork, tid is %d\n", tid );
3218 #endif
3219
3220   tt_status = call_ttrace (TT_PROC_SET_EVENT_MASK,
3221                            tid,
3222                            (TTRACE_ARG_TYPE) &ttrace_events,
3223                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
3224                            TT_NIL);
3225
3226   if (errno)
3227     perror_with_name ("ttrace");
3228 }
3229
3230
3231 static void
3232 hppa_disable_catch_vfork (tid)
3233   int  tid;
3234 {
3235   int  tt_status;
3236   ttevent_t  ttrace_events;
3237
3238   /* Get the set of events that are currently enabled. */
3239   tt_status = call_ttrace (TT_PROC_GET_EVENT_MASK,
3240                            tid,
3241                            (TTRACE_ARG_TYPE) &ttrace_events,
3242                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
3243                            TT_NIL);
3244
3245   if (errno)
3246     perror_with_name ("ttrace");
3247
3248   /* Remove vforks from that set. */
3249   ttrace_events.tte_events &= ~TTEVT_VFORK;
3250
3251 #ifdef THREAD_DEBUG
3252   if( debug_on )
3253       printf("disable vfork, tid is %d\n", tid );
3254 #endif
3255   tt_status = call_ttrace (TT_PROC_SET_EVENT_MASK,
3256                            tid,
3257                            (TTRACE_ARG_TYPE) &ttrace_events,
3258                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
3259                            TT_NIL);
3260
3261   if (errno)
3262     perror_with_name ("ttrace");
3263 }
3264
3265
3266 #if defined(CHILD_INSERT_VFORK_CATCHPOINT)
3267 int
3268 child_insert_vfork_catchpoint (tid)
3269   int  tid;
3270 {
3271   /* Enable reporting of vfork events from the kernel. */
3272   /* ??rehrauer: For the moment, we're always enabling these events,
3273      and just ignoring them if there's no catchpoint to catch them.
3274      */
3275   return 0;
3276 }
3277 #endif
3278
3279
3280 #if defined(CHILD_REMOVE_VFORK_CATCHPOINT)
3281 int
3282 child_remove_vfork_catchpoint (tid)
3283   int  tid;
3284 {
3285   /* Disable reporting of vfork events from the kernel. */
3286   /* ??rehrauer: For the moment, we're always enabling these events,
3287      and just ignoring them if there's no catchpoint to catch them.
3288      */
3289   return 0;
3290 }
3291 #endif
3292
3293 #if defined(CHILD_HAS_FORKED)
3294
3295 /* Q: Do we need to map the returned process ID to a thread ID?
3296  *
3297  * A: I don't think so--here we want a _real_ pid.  Any later
3298  *    operations will call "require_notification_of_events" and
3299  *    start the mapping.
3300  */
3301 int
3302 child_has_forked (tid, childpid)
3303   int  tid;
3304   int *childpid;
3305 {
3306   int  tt_status;
3307   ttstate_t  ttrace_state;
3308   thread_info *  tinfo;
3309
3310   /* Do we have cached thread state that we can consult?  If so, use it. */
3311   tinfo = find_thread_info (map_from_gdb_tid (tid));
3312   if (tinfo != NULL) {
3313     copy_ttstate_t (&ttrace_state, &tinfo->last_stop_state);
3314   }
3315
3316   /* Nope, must read the thread's current state */
3317   else
3318     {
3319       tt_status = call_ttrace (TT_LWP_GET_STATE,
3320                                tid,
3321                                (TTRACE_ARG_TYPE) &ttrace_state,
3322                                (TTRACE_ARG_TYPE) sizeof (ttrace_state),
3323                                TT_NIL);
3324
3325       if (errno)
3326         perror_with_name ("ttrace");
3327     
3328       if (tt_status < 0)
3329         return 0;
3330     }
3331
3332   if (ttrace_state.tts_event & TTEVT_FORK)
3333     {
3334       *childpid = ttrace_state.tts_u.tts_fork.tts_fpid;
3335       return 1;
3336     }
3337
3338   return 0;
3339 }
3340 #endif
3341
3342
3343 #if defined(CHILD_HAS_VFORKED)
3344
3345 /* See child_has_forked for pid discussion.
3346  */
3347 int
3348 child_has_vforked (tid, childpid)
3349   int  tid;
3350   int *  childpid;
3351 {
3352   int  tt_status;
3353   ttstate_t  ttrace_state;
3354   thread_info *  tinfo;
3355
3356   /* Do we have cached thread state that we can consult?  If so, use it. */
3357   tinfo = find_thread_info (map_from_gdb_tid (tid));
3358   if (tinfo != NULL)
3359     copy_ttstate_t (&ttrace_state, &tinfo->last_stop_state);
3360
3361   /* Nope, must read the thread's current state */
3362   else
3363     {
3364       tt_status = call_ttrace (TT_LWP_GET_STATE,
3365                                tid,
3366                                (TTRACE_ARG_TYPE) &ttrace_state,
3367                                (TTRACE_ARG_TYPE) sizeof (ttrace_state),
3368                                TT_NIL);
3369
3370       if (errno)
3371         perror_with_name ("ttrace");
3372     
3373       if (tt_status < 0)
3374         return 0;
3375     }
3376
3377   if (ttrace_state.tts_event & TTEVT_VFORK)
3378     {
3379       *childpid = ttrace_state.tts_u.tts_fork.tts_fpid;
3380       return 1;
3381     }
3382
3383   return 0;
3384 }
3385 #endif
3386
3387
3388 #if defined(CHILD_CAN_FOLLOW_VFORK_PRIOR_TO_EXEC)
3389 int
3390 child_can_follow_vfork_prior_to_exec ()
3391 {
3392   /* ttrace does allow this.
3393
3394      ??rehrauer: However, I had major-league problems trying to
3395      convince wait_for_inferior to handle that case.  Perhaps when
3396      it is rewritten to grok multiple processes in an explicit way...
3397      */
3398   return 0;
3399 }
3400 #endif
3401
3402
3403 #if defined(CHILD_INSERT_EXEC_CATCHPOINT)
3404 int
3405 child_insert_exec_catchpoint (tid)
3406   int  tid;
3407 {
3408   /* Enable reporting of exec events from the kernel. */
3409   /* ??rehrauer: For the moment, we're always enabling these events,
3410      and just ignoring them if there's no catchpoint to catch them.
3411      */
3412   return 0;
3413 }
3414 #endif
3415
3416
3417 #if defined(CHILD_REMOVE_EXEC_CATCHPOINT)
3418 int
3419 child_remove_exec_catchpoint (tid)
3420   int  tid;
3421 {
3422   /* Disable reporting of execevents from the kernel. */
3423   /* ??rehrauer: For the moment, we're always enabling these events,
3424      and just ignoring them if there's no catchpoint to catch them.
3425      */
3426   return 0;
3427 }
3428 #endif
3429
3430
3431 #if defined(CHILD_HAS_EXECD)
3432 int
3433 child_has_execd (tid, execd_pathname)
3434   int  tid;
3435   char **  execd_pathname;
3436 {
3437   int  tt_status;
3438   ttstate_t  ttrace_state;
3439   thread_info *  tinfo;
3440
3441   /* Do we have cached thread state that we can consult?  If so, use it. */
3442   tinfo = find_thread_info (map_from_gdb_tid (tid));
3443   if (tinfo != NULL)
3444     copy_ttstate_t (&ttrace_state, &tinfo->last_stop_state);
3445
3446   /* Nope, must read the thread's current state */
3447   else
3448     {
3449       tt_status = call_ttrace (TT_LWP_GET_STATE,
3450                                tid,
3451                                (TTRACE_ARG_TYPE) &ttrace_state,
3452                                (TTRACE_ARG_TYPE) sizeof (ttrace_state),
3453                                TT_NIL);
3454
3455       if (errno)
3456         perror_with_name ("ttrace");
3457     
3458       if (tt_status < 0)
3459         return 0;
3460     }
3461
3462   if (ttrace_state.tts_event & TTEVT_EXEC)
3463     {
3464       /* See child_pid_to_exec_file in this file: this is a macro.
3465        */
3466       char *  exec_file = target_pid_to_exec_file (tid);
3467       
3468       *execd_pathname = savestring (exec_file, strlen (exec_file));
3469       return 1;
3470     }
3471
3472   return 0;
3473 }
3474 #endif
3475
3476
3477 #if defined(CHILD_HAS_SYSCALL_EVENT)
3478 int
3479 child_has_syscall_event (pid, kind, syscall_id)
3480   int  pid;
3481   enum target_waitkind *  kind;
3482   int *  syscall_id;
3483 {
3484   int  tt_status;
3485   ttstate_t  ttrace_state;
3486   thread_info *  tinfo;
3487
3488   /* Do we have cached thread state that we can consult?  If so, use it. */
3489   tinfo = find_thread_info (map_from_gdb_tid (pid));
3490   if (tinfo != NULL)
3491     copy_ttstate_t (&ttrace_state, &tinfo->last_stop_state);
3492
3493   /* Nope, must read the thread's current state */
3494   else
3495     {
3496     tt_status = call_ttrace (TT_LWP_GET_STATE,
3497                                pid,
3498                                (TTRACE_ARG_TYPE) &ttrace_state,
3499                                (TTRACE_ARG_TYPE) sizeof (ttrace_state),
3500                                TT_NIL);
3501
3502       if (errno)
3503         perror_with_name ("ttrace");
3504     
3505       if (tt_status < 0)
3506         return 0;
3507     }
3508
3509   *kind = TARGET_WAITKIND_SPURIOUS;  /* Until proven otherwise... */
3510   *syscall_id = -1;
3511
3512   if (ttrace_state.tts_event & TTEVT_SYSCALL_ENTRY)
3513     *kind = TARGET_WAITKIND_SYSCALL_ENTRY;
3514   else if (ttrace_state.tts_event & TTEVT_SYSCALL_RETURN)
3515     *kind = TARGET_WAITKIND_SYSCALL_RETURN;
3516   else
3517     return 0;
3518
3519   *syscall_id = ttrace_state.tts_scno;
3520   return 1;
3521 }
3522 #endif
3523
3524
3525 \f
3526 #if defined(CHILD_THREAD_ALIVE)
3527
3528 /* Check to see if the given thread is alive.
3529  *
3530  * We'll trust the thread list, as the more correct
3531  * approach of stopping the process and spinning down
3532  * the OS's thread list is _very_ expensive.
3533  *
3534  * May need a FIXME for that reason.
3535  */
3536 int
3537 child_thread_alive (gdb_tid)
3538      lwpid_t gdb_tid;
3539 {
3540    lwpid_t  tid;
3541
3542    /* This spins down the lists twice.
3543     * Possible peformance improvement here!
3544     */
3545    tid = map_from_gdb_tid( gdb_tid );
3546    return !is_terminated( tid );
3547 }
3548
3549 #endif
3550
3551
3552 \f
3553 /* This function attempts to read the specified number of bytes from the
3554    save_state_t that is our view into the hardware registers, starting at
3555    ss_offset, and ending at ss_offset + sizeof_buf - 1
3556
3557    If this function succeeds, it deposits the fetched bytes into buf,
3558    and returns 0.
3559
3560    If it fails, it returns a negative result.  The contents of buf are
3561    undefined it this function fails.
3562    */
3563 int
3564 read_from_register_save_state (tid, ss_offset, buf, sizeof_buf)
3565     int  tid;
3566     TTRACE_ARG_TYPE  ss_offset;
3567     char *  buf;
3568     int  sizeof_buf;
3569 {
3570   int  tt_status;
3571   register_value_t  register_value = 0;
3572
3573   tt_status = call_ttrace (TT_LWP_RUREGS,
3574                            tid,
3575                            ss_offset,
3576                            (TTRACE_ARG_TYPE) sizeof_buf,
3577                            (TTRACE_ARG_TYPE) buf);
3578
3579   if( tt_status == 1 )
3580       /* Map ttrace's version of success to our version.
3581        * Sometime ttrace returns 0, but that's ok here.
3582        */
3583       return 0;
3584       
3585   return tt_status;
3586 }
3587
3588 \f
3589 /* This function attempts to write the specified number of bytes to the
3590    save_state_t that is our view into the hardware registers, starting at
3591    ss_offset, and ending at ss_offset + sizeof_buf - 1
3592
3593    If this function succeeds, it deposits the bytes in buf, and returns 0.
3594
3595    If it fails, it returns a negative result.  The contents of the save_state_t
3596    are undefined it this function fails.
3597    */
3598 int
3599 write_to_register_save_state (tid, ss_offset, buf, sizeof_buf)
3600     int  tid;
3601     TTRACE_ARG_TYPE  ss_offset;
3602     char *  buf;
3603     int  sizeof_buf;
3604 {
3605   int  tt_status;
3606   register_value_t  register_value = 0;
3607
3608   tt_status = call_ttrace (TT_LWP_WUREGS,
3609                            tid,
3610                            ss_offset,
3611                            (TTRACE_ARG_TYPE) sizeof_buf,
3612                            (TTRACE_ARG_TYPE) buf);
3613   return tt_status;
3614 }
3615
3616 \f
3617 /* This function is a sop to the largeish number of direct calls
3618    to call_ptrace that exist in other files.  Rather than create
3619    functions whose name abstracts away from ptrace, and change all
3620    the present callers of call_ptrace, we'll do the expedient (and
3621    perhaps only practical) thing.
3622
3623    Note HP-UX explicitly disallows a mix of ptrace & ttrace on a traced
3624    process.  Thus, we must translate all ptrace requests into their
3625    process-specific, ttrace equivalents.
3626    */
3627 int
3628 call_ptrace (pt_request, gdb_tid, addr, data)
3629      int               pt_request;
3630      int               gdb_tid;
3631      PTRACE_ARG3_TYPE  addr;
3632      int               data;
3633 {
3634   ttreq_t           tt_request;
3635   TTRACE_ARG_TYPE   tt_addr = (TTRACE_ARG_TYPE) addr;
3636   TTRACE_ARG_TYPE   tt_data = (TTRACE_ARG_TYPE) data;
3637   TTRACE_ARG_TYPE   tt_addr2 = TT_NIL;
3638   int               tt_status;
3639   register_value_t  register_value;
3640   int               read_buf;
3641
3642   /* Perform the necessary argument translation.  Note that some
3643      cases are funky enough in the ttrace realm that we handle them
3644      very specially.
3645    */
3646   switch (pt_request) {
3647       /* The following cases cannot conveniently be handled conveniently
3648          by merely adjusting the ptrace arguments and feeding into the
3649          generic call to ttrace at the bottom of this function.
3650
3651          Note that because all branches of this switch end in "return",
3652          there's no need for any "break" statements.
3653          */
3654       case PT_SETTRC :
3655           return parent_attach_all ();
3656           
3657       case PT_RUREGS :
3658           tt_status = read_from_register_save_state (gdb_tid,
3659                                                      tt_addr,
3660                                                      &register_value,
3661                                                      sizeof (register_value));
3662           if (tt_status < 0)
3663             return tt_status;
3664           return register_value;
3665
3666       case PT_WUREGS :
3667           register_value = (int) tt_data;
3668           tt_status = write_to_register_save_state (gdb_tid,
3669                                                     tt_addr,
3670                                                     &register_value,
3671                                                     sizeof (register_value));
3672           return tt_status;
3673           break;
3674
3675       case PT_READ_I :
3676           tt_status = call_ttrace (TT_PROC_RDTEXT,  /* Implicit 4-byte xfer becomes block-xfer. */
3677                                    gdb_tid,
3678                                    tt_addr,
3679                                    (TTRACE_ARG_TYPE) 4,
3680                                    (TTRACE_ARG_TYPE) &read_buf);
3681           if (tt_status < 0)
3682             return tt_status;
3683           return read_buf;
3684
3685       case PT_READ_D :
3686           tt_status = call_ttrace (TT_PROC_RDDATA,  /* Implicit 4-byte xfer becomes block-xfer. */
3687                                    gdb_tid,
3688                                    tt_addr,
3689                                    (TTRACE_ARG_TYPE) 4,
3690                                    (TTRACE_ARG_TYPE) &read_buf);
3691           if (tt_status < 0)
3692             return tt_status;
3693           return read_buf;
3694
3695       case PT_ATTACH :
3696           tt_status = call_real_ttrace (TT_PROC_ATTACH,
3697                                         map_from_gdb_tid (gdb_tid),
3698                                         (lwpid_t) TT_NIL,
3699                                         tt_addr,
3700                                         (TTRACE_ARG_TYPE) TT_VERSION,
3701                                         tt_addr2);
3702           if (tt_status < 0)
3703             return tt_status;
3704           return tt_status;
3705
3706       /* The following cases are handled by merely adjusting the ptrace
3707          arguments and feeding into the generic call to ttrace.
3708          */
3709       case PT_DETACH :
3710           tt_request = TT_PROC_DETACH;
3711           break;
3712
3713       case PT_WRITE_I :
3714           tt_request = TT_PROC_WRTEXT;  /* Translates 4-byte xfer to block-xfer. */
3715           tt_data = 4;                  /* This many bytes. */
3716           tt_addr2 = (TTRACE_ARG_TYPE) &data;  /* Address of xfer source. */
3717           break;
3718
3719       case PT_WRITE_D :
3720           tt_request = TT_PROC_WRDATA;  /* Translates 4-byte xfer to block-xfer. */
3721           tt_data = 4;                  /* This many bytes. */
3722           tt_addr2 = (TTRACE_ARG_TYPE) &data;  /* Address of xfer source. */
3723           break;
3724
3725       case PT_RDTEXT :
3726           tt_request = TT_PROC_RDTEXT;
3727           break;
3728
3729       case PT_RDDATA :
3730           tt_request = TT_PROC_RDDATA;
3731           break;
3732
3733       case PT_WRTEXT :
3734           tt_request = TT_PROC_WRTEXT;
3735           break;
3736
3737       case PT_WRDATA :
3738           tt_request = TT_PROC_WRDATA;
3739           break;
3740
3741       case PT_CONTINUE :
3742           tt_request = TT_PROC_CONTINUE;
3743           break;
3744
3745       case PT_STEP :
3746           tt_request = TT_LWP_SINGLE;  /* Should not be making this request? */
3747           break;
3748
3749       case PT_KILL :
3750           tt_request = TT_PROC_EXIT;
3751           break;
3752
3753       case PT_GET_PROCESS_PATHNAME :
3754           tt_request = TT_PROC_GET_PATHNAME;
3755           break;
3756
3757       default :
3758           tt_request = pt_request;  /* Let ttrace be the one to complain. */
3759           break;
3760   }
3761
3762   return call_ttrace (tt_request,
3763                       gdb_tid,
3764                       tt_addr,
3765                       tt_data,
3766                       tt_addr2);
3767 }
3768
3769 /* Kill that pesky process!
3770  */
3771 void
3772 kill_inferior ()
3773 {
3774   int  tid;
3775   int  wait_status;
3776   thread_info *  t;
3777   thread_info **paranoia;
3778   int           para_count, i;
3779
3780   if (inferior_pid == 0)
3781     return;
3782
3783   /* Walk the list of "threads", some of which are "pseudo threads",
3784      aka "processes".  For each that is NOT inferior_pid, stop it,
3785      and detach it.
3786
3787      You see, we may not have just a single process to kill.  If we're
3788      restarting or quitting or detaching just after the inferior has
3789      forked, then we've actually two processes to clean up.
3790
3791      But we can't just call target_mourn_inferior() for each, since that
3792      zaps the target vector.
3793      */
3794
3795   paranoia = (thread_info **) malloc( thread_head.count *
3796                                       sizeof(thread_info *));
3797   para_count = 0;
3798   
3799   t = thread_head.head;
3800   while (t) {
3801   
3802     paranoia[ para_count ] = t;
3803     for( i = 0; i < para_count; i++ ){
3804         if( t->next == paranoia[i] ) {
3805             warning( "Bad data in gdb's thread data; repairing." );
3806             t->next = 0;
3807         }
3808     }
3809     para_count++;
3810
3811     if (t->am_pseudo && (t->pid != inferior_pid))
3812       {
3813         /* TT_PROC_STOP doesn't require a subsequent ttrace_wait, as it
3814          * generates no event.
3815          */
3816         call_ttrace (TT_PROC_STOP,
3817                      t->pid,
3818                      TT_NIL,
3819                      TT_NIL,
3820                      TT_NIL);
3821
3822         call_ttrace (TT_PROC_DETACH,
3823                      t->pid,
3824                      TT_NIL,
3825                      (TTRACE_ARG_TYPE) TARGET_SIGNAL_0,
3826                      TT_NIL);
3827       }
3828     t = t->next;
3829   }
3830
3831   free( paranoia );
3832   
3833   call_ttrace (TT_PROC_STOP,
3834                inferior_pid,
3835                TT_NIL,
3836                TT_NIL,
3837                TT_NIL);
3838   target_mourn_inferior ();
3839   clear_thread_info();
3840 }
3841
3842
3843 #ifndef CHILD_RESUME
3844
3845 /* Sanity check a thread about to be continued.
3846  */
3847 static void
3848 thread_dropping_event_check( p )
3849     thread_info *p;
3850 {
3851     if( !p->handled ) {
3852         /*
3853          * This seems to happen when we "next" over a
3854          * "fork()" while following the parent.  If it's
3855          * the FORK event, that's ok.  If it's a SIGNAL
3856          * in the unfollowed child, that's ok to--but
3857          * how can we know that's what's going on?
3858          *
3859          * FIXME!
3860          */
3861          if( p->have_state ) {
3862              if( p->last_stop_state.tts_event == TTEVT_FORK ) {
3863                  /* Ok */
3864                  ;
3865              }
3866              else if( p->last_stop_state.tts_event == TTEVT_SIGNAL ) {
3867                  /* Ok, close eyes and let it happen.
3868                   */
3869                  ;
3870              }
3871              else {
3872                  /* This shouldn't happen--we're dropping a
3873                   * real event.
3874                   */
3875                  warning( "About to continue process %d, thread %d with unhandled event %s.",
3876                          p->pid, p->tid,
3877                          get_printable_name_of_ttrace_event(
3878                                    p->last_stop_state.tts_event ));
3879
3880 #ifdef PARANOIA
3881                  if( debug_on )
3882                      print_tthread( p );
3883 #endif
3884             }
3885         }
3886         else {
3887             /* No saved state, have to assume it failed.
3888              */
3889             warning( "About to continue process %d, thread %d with unhandled event.",
3890                      p->pid, p->tid );
3891 #ifdef PARANOIA
3892             if( debug_on )
3893                 print_tthread( p );
3894 #endif
3895         }
3896     }
3897     
3898 }   /* thread_dropping_event_check */
3899
3900 /* Use a loop over the threads to continue all the threads but
3901  * the one specified, which is to be stepped.
3902  */
3903 static void
3904 threads_continue_all_but_one( gdb_tid, signal )
3905     lwpid_t gdb_tid;
3906     int     signal;
3907 {
3908     thread_info  *p;
3909     int           thread_signal;
3910     lwpid_t       real_tid;
3911     lwpid_t       scan_tid;
3912     ttstate_t     state;
3913     int           real_pid;
3914     
3915 #ifdef THREAD_DEBUG
3916     if( debug_on )
3917         printf( "Using loop over threads to step/resume with signals\n" );
3918 #endif
3919
3920     /* First update the thread list.
3921      */
3922     set_all_unseen();
3923     real_tid = map_from_gdb_tid( gdb_tid );
3924     real_pid = get_pid_for( real_tid );
3925     
3926     scan_tid = get_process_first_stopped_thread_id( real_pid, &state );
3927     while ( 0 != scan_tid ) {
3928     
3929 #ifdef THREAD_DEBUG
3930         /* FIX: later should check state is stopped;
3931          * state.tts_flags & TTS_STATEMASK == TTS_WASSUSPENDED
3932          */
3933         if( debug_on )
3934             if( state.tts_flags & TTS_STATEMASK != TTS_WASSUSPENDED )
3935                 printf( "About to continue non-stopped thread %d\n", scan_tid );
3936 #endif
3937
3938         p = find_thread_info( scan_tid );
3939         if( NULL == p ) {
3940             add_tthread( real_pid, scan_tid );
3941             p = find_thread_info( scan_tid );
3942
3943             /* This is either a newly-created thread or the
3944              * result of a fork; in either case there's no
3945              * actual event to worry about.
3946              */
3947             p->handled = 1;
3948
3949             if( state.tts_event != TTEVT_NONE ) {
3950                 /* Oops, do need to worry!
3951                  */
3952                 warning( "Unexpected thread with \"%s\" event.",
3953                     get_printable_name_of_ttrace_event( state.tts_event ));
3954             }
3955         }
3956         else if( scan_tid != p->tid )
3957             error( "Bad data in thread database." );
3958
3959 #ifdef THREAD_DEBUG
3960         if( debug_on )
3961             if( p->terminated )
3962                 printf( "Why are we continuing a dead thread?\n" );
3963 #endif
3964
3965         p->seen = 1;
3966             
3967         scan_tid = get_process_next_stopped_thread_id( real_pid, &state );
3968     }
3969
3970     /* Remove unseen threads.
3971      */
3972     update_thread_list();
3973
3974     /* Now run down the thread list and continue or step.
3975      */
3976     for( p = thread_head.head; p; p = p->next ) {
3977
3978         /* Sanity check.
3979          */
3980         thread_dropping_event_check( p );
3981
3982         /* Pass the correct signals along.
3983          */
3984         if( p->have_signal ) {
3985             thread_signal  = p->signal_value;
3986             p->have_signal = 0;
3987         }
3988         else
3989             thread_signal = 0;
3990              
3991         if( p->tid != real_tid ) {
3992             /*
3993              * Not the thread of interest, so continue it
3994              * as the user expects.
3995              */
3996             if( p->stepping_mode == DO_STEP ) {
3997                 /* Just step this thread.
3998                  */
3999                 call_ttrace(
4000                      TT_LWP_SINGLE,
4001                      p->tid,
4002                      TT_USE_CURRENT_PC,
4003                      (TTRACE_ARG_TYPE) target_signal_to_host( signal ),
4004                      TT_NIL );
4005             }
4006             else {
4007                 /* Regular continue (default case).
4008                  */
4009                 call_ttrace(
4010                          TT_LWP_CONTINUE,
4011                          p->tid,
4012                          TT_USE_CURRENT_PC,
4013                          (TTRACE_ARG_TYPE) target_signal_to_host( thread_signal ),
4014                          TT_NIL );
4015             }
4016         }
4017         else {
4018            /* Step the thread of interest.
4019             */
4020             call_ttrace(
4021                      TT_LWP_SINGLE,
4022                      real_tid,
4023                      TT_USE_CURRENT_PC,
4024                      (TTRACE_ARG_TYPE) target_signal_to_host( signal ),
4025                      TT_NIL );
4026         }   
4027     }   /* Loop over threads */
4028 }   /* End threads_continue_all_but_one */
4029
4030 /* Use a loop over the threads to continue all the threads.
4031  * This is done when a signal must be sent to any of the threads.
4032  */
4033 static void
4034 threads_continue_all_with_signals( gdb_tid, signal )
4035     lwpid_t gdb_tid;
4036     int     signal;
4037 {
4038     thread_info  *p;
4039     int           thread_signal;
4040     lwpid_t       real_tid;
4041     lwpid_t       scan_tid;
4042     ttstate_t     state;
4043     int           real_pid;
4044
4045 #ifdef THREAD_DEBUG
4046     if( debug_on )
4047         printf( "Using loop over threads to resume with signals\n" );
4048 #endif
4049
4050     /* Scan and update thread list.
4051      */
4052     set_all_unseen();
4053     real_tid = map_from_gdb_tid( gdb_tid ); 
4054     real_pid = get_pid_for( real_tid );
4055
4056     scan_tid = get_process_first_stopped_thread_id( real_pid, &state );
4057     while ( 0 != scan_tid ) {
4058     
4059 #ifdef THREAD_DEBUG
4060         if( debug_on )
4061             if( state.tts_flags & TTS_STATEMASK != TTS_WASSUSPENDED )
4062                 warning( "About to continue non-stopped thread %d\n", scan_tid );
4063 #endif
4064
4065         p = find_thread_info( scan_tid );
4066         if( NULL == p ) {
4067             add_tthread( real_pid, scan_tid );
4068             p = find_thread_info( scan_tid );
4069
4070             /* This is either a newly-created thread or the
4071              * result of a fork; in either case there's no
4072              * actual event to worry about.
4073              */
4074             p->handled = 1;
4075
4076             if( state.tts_event != TTEVT_NONE ) {
4077                 /* Oops, do need to worry!
4078                  */
4079                 warning( "Unexpected thread with \"%s\" event.",
4080                     get_printable_name_of_ttrace_event( state.tts_event ));
4081             }
4082         }
4083
4084 #ifdef THREAD_DEBUG
4085         if( debug_on )
4086             if( p->terminated )
4087                 printf( "Why are we continuing a dead thread? (1)\n" );
4088 #endif
4089
4090         p->seen = 1;
4091
4092         scan_tid = get_process_next_stopped_thread_id( real_pid, &state );
4093     }
4094
4095     /* Remove unseen threads from our list.
4096      */
4097     update_thread_list();
4098
4099     /* Continue the threads.
4100      */
4101     for( p = thread_head.head; p; p = p->next ) {
4102
4103         /* Sanity check.
4104          */
4105         thread_dropping_event_check( p );
4106
4107         /* Pass the correct signals along.
4108          */
4109         if( p->tid == real_tid ) {
4110             thread_signal  = signal;
4111             p->have_signal = 0;
4112         }
4113         else if( p->have_signal ) {
4114             thread_signal  = p->signal_value;
4115             p->have_signal = 0;
4116         }
4117         else
4118             thread_signal  = 0;
4119
4120         if( p->stepping_mode == DO_STEP ) {
4121             call_ttrace(
4122                      TT_LWP_SINGLE,
4123                      p->tid,
4124                      TT_USE_CURRENT_PC,
4125                      (TTRACE_ARG_TYPE) target_signal_to_host( signal ),
4126                      TT_NIL );
4127         }
4128         else {
4129             /* Continue this thread (default case).
4130              */
4131             call_ttrace(
4132                     TT_LWP_CONTINUE,
4133                     p->tid,
4134                     TT_USE_CURRENT_PC,
4135                     (TTRACE_ARG_TYPE) target_signal_to_host( thread_signal ),
4136                     TT_NIL );
4137         }
4138     }
4139 }   /* End threads_continue_all_with_signals */
4140
4141 /* Step one thread only.  
4142  */
4143 static void
4144 thread_fake_step( tid, signal )
4145     lwpid_t            tid;
4146     enum target_signal signal;
4147 {
4148     thread_info *p;
4149
4150 #ifdef THREAD_DEBUG
4151     if( debug_on ) {
4152         printf( "Doing a fake-step over a bpt, etc. for %d\n", tid );
4153
4154         if( is_terminated( tid ))
4155             printf( "Why are we continuing a dead thread? (4)\n" );
4156     }
4157 #endif
4158           
4159     if( doing_fake_step )
4160         warning( "Step while step already in progress." );
4161
4162     /* See if there's a saved signal value for this
4163      * thread to be passed on, but no current signal.
4164      */
4165     p = find_thread_info( tid );
4166     if( p != NULL ) {
4167         if( p->have_signal && signal == NULL ) {
4168             /* Pass on a saved signal.
4169              */
4170             signal = p->signal_value;
4171         }
4172         
4173         p->have_signal  = 0;
4174     }
4175
4176     if( !p->handled )
4177         warning( "Internal error: continuing unhandled thread." );
4178         
4179     call_ttrace( TT_LWP_SINGLE,
4180                  tid,
4181                  TT_USE_CURRENT_PC,
4182                  (TTRACE_ARG_TYPE) target_signal_to_host (signal),
4183                  TT_NIL );
4184
4185     /* Do bookkeeping so "call_ttrace_wait" knows it has to wait
4186      * for this thread only, and clear any saved signal info.
4187      */
4188     doing_fake_step   = 1;
4189     fake_step_tid     = tid;
4190
4191 }   /* End thread_fake_step */
4192
4193 /* Continue one thread when a signal must be sent to it.
4194  */
4195 static void
4196 threads_continue_one_with_signal( gdb_tid, signal )
4197     lwpid_t gdb_tid;
4198     int     signal;
4199 {
4200     thread_info  *p;
4201     lwpid_t       real_tid;
4202     int           real_pid;
4203     
4204 #ifdef THREAD_DEBUG
4205     if( debug_on )
4206         printf( "Continuing one thread with a signal\n" );
4207 #endif
4208
4209     real_tid = map_from_gdb_tid( gdb_tid );
4210     real_pid = get_pid_for( real_tid );
4211
4212     p = find_thread_info( real_tid );
4213     if( NULL == p ) {
4214         add_tthread( real_pid, real_tid );
4215     }
4216
4217 #ifdef THREAD_DEBUG
4218     if( debug_on )
4219         if( p->terminated )
4220             printf( "Why are we continuing a dead thread? (2)\n" );
4221 #endif
4222
4223     if( !p->handled )
4224         warning( "Internal error: continuing unhandled thread." );
4225         
4226     p->have_signal = 0;
4227              
4228     call_ttrace( TT_LWP_CONTINUE,
4229                  gdb_tid,
4230                  TT_USE_CURRENT_PC,
4231                  (TTRACE_ARG_TYPE) target_signal_to_host( signal ),
4232                  TT_NIL );
4233 }
4234 #endif
4235
4236 #ifndef CHILD_RESUME
4237
4238 /* Resume execution of the inferior process.
4239  *
4240  * This routine is in charge of setting the "handled" bits. 
4241  *
4242  *   If STEP is zero,      continue it.
4243  *   If STEP is nonzero,   single-step it.
4244  *   
4245  *   If SIGNAL is nonzero, give it that signal.
4246  *
4247  *   If TID is -1,         apply to all threads.
4248  *   If TID is not -1,     apply to specified thread.
4249  *   
4250  *           STEP
4251  *      \      !0                        0
4252  *  TID  \________________________________________________
4253  *       |
4254  *   -1  |   Step current            Continue all threads
4255  *       |   thread and              (but which gets any
4256  *       |   continue others         signal?--We look at
4257  *       |                           "inferior_pid")
4258  *       |
4259  *    N  |   Step _this_ thread      Continue _this_ thread
4260  *       |   and leave others        and leave others 
4261  *       |   stopped; internally     stopped; used only for
4262  *       |   used by gdb, never      hardware watchpoints
4263  *       |   a user command.         and attach, never a
4264  *       |                           user command.
4265  */
4266 void
4267 child_resume( gdb_tid, step, signal )
4268      lwpid_t gdb_tid;
4269      int     step;
4270      enum target_signal signal;
4271 {
4272   int     resume_all_threads;
4273   lwpid_t tid;
4274   process_state_t  new_process_state;
4275
4276   resume_all_threads =
4277     (gdb_tid == INFTTRACE_ALL_THREADS) ||
4278     (vfork_in_flight);
4279
4280   if (resume_all_threads) {
4281     /* Resume all threads, but first pick a tid value
4282      * so we can get the pid when in call_ttrace doing
4283      * the map.
4284      */
4285     if (vfork_in_flight)
4286         tid = vforking_child_pid;
4287     else
4288         tid = map_from_gdb_tid( inferior_pid );
4289   }
4290   else
4291       tid = map_from_gdb_tid( gdb_tid );
4292
4293 #ifdef THREAD_DEBUG
4294   if( debug_on ) {
4295       if( more_events_left )
4296           printf( "More events; " );
4297
4298       if( signal != 0 )
4299           printf( "Sending signal %d; ", signal );
4300       
4301       if( resume_all_threads ) {
4302           if( step == 0 )
4303               printf( "Continue process %d\n", tid );
4304           else
4305               printf( "Step/continue thread %d\n", tid );
4306       }
4307       else {
4308           if( step == 0 )
4309               printf( "Continue thread %d\n", tid );
4310           else
4311               printf( "Step just thread %d\n", tid );
4312       }
4313
4314       if( vfork_in_flight )
4315           printf( "Vfork in flight\n" );
4316   }
4317 #endif
4318
4319   if( process_state == RUNNING )
4320       warning( "Internal error in resume logic; doing resume or step anyway." );
4321       
4322   if(   !step                    /* Asked to continue...       */
4323      && resume_all_threads       /* whole process..            */
4324      && signal != 0              /* with a signal...           */
4325      && more_events_left > 0 ) { /* but we can't yet--save it! */
4326
4327       /* Continue with signal means we have to set the pending
4328        * signal value for this thread.
4329        */
4330       thread_info *k;
4331       
4332 #ifdef THREAD_DEBUG
4333       if( debug_on )
4334            printf( "Saving signal %d for thread %d\n", signal, tid );
4335 #endif
4336
4337        k = find_thread_info( tid );
4338        if( k != NULL ) {
4339            k->have_signal  = 1;
4340            k->signal_value = signal;
4341
4342 #ifdef THREAD_DEBUG
4343            if( debug_on )
4344                if( k->terminated )
4345                    printf( "Why are we continuing a dead thread? (3)\n" );
4346 #endif
4347
4348        }
4349
4350 #ifdef THREAD_DEBUG
4351        else if( debug_on ) {
4352            printf( "No thread info for tid %d\n", tid );
4353        }
4354 #endif
4355   }
4356
4357   /* Are we faking this "continue" or "step"?
4358    *
4359    * We used to do steps by continuing all the threads for 
4360    * which the events had been handled already.  While
4361    * conceptually nicer (hides it all in a lower level), this
4362    * can lead to starvation and a hang (e.g. all but one thread
4363    * are unhandled at a breakpoint just before a "join" operation,
4364    * and one thread is in the join, and the user wants to step that
4365    * thread).
4366    */
4367   if( resume_all_threads       /* Whole process, therefore user command */
4368    && more_events_left > 0 ) { /* But we can't do this yet--fake it! */
4369       thread_info *p;
4370       
4371       if( !step ) {
4372           /* No need to do any notes on a per-thread
4373            * basis--we're done!
4374            */
4375 #ifdef WAIT_BUFFER_DEBUG
4376           if( debug_on )
4377               printf( "Faking a process resume.\n" );
4378 #endif
4379
4380           return;
4381       }
4382       else {
4383
4384 #ifdef WAIT_BUFFER_DEBUG
4385           if( debug_on )
4386               printf( "Faking a process step.\n" );
4387 #endif
4388
4389       }
4390       
4391       p = find_thread_info( tid );
4392       if( p == NULL ) {
4393           warning( "No thread information for tid %d, 'next' command ignored.\n", tid );
4394           return;
4395       }
4396       else {
4397
4398 #ifdef THREAD_DEBUG
4399           if( debug_on )
4400               if( p->terminated )
4401                   printf( "Why are we continuing a dead thread? (3.5)\n" );
4402 #endif
4403
4404           if( p->stepping_mode != DO_DEFAULT ) {
4405               warning( "Step or continue command applied to thread which is already stepping or continuing; command ignored." );
4406
4407               return;
4408           }
4409
4410           if( step )
4411               p->stepping_mode = DO_STEP;
4412           else
4413               p->stepping_mode = DO_CONTINUE;
4414
4415           return;
4416       }   /* Have thread info */
4417   }   /* Must fake step or go */
4418
4419   /* Execept for fake-steps, from here on we know we are
4420    * going to wind up with a running process which will
4421    * need a real wait.
4422    */
4423   new_process_state = RUNNING;
4424
4425   /* An address of TT_USE_CURRENT_PC tells ttrace to continue from where
4426    * it was.  (If GDB wanted it to start some other way, we have already
4427    * written a new PC value to the child.)
4428    *
4429    * If this system does not support PT_STEP, a higher level function will
4430    * have called single_step() to transmute the step request into a
4431    * continue request (by setting breakpoints on all possible successor
4432    * instructions), so we don't have to worry about that here.
4433    */
4434   if (step) {
4435       if( resume_all_threads ) {
4436           /*
4437            * Regular user step: other threads get a "continue".
4438            */
4439           threads_continue_all_but_one( tid, signal );
4440           clear_all_handled();
4441           clear_all_stepping_mode();
4442       }
4443
4444       else {
4445           /* "Fake step": gdb is stepping one thread over a
4446            * breakpoint, watchpoint, or out of a library load
4447            * event, etc.  The rest just stay where they are.
4448            *
4449            * Also used when there are pending events: we really
4450            * step the current thread, but leave the rest stopped.
4451            * Users can't request this, but "wait_for_inferior"
4452            * does--a lot!
4453            */
4454           thread_fake_step( tid, signal );
4455
4456           /* Clear the "handled" state of this thread, because
4457            * we'll soon get a new event for it.  Other events
4458            * stay as they were.
4459            */
4460           clear_handled( tid );
4461           clear_stepping_mode( tid );
4462           new_process_state = FAKE_STEPPING;
4463       }
4464   }
4465   
4466   else {
4467       /* TT_LWP_CONTINUE can pass signals to threads,
4468        * TT_PROC_CONTINUE can't.  So if there are any
4469        * signals to pass, we have to use the (slower)
4470        * loop over the stopped threads.
4471        *
4472        * Equally, if we have to not continue some threads,
4473        * due to saved events, we have to use the loop.
4474        */
4475       if( (signal != 0) || saved_signals_exist()) {
4476           if( resume_all_threads ) {
4477
4478 #ifdef THREAD_DEBUG
4479               if( debug_on )
4480                   printf( "Doing a continue by loop of all threads\n" );
4481 #endif
4482
4483               threads_continue_all_with_signals( tid, signal );
4484
4485               clear_all_handled();
4486               clear_all_stepping_mode();
4487           }
4488
4489           else {
4490 #ifdef THREAD_DEBUG
4491               printf( "Doing a continue w/signal of just thread %d\n", tid );
4492 #endif
4493
4494               threads_continue_one_with_signal( tid, signal );
4495
4496               /* Clear the "handled" state of this thread, because
4497                * we'll soon get a new event for it.  Other events
4498                * can stay as they were.
4499                */
4500               clear_handled( tid );
4501               clear_stepping_mode( tid );
4502           }
4503       }
4504
4505       else {
4506           /* No signals to send.
4507            */
4508           if( resume_all_threads ) {
4509 #ifdef THREAD_DEBUG
4510               if( debug_on )
4511                   printf( "Doing a continue by process of process %d\n", tid );
4512 #endif
4513
4514               if( more_events_left > 0 ) {
4515                   warning( "Losing buffered events on continue." );
4516                   more_events_left = 0;
4517               }
4518
4519               call_ttrace( TT_PROC_CONTINUE,
4520                            tid,
4521                            TT_NIL,
4522                            TT_NIL,
4523                            TT_NIL );
4524
4525               clear_all_handled();
4526               clear_all_stepping_mode();
4527           }
4528
4529           else {
4530 #ifdef THREAD_DEBUG
4531               if( debug_on ) {
4532                   printf( "Doing a continue of just thread %d\n", tid );
4533                   if( is_terminated( tid ))
4534                        printf( "Why are we continuing a dead thread? (5)\n" );
4535               }
4536 #endif
4537
4538               call_ttrace( TT_LWP_CONTINUE,
4539                            tid,
4540                            TT_NIL,
4541                            TT_NIL,
4542                            TT_NIL );
4543
4544               /* Clear the "handled" state of this thread, because
4545                * we'll soon get a new event for it.  Other events
4546                * can stay as they were.
4547                */
4548               clear_handled( tid );
4549               clear_stepping_mode( tid );
4550           }
4551       }
4552   }
4553
4554   process_state = new_process_state;
4555
4556 #ifdef WAIT_BUFFER_DEBUG
4557   if( debug_on )
4558       printf( "Process set to %s\n",
4559               get_printable_name_of_process_state (process_state) );
4560 #endif
4561
4562 }
4563 #endif /* CHILD_RESUME */
4564
4565 \f
4566 #ifdef ATTACH_DETACH
4567 /*
4568  * Like it says.
4569  *
4570  * One worry is that we may not be attaching to "inferior_pid"
4571  * and thus may not want to clear out our data.  FIXME?
4572  * 
4573  */
4574 static void
4575 update_thread_state_after_attach( pid, kind_of_go )
4576   int               pid;
4577   attach_continue_t kind_of_go;
4578 {
4579   int        tt_status;
4580   ttstate_t  thread_state;
4581   lwpid_t    a_thread;
4582   lwpid_t    tid;
4583
4584   /* The process better be stopped.
4585    */
4586   if( process_state != STOPPED
4587    && process_state != VFORKING )
4588       warning( "Internal error attaching." );
4589
4590   /* Clear out old tthread info and start over.  This has the
4591    * side effect of ensuring that the TRAP is reported as being
4592    * in the right thread (re-mapped from tid to pid).
4593    *
4594    * It's because we need to add the tthread _now_ that we
4595    * need to call "clear_thread_info" _now_, and that's why
4596    * "require_notification_of_events" doesn't clear the thread
4597    * info (it's called later than this routine).
4598    */
4599   clear_thread_info();
4600   a_thread = 0;
4601
4602   for (tid = get_process_first_stopped_thread_id (pid, &thread_state);
4603        tid != 0;
4604        tid = get_process_next_stopped_thread_id (pid, &thread_state))
4605     {
4606       thread_info *p;
4607     
4608       if (a_thread == 0)
4609         {
4610           a_thread = tid;
4611 #ifdef THREAD_DEBUG
4612           if( debug_on )
4613               printf( "Attaching to process %d, thread %d\n",
4614                       pid, a_thread );
4615 #endif
4616         }
4617
4618       /* Tell ourselves and the "rest of gdb" that this thread
4619        * exists.
4620        *
4621        * This isn't really a hack.  Other thread-based versions
4622        * of gdb (e.g. gnu-nat.c) seem to do the same thing.
4623        *
4624        * We don't need to do mapping here, as we know this
4625        * is the first thread and thus gets the real pid
4626        * (and is "inferior_pid").
4627        *
4628        * NOTE: it probably isn't the originating thread,
4629        *       but that doesn't matter (we hope!).
4630        */
4631       add_tthread( pid, tid );
4632       p = find_thread_info( tid );
4633       if( NULL == p ) /* ?We just added it! */
4634           error( "Internal error adding a thread on attach." );
4635           
4636       copy_ttstate_t( &p->last_stop_state, thread_state );
4637       p->have_state = 1;
4638       
4639       if( DO_ATTACH_CONTINUE == kind_of_go ) {
4640           /*
4641            * If we are going to CONTINUE afterwards,
4642            * raising a SIGTRAP, don't bother trying to
4643            * handle this event.  But check first!
4644            */
4645           switch( p->last_stop_state.tts_event ) {
4646
4647           case TTEVT_NONE:
4648              /* Ok to set this handled.
4649               */
4650               break;
4651
4652           default:
4653               warning( "Internal error; skipping event %s on process %d, thread %d.",
4654                   get_printable_name_of_ttrace_event(
4655                        p->last_stop_state.tts_event ),
4656                   p->pid, p->tid);
4657           }
4658
4659           set_handled( pid, tid );
4660
4661       }
4662       else {
4663           /* There will be no "continue" opertion, so the
4664            * process remains stopped.  Don't set any events
4665            * handled except the "gimmies".
4666            */
4667           switch( p->last_stop_state.tts_event ) {
4668
4669           case TTEVT_NONE:
4670               /* Ok to ignore this.
4671                */
4672               set_handled( pid, tid );
4673               break;
4674
4675           case TTEVT_EXEC:
4676           case TTEVT_FORK:
4677               /* Expected "other" FORK or EXEC event from a
4678                * fork or vfork.
4679                */
4680               break;
4681
4682           default:
4683               printf( "Internal error: failed to handle event %s on process %d, thread %d.",
4684                   get_printable_name_of_ttrace_event(
4685                        p->last_stop_state.tts_event ),
4686                   p->pid, p->tid);
4687           }
4688       }
4689       
4690       add_thread( tid );       /* in thread.c */
4691     }
4692  
4693 #ifdef PARANOIA
4694     if( debug_on )
4695         print_tthreads();
4696 #endif
4697
4698   /* One mustn't call ttrace_wait() after attaching via ttrace,
4699      'cause the process is stopped already.
4700      
4701      However, the upper layers of gdb's execution control will
4702      want to wait after attaching (but not after forks, in
4703      which case they will be doing a "target_resume", anticipating
4704      a later TTEVT_EXEC or TTEVT_FORK event).
4705
4706      To make this attach() implementation more compatible with
4707      others, we'll make the attached-to process raise a SIGTRAP.
4708
4709      Issue: this continues only one thread.  That could be
4710      dangerous if the thread is blocked--the process won't run
4711      and no trap will be raised.  FIX! (check state.tts_flags?
4712      need one that's either TTS_WASRUNNING--but we've stopped
4713      it and made it TTS_WASSUSPENDED.  Hum...FIXME!)
4714    */
4715   if( DO_ATTACH_CONTINUE == kind_of_go ) {
4716       tt_status = call_real_ttrace(
4717                       TT_LWP_CONTINUE,
4718                       pid,
4719                       a_thread,
4720                       TT_USE_CURRENT_PC,
4721                       (TTRACE_ARG_TYPE) target_signal_to_host (TARGET_SIGNAL_TRAP),
4722                       TT_NIL);
4723       if (errno)
4724           perror_with_name ("ttrace");
4725
4726       clear_handled( a_thread );  /* So TRAP will be reported. */
4727
4728       /* Now running.
4729        */
4730       process_state = RUNNING;
4731   }
4732
4733   attach_flag = 1;
4734 }
4735 #endif /* ATTACH_DETACH */
4736
4737 \f
4738 #ifdef ATTACH_DETACH
4739 /* Start debugging the process whose number is PID.
4740  * (A _real_ pid).
4741  */
4742 int
4743 attach( pid )
4744      int pid;
4745 {
4746   int       tt_status;
4747   
4748   tt_status = call_real_ttrace (
4749                            TT_PROC_ATTACH,
4750                            pid,
4751                            (lwpid_t) TT_NIL,
4752                            TT_NIL,
4753                            (TTRACE_ARG_TYPE) TT_VERSION,
4754                            TT_NIL);
4755   if (errno)
4756     perror_with_name ("ttrace attach");
4757
4758   /* If successful, the process is now stopped.
4759    */
4760   process_state = STOPPED;
4761
4762   /* Our caller ("attach_command" in "infcmd.c")
4763    * expects to do a "wait_for_inferior" after
4764    * the attach, so make sure the inferior is
4765    * running when we're done.
4766    */
4767   update_thread_state_after_attach( pid, DO_ATTACH_CONTINUE );
4768
4769   return pid;
4770 }
4771
4772
4773 #if defined(CHILD_POST_ATTACH)
4774 void
4775 child_post_attach (pid)
4776   int  pid;
4777 {
4778 #ifdef THREAD_DEBUG
4779   if( debug_on )
4780       printf( "child-post-attach call\n" );
4781 #endif
4782
4783   require_notification_of_events (pid);
4784 }
4785 #endif
4786
4787
4788 /* Stop debugging the process whose number is PID
4789    and continue it with signal number SIGNAL.
4790    SIGNAL = 0 means just continue it.
4791  */
4792 void
4793 detach( signal )
4794      int signal;
4795 {
4796   errno = 0;
4797   call_ttrace (TT_PROC_DETACH,
4798                inferior_pid,
4799                TT_NIL,
4800                (TTRACE_ARG_TYPE) signal,
4801                TT_NIL);
4802   attach_flag = 0;
4803
4804   clear_thread_info();
4805
4806   /* Process-state? */
4807 }
4808 #endif /* ATTACH_DETACH */
4809
4810 \f
4811 /* Default the type of the ttrace transfer to int.  */
4812 #ifndef TTRACE_XFER_TYPE
4813 #define TTRACE_XFER_TYPE int
4814 #endif
4815
4816 void
4817 _initialize_kernel_u_addr ()
4818 {
4819 }
4820
4821 #if !defined (CHILD_XFER_MEMORY)
4822 /* NOTE! I tried using TTRACE_READDATA, etc., to read and write memory
4823    in the NEW_SUN_TTRACE case.
4824    It ought to be straightforward.  But it appears that writing did
4825    not write the data that I specified.  I cannot understand where
4826    it got the data that it actually did write.  */
4827
4828 /* Copy LEN bytes to or from inferior's memory starting at MEMADDR
4829    to debugger memory starting at MYADDR.   Copy to inferior if
4830    WRITE is nonzero.
4831   
4832    Returns the length copied, which is either the LEN argument or zero.
4833    This xfer function does not do partial moves, since child_ops
4834    doesn't allow memory operations to cross below us in the target stack
4835    anyway.  */
4836
4837 int
4838 child_xfer_memory (memaddr, myaddr, len, write, target)
4839      CORE_ADDR memaddr;
4840      char *myaddr;
4841      int len;
4842      int write;
4843      struct target_ops *target;         /* ignored */
4844 {
4845   register int i;
4846   /* Round starting address down to longword boundary.  */
4847   register CORE_ADDR addr = memaddr & - sizeof (TTRACE_XFER_TYPE);
4848   /* Round ending address up; get number of longwords that makes.  */
4849   register int count
4850     = (((memaddr + len) - addr) + sizeof (TTRACE_XFER_TYPE) - 1)
4851       / sizeof (TTRACE_XFER_TYPE);
4852   /* Allocate buffer of that many longwords.  */
4853   register TTRACE_XFER_TYPE *buffer
4854     = (TTRACE_XFER_TYPE *) alloca (count * sizeof (TTRACE_XFER_TYPE));
4855
4856   if (write)
4857     {
4858       /* Fill start and end extra bytes of buffer with existing memory data.  */
4859
4860       if (addr != memaddr || len < (int) sizeof (TTRACE_XFER_TYPE)) {
4861         /* Need part of initial word -- fetch it.  */
4862         buffer[0] = call_ttrace (TT_LWP_RDTEXT,
4863                                  inferior_pid,
4864                                  (TTRACE_ARG_TYPE) addr,
4865                                  TT_NIL,
4866                                  TT_NIL);
4867       }
4868
4869       if (count > 1)            /* FIXME, avoid if even boundary */
4870         {
4871           buffer[count - 1] = call_ttrace (TT_LWP_RDTEXT,
4872                                            inferior_pid,
4873                                            ((TTRACE_ARG_TYPE)
4874                                             (addr + (count - 1) * sizeof (TTRACE_XFER_TYPE))),
4875                                            TT_NIL,
4876                                            TT_NIL);
4877         }
4878
4879       /* Copy data to be written over corresponding part of buffer */
4880
4881       memcpy ((char *) buffer + (memaddr & (sizeof (TTRACE_XFER_TYPE) - 1)),
4882               myaddr,
4883               len);
4884
4885       /* Write the entire buffer.  */
4886
4887       for (i = 0; i < count; i++, addr += sizeof (TTRACE_XFER_TYPE))
4888         {
4889           errno = 0;
4890           call_ttrace (TT_LWP_WRDATA,
4891                        inferior_pid,
4892                        (TTRACE_ARG_TYPE) addr,
4893                        (TTRACE_ARG_TYPE) buffer[i],
4894                        TT_NIL);
4895           if (errno)
4896             {
4897               /* Using the appropriate one (I or D) is necessary for
4898                  Gould NP1, at least.  */
4899               errno = 0;
4900               call_ttrace (TT_LWP_WRTEXT,
4901                            inferior_pid,
4902                            (TTRACE_ARG_TYPE) addr,
4903                            (TTRACE_ARG_TYPE) buffer[i],
4904                            TT_NIL);
4905             }
4906           if (errno)
4907             return 0;
4908         }
4909     }
4910   else
4911     {
4912       /* Read all the longwords */
4913       for (i = 0; i < count; i++, addr += sizeof (TTRACE_XFER_TYPE))
4914         {
4915           errno = 0;
4916           buffer[i] = call_ttrace (TT_LWP_RDTEXT,
4917                                    inferior_pid,
4918                                    (TTRACE_ARG_TYPE) addr,
4919                                    TT_NIL,
4920                                    TT_NIL);
4921           if (errno)
4922             return 0;
4923           QUIT;
4924         }
4925
4926       /* Copy appropriate bytes out of the buffer.  */
4927       memcpy (myaddr,
4928               (char *) buffer + (memaddr & (sizeof (TTRACE_XFER_TYPE) - 1)),
4929               len);
4930     }
4931   return len;
4932 }
4933
4934 \f
4935 static void
4936 udot_info ()
4937 {
4938   int udot_off;         /* Offset into user struct */
4939   int udot_val;         /* Value from user struct at udot_off */
4940   char mess[128];       /* For messages */
4941
4942    if (!target_has_execution)
4943      {
4944        error ("The program is not being run.");
4945      }
4946
4947 #if !defined (KERNEL_U_SIZE)
4948
4949   /* Adding support for this command is easy.  Typically you just add a
4950      routine, called "kernel_u_size" that returns the size of the user
4951      struct, to the appropriate *-nat.c file and then add to the native
4952      config file "#define KERNEL_U_SIZE kernel_u_size()" */
4953   error ("Don't know how large ``struct user'' is in this version of gdb.");
4954
4955 #else
4956
4957   for (udot_off = 0; udot_off < KERNEL_U_SIZE; udot_off += sizeof (udot_val))
4958     {
4959       if ((udot_off % 24) == 0)
4960         {
4961           if (udot_off > 0)
4962             {
4963               printf_filtered ("\n");
4964             }
4965           printf_filtered ("%04x:", udot_off);
4966         }
4967       udot_val = call_ttrace (TT_LWP_RUREGS,
4968                               inferior_pid,
4969                               (TTRACE_ARG_TYPE) udot_off,
4970                               TT_NIL,
4971                               TT_NIL);
4972       if (errno != 0)
4973         {
4974           sprintf (mess, "\nreading user struct at offset 0x%x", udot_off);
4975           perror_with_name (mess);
4976         }
4977       /* Avoid using nonportable (?) "*" in print specs */
4978       printf_filtered (sizeof (int) == 4 ? " 0x%08x" : " 0x%16x", udot_val);
4979     }
4980   printf_filtered ("\n");
4981
4982 #endif
4983 }
4984 #endif /* !defined (CHILD_XFER_MEMORY).  */
4985
4986 /* TTrace version of "target_pid_to_exec_file"
4987  */
4988 char *
4989 child_pid_to_exec_file (tid)
4990     int  tid;
4991 {
4992   static char  exec_file_buffer[1024];
4993   int  tt_status;
4994   CORE_ADDR  top_of_stack;
4995   char  four_chars[4];
4996   int  name_index;
4997   int  i;
4998   int  done;
4999   int  saved_inferior_pid;
5000   
5001   /* As of 10.x HP-UX, there's an explicit request to get the
5002    *pathname.
5003    */
5004   tt_status = call_ttrace (TT_PROC_GET_PATHNAME,
5005                            tid,
5006                            (TTRACE_ARG_TYPE) exec_file_buffer,
5007                            (TTRACE_ARG_TYPE) sizeof (exec_file_buffer) - 1,
5008                            TT_NIL);
5009   if (tt_status >= 0)
5010     return exec_file_buffer;
5011
5012   /* ??rehrauer: The above request may or may not be broken.  It
5013      doesn't seem to work when I use it.  But, it may be designed
5014      to only work immediately after an exec event occurs.  (I'm
5015      waiting for COSL to explain.)
5016
5017      In any case, if it fails, try a really, truly amazingly gross
5018      hack that DDE uses, of pawing through the process' data
5019      segment to find the pathname.
5020      */
5021   top_of_stack = 0x7b03a000;
5022   name_index = 0;
5023   done = 0;
5024
5025   /* On the chance that pid != inferior_pid, set inferior_pid
5026      to pid, so that (grrrr!) implicit uses of inferior_pid get
5027      the right id.
5028      */
5029   saved_inferior_pid = inferior_pid;
5030   inferior_pid = tid;
5031
5032   /* Try to grab a null-terminated string. */
5033   while (! done) {
5034     if (target_read_memory (top_of_stack, four_chars, 4) != 0)
5035       {
5036         inferior_pid = saved_inferior_pid;
5037         return NULL;
5038       }
5039     for (i = 0; i < 4; i++) {
5040       exec_file_buffer[name_index++] = four_chars[i];
5041       done = (four_chars[i] == '\0');
5042       if (done)
5043         break;
5044     }
5045     top_of_stack += 4;
5046   }
5047
5048   if (exec_file_buffer[0] == '\0')
5049     {
5050       inferior_pid = saved_inferior_pid;
5051       return NULL;
5052     }
5053
5054   inferior_pid = saved_inferior_pid;
5055   return exec_file_buffer;
5056 }
5057
5058
5059 void
5060 pre_fork_inferior ()
5061 {
5062   int  status;
5063
5064   status = pipe (startup_semaphore.parent_channel);
5065   if (status < 0) {
5066       warning ("error getting parent pipe for startup semaphore");
5067       return;
5068   }
5069
5070   status = pipe (startup_semaphore.child_channel);
5071   if (status < 0) {
5072       warning ("error getting child pipe for startup semaphore");
5073       return;
5074   }
5075 }
5076
5077 /* Called via #define REQUIRE_ATTACH from inftarg.c,
5078  * ultimately from "follow_inferior_fork" in infrun.c,
5079  * itself called from "resume".
5080  *
5081  * This seems to be intended to attach after a fork or
5082  * vfork, while "attach" is used to attach to a pid
5083  * given by the user.  The check for an existing attach
5084  * seems odd--it always fails in our test system.
5085  */
5086 int
5087 hppa_require_attach (pid)
5088   int  pid;
5089 {
5090   int             tt_status;
5091   CORE_ADDR       pc;
5092   CORE_ADDR       pc_addr;
5093   unsigned int    regs_offset;
5094   process_state_t old_process_state = process_state;
5095   
5096   /* Are we already attached?  There appears to be no explicit
5097    * way to answer this via ttrace, so we try something which
5098    * should be innocuous if we are attached.  If that fails,
5099    * then we assume we're not attached, and so attempt to make
5100    * it so.
5101    */
5102   errno = 0;
5103   tt_status = call_real_ttrace (TT_PROC_STOP,
5104                                 pid,
5105                                 (lwpid_t) TT_NIL,
5106                                 (TTRACE_ARG_TYPE) TT_NIL,
5107                                 (TTRACE_ARG_TYPE) TT_NIL,
5108                                 TT_NIL);
5109   
5110   if (errno)
5111     {
5112       /* No change to process-state!
5113        */
5114       errno = 0;
5115       pid   = attach (pid);
5116     }
5117   else
5118     {
5119      /* If successful, the process is now stopped.  But if
5120       * we're VFORKING, the parent is still running, so don't
5121       * change the process state.
5122       */
5123      if( process_state != VFORKING )
5124          process_state = STOPPED;
5125
5126      /* If we were already attached, you'd think that we
5127       * would need to start going again--but you'd be wrong,
5128       * as the fork-following code is actually in the middle
5129       * of the "resume" routine in in "infrun.c" and so
5130       * will (almost) immediately do a resume.
5131       *
5132       * On the other hand, if we are VFORKING, which means
5133       * that the child and the parent share a process for a
5134       * while, we know that "resume" won't be resuming
5135       * until the child EXEC event is seen.  But we still
5136       * don't want to continue, as the event is already
5137       * there waiting.
5138       */
5139      update_thread_state_after_attach( pid, DONT_ATTACH_CONTINUE );
5140     }   /* STOP succeeded */
5141     
5142   return pid;
5143 }
5144
5145 int
5146 hppa_require_detach (pid, signal)
5147   int  pid;
5148   int  signal;
5149 {
5150   int  tt_status;
5151
5152   /* If signal is non-zero, we must pass the signal on to the active
5153      thread prior to detaching.  We do this by continuing the threads
5154      with the signal.
5155    */
5156   if (signal != 0)
5157     {
5158       errno = 0;
5159       threads_continue_all_with_signals( pid, signal );
5160     }
5161
5162   errno = 0;
5163   tt_status = call_ttrace (TT_PROC_DETACH,
5164                            pid,
5165                            TT_NIL,
5166                            TT_NIL,
5167                            TT_NIL);
5168
5169   errno = 0; /* Ignore any errors. */
5170
5171   /* process_state? */
5172   
5173   return pid;
5174 }
5175
5176 /* Given the starting address of a memory page, hash it to a bucket in
5177    the memory page dictionary.
5178    */
5179 static int
5180 get_dictionary_bucket_of_page (page_start)
5181   CORE_ADDR  page_start;
5182 {
5183   int  hash;
5184
5185   hash = (page_start / memory_page_dictionary.page_size);
5186   hash = hash % MEMORY_PAGE_DICTIONARY_BUCKET_COUNT;
5187
5188   return hash;
5189 }
5190
5191
5192 /* Given a memory page's starting address, get (i.e., find an existing
5193    or create a new) dictionary entry for the page.  The page will be
5194    write-protected when this function returns, but may have a reference
5195    count of 0 (if the page was newly-added to the dictionary).
5196    */
5197 static memory_page_t *
5198 get_dictionary_entry_of_page (pid, page_start)
5199   int  pid;
5200   CORE_ADDR  page_start;
5201 {
5202   int  bucket;
5203   memory_page_t *  page = NULL;
5204   memory_page_t *  previous_page = NULL;
5205
5206   /* We're going to be using the dictionary now, than-kew. */
5207   require_memory_page_dictionary (pid);
5208
5209   /* Try to find an existing dictionary entry for this page.  Hash
5210      on the page's starting address.
5211      */
5212   bucket = get_dictionary_bucket_of_page (page_start);
5213   page = &memory_page_dictionary.buckets[bucket];
5214   while (page != NULL)
5215     {
5216       if (page->page_start == page_start)
5217         break;
5218       previous_page = page;
5219       page = page->next;
5220     }
5221
5222   /* Did we find a dictionary entry for this page?  If not, then
5223      add it to the dictionary now.
5224      */
5225   if (page == NULL)
5226     {
5227       /* Create a new entry. */
5228       page = (memory_page_t *) xmalloc (sizeof (memory_page_t));
5229       page->page_start = page_start;
5230       page->reference_count = 0;
5231       page->next = NULL;
5232       page->previous = NULL;
5233
5234       /* We'll write-protect the page now, if that's allowed. */
5235       page->original_permissions = write_protect_page (pid, page_start);
5236
5237       /* Add the new entry to the dictionary. */
5238       page->previous = previous_page;
5239       previous_page->next = page;
5240
5241       memory_page_dictionary.page_count++;
5242     }
5243
5244   return page;
5245 }
5246
5247
5248 static void
5249 remove_dictionary_entry_of_page (pid, page)
5250   int  pid;
5251   memory_page_t *  page;
5252 {
5253   /* Restore the page's original permissions. */
5254   unwrite_protect_page (pid, page->page_start, page->original_permissions);
5255
5256   /* Kick the page out of the dictionary. */
5257   if (page->previous != NULL)
5258     page->previous->next = page->next;
5259   if (page->next != NULL)
5260     page->next->previous = page->previous;
5261
5262   /* Just in case someone retains a handle to this after it's freed. */
5263   page->page_start = (CORE_ADDR) 0;
5264
5265   memory_page_dictionary.page_count--;
5266
5267   free (page);
5268 }
5269
5270
5271 static void
5272 hppa_enable_syscall_events (pid)
5273   int  pid;
5274 {
5275   int  tt_status;
5276   ttevent_t  ttrace_events;
5277
5278   /* Get the set of events that are currently enabled. */
5279   tt_status = call_ttrace (TT_PROC_GET_EVENT_MASK,
5280                            pid,
5281                            (TTRACE_ARG_TYPE) &ttrace_events,
5282                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
5283                            TT_NIL);
5284   if (errno)
5285     perror_with_name ("ttrace");
5286
5287   /* Add syscall events to that set. */
5288   ttrace_events.tte_events |= TTEVT_SYSCALL_ENTRY;
5289   ttrace_events.tte_events |= TTEVT_SYSCALL_RETURN;
5290
5291   tt_status = call_ttrace (TT_PROC_SET_EVENT_MASK,
5292                            pid,
5293                            (TTRACE_ARG_TYPE) &ttrace_events,
5294                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
5295                            TT_NIL);
5296   if (errno)
5297     perror_with_name ("ttrace");
5298 }
5299
5300
5301 static void
5302 hppa_disable_syscall_events (pid)
5303   int  pid;
5304 {
5305   int  tt_status;
5306   ttevent_t  ttrace_events;
5307
5308   /* Get the set of events that are currently enabled. */
5309   tt_status = call_ttrace (TT_PROC_GET_EVENT_MASK,
5310                            pid,
5311                            (TTRACE_ARG_TYPE) &ttrace_events,
5312                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
5313                            TT_NIL);
5314   if (errno)
5315     perror_with_name ("ttrace");
5316
5317   /* Remove syscall events from that set. */
5318   ttrace_events.tte_events &= ~TTEVT_SYSCALL_ENTRY;
5319   ttrace_events.tte_events &= ~TTEVT_SYSCALL_RETURN;
5320
5321   tt_status = call_ttrace (TT_PROC_SET_EVENT_MASK,
5322                            pid,
5323                            (TTRACE_ARG_TYPE) &ttrace_events,
5324                            (TTRACE_ARG_TYPE) sizeof (ttrace_events),
5325                            TT_NIL);
5326   if (errno)
5327     perror_with_name ("ttrace");
5328 }
5329
5330
5331 /* The address range beginning with START and ending with START+LEN-1
5332    (inclusive) is to be watched via page-protection by a new watchpoint.
5333    Set protection for all pages that overlap that range.
5334
5335    Note that our caller sets TYPE to:
5336      0 for a bp_hardware_watchpoint,
5337      1 for a bp_read_watchpoint,
5338      2 for a bp_access_watchpoint
5339
5340    (Yes, this is intentionally (though lord only knows why) different
5341    from the TYPE that is passed to hppa_remove_hw_watchpoint.)
5342    */
5343 int
5344 hppa_insert_hw_watchpoint (pid, start, len, type)
5345   int  pid;
5346   CORE_ADDR  start;
5347   LONGEST  len;
5348   int  type;
5349 {
5350   CORE_ADDR  page_start;
5351   int  dictionary_was_empty;
5352   int  page_size;
5353   int  page_id;
5354   LONGEST  range_size_in_pages;
5355
5356   if (type != 0)
5357     error ("read or access hardware watchpoints not supported on HP-UX");
5358
5359   /* Examine all pages in the address range. */
5360   require_memory_page_dictionary ();
5361
5362   dictionary_was_empty = (memory_page_dictionary.page_count == (LONGEST) 0);
5363
5364   page_size = memory_page_dictionary.page_size;
5365   page_start = (start / page_size) * page_size;
5366   range_size_in_pages = ((LONGEST) len + (LONGEST) page_size - 1) / (LONGEST) page_size;
5367
5368   for (page_id=0; page_id < range_size_in_pages; page_id++, page_start+=page_size)
5369     {
5370       memory_page_t *  page;
5371
5372       /* This gets the page entered into the dictionary if it was
5373          not already entered.
5374          */
5375       page = get_dictionary_entry_of_page (pid, page_start);
5376       page->reference_count++;
5377     }
5378
5379   /* Our implementation depends on seeing calls to kernel code, for the
5380      following reason.  Here we ask to be notified of syscalls.
5381
5382      When a protected page is accessed by user code, HP-UX raises a SIGBUS.
5383      Fine.
5384
5385      But when kernel code accesses the page, it doesn't give a SIGBUS.
5386      Rather, the system call that touched the page fails, with errno=EFAULT.
5387      Not good for us.
5388
5389      We could accomodate this "feature" by asking to be notified of syscall
5390      entries & exits; upon getting an entry event, disabling page-protections;
5391      upon getting an exit event, reenabling page-protections and then checking
5392      if any watchpoints triggered.
5393
5394      However, this turns out to be a real performance loser.  syscalls are
5395      usually a frequent occurrence.  Having to unprotect-reprotect all watched
5396      pages, and also to then read all watched memory locations and compare for
5397      triggers, can be quite expensive.
5398
5399      Instead, we'll only ask to be notified of syscall exits.  When we get
5400      one, we'll check whether errno is set.  If not, or if it's not EFAULT,
5401      we can just continue the inferior.
5402
5403      If errno is set upon syscall exit to EFAULT, we must perform some fairly
5404      hackish stuff to determine whether the failure really was due to a
5405      page-protect trap on a watched location.
5406      */
5407   if (dictionary_was_empty)
5408     hppa_enable_syscall_events (pid);
5409
5410   return 1;
5411 }
5412
5413
5414 /* The address range beginning with START and ending with START+LEN-1
5415    (inclusive) was being watched via page-protection by a watchpoint
5416    which has been removed.  Remove protection for all pages that
5417    overlap that range, which are not also being watched by other
5418    watchpoints.
5419    */
5420 int
5421 hppa_remove_hw_watchpoint (pid, start, len, type)
5422   int  pid;
5423   CORE_ADDR  start;
5424   LONGEST  len;
5425   enum bptype  type;
5426 {
5427   CORE_ADDR  page_start;
5428   int  dictionary_is_empty;
5429   int  page_size;
5430   int  page_id;
5431   LONGEST  range_size_in_pages;
5432
5433   if (type != 0)
5434     error ("read or access hardware watchpoints not supported on HP-UX");
5435
5436   /* Examine all pages in the address range. */
5437   require_memory_page_dictionary ();
5438
5439   page_size = memory_page_dictionary.page_size;
5440   page_start = (start / page_size) * page_size;
5441   range_size_in_pages = ((LONGEST) len + (LONGEST) page_size - 1) / (LONGEST) page_size;
5442
5443   for (page_id=0; page_id < range_size_in_pages; page_id++, page_start+=page_size)
5444     {
5445       memory_page_t *  page;
5446
5447       page = get_dictionary_entry_of_page (pid, page_start);
5448       page->reference_count--;
5449
5450       /* Was this the last reference of this page?  If so, then we
5451          must scrub the entry from the dictionary, and also restore
5452          the page's original permissions.
5453          */
5454       if (page->reference_count == 0)
5455         remove_dictionary_entry_of_page (pid, page);
5456     }
5457
5458   dictionary_is_empty = (memory_page_dictionary.page_count == (LONGEST) 0);
5459
5460   /* If write protections are currently disallowed, then that implies that
5461      wait_for_inferior believes that the inferior is within a system call.
5462      Since we want to see both syscall entry and return, it's clearly not
5463      good to disable syscall events in this state!
5464
5465      ??rehrauer: Yeah, it'd be better if we had a specific flag that said,
5466      "inferior is between syscall events now".  Oh well.
5467      */
5468   if (dictionary_is_empty && memory_page_dictionary.page_protections_allowed)
5469     hppa_disable_syscall_events (pid);
5470
5471   return 1;
5472 }
5473
5474
5475 /* Could we implement a watchpoint of this type via our available
5476    hardware support?
5477
5478    This query does not consider whether a particular address range
5479    could be so watched, but just whether support is generally available
5480    for such things.  See hppa_range_profitable_for_hw_watchpoint for a
5481    query that answers whether a particular range should be watched via
5482    hardware support.
5483    */
5484 int
5485 hppa_can_use_hw_watchpoint (type, cnt, ot)
5486   enum bptype  type;
5487   int  cnt;
5488   enum bptype  ot;
5489 {
5490   return (type == bp_hardware_watchpoint);
5491 }
5492
5493
5494 /* Assuming we could set a hardware watchpoint on this address, do
5495    we think it would be profitable ("a good idea") to do so?  If not,
5496    we can always set a regular (aka single-step & test) watchpoint
5497    on the address...
5498    */
5499 int
5500 hppa_range_profitable_for_hw_watchpoint (pid, start, len)
5501   int  pid;
5502   CORE_ADDR  start;
5503   LONGEST  len;
5504 {
5505   int  range_is_stack_based;
5506   int  range_is_accessible;
5507   CORE_ADDR  page_start;
5508   int  page_size;
5509   int  page;
5510   LONGEST  range_size_in_pages;
5511
5512   /* ??rehrauer: For now, say that all addresses are potentially
5513      profitable.  Possibly later we'll want to test the address
5514      for "stackness"?
5515      */
5516   range_is_stack_based = 0;
5517
5518   /* If any page in the range is inaccessible, then we cannot
5519      really use hardware watchpointing, even though our client
5520      thinks we can.  In that case, it's actually an error to
5521      attempt to use hw watchpoints, so we'll tell our client
5522      that the range is "unprofitable", and hope that they listen...
5523      */
5524   range_is_accessible = 1;  /* Until proven otherwise. */
5525
5526   /* Examine all pages in the address range. */
5527   errno = 0;
5528   page_size = sysconf (_SC_PAGE_SIZE);
5529
5530   /* If we can't determine page size, we're hosed.  Tell our
5531      client it's unprofitable to use hw watchpoints for this
5532      range.
5533      */
5534   if (errno || (page_size <= 0))
5535     {
5536       errno = 0;
5537       return 0;
5538     }
5539
5540   page_start = (start / page_size) * page_size;
5541   range_size_in_pages = len / (LONGEST)page_size;
5542
5543   for (page=0; page < range_size_in_pages; page++, page_start+=page_size)
5544     {
5545       int  tt_status;
5546       int  page_permissions;
5547
5548       /* Is this page accessible? */
5549       errno = 0;
5550       tt_status = call_ttrace (TT_PROC_GET_MPROTECT,
5551                                pid,
5552                                (TTRACE_ARG_TYPE) page_start,
5553                                TT_NIL,
5554                                (TTRACE_ARG_TYPE) &page_permissions);
5555       if (errno || (tt_status < 0))
5556         {
5557           errno = 0;
5558           range_is_accessible = 0;
5559           break;
5560         }
5561
5562       /* Yes, go for another... */
5563     }
5564
5565   return (! range_is_stack_based && range_is_accessible);
5566 }
5567
5568
5569 char *
5570 hppa_pid_or_tid_to_str (id)
5571   pid_t  id;
5572 {
5573   static char  buf[100]; /* Static because address returned. */
5574
5575   /* Does this appear to be a process?  If so, print it that way. */
5576   if (is_process_id (id))
5577     return hppa_pid_to_str (id);
5578
5579   /* Else, print both the GDB thread number and the system thread id. */
5580   sprintf (buf, "thread %d (", pid_to_thread_id (id));
5581   strcat (buf, hppa_tid_to_str (id));
5582   strcat (buf, ")\0");
5583
5584   return buf;
5585 }
5586
5587 \f
5588 /* If the current pid is not the pid this module reported
5589  * from "ptrace_wait" with the most recent event, then the
5590  * user has switched threads.
5591  *
5592  * If the last reported event was a breakpoint, then return
5593  * the old thread id, else return 0.
5594  */
5595 pid_t 
5596 hppa_switched_threads( gdb_pid )
5597   pid_t gdb_pid;
5598 {
5599   if( gdb_pid == old_gdb_pid ) {
5600       /*
5601        * Core gdb is working with the same pid that it
5602        * was before we reported the last event.  This
5603        * is ok: e.g. we reported hitting a thread-specific
5604        * breakpoint, but we were reporting the wrong
5605        * thread, so the core just ignored the event.
5606        *
5607        * No thread switch has happened.
5608        */
5609       return (pid_t) 0;
5610   }
5611   else if( gdb_pid == reported_pid ) {
5612       /*
5613        * Core gdb is working with the pid we reported, so
5614        * any continue or step will be able to figure out
5615        * that it needs to step over any hit breakpoints
5616        * without our (i.e. PREPARE_TO_PROCEED's) help.
5617        */
5618       return (pid_t) 0;
5619   }
5620   else if( !reported_bpt ) {
5621        /*
5622         * The core switched, but we didn't just report a
5623         * breakpoint, so there's no just-hit breakpoint
5624         * instruction at "reported_pid"'s PC, and thus there
5625         * is no need to step over it.
5626         */
5627       return (pid_t) 0;
5628   }
5629   else {
5630        /* There's been a real switch, and we reported
5631         * a hit breakpoint.  Let "hppa_prepare_to_proceed"
5632         * know, so it can see whether the breakpoint is
5633         * still active.
5634         */
5635        return reported_pid;
5636   }
5637
5638   /* Keep compiler happy with an obvious return at the end.
5639    */
5640   return (pid_t) 0;  
5641 }
5642
5643 void
5644 hppa_ensure_vforking_parent_remains_stopped (pid)
5645   int  pid;
5646 {
5647   /* Nothing to do when using ttrace.  Only the ptrace-based implementation
5648      must do real work.
5649    */
5650 }
5651
5652
5653 int
5654 hppa_resume_execd_vforking_child_to_get_parent_vfork ()
5655 {
5656   return 0;  /* No, the parent vfork is available now. */
5657 }
5658
5659
5660 \f
5661 void
5662 _initialize_infttrace ()
5663 {
5664   /* Initialize the ttrace-based hardware watchpoint implementation. */
5665   memory_page_dictionary.page_count = (LONGEST) -1;
5666   memory_page_dictionary.page_protections_allowed = 1;
5667
5668   errno = 0;
5669   memory_page_dictionary.page_size = sysconf (_SC_PAGE_SIZE);
5670
5671   if (errno || (memory_page_dictionary.page_size <= 0))
5672     perror_with_name ("sysconf");
5673 }
5674