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