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