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