7983678a084c43f1adec06e788a5a4108443d8eb
[platform/upstream/binutils.git] / gdb / procfs.c
1 /* Machine independent support for SVR4 /proc (process file system) for GDB.
2    Copyright 1999, 2000, 2001 Free Software Foundation, Inc.
3    Written by Michael Snyder at Cygnus Solutions.
4    Based on work by Fred Fish, Stu Grossman, Geoff Noer, and others.
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 Foundation, 
20 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 #include "defs.h"
23 #include "inferior.h"
24 #include "target.h"
25 #include "gdbcore.h"
26 #include "gdbcmd.h"
27 #include "gdbthread.h"
28
29 #if defined (NEW_PROC_API)
30 #define _STRUCTURED_PROC 1      /* Should be done by configure script. */
31 #endif
32
33 #include <sys/procfs.h>
34 #ifdef HAVE_SYS_FAULT_H
35 #include <sys/fault.h>
36 #endif
37 #ifdef HAVE_SYS_SYSCALL_H
38 #include <sys/syscall.h>
39 #endif
40 #include <sys/errno.h>
41 #include <sys/wait.h>
42 #include <signal.h>
43 #include <ctype.h>
44
45 /* 
46  * PROCFS.C
47  *
48  * This module provides the interface between GDB and the
49  * /proc file system, which is used on many versions of Unix
50  * as a means for debuggers to control other processes.
51  * Examples of the systems that use this interface are:
52  *   Irix
53  *   Solaris
54  *   OSF
55  *   Unixware
56  *   AIX5
57  *
58  * /proc works by immitating a file system: you open a simulated file
59  * that represents the process you wish to interact with, and
60  * perform operations on that "file" in order to examine or change
61  * the state of the other process.
62  *
63  * The most important thing to know about /proc and this module
64  * is that there are two very different interfaces to /proc:
65  *   One that uses the ioctl system call, and
66  *   another that uses read and write system calls.
67  * This module has to support both /proc interfaces.  This means
68  * that there are two different ways of doing every basic operation.
69  *
70  * In order to keep most of the code simple and clean, I have 
71  * defined an interface "layer" which hides all these system calls.
72  * An ifdef (NEW_PROC_API) determines which interface we are using,
73  * and most or all occurrances of this ifdef should be confined to
74  * this interface layer.
75  */
76
77
78 /* Determine which /proc API we are using:
79    The ioctl API defines PIOCSTATUS, while 
80    the read/write (multiple fd) API never does.  */
81
82 #ifdef NEW_PROC_API
83 #include <sys/types.h>
84 #include "gdb_dirent.h" /* opendir/readdir, for listing the LWP's */
85 #endif
86
87 #include <fcntl.h>      /* for O_RDONLY */
88 #include <unistd.h>     /* for "X_OK" */
89 #include "gdb_stat.h"   /* for struct stat */
90
91 /* Note: procfs-utils.h must be included after the above system header
92    files, because it redefines various system calls using macros.
93    This may be incompatible with the prototype declarations.  */
94
95 #include "proc-utils.h"
96
97 /* Prototypes for supply_gregset etc. */
98 #include "gregset.h"
99
100 /* =================== TARGET_OPS "MODULE" =================== */
101
102 /*
103  * This module defines the GDB target vector and its methods.
104  */
105
106 static void procfs_open (char *, int);
107 static void procfs_attach (char *, int);
108 static void procfs_detach (char *, int);
109 static void procfs_resume (ptid_t, int, enum target_signal);
110 static int procfs_can_run (void);
111 static void procfs_stop (void);
112 static void procfs_files_info (struct target_ops *);
113 static void procfs_fetch_registers (int);
114 static void procfs_store_registers (int);
115 static void procfs_notice_signals (ptid_t);
116 static void procfs_prepare_to_store (void);
117 static void procfs_kill_inferior (void);
118 static void procfs_mourn_inferior (void);
119 static void procfs_create_inferior (char *, char *, char **);
120 static ptid_t procfs_wait (ptid_t, struct target_waitstatus *);
121 static int procfs_xfer_memory (CORE_ADDR, char *, int, int,
122                                struct mem_attrib *attrib,
123                                struct target_ops *);
124
125 static int procfs_thread_alive (ptid_t);
126
127 void procfs_find_new_threads (void);
128 char *procfs_pid_to_str (ptid_t);
129
130 struct target_ops procfs_ops;           /* the target vector */
131
132 static void
133 init_procfs_ops (void)
134 {
135   procfs_ops.to_shortname          = "procfs";
136   procfs_ops.to_longname           = "Unix /proc child process";
137   procfs_ops.to_doc                = 
138     "Unix /proc child process (started by the \"run\" command).";
139   procfs_ops.to_open               = procfs_open;
140   procfs_ops.to_can_run            = procfs_can_run;
141   procfs_ops.to_create_inferior    = procfs_create_inferior;
142   procfs_ops.to_kill               = procfs_kill_inferior;
143   procfs_ops.to_mourn_inferior     = procfs_mourn_inferior;
144   procfs_ops.to_attach             = procfs_attach;
145   procfs_ops.to_detach             = procfs_detach;
146   procfs_ops.to_wait               = procfs_wait;
147   procfs_ops.to_resume             = procfs_resume;
148   procfs_ops.to_prepare_to_store   = procfs_prepare_to_store;
149   procfs_ops.to_fetch_registers    = procfs_fetch_registers;
150   procfs_ops.to_store_registers    = procfs_store_registers;
151   procfs_ops.to_xfer_memory        = procfs_xfer_memory;
152   procfs_ops.to_insert_breakpoint  =  memory_insert_breakpoint;
153   procfs_ops.to_remove_breakpoint  =  memory_remove_breakpoint;
154   procfs_ops.to_notice_signals     = procfs_notice_signals;
155   procfs_ops.to_files_info         = procfs_files_info;
156   procfs_ops.to_stop               = procfs_stop;
157
158   procfs_ops.to_terminal_init      = terminal_init_inferior;
159   procfs_ops.to_terminal_inferior  = terminal_inferior;
160   procfs_ops.to_terminal_ours_for_output = terminal_ours_for_output;
161   procfs_ops.to_terminal_ours      = terminal_ours;
162   procfs_ops.to_terminal_info      = child_terminal_info;
163
164   procfs_ops.to_find_new_threads   = procfs_find_new_threads;
165   procfs_ops.to_thread_alive       = procfs_thread_alive;
166   procfs_ops.to_pid_to_str         = procfs_pid_to_str;
167
168   procfs_ops.to_has_all_memory     = 1;
169   procfs_ops.to_has_memory         = 1;
170   procfs_ops.to_has_execution      = 1;
171   procfs_ops.to_has_stack          = 1;
172   procfs_ops.to_has_registers      = 1;
173   procfs_ops.to_stratum            = process_stratum;
174   procfs_ops.to_has_thread_control = tc_schedlock;
175   procfs_ops.to_magic              = OPS_MAGIC;
176 }
177
178 /* =================== END, TARGET_OPS "MODULE" =================== */
179
180 /*
181  * World Unification:
182  *
183  * Put any typedefs, defines etc. here that are required for
184  * the unification of code that handles different versions of /proc.
185  */
186
187 #ifdef NEW_PROC_API             /* Solaris 7 && 8 method for watchpoints */
188 #ifdef WA_READ
189      enum { READ_WATCHFLAG  = WA_READ, 
190             WRITE_WATCHFLAG = WA_WRITE,
191             EXEC_WATCHFLAG  = WA_EXEC,
192             AFTER_WATCHFLAG = WA_TRAPAFTER
193      };
194 #endif
195 #else                           /* Irix method for watchpoints */
196      enum { READ_WATCHFLAG  = MA_READ, 
197             WRITE_WATCHFLAG = MA_WRITE,
198             EXEC_WATCHFLAG  = MA_EXEC,
199             AFTER_WATCHFLAG = 0         /* trapafter not implemented */
200      };
201 #endif
202
203 /* gdb_sigset_t */
204 #ifdef HAVE_PR_SIGSET_T
205 typedef pr_sigset_t gdb_sigset_t;
206 #else
207 typedef sigset_t gdb_sigset_t;
208 #endif
209
210 /* sigaction */
211 #ifdef HAVE_PR_SIGACTION64_T
212 typedef pr_sigaction64_t gdb_sigaction_t;
213 #else
214 typedef struct sigaction gdb_sigaction_t;
215 #endif
216
217 /* siginfo */
218 #ifdef HAVE_PR_SIGINFO64_T
219 typedef pr_siginfo64_t gdb_siginfo_t;
220 #else
221 typedef struct siginfo gdb_siginfo_t;
222 #endif
223
224 /* gdb_premptysysset */
225 #ifdef premptysysset
226 #define gdb_premptysysset premptysysset
227 #else
228 #define gdb_premptysysset premptyset
229 #endif
230
231 /* praddsysset */
232 #ifdef praddsysset
233 #define gdb_praddsysset praddsysset
234 #else
235 #define gdb_praddsysset praddset
236 #endif
237
238 /* prdelsysset */
239 #ifdef prdelsysset
240 #define gdb_prdelsysset prdelsysset
241 #else
242 #define gdb_prdelsysset prdelset
243 #endif
244
245 /* prissyssetmember */
246 #ifdef prissyssetmember
247 #define gdb_pr_issyssetmember prissyssetmember
248 #else
249 #define gdb_pr_issyssetmember prismember
250 #endif
251
252 /* As a feature test, saying ``#if HAVE_PRSYSENT_T'' everywhere isn't
253    as intuitively descriptive as it could be, so we'll define
254    DYNAMIC_SYSCALLS to mean the same thing.  Anyway, at the time of
255    this writing, this feature is only found on AIX5 systems and
256    basically means that the set of syscalls is not fixed.  I.e,
257    there's no nice table that one can #include to get all of the
258    syscall numbers.  Instead, they're stored in /proc/PID/sysent
259    for each process.  We are at least guaranteed that they won't
260    change over the lifetime of the process.  But each process could
261    (in theory) have different syscall numbers.
262 */
263 #ifdef HAVE_PRSYSENT_T
264 #define DYNAMIC_SYSCALLS
265 #endif
266
267
268
269 /* =================== STRUCT PROCINFO "MODULE" =================== */
270
271      /* FIXME: this comment will soon be out of date W.R.T. threads.  */
272
273 /* The procinfo struct is a wrapper to hold all the state information
274    concerning a /proc process.  There should be exactly one procinfo
275    for each process, and since GDB currently can debug only one
276    process at a time, that means there should be only one procinfo.
277    All of the LWP's of a process can be accessed indirectly thru the
278    single process procinfo.
279
280    However, against the day when GDB may debug more than one process,
281    this data structure is kept in a list (which for now will hold no
282    more than one member), and many functions will have a pointer to a
283    procinfo as an argument.
284
285    There will be a separate procinfo structure for use by the (not yet
286    implemented) "info proc" command, so that we can print useful
287    information about any random process without interfering with the
288    inferior's procinfo information. */
289
290 #ifdef NEW_PROC_API
291 /* format strings for /proc paths */
292 # ifndef CTL_PROC_NAME_FMT
293 #  define MAIN_PROC_NAME_FMT   "/proc/%d"
294 #  define CTL_PROC_NAME_FMT    "/proc/%d/ctl"
295 #  define AS_PROC_NAME_FMT     "/proc/%d/as"
296 #  define MAP_PROC_NAME_FMT    "/proc/%d/map"
297 #  define STATUS_PROC_NAME_FMT "/proc/%d/status"
298 #  define MAX_PROC_NAME_SIZE sizeof("/proc/99999/lwp/8096/lstatus")
299 # endif
300 /* the name of the proc status struct depends on the implementation */
301 typedef pstatus_t   gdb_prstatus_t;
302 typedef lwpstatus_t gdb_lwpstatus_t;
303 #else /* ! NEW_PROC_API */
304 /* format strings for /proc paths */
305 # ifndef CTL_PROC_NAME_FMT
306 #  define MAIN_PROC_NAME_FMT   "/proc/%05d"
307 #  define CTL_PROC_NAME_FMT    "/proc/%05d"
308 #  define AS_PROC_NAME_FMT     "/proc/%05d"
309 #  define MAP_PROC_NAME_FMT    "/proc/%05d"
310 #  define STATUS_PROC_NAME_FMT "/proc/%05d"
311 #  define MAX_PROC_NAME_SIZE sizeof("/proc/ttttppppp")
312 # endif
313 /* the name of the proc status struct depends on the implementation */
314 typedef prstatus_t gdb_prstatus_t;
315 typedef prstatus_t gdb_lwpstatus_t;
316 #endif /* NEW_PROC_API */
317
318 typedef struct procinfo {
319   struct procinfo *next;
320   int pid;                      /* Process ID    */
321   int tid;                      /* Thread/LWP id */
322
323   /* process state */
324   int was_stopped;
325   int ignore_next_sigstop;
326
327   /* The following four fd fields may be identical, or may contain 
328      several different fd's, depending on the version of /proc
329      (old ioctl or new read/write).  */
330
331   int ctl_fd;                   /* File descriptor for /proc control file */
332   /*
333    * The next three file descriptors are actually only needed in the
334    * read/write, multiple-file-descriptor implemenation (NEW_PROC_API).
335    * However, to avoid a bunch of #ifdefs in the code, we will use 
336    * them uniformly by (in the case of the ioctl single-file-descriptor
337    * implementation) filling them with copies of the control fd.
338    */
339   int status_fd;                /* File descriptor for /proc status file */
340   int as_fd;                    /* File descriptor for /proc as file */
341
342   char pathname[MAX_PROC_NAME_SIZE];    /* Pathname to /proc entry */
343
344   fltset_t saved_fltset;        /* Saved traced hardware fault set */
345   gdb_sigset_t saved_sigset;    /* Saved traced signal set */
346   gdb_sigset_t saved_sighold;   /* Saved held signal set */
347   sysset_t *saved_exitset;      /* Saved traced system call exit set */
348   sysset_t *saved_entryset;     /* Saved traced system call entry set */
349
350   gdb_prstatus_t prstatus;      /* Current process status info */
351
352 #ifndef NEW_PROC_API
353   gdb_fpregset_t fpregset;      /* Current floating point registers */
354 #endif
355
356 #ifdef DYNAMIC_SYSCALLS
357   int num_syscalls;             /* Total number of syscalls */
358   char **syscall_names;         /* Syscall number to name map */
359 #endif
360   
361   struct procinfo *thread_list;
362
363   int status_valid : 1;
364   int gregs_valid  : 1;
365   int fpregs_valid : 1;
366   int threads_valid: 1;
367 } procinfo;
368
369 static char errmsg[128];        /* shared error msg buffer */
370
371 /* Function prototypes for procinfo module: */
372
373 static procinfo *find_procinfo_or_die (int pid, int tid);
374 static procinfo *find_procinfo (int pid, int tid);
375 static procinfo *create_procinfo (int pid, int tid);
376 static void destroy_procinfo (procinfo * p);
377 static void do_destroy_procinfo_cleanup (void *);
378 static void dead_procinfo (procinfo * p, char *msg, int killp);
379 static int open_procinfo_files (procinfo * p, int which);
380 static void close_procinfo_files (procinfo * p);
381 static int sysset_t_size (procinfo *p);
382 static sysset_t *sysset_t_alloc (procinfo * pi);
383 #ifdef DYNAMIC_SYSCALLS
384 static void load_syscalls (procinfo *pi);
385 static void free_syscalls (procinfo *pi);
386 static int find_syscall (procinfo *pi, char *name);
387 #endif /* DYNAMIC_SYSCALLS */
388
389 /* The head of the procinfo list: */
390 static procinfo * procinfo_list;
391
392 /*
393  * Function: find_procinfo
394  *
395  * Search the procinfo list.
396  *
397  * Returns: pointer to procinfo, or NULL if not found.
398  */
399
400 static procinfo * 
401 find_procinfo (int pid, int tid)
402 {
403   procinfo *pi;
404
405   for (pi = procinfo_list; pi; pi = pi->next)
406     if (pi->pid == pid)
407       break;
408
409   if (pi)
410     if (tid)
411       {
412         /* Don't check threads_valid.  If we're updating the
413            thread_list, we want to find whatever threads are already
414            here.  This means that in general it is the caller's
415            responsibility to check threads_valid and update before
416            calling find_procinfo, if the caller wants to find a new
417            thread. */
418
419         for (pi = pi->thread_list; pi; pi = pi->next)
420           if (pi->tid == tid)
421             break;
422       }
423
424   return pi;
425 }
426
427 /*
428  * Function: find_procinfo_or_die
429  *
430  * Calls find_procinfo, but errors on failure.
431  */
432
433 static procinfo *
434 find_procinfo_or_die (int pid, int tid)
435 {
436   procinfo *pi = find_procinfo (pid, tid);
437
438   if (pi == NULL)
439     {
440       if (tid)
441         error ("procfs: couldn't find pid %d (kernel thread %d) in procinfo list.", 
442                pid, tid);
443       else
444         error ("procfs: couldn't find pid %d in procinfo list.", pid);
445     }
446   return pi;
447 }
448
449 /* open_with_retry() is a wrapper for open().  The appropriate
450    open() call is attempted; if unsuccessful, it will be retried as
451    many times as needed for the EAGAIN and EINTR conditions.
452    
453    For other conditions, open_with_retry() will retry the open() a
454    limited number of times.  In addition, a short sleep is imposed
455    prior to retrying the open().  The reason for this sleep is to give
456    the kernel a chance to catch up and create the file in question in
457    the event that GDB "wins" the race to open a file before the kernel
458    has created it.  */
459    
460 static int
461 open_with_retry (const char *pathname, int flags)
462 {
463   int retries_remaining, status;
464
465   retries_remaining = 2;
466
467   while (1)
468     {
469       status = open (pathname, flags);
470
471       if (status >= 0 || retries_remaining == 0)
472         break;
473       else if (errno != EINTR && errno != EAGAIN)
474         {
475           retries_remaining--;
476           sleep (1);
477         }
478     }
479
480   return status;
481 }
482
483 /*
484  * Function: open_procinfo_files
485  *
486  * Open the file descriptor for the process or LWP.
487  * ifdef NEW_PROC_API, we only open the control file descriptor;
488  * the others are opened lazily as needed.
489  * else (if not NEW_PROC_API), there is only one real
490  * file descriptor, but we keep multiple copies of it so that
491  * the code that uses them does not have to be #ifdef'd.
492  *
493  * Return: file descriptor, or zero for failure.
494  */
495
496 enum { FD_CTL, FD_STATUS, FD_AS };
497
498 static int
499 open_procinfo_files (procinfo *pi, int which)
500 {
501 #ifdef NEW_PROC_API
502   char tmp[MAX_PROC_NAME_SIZE];
503 #endif
504   int  fd;
505
506   /* 
507    * This function is getting ALMOST long enough to break up into several.
508    * Here is some rationale:
509    *
510    * NEW_PROC_API (Solaris 2.6, Solaris 2.7, Unixware):
511    *   There are several file descriptors that may need to be open 
512    *   for any given process or LWP.  The ones we're intereted in are:
513    *     - control       (ctl)    write-only    change the state
514    *     - status        (status) read-only     query the state
515    *     - address space (as)     read/write    access memory
516    *     - map           (map)    read-only     virtual addr map
517    *   Most of these are opened lazily as they are needed.
518    *   The pathnames for the 'files' for an LWP look slightly 
519    *   different from those of a first-class process:
520    *     Pathnames for a process (<proc-id>):
521    *       /proc/<proc-id>/ctl
522    *       /proc/<proc-id>/status
523    *       /proc/<proc-id>/as
524    *       /proc/<proc-id>/map
525    *     Pathnames for an LWP (lwp-id):
526    *       /proc/<proc-id>/lwp/<lwp-id>/lwpctl
527    *       /proc/<proc-id>/lwp/<lwp-id>/lwpstatus
528    *   An LWP has no map or address space file descriptor, since
529    *   the memory map and address space are shared by all LWPs.
530    *
531    * Everyone else (Solaris 2.5, Irix, OSF)
532    *   There is only one file descriptor for each process or LWP.
533    *   For convenience, we copy the same file descriptor into all
534    *   three fields of the procinfo struct (ctl_fd, status_fd, and
535    *   as_fd, see NEW_PROC_API above) so that code that uses them
536    *   doesn't need any #ifdef's.  
537    *     Pathname for all:
538    *       /proc/<proc-id>
539    *
540    *   Solaris 2.5 LWP's:
541    *     Each LWP has an independent file descriptor, but these 
542    *     are not obtained via the 'open' system call like the rest:
543    *     instead, they're obtained thru an ioctl call (PIOCOPENLWP)
544    *     to the file descriptor of the parent process.
545    *
546    *   OSF threads:
547    *     These do not even have their own independent file descriptor.
548    *     All operations are carried out on the file descriptor of the
549    *     parent process.  Therefore we just call open again for each
550    *     thread, getting a new handle for the same 'file'.
551    */
552
553 #ifdef NEW_PROC_API
554   /*
555    * In this case, there are several different file descriptors that
556    * we might be asked to open.  The control file descriptor will be
557    * opened early, but the others will be opened lazily as they are
558    * needed.
559    */
560
561   strcpy (tmp, pi->pathname);
562   switch (which) {      /* which file descriptor to open? */
563   case FD_CTL:
564     if (pi->tid)
565       strcat (tmp, "/lwpctl");
566     else
567       strcat (tmp, "/ctl");
568     fd = open_with_retry (tmp, O_WRONLY);
569     if (fd <= 0)
570       return 0;         /* fail */
571     pi->ctl_fd = fd;
572     break;
573   case FD_AS:
574     if (pi->tid)
575       return 0;         /* there is no 'as' file descriptor for an lwp */
576     strcat (tmp, "/as");
577     fd = open_with_retry (tmp, O_RDWR);
578     if (fd <= 0)
579       return 0;         /* fail */
580     pi->as_fd = fd;
581     break;
582   case FD_STATUS:
583     if (pi->tid)
584       strcat (tmp, "/lwpstatus");
585     else
586       strcat (tmp, "/status");
587     fd = open_with_retry (tmp, O_RDONLY);
588     if (fd <= 0)
589       return 0;         /* fail */
590     pi->status_fd = fd;
591     break;
592   default:
593     return 0;           /* unknown file descriptor */
594   }
595 #else  /* not NEW_PROC_API */
596   /*
597    * In this case, there is only one file descriptor for each procinfo
598    * (ie. each process or LWP).  In fact, only the file descriptor for
599    * the process can actually be opened by an 'open' system call.
600    * The ones for the LWPs have to be obtained thru an IOCTL call 
601    * on the process's file descriptor. 
602    *
603    * For convenience, we copy each procinfo's single file descriptor
604    * into all of the fields occupied by the several file descriptors 
605    * of the NEW_PROC_API implementation.  That way, the code that uses
606    * them can be written without ifdefs.
607    */
608
609
610 #ifdef PIOCTSTATUS      /* OSF */
611   /* Only one FD; just open it. */
612   if ((fd = open_with_retry (pi->pathname, O_RDWR)) == 0)
613     return 0;
614 #else                   /* Sol 2.5, Irix, other? */
615   if (pi->tid == 0)     /* Master procinfo for the process */
616     {
617       fd = open_with_retry (pi->pathname, O_RDWR);
618       if (fd <= 0)
619         return 0;       /* fail */
620     }
621   else                  /* LWP thread procinfo */
622     {
623 #ifdef PIOCOPENLWP      /* Sol 2.5, thread/LWP */
624       procinfo *process;
625       int lwpid = pi->tid;
626
627       /* Find the procinfo for the entire process. */
628       if ((process = find_procinfo (pi->pid, 0)) == NULL)
629         return 0;       /* fail */
630
631       /* Now obtain the file descriptor for the LWP. */
632       if ((fd = ioctl (process->ctl_fd, PIOCOPENLWP, &lwpid)) <= 0)
633         return 0;       /* fail */
634 #else                   /* Irix, other? */
635       return 0;         /* Don't know how to open threads */
636 #endif  /* Sol 2.5 PIOCOPENLWP */
637     }
638 #endif  /* OSF     PIOCTSTATUS */
639   pi->ctl_fd = pi->as_fd = pi->status_fd = fd;
640 #endif  /* NEW_PROC_API */
641
642   return 1;             /* success */
643 }
644
645 /*
646  * Function: create_procinfo
647  *
648  * Allocate a data structure and link it into the procinfo list.
649  * (First tries to find a pre-existing one (FIXME: why?)
650  *
651  * Return: pointer to new procinfo struct.
652  */
653
654 static procinfo *
655 create_procinfo (int pid, int tid)
656 {
657   procinfo *pi, *parent;
658
659   if ((pi = find_procinfo (pid, tid)))
660     return pi;                  /* Already exists, nothing to do. */
661
662   /* find parent before doing malloc, to save having to cleanup */
663   if (tid != 0)
664     parent = find_procinfo_or_die (pid, 0);     /* FIXME: should I
665                                                    create it if it
666                                                    doesn't exist yet? */
667
668   pi = (procinfo *) xmalloc (sizeof (procinfo));
669   memset (pi, 0, sizeof (procinfo));
670   pi->pid = pid;
671   pi->tid = tid;
672
673 #ifdef DYNAMIC_SYSCALLS
674   load_syscalls (pi);
675 #endif
676
677   pi->saved_entryset = sysset_t_alloc (pi);
678   pi->saved_exitset = sysset_t_alloc (pi);
679
680   /* Chain into list.  */
681   if (tid == 0)
682     {
683       sprintf (pi->pathname, MAIN_PROC_NAME_FMT, pid);
684       pi->next = procinfo_list;
685       procinfo_list = pi;
686     }
687   else
688     {
689 #ifdef NEW_PROC_API
690       sprintf (pi->pathname, "/proc/%05d/lwp/%d", pid, tid);
691 #else
692       sprintf (pi->pathname, MAIN_PROC_NAME_FMT, pid);
693 #endif
694       pi->next = parent->thread_list;
695       parent->thread_list = pi;
696     }
697   return pi;
698 }
699
700 /*
701  * Function: close_procinfo_files
702  *
703  * Close all file descriptors associated with the procinfo
704  */
705
706 static void
707 close_procinfo_files (procinfo *pi)
708 {
709   if (pi->ctl_fd > 0)
710     close (pi->ctl_fd);
711 #ifdef NEW_PROC_API
712   if (pi->as_fd > 0)
713     close (pi->as_fd);
714   if (pi->status_fd > 0)
715     close (pi->status_fd);
716 #endif
717   pi->ctl_fd = pi->as_fd = pi->status_fd = 0;
718 }
719
720 /*
721  * Function: destroy_procinfo
722  *
723  * Destructor function.  Close, unlink and deallocate the object.
724  */
725
726 static void
727 destroy_one_procinfo (procinfo **list, procinfo *pi)
728 {
729   procinfo *ptr;
730
731   /* Step one: unlink the procinfo from its list */
732   if (pi == *list)
733     *list = pi->next;
734   else 
735     for (ptr = *list; ptr; ptr = ptr->next)
736       if (ptr->next == pi)
737         {
738           ptr->next =  pi->next;
739           break;
740         }
741
742   /* Step two: close any open file descriptors */
743   close_procinfo_files (pi);
744
745   /* Step three: free the memory. */
746 #ifdef DYNAMIC_SYSCALLS
747   free_syscalls (pi);
748 #endif
749   xfree (pi->saved_entryset);
750   xfree (pi->saved_exitset);
751   xfree (pi);
752 }
753
754 static void
755 destroy_procinfo (procinfo *pi)
756 {
757   procinfo *tmp;
758
759   if (pi->tid != 0)     /* destroy a thread procinfo */
760     {
761       tmp = find_procinfo (pi->pid, 0); /* find the parent process */
762       destroy_one_procinfo (&tmp->thread_list, pi);
763     }
764   else                  /* destroy a process procinfo and all its threads */
765     {
766       /* First destroy the children, if any; */
767       while (pi->thread_list != NULL)
768         destroy_one_procinfo (&pi->thread_list, pi->thread_list);
769       /* Then destroy the parent.  Genocide!!!  */
770       destroy_one_procinfo (&procinfo_list, pi);
771     }
772 }
773
774 static void
775 do_destroy_procinfo_cleanup (void *pi)
776 {
777   destroy_procinfo (pi);
778 }
779
780 enum { NOKILL, KILL };
781
782 /*
783  * Function: dead_procinfo
784  *
785  * To be called on a non_recoverable error for a procinfo.
786  * Prints error messages, optionally sends a SIGKILL to the process,
787  * then destroys the data structure.
788  */
789
790 static void
791 dead_procinfo (procinfo *pi, char *msg, int kill_p)
792 {
793   char procfile[80];
794
795   if (pi->pathname)
796     {
797       print_sys_errmsg (pi->pathname, errno);
798     }
799   else
800     {
801       sprintf (procfile, "process %d", pi->pid);
802       print_sys_errmsg (procfile, errno);
803     }
804   if (kill_p == KILL)
805     kill (pi->pid, SIGKILL);
806
807   destroy_procinfo (pi);
808   error (msg);
809 }
810
811 /*
812  * Function: sysset_t_size
813  *
814  * Returns the (complete) size of a sysset_t struct.  Normally, this
815  * is just sizeof (syset_t), but in the case of Monterey/64, the actual
816  * size of sysset_t isn't known until runtime.
817  */
818
819 static int
820 sysset_t_size (procinfo * pi)
821 {
822 #ifndef DYNAMIC_SYSCALLS
823   return sizeof (sysset_t);
824 #else
825   return sizeof (sysset_t) - sizeof (uint64_t)
826     + sizeof (uint64_t) * ((pi->num_syscalls + (8 * sizeof (uint64_t) - 1))
827                            / (8 * sizeof (uint64_t)));
828 #endif
829 }
830
831 /* Function: sysset_t_alloc
832   
833    Allocate and (partially) initialize a sysset_t struct.  */
834
835 static sysset_t *
836 sysset_t_alloc (procinfo * pi)
837 {
838   sysset_t *ret;
839   int size = sysset_t_size (pi);
840   ret = xmalloc (size);
841 #ifdef DYNAMIC_SYSCALLS
842   ret->pr_size = (pi->num_syscalls + (8 * sizeof (uint64_t) - 1))
843                  / (8 * sizeof (uint64_t));
844 #endif
845   return ret;
846 }
847
848 #ifdef DYNAMIC_SYSCALLS
849
850 /* Function: load_syscalls
851   
852    Extract syscall numbers and names from /proc/<pid>/sysent.  Initialize
853    pi->num_syscalls with the number of syscalls and pi->syscall_names
854    with the names.  (Certain numbers may be skipped in which case the
855    names for these numbers will be left as NULL.) */
856
857 #define MAX_SYSCALL_NAME_LENGTH 256
858 #define MAX_SYSCALLS 65536
859
860 static void
861 load_syscalls (procinfo *pi)
862 {
863   char pathname[MAX_PROC_NAME_SIZE];
864   int sysent_fd;
865   prsysent_t header;
866   prsyscall_t *syscalls;
867   int i, size, maxcall;
868
869   pi->num_syscalls = 0;
870   pi->syscall_names = 0;
871
872   /* Open the file descriptor for the sysent file */
873   sprintf (pathname, "/proc/%d/sysent", pi->pid);
874   sysent_fd = open_with_retry (pathname, O_RDONLY);
875   if (sysent_fd < 0)
876     {
877       error ("load_syscalls: Can't open /proc/%d/sysent", pi->pid);
878     }
879
880   size = sizeof header - sizeof (prsyscall_t);
881   if (read (sysent_fd, &header, size) != size)
882     {
883       error ("load_syscalls: Error reading /proc/%d/sysent", pi->pid);
884     }
885
886   if (header.pr_nsyscalls == 0)
887     {
888       error ("load_syscalls: /proc/%d/sysent contains no syscalls!", pi->pid);
889     }
890
891   size = header.pr_nsyscalls * sizeof (prsyscall_t);
892   syscalls = xmalloc (size);
893
894   if (read (sysent_fd, syscalls, size) != size)
895     {
896       xfree (syscalls);
897       error ("load_syscalls: Error reading /proc/%d/sysent", pi->pid);
898     }
899
900   /* Find maximum syscall number.  This may not be the same as
901      pr_nsyscalls since that value refers to the number of entries
902      in the table.  (Also, the docs indicate that some system
903      call numbers may be skipped.) */
904
905   maxcall = syscalls[0].pr_number;
906
907   for (i = 1; i <  header.pr_nsyscalls; i++)
908     if (syscalls[i].pr_number > maxcall
909         && syscalls[i].pr_nameoff > 0
910         && syscalls[i].pr_number < MAX_SYSCALLS)
911       maxcall = syscalls[i].pr_number;
912
913   pi->num_syscalls = maxcall+1;
914   pi->syscall_names = xmalloc (pi->num_syscalls * sizeof (char *));
915
916   for (i = 0; i < pi->num_syscalls; i++)
917     pi->syscall_names[i] = NULL;
918
919   /* Read the syscall names in */
920   for (i = 0; i < header.pr_nsyscalls; i++)
921     {
922       char namebuf[MAX_SYSCALL_NAME_LENGTH];
923       int nread;
924       int callnum;
925
926       if (syscalls[i].pr_number >= MAX_SYSCALLS
927           || syscalls[i].pr_number < 0
928           || syscalls[i].pr_nameoff <= 0
929           || (lseek (sysent_fd, (off_t) syscalls[i].pr_nameoff, SEEK_SET)
930                                        != (off_t) syscalls[i].pr_nameoff))
931         continue;
932
933       nread = read (sysent_fd, namebuf, sizeof namebuf);
934       if (nread <= 0)
935         continue;
936
937       callnum = syscalls[i].pr_number;
938
939       if (pi->syscall_names[callnum] != NULL)
940         {
941           /* FIXME: Generate warning */
942           continue;
943         }
944
945       namebuf[nread-1] = '\0';
946       size = strlen (namebuf) + 1;
947       pi->syscall_names[callnum] = xmalloc (size);
948       strncpy (pi->syscall_names[callnum], namebuf, size-1);
949       pi->syscall_names[callnum][size-1] = '\0';
950     }
951   
952   close (sysent_fd);
953   xfree (syscalls);
954 }
955
956 /* Function: free_syscalls
957    
958    Free the space allocated for the syscall names from the procinfo
959    structure.  */
960
961 static void
962 free_syscalls (procinfo *pi)
963 {
964   if (pi->syscall_names)
965     {
966       int i;
967
968       for (i = 0; i < pi->num_syscalls; i++)
969         if (pi->syscall_names[i] != NULL)
970           xfree (pi->syscall_names[i]);
971
972       xfree (pi->syscall_names);
973       pi->syscall_names = 0;
974     }
975 }
976
977 /* Function: find_syscall
978
979    Given a name, look up (and return) the corresponding syscall number.
980    If no match is found, return -1.  */
981    
982 static int
983 find_syscall (procinfo *pi, char *name)
984 {
985   int i;
986   for (i = 0; i < pi->num_syscalls; i++)
987     {
988       if (pi->syscall_names[i] && strcmp (name, pi->syscall_names[i]) == 0)
989         return i;
990     }
991   return -1;
992 }
993 #endif
994
995 /* =================== END, STRUCT PROCINFO "MODULE" =================== */
996
997 /* ===================  /proc  "MODULE" =================== */
998
999 /*
1000  * This "module" is the interface layer between the /proc system API
1001  * and the gdb target vector functions.  This layer consists of 
1002  * access functions that encapsulate each of the basic operations
1003  * that we need to use from the /proc API.
1004  *
1005  * The main motivation for this layer is to hide the fact that
1006  * there are two very different implementations of the /proc API.
1007  * Rather than have a bunch of #ifdefs all thru the gdb target vector
1008  * functions, we do our best to hide them all in here.
1009  */
1010
1011 int proc_get_status (procinfo * pi);
1012 long proc_flags (procinfo * pi);
1013 int proc_why (procinfo * pi);
1014 int proc_what (procinfo * pi);
1015 int proc_set_run_on_last_close (procinfo * pi);
1016 int proc_unset_run_on_last_close (procinfo * pi);
1017 int proc_set_inherit_on_fork (procinfo * pi);
1018 int proc_unset_inherit_on_fork (procinfo * pi);
1019 int proc_set_async (procinfo * pi);
1020 int proc_unset_async (procinfo * pi);
1021 int proc_stop_process (procinfo * pi);
1022 int proc_trace_signal (procinfo * pi, int signo);
1023 int proc_ignore_signal (procinfo * pi, int signo);
1024 int proc_clear_current_fault (procinfo * pi);
1025 int proc_set_current_signal (procinfo * pi, int signo);
1026 int proc_clear_current_signal (procinfo * pi);
1027 int proc_set_gregs (procinfo * pi);
1028 int proc_set_fpregs (procinfo * pi);
1029 int proc_wait_for_stop (procinfo * pi);
1030 int proc_run_process (procinfo * pi, int step, int signo);
1031 int proc_kill (procinfo * pi, int signo);
1032 int proc_parent_pid (procinfo * pi);
1033 int proc_get_nthreads (procinfo * pi);
1034 int proc_get_current_thread (procinfo * pi);
1035 int proc_set_held_signals (procinfo * pi, gdb_sigset_t * sighold);
1036 int proc_set_traced_sysexit (procinfo * pi, sysset_t * sysset);
1037 int proc_set_traced_sysentry (procinfo * pi, sysset_t * sysset);
1038 int proc_set_traced_faults (procinfo * pi, fltset_t * fltset);
1039 int proc_set_traced_signals (procinfo * pi, gdb_sigset_t * sigset);
1040
1041 int proc_update_threads (procinfo * pi);
1042 int proc_iterate_over_threads (procinfo * pi,
1043                                int (*func) (procinfo *, procinfo *, void *),
1044                                void *ptr);
1045
1046 gdb_gregset_t *proc_get_gregs (procinfo * pi);
1047 gdb_fpregset_t *proc_get_fpregs (procinfo * pi);
1048 sysset_t *proc_get_traced_sysexit (procinfo * pi, sysset_t * save);
1049 sysset_t *proc_get_traced_sysentry (procinfo * pi, sysset_t * save);
1050 fltset_t *proc_get_traced_faults (procinfo * pi, fltset_t * save);
1051 gdb_sigset_t *proc_get_traced_signals (procinfo * pi, gdb_sigset_t * save);
1052 gdb_sigset_t *proc_get_held_signals (procinfo * pi, gdb_sigset_t * save);
1053 gdb_sigset_t *proc_get_pending_signals (procinfo * pi, gdb_sigset_t * save);
1054 gdb_sigaction_t *proc_get_signal_actions (procinfo * pi, gdb_sigaction_t *save);
1055
1056 void proc_warn (procinfo * pi, char *func, int line);
1057 void proc_error (procinfo * pi, char *func, int line);
1058
1059 void
1060 proc_warn (procinfo *pi, char *func, int line)
1061 {
1062   sprintf (errmsg, "procfs: %s line %d, %s", func, line, pi->pathname);
1063   print_sys_errmsg (errmsg, errno);
1064 }
1065
1066 void
1067 proc_error (procinfo *pi, char *func, int line)
1068 {
1069   sprintf (errmsg, "procfs: %s line %d, %s", func, line, pi->pathname);
1070   perror_with_name (errmsg);
1071 }
1072
1073 /*
1074  * Function: proc_get_status
1075  *
1076  * Updates the status struct in the procinfo.
1077  * There is a 'valid' flag, to let other functions know when
1078  * this function needs to be called (so the status is only
1079  * read when it is needed).  The status file descriptor is
1080  * also only opened when it is needed.
1081  *
1082  * Return: non-zero for success, zero for failure.
1083  */
1084
1085 int
1086 proc_get_status (procinfo *pi)
1087 {
1088   /* Status file descriptor is opened "lazily" */
1089   if (pi->status_fd == 0 &&
1090       open_procinfo_files (pi, FD_STATUS) == 0)
1091     {
1092       pi->status_valid = 0;
1093       return 0;
1094     }
1095
1096 #ifdef NEW_PROC_API
1097   if (lseek (pi->status_fd, 0, SEEK_SET) < 0)
1098     pi->status_valid = 0;                       /* fail */
1099   else
1100     {
1101       /* Sigh... I have to read a different data structure, 
1102          depending on whether this is a main process or an LWP. */
1103       if (pi->tid)
1104         pi->status_valid = (read (pi->status_fd, 
1105                                   (char *) &pi->prstatus.pr_lwp, 
1106                                   sizeof (lwpstatus_t))
1107                             == sizeof (lwpstatus_t));
1108       else
1109         {
1110           pi->status_valid = (read (pi->status_fd, 
1111                                     (char *) &pi->prstatus,
1112                                     sizeof (gdb_prstatus_t))
1113                               == sizeof (gdb_prstatus_t));
1114 #if 0 /*def UNIXWARE*/
1115           if (pi->status_valid &&
1116               (pi->prstatus.pr_lwp.pr_flags & PR_ISTOP) &&
1117               pi->prstatus.pr_lwp.pr_why == PR_REQUESTED)
1118             /* Unixware peculiarity -- read the damn thing again! */
1119             pi->status_valid = (read (pi->status_fd, 
1120                                       (char *) &pi->prstatus,
1121                                       sizeof (gdb_prstatus_t))
1122                                 == sizeof (gdb_prstatus_t));
1123 #endif /* UNIXWARE */
1124         }
1125     }
1126 #else   /* ioctl method */
1127 #ifdef PIOCTSTATUS      /* osf */
1128   if (pi->tid == 0)     /* main process */
1129     {
1130       /* Just read the danged status.  Now isn't that simple? */
1131       pi->status_valid = 
1132         (ioctl (pi->status_fd, PIOCSTATUS, &pi->prstatus) >= 0);
1133     }
1134   else
1135     {
1136       int win;
1137       struct {
1138         long pr_count;
1139         tid_t pr_error_thread;
1140         struct prstatus status;
1141       } thread_status;
1142
1143       thread_status.pr_count = 1;
1144       thread_status.status.pr_tid = pi->tid;
1145       win = (ioctl (pi->status_fd, PIOCTSTATUS, &thread_status) >= 0);
1146       if (win)
1147         {
1148           memcpy (&pi->prstatus, &thread_status.status, 
1149                   sizeof (pi->prstatus));
1150           pi->status_valid = 1;
1151         }
1152     }
1153 #else
1154   /* Just read the danged status.  Now isn't that simple? */
1155   pi->status_valid = (ioctl (pi->status_fd, PIOCSTATUS, &pi->prstatus) >= 0);
1156 #endif
1157 #endif
1158
1159   if (pi->status_valid)
1160     {
1161       PROC_PRETTYFPRINT_STATUS (proc_flags (pi), 
1162                                 proc_why (pi),
1163                                 proc_what (pi), 
1164                                 proc_get_current_thread (pi));
1165     }
1166
1167   /* The status struct includes general regs, so mark them valid too */
1168   pi->gregs_valid  = pi->status_valid;
1169 #ifdef NEW_PROC_API
1170   /* In the read/write multiple-fd model, 
1171      the status struct includes the fp regs too, so mark them valid too */
1172   pi->fpregs_valid = pi->status_valid;
1173 #endif
1174   return pi->status_valid;      /* True if success, false if failure. */
1175 }
1176
1177 /*
1178  * Function: proc_flags
1179  *
1180  * returns the process flags (pr_flags field).
1181  */ 
1182
1183 long
1184 proc_flags (procinfo *pi)
1185 {
1186   if (!pi->status_valid)
1187     if (!proc_get_status (pi))
1188       return 0; /* FIXME: not a good failure value (but what is?) */
1189
1190 #ifdef NEW_PROC_API
1191 # ifdef UNIXWARE
1192   /* UnixWare 7.1 puts process status flags, e.g. PR_ASYNC, in
1193      pstatus_t and LWP status flags, e.g. PR_STOPPED, in lwpstatus_t.
1194      The two sets of flags don't overlap. */
1195   return pi->prstatus.pr_flags | pi->prstatus.pr_lwp.pr_flags;
1196 # else
1197   return pi->prstatus.pr_lwp.pr_flags;
1198 # endif
1199 #else
1200   return pi->prstatus.pr_flags;
1201 #endif
1202 }
1203
1204 /*
1205  * Function: proc_why
1206  *
1207  * returns the pr_why field (why the process stopped).
1208  */
1209
1210 int
1211 proc_why (procinfo *pi)
1212 {
1213   if (!pi->status_valid)
1214     if (!proc_get_status (pi))
1215       return 0; /* FIXME: not a good failure value (but what is?) */
1216
1217 #ifdef NEW_PROC_API
1218   return pi->prstatus.pr_lwp.pr_why;
1219 #else
1220   return pi->prstatus.pr_why;
1221 #endif
1222 }
1223
1224 /*
1225  * Function: proc_what
1226  *
1227  * returns the pr_what field (details of why the process stopped).
1228  */
1229
1230 int
1231 proc_what (procinfo *pi)
1232 {
1233   if (!pi->status_valid)
1234     if (!proc_get_status (pi))
1235       return 0; /* FIXME: not a good failure value (but what is?) */
1236
1237 #ifdef NEW_PROC_API
1238   return pi->prstatus.pr_lwp.pr_what;
1239 #else
1240   return pi->prstatus.pr_what;
1241 #endif
1242 }
1243
1244 #ifndef PIOCSSPCACT     /* The following is not supported on OSF.  */
1245 /*
1246  * Function: proc_nsysarg
1247  *
1248  * returns the pr_nsysarg field (number of args to the current syscall).
1249  */
1250
1251 int
1252 proc_nsysarg (procinfo *pi)
1253 {
1254   if (!pi->status_valid)
1255     if (!proc_get_status (pi))
1256       return 0;
1257   
1258 #ifdef NEW_PROC_API
1259   return pi->prstatus.pr_lwp.pr_nsysarg;
1260 #else
1261   return pi->prstatus.pr_nsysarg;
1262 #endif
1263 }
1264
1265 /*
1266  * Function: proc_sysargs
1267  *
1268  * returns the pr_sysarg field (pointer to the arguments of current syscall).
1269  */
1270
1271 long *
1272 proc_sysargs (procinfo *pi)
1273 {
1274   if (!pi->status_valid)
1275     if (!proc_get_status (pi))
1276       return NULL;
1277   
1278 #ifdef NEW_PROC_API
1279   return (long *) &pi->prstatus.pr_lwp.pr_sysarg;
1280 #else
1281   return (long *) &pi->prstatus.pr_sysarg;
1282 #endif
1283 }
1284
1285 /*
1286  * Function: proc_syscall
1287  *
1288  * returns the pr_syscall field (id of current syscall if we are in one).
1289  */
1290
1291 int
1292 proc_syscall (procinfo *pi)
1293 {
1294   if (!pi->status_valid)
1295     if (!proc_get_status (pi))
1296       return 0;
1297   
1298 #ifdef NEW_PROC_API
1299   return pi->prstatus.pr_lwp.pr_syscall;
1300 #else
1301   return pi->prstatus.pr_syscall;
1302 #endif
1303 }
1304 #endif /* PIOCSSPCACT */
1305
1306 /*
1307  * Function: proc_cursig:
1308  *
1309  * returns the pr_cursig field (current signal).
1310  */
1311
1312 long
1313 proc_cursig (struct procinfo *pi)
1314 {
1315   if (!pi->status_valid)
1316     if (!proc_get_status (pi))
1317       return 0; /* FIXME: not a good failure value (but what is?) */
1318
1319 #ifdef NEW_PROC_API
1320   return pi->prstatus.pr_lwp.pr_cursig;
1321 #else
1322   return pi->prstatus.pr_cursig;
1323 #endif
1324 }
1325
1326 /*
1327  * Function: proc_modify_flag 
1328  *
1329  *  === I appologize for the messiness of this function. 
1330  *  === This is an area where the different versions of
1331  *  === /proc are more inconsistent than usual.     MVS
1332  *
1333  * Set or reset any of the following process flags:
1334  *    PR_FORK   -- forked child will inherit trace flags
1335  *    PR_RLC    -- traced process runs when last /proc file closed.
1336  *    PR_KLC    -- traced process is killed when last /proc file closed.
1337  *    PR_ASYNC  -- LWP's get to run/stop independently.
1338  *
1339  * There are three methods for doing this function:
1340  * 1) Newest: read/write [PCSET/PCRESET/PCUNSET]
1341  *    [Sol6, Sol7, UW]
1342  * 2) Middle: PIOCSET/PIOCRESET
1343  *    [Irix, Sol5]
1344  * 3) Oldest: PIOCSFORK/PIOCRFORK/PIOCSRLC/PIOCRRLC
1345  *    [OSF, Sol5]
1346  *
1347  * Note: Irix does not define PR_ASYNC.
1348  * Note: OSF  does not define PR_KLC.
1349  * Note: OSF  is the only one that can ONLY use the oldest method.
1350  *
1351  * Arguments: 
1352  *    pi   -- the procinfo
1353  *    flag -- one of PR_FORK, PR_RLC, or PR_ASYNC
1354  *    mode -- 1 for set, 0 for reset.
1355  *
1356  * Returns non-zero for success, zero for failure.
1357  */
1358
1359 enum { FLAG_RESET, FLAG_SET };
1360
1361 static int
1362 proc_modify_flag (procinfo *pi, long flag, long mode)
1363 {
1364   long win = 0;         /* default to fail */
1365
1366   /* 
1367    * These operations affect the process as a whole, and applying 
1368    * them to an individual LWP has the same meaning as applying them 
1369    * to the main process.  Therefore, if we're ever called with a 
1370    * pointer to an LWP's procinfo, let's substitute the process's 
1371    * procinfo and avoid opening the LWP's file descriptor 
1372    * unnecessarily.  
1373    */
1374
1375   if (pi->pid != 0)
1376     pi = find_procinfo_or_die (pi->pid, 0);
1377
1378 #ifdef NEW_PROC_API     /* Newest method: UnixWare and newer Solarii */
1379   /* First normalize the PCUNSET/PCRESET command opcode 
1380      (which for no obvious reason has a different definition
1381      from one operating system to the next...)  */
1382 #ifdef  PCUNSET
1383 #define GDBRESET PCUNSET
1384 #else
1385 #ifdef  PCRESET
1386 #define GDBRESET PCRESET
1387 #endif
1388 #endif
1389   {
1390     procfs_ctl_t arg[2];
1391
1392     if (mode == FLAG_SET)       /* Set the flag (RLC, FORK, or ASYNC) */
1393       arg[0] = PCSET;
1394     else                        /* Reset the flag */
1395       arg[0] = GDBRESET;
1396
1397     arg[1] = flag;
1398     win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1399   }
1400 #else
1401 #ifdef PIOCSET          /* Irix/Sol5 method */
1402   if (mode == FLAG_SET) /* Set the flag (hopefully RLC, FORK, or ASYNC) */
1403     {
1404       win = (ioctl (pi->ctl_fd, PIOCSET, &flag)   >= 0);
1405     }
1406   else                  /* Reset the flag */
1407     {
1408       win = (ioctl (pi->ctl_fd, PIOCRESET, &flag) >= 0);
1409     }
1410
1411 #else
1412 #ifdef PIOCSRLC         /* Oldest method: OSF */
1413   switch (flag) {
1414   case PR_RLC:
1415     if (mode == FLAG_SET)       /* Set run-on-last-close */
1416       {
1417         win = (ioctl (pi->ctl_fd, PIOCSRLC, NULL) >= 0);
1418       }
1419     else                        /* Clear run-on-last-close */
1420       {
1421         win = (ioctl (pi->ctl_fd, PIOCRRLC, NULL) >= 0);
1422       }
1423     break;
1424   case PR_FORK:
1425     if (mode == FLAG_SET)       /* Set inherit-on-fork */
1426       {
1427         win = (ioctl (pi->ctl_fd, PIOCSFORK, NULL) >= 0);
1428       }
1429     else                        /* Clear inherit-on-fork */
1430       {
1431         win = (ioctl (pi->ctl_fd, PIOCRFORK, NULL) >= 0);
1432       }
1433     break;
1434   default:
1435     win = 0;            /* fail -- unknown flag (can't do PR_ASYNC) */
1436     break;
1437   }
1438 #endif
1439 #endif
1440 #endif
1441 #undef GDBRESET
1442   /* The above operation renders the procinfo's cached pstatus obsolete. */
1443   pi->status_valid = 0;
1444
1445   if (!win)
1446     warning ("procfs: modify_flag failed to turn %s %s", 
1447              flag == PR_FORK  ? "PR_FORK"  :
1448              flag == PR_RLC   ? "PR_RLC"   :
1449 #ifdef PR_ASYNC
1450              flag == PR_ASYNC ? "PR_ASYNC" :
1451 #endif
1452 #ifdef PR_KLC
1453              flag == PR_KLC   ? "PR_KLC"   :
1454 #endif
1455              "<unknown flag>",
1456              mode == FLAG_RESET ? "off" : "on");
1457
1458   return win;
1459 }
1460
1461 /*
1462  * Function: proc_set_run_on_last_close
1463  *
1464  * Set the run_on_last_close flag.
1465  * Process with all threads will become runnable
1466  * when debugger closes all /proc fds.
1467  *
1468  * Returns non-zero for success, zero for failure.
1469  */
1470
1471 int
1472 proc_set_run_on_last_close (procinfo *pi)
1473 {
1474   return proc_modify_flag (pi, PR_RLC, FLAG_SET);
1475 }
1476
1477 /*
1478  * Function: proc_unset_run_on_last_close
1479  *
1480  * Reset the run_on_last_close flag.
1481  * Process will NOT become runnable
1482  * when debugger closes its file handles.
1483  *
1484  * Returns non-zero for success, zero for failure.
1485  */
1486
1487 int
1488 proc_unset_run_on_last_close (procinfo *pi)
1489 {
1490   return proc_modify_flag (pi, PR_RLC, FLAG_RESET);
1491 }
1492
1493 #ifdef PR_KLC
1494 /*
1495  * Function: proc_set_kill_on_last_close
1496  *
1497  * Set the kill_on_last_close flag.
1498  * Process with all threads will be killed when debugger
1499  * closes all /proc fds (or debugger exits or dies).
1500  *
1501  * Returns non-zero for success, zero for failure.
1502  */
1503
1504 int
1505 proc_set_kill_on_last_close (procinfo *pi)
1506 {
1507   return proc_modify_flag (pi, PR_KLC, FLAG_SET);
1508 }
1509
1510 /*
1511  * Function: proc_unset_kill_on_last_close
1512  *
1513  * Reset the kill_on_last_close flag.
1514  * Process will NOT be killed when debugger 
1515  * closes its file handles (or exits or dies).
1516  *
1517  * Returns non-zero for success, zero for failure.
1518  */
1519
1520 int
1521 proc_unset_kill_on_last_close (procinfo *pi)
1522 {
1523   return proc_modify_flag (pi, PR_KLC, FLAG_RESET);
1524 }
1525 #endif /* PR_KLC */
1526
1527 /*
1528  * Function: proc_set_inherit_on_fork
1529  *
1530  * Set inherit_on_fork flag.
1531  * If the process forks a child while we are registered for events
1532  * in the parent, then we will also recieve events from the child.
1533  *
1534  * Returns non-zero for success, zero for failure.
1535  */
1536
1537 int
1538 proc_set_inherit_on_fork (procinfo *pi)
1539 {
1540   return proc_modify_flag (pi, PR_FORK, FLAG_SET);
1541 }
1542
1543 /*
1544  * Function: proc_unset_inherit_on_fork
1545  *
1546  * Reset inherit_on_fork flag.
1547  * If the process forks a child while we are registered for events
1548  * in the parent, then we will NOT recieve events from the child.
1549  *
1550  * Returns non-zero for success, zero for failure.
1551  */
1552
1553 int
1554 proc_unset_inherit_on_fork (procinfo *pi)
1555 {
1556   return proc_modify_flag (pi, PR_FORK, FLAG_RESET);
1557 }
1558
1559 #ifdef PR_ASYNC
1560 /*
1561  * Function: proc_set_async
1562  *
1563  * Set PR_ASYNC flag.
1564  * If one LWP stops because of a debug event (signal etc.), 
1565  * the remaining LWPs will continue to run.
1566  *
1567  * Returns non-zero for success, zero for failure.
1568  */
1569
1570 int
1571 proc_set_async (procinfo *pi)
1572 {
1573   return proc_modify_flag (pi, PR_ASYNC, FLAG_SET);
1574 }
1575
1576 /*
1577  * Function: proc_unset_async
1578  *
1579  * Reset PR_ASYNC flag.
1580  * If one LWP stops because of a debug event (signal etc.),
1581  * then all other LWPs will stop as well.
1582  *
1583  * Returns non-zero for success, zero for failure.
1584  */
1585
1586 int
1587 proc_unset_async (procinfo *pi)
1588 {
1589   return proc_modify_flag (pi, PR_ASYNC, FLAG_RESET);
1590 }
1591 #endif /* PR_ASYNC */
1592
1593 /*
1594  * Function: proc_stop_process
1595  *
1596  * Request the process/LWP to stop.  Does not wait.
1597  * Returns non-zero for success, zero for failure. 
1598  */
1599
1600 int
1601 proc_stop_process (procinfo *pi)
1602 {
1603   int win;
1604
1605   /*
1606    * We might conceivably apply this operation to an LWP, and
1607    * the LWP's ctl file descriptor might not be open.
1608    */
1609
1610   if (pi->ctl_fd == 0 &&
1611       open_procinfo_files (pi, FD_CTL) == 0)
1612     return 0;
1613   else
1614     {
1615 #ifdef NEW_PROC_API
1616       procfs_ctl_t cmd = PCSTOP;
1617       win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
1618 #else   /* ioctl method */
1619       win = (ioctl (pi->ctl_fd, PIOCSTOP, &pi->prstatus) >= 0);
1620       /* Note: the call also reads the prstatus.  */
1621       if (win)
1622         {
1623           pi->status_valid = 1;
1624           PROC_PRETTYFPRINT_STATUS (proc_flags (pi), 
1625                                     proc_why (pi),
1626                                     proc_what (pi), 
1627                                     proc_get_current_thread (pi));
1628         }
1629 #endif
1630     }
1631
1632   return win;
1633 }
1634
1635 /*
1636  * Function: proc_wait_for_stop
1637  *
1638  * Wait for the process or LWP to stop (block until it does).
1639  * Returns non-zero for success, zero for failure. 
1640  */
1641
1642 int
1643 proc_wait_for_stop (procinfo *pi)
1644 {
1645   int win;
1646
1647   /*
1648    * We should never have to apply this operation to any procinfo
1649    * except the one for the main process.  If that ever changes
1650    * for any reason, then take out the following clause and 
1651    * replace it with one that makes sure the ctl_fd is open.
1652    */
1653   
1654   if (pi->tid != 0)
1655     pi = find_procinfo_or_die (pi->pid, 0);
1656
1657 #ifdef NEW_PROC_API
1658   {
1659     procfs_ctl_t cmd = PCWSTOP;
1660     win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
1661     /* We been runnin' and we stopped -- need to update status.  */
1662     pi->status_valid = 0;
1663   }
1664 #else   /* ioctl method */
1665   win = (ioctl (pi->ctl_fd, PIOCWSTOP, &pi->prstatus) >= 0);
1666   /* Above call also refreshes the prstatus.  */
1667   if (win)
1668     {
1669       pi->status_valid = 1;
1670       PROC_PRETTYFPRINT_STATUS (proc_flags (pi), 
1671                                 proc_why (pi),
1672                                 proc_what (pi), 
1673                                 proc_get_current_thread (pi));
1674     }
1675 #endif
1676
1677   return win;
1678 }
1679
1680 /*
1681  * Function: proc_run_process
1682  *
1683  * Make the process or LWP runnable.
1684  * Options (not all are implemented):
1685  *   - single-step
1686  *   - clear current fault
1687  *   - clear current signal
1688  *   - abort the current system call
1689  *   - stop as soon as finished with system call
1690  *   - (ioctl): set traced signal set
1691  *   - (ioctl): set held   signal set
1692  *   - (ioctl): set traced fault  set
1693  *   - (ioctl): set start pc (vaddr)
1694  * Always clear the current fault.
1695  * Clear the current signal if 'signo' is zero.
1696  *
1697  * Arguments:
1698  *   pi         the process or LWP to operate on.
1699  *   step       if true, set the process or LWP to trap after one instr.
1700  *   signo      if zero, clear the current signal if any.
1701  *              if non-zero, set the current signal to this one.
1702  *
1703  * Returns non-zero for success, zero for failure. 
1704  */
1705
1706 int
1707 proc_run_process (procinfo *pi, int step, int signo)
1708 {
1709   int win;
1710   int runflags;
1711
1712   /*
1713    * We will probably have to apply this operation to individual threads,
1714    * so make sure the control file descriptor is open.
1715    */
1716   
1717   if (pi->ctl_fd == 0 &&
1718       open_procinfo_files (pi, FD_CTL) == 0)
1719     {
1720       return 0;
1721     }
1722
1723   runflags    = PRCFAULT;       /* always clear current fault  */
1724   if (step)
1725     runflags |= PRSTEP;
1726   if (signo == 0)
1727     runflags |= PRCSIG;
1728   else if (signo != -1)         /* -1 means do nothing W.R.T. signals */
1729     proc_set_current_signal (pi, signo);
1730
1731 #ifdef NEW_PROC_API
1732   {
1733     procfs_ctl_t cmd[2];
1734
1735     cmd[0]  = PCRUN;
1736     cmd[1]  = runflags;
1737     win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
1738   }
1739 #else   /* ioctl method */
1740   {
1741     prrun_t prrun;
1742
1743     memset (&prrun, 0, sizeof (prrun));
1744     prrun.pr_flags  = runflags;
1745     win = (ioctl (pi->ctl_fd, PIOCRUN, &prrun) >= 0);
1746   }
1747 #endif
1748
1749   return win;
1750 }
1751
1752 /*
1753  * Function: proc_set_traced_signals
1754  *
1755  * Register to trace signals in the process or LWP.
1756  * Returns non-zero for success, zero for failure. 
1757  */
1758
1759 int
1760 proc_set_traced_signals (procinfo *pi, gdb_sigset_t *sigset)
1761 {
1762   int win;
1763
1764   /*
1765    * We should never have to apply this operation to any procinfo
1766    * except the one for the main process.  If that ever changes
1767    * for any reason, then take out the following clause and 
1768    * replace it with one that makes sure the ctl_fd is open.
1769    */
1770   
1771   if (pi->tid != 0)
1772     pi = find_procinfo_or_die (pi->pid, 0);
1773
1774 #ifdef NEW_PROC_API
1775   {
1776     struct {
1777       procfs_ctl_t cmd;
1778       /* Use char array to avoid alignment issues.  */
1779       char sigset[sizeof (gdb_sigset_t)];
1780     } arg;
1781
1782     arg.cmd = PCSTRACE;
1783     memcpy (&arg.sigset, sigset, sizeof (gdb_sigset_t));
1784
1785     win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1786   }
1787 #else   /* ioctl method */
1788   win = (ioctl (pi->ctl_fd, PIOCSTRACE, sigset) >= 0);
1789 #endif
1790   /* The above operation renders the procinfo's cached pstatus obsolete. */
1791   pi->status_valid = 0;
1792
1793   if (!win)
1794     warning ("procfs: set_traced_signals failed");
1795   return win;
1796 }
1797
1798 /*
1799  * Function: proc_set_traced_faults
1800  *
1801  * Register to trace hardware faults in the process or LWP.
1802  * Returns non-zero for success, zero for failure. 
1803  */
1804
1805 int
1806 proc_set_traced_faults (procinfo *pi, fltset_t *fltset)
1807 {
1808   int win;
1809
1810   /*
1811    * We should never have to apply this operation to any procinfo
1812    * except the one for the main process.  If that ever changes
1813    * for any reason, then take out the following clause and 
1814    * replace it with one that makes sure the ctl_fd is open.
1815    */
1816   
1817   if (pi->tid != 0)
1818     pi = find_procinfo_or_die (pi->pid, 0);
1819
1820 #ifdef NEW_PROC_API
1821   {
1822     struct {
1823       procfs_ctl_t cmd;
1824       /* Use char array to avoid alignment issues.  */
1825       char fltset[sizeof (fltset_t)];
1826     } arg;
1827
1828     arg.cmd = PCSFAULT;
1829     memcpy (&arg.fltset, fltset, sizeof (fltset_t));
1830
1831     win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1832   }
1833 #else   /* ioctl method */
1834   win = (ioctl (pi->ctl_fd, PIOCSFAULT, fltset) >= 0);
1835 #endif
1836   /* The above operation renders the procinfo's cached pstatus obsolete. */
1837   pi->status_valid = 0;
1838
1839   return win;
1840 }
1841
1842 /*
1843  * Function: proc_set_traced_sysentry
1844  *
1845  * Register to trace entry to system calls in the process or LWP.
1846  * Returns non-zero for success, zero for failure. 
1847  */
1848
1849 int
1850 proc_set_traced_sysentry (procinfo *pi, sysset_t *sysset)
1851 {
1852   int win;
1853
1854   /*
1855    * We should never have to apply this operation to any procinfo
1856    * except the one for the main process.  If that ever changes
1857    * for any reason, then take out the following clause and 
1858    * replace it with one that makes sure the ctl_fd is open.
1859    */
1860   
1861   if (pi->tid != 0)
1862     pi = find_procinfo_or_die (pi->pid, 0);
1863
1864 #ifdef NEW_PROC_API
1865   {
1866     struct gdb_proc_ctl_pcsentry {
1867       procfs_ctl_t cmd;
1868       /* Use char array to avoid alignment issues.  */
1869       char sysset[sizeof (sysset_t)];
1870     } *argp;
1871     int argp_size = sizeof (struct gdb_proc_ctl_pcsentry)
1872                   - sizeof (sysset_t)
1873                   + sysset_t_size (pi);
1874
1875     argp = xmalloc (argp_size);
1876
1877     argp->cmd = PCSENTRY;
1878     memcpy (&argp->sysset, sysset, sysset_t_size (pi));
1879
1880     win = (write (pi->ctl_fd, (char *) argp, argp_size) == argp_size);
1881     xfree (argp);
1882   }
1883 #else   /* ioctl method */
1884   win = (ioctl (pi->ctl_fd, PIOCSENTRY, sysset) >= 0);
1885 #endif
1886   /* The above operation renders the procinfo's cached pstatus obsolete. */
1887   pi->status_valid = 0;
1888      
1889   return win;
1890 }
1891
1892 /*
1893  * Function: proc_set_traced_sysexit
1894  *
1895  * Register to trace exit from system calls in the process or LWP.
1896  * Returns non-zero for success, zero for failure. 
1897  */
1898
1899 int
1900 proc_set_traced_sysexit (procinfo *pi, sysset_t *sysset)
1901 {
1902   int win;
1903
1904   /*
1905    * We should never have to apply this operation to any procinfo
1906    * except the one for the main process.  If that ever changes
1907    * for any reason, then take out the following clause and 
1908    * replace it with one that makes sure the ctl_fd is open.
1909    */
1910   
1911   if (pi->tid != 0)
1912     pi = find_procinfo_or_die (pi->pid, 0);
1913
1914 #ifdef NEW_PROC_API
1915   {
1916     struct gdb_proc_ctl_pcsexit {
1917       procfs_ctl_t cmd;
1918       /* Use char array to avoid alignment issues.  */
1919       char sysset[sizeof (sysset_t)];
1920     } *argp;
1921     int argp_size = sizeof (struct gdb_proc_ctl_pcsexit)
1922                   - sizeof (sysset_t)
1923                   + sysset_t_size (pi);
1924
1925     argp = xmalloc (argp_size);
1926
1927     argp->cmd = PCSEXIT;
1928     memcpy (&argp->sysset, sysset, sysset_t_size (pi));
1929
1930     win = (write (pi->ctl_fd, (char *) argp, argp_size) == argp_size);
1931     xfree (argp);
1932   }
1933 #else   /* ioctl method */
1934   win = (ioctl (pi->ctl_fd, PIOCSEXIT, sysset) >= 0);
1935 #endif
1936   /* The above operation renders the procinfo's cached pstatus obsolete. */
1937   pi->status_valid = 0;
1938
1939   return win;
1940 }
1941
1942 /*
1943  * Function: proc_set_held_signals
1944  *
1945  * Specify the set of blocked / held signals in the process or LWP.
1946  * Returns non-zero for success, zero for failure. 
1947  */
1948
1949 int
1950 proc_set_held_signals (procinfo *pi, gdb_sigset_t *sighold)
1951 {
1952   int win;
1953
1954   /*
1955    * We should never have to apply this operation to any procinfo
1956    * except the one for the main process.  If that ever changes
1957    * for any reason, then take out the following clause and 
1958    * replace it with one that makes sure the ctl_fd is open.
1959    */
1960   
1961   if (pi->tid != 0)
1962     pi = find_procinfo_or_die (pi->pid, 0);
1963
1964 #ifdef NEW_PROC_API
1965   {
1966     struct {
1967       procfs_ctl_t cmd;
1968       /* Use char array to avoid alignment issues.  */
1969       char hold[sizeof (gdb_sigset_t)];
1970     } arg;
1971
1972     arg.cmd  = PCSHOLD;
1973     memcpy (&arg.hold, sighold, sizeof (gdb_sigset_t));
1974     win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1975   }
1976 #else
1977   win = (ioctl (pi->ctl_fd, PIOCSHOLD, sighold) >= 0);
1978 #endif
1979   /* The above operation renders the procinfo's cached pstatus obsolete. */
1980   pi->status_valid = 0;
1981
1982   return win;
1983 }
1984
1985 /*
1986  * Function: proc_get_pending_signals
1987  *
1988  * returns the set of signals that are pending in the process or LWP.
1989  * Will also copy the sigset if 'save' is non-zero.
1990  */
1991
1992 gdb_sigset_t *
1993 proc_get_pending_signals (procinfo *pi, gdb_sigset_t *save)
1994 {
1995   gdb_sigset_t *ret = NULL;
1996
1997   /*
1998    * We should never have to apply this operation to any procinfo
1999    * except the one for the main process.  If that ever changes
2000    * for any reason, then take out the following clause and 
2001    * replace it with one that makes sure the ctl_fd is open.
2002    */
2003   
2004   if (pi->tid != 0)
2005     pi = find_procinfo_or_die (pi->pid, 0);
2006
2007   if (!pi->status_valid)
2008     if (!proc_get_status (pi))
2009       return NULL;
2010
2011 #ifdef NEW_PROC_API
2012   ret = &pi->prstatus.pr_lwp.pr_lwppend;
2013 #else
2014   ret = &pi->prstatus.pr_sigpend;
2015 #endif
2016   if (save && ret)
2017     memcpy (save, ret, sizeof (gdb_sigset_t));
2018
2019   return ret;
2020 }
2021
2022 /*
2023  * Function: proc_get_signal_actions
2024  *
2025  * returns the set of signal actions.
2026  * Will also copy the sigactionset if 'save' is non-zero.
2027  */
2028
2029 gdb_sigaction_t *
2030 proc_get_signal_actions (procinfo *pi, gdb_sigaction_t *save)
2031 {
2032   gdb_sigaction_t *ret = NULL;
2033
2034   /*
2035    * We should never have to apply this operation to any procinfo
2036    * except the one for the main process.  If that ever changes
2037    * for any reason, then take out the following clause and 
2038    * replace it with one that makes sure the ctl_fd is open.
2039    */
2040   
2041   if (pi->tid != 0)
2042     pi = find_procinfo_or_die (pi->pid, 0);
2043
2044   if (!pi->status_valid)
2045     if (!proc_get_status (pi))
2046       return NULL;
2047
2048 #ifdef NEW_PROC_API
2049   ret = &pi->prstatus.pr_lwp.pr_action;
2050 #else
2051   ret = &pi->prstatus.pr_action;
2052 #endif
2053   if (save && ret)
2054     memcpy (save, ret, sizeof (gdb_sigaction_t));
2055
2056   return ret;
2057 }
2058
2059 /*
2060  * Function: proc_get_held_signals
2061  *
2062  * returns the set of signals that are held / blocked.
2063  * Will also copy the sigset if 'save' is non-zero.
2064  */
2065
2066 gdb_sigset_t *
2067 proc_get_held_signals (procinfo *pi, gdb_sigset_t *save)
2068 {
2069   gdb_sigset_t *ret = NULL;
2070
2071   /*
2072    * We should never have to apply this operation to any procinfo
2073    * except the one for the main process.  If that ever changes
2074    * for any reason, then take out the following clause and 
2075    * replace it with one that makes sure the ctl_fd is open.
2076    */
2077   
2078   if (pi->tid != 0)
2079     pi = find_procinfo_or_die (pi->pid, 0);
2080
2081 #ifdef NEW_PROC_API
2082   if (!pi->status_valid)
2083     if (!proc_get_status (pi))
2084       return NULL;
2085
2086 #ifdef UNIXWARE
2087   ret = &pi->prstatus.pr_lwp.pr_context.uc_sigmask;
2088 #else
2089   ret = &pi->prstatus.pr_lwp.pr_lwphold;
2090 #endif /* UNIXWARE */
2091 #else  /* not NEW_PROC_API */
2092   {
2093     static gdb_sigset_t sigheld;
2094
2095     if (ioctl (pi->ctl_fd, PIOCGHOLD, &sigheld) >= 0)
2096       ret = &sigheld;
2097   }
2098 #endif /* NEW_PROC_API */
2099   if (save && ret)
2100     memcpy (save, ret, sizeof (gdb_sigset_t));
2101
2102   return ret;
2103 }
2104
2105 /*
2106  * Function: proc_get_traced_signals
2107  *
2108  * returns the set of signals that are traced / debugged.
2109  * Will also copy the sigset if 'save' is non-zero.
2110  */
2111
2112 gdb_sigset_t *
2113 proc_get_traced_signals (procinfo *pi, gdb_sigset_t *save)
2114 {
2115   gdb_sigset_t *ret = NULL;
2116
2117   /*
2118    * We should never have to apply this operation to any procinfo
2119    * except the one for the main process.  If that ever changes
2120    * for any reason, then take out the following clause and 
2121    * replace it with one that makes sure the ctl_fd is open.
2122    */
2123   
2124   if (pi->tid != 0)
2125     pi = find_procinfo_or_die (pi->pid, 0);
2126
2127 #ifdef NEW_PROC_API
2128   if (!pi->status_valid)
2129     if (!proc_get_status (pi))
2130       return NULL;
2131
2132   ret = &pi->prstatus.pr_sigtrace;
2133 #else
2134   {
2135     static gdb_sigset_t sigtrace;
2136
2137     if (ioctl (pi->ctl_fd, PIOCGTRACE, &sigtrace) >= 0)
2138       ret = &sigtrace;
2139   }
2140 #endif
2141   if (save && ret)
2142     memcpy (save, ret, sizeof (gdb_sigset_t));
2143
2144   return ret;
2145 }
2146
2147 /*
2148  * Function: proc_trace_signal
2149  *
2150  * Add 'signo' to the set of signals that are traced.
2151  * Returns non-zero for success, zero for failure.
2152  */
2153
2154 int
2155 proc_trace_signal (procinfo *pi, int signo)
2156 {
2157   gdb_sigset_t temp;
2158
2159   /*
2160    * We should never have to apply this operation to any procinfo
2161    * except the one for the main process.  If that ever changes
2162    * for any reason, then take out the following clause and 
2163    * replace it with one that makes sure the ctl_fd is open.
2164    */
2165   
2166   if (pi->tid != 0)
2167     pi = find_procinfo_or_die (pi->pid, 0);
2168
2169   if (pi)
2170     {
2171       if (proc_get_traced_signals (pi, &temp))
2172         {
2173           praddset (&temp, signo);
2174           return proc_set_traced_signals (pi, &temp);
2175         }
2176     }
2177
2178   return 0;     /* failure */
2179 }
2180
2181 /*
2182  * Function: proc_ignore_signal
2183  *
2184  * Remove 'signo' from the set of signals that are traced.
2185  * Returns non-zero for success, zero for failure.
2186  */
2187
2188 int
2189 proc_ignore_signal (procinfo *pi, int signo)
2190 {
2191   gdb_sigset_t temp;
2192
2193   /*
2194    * We should never have to apply this operation to any procinfo
2195    * except the one for the main process.  If that ever changes
2196    * for any reason, then take out the following clause and 
2197    * replace it with one that makes sure the ctl_fd is open.
2198    */
2199   
2200   if (pi->tid != 0)
2201     pi = find_procinfo_or_die (pi->pid, 0);
2202
2203   if (pi)
2204     {
2205       if (proc_get_traced_signals (pi, &temp))
2206         {
2207           prdelset (&temp, signo);
2208           return proc_set_traced_signals (pi, &temp);
2209         }
2210     }
2211
2212   return 0;     /* failure */
2213 }
2214
2215 /*
2216  * Function: proc_get_traced_faults
2217  *
2218  * returns the set of hardware faults that are traced /debugged.
2219  * Will also copy the faultset if 'save' is non-zero.
2220  */
2221
2222 fltset_t *
2223 proc_get_traced_faults (procinfo *pi, fltset_t *save)
2224 {
2225   fltset_t *ret = NULL;
2226
2227   /*
2228    * We should never have to apply this operation to any procinfo
2229    * except the one for the main process.  If that ever changes
2230    * for any reason, then take out the following clause and 
2231    * replace it with one that makes sure the ctl_fd is open.
2232    */
2233   
2234   if (pi->tid != 0)
2235     pi = find_procinfo_or_die (pi->pid, 0);
2236
2237 #ifdef NEW_PROC_API
2238   if (!pi->status_valid)
2239     if (!proc_get_status (pi))
2240       return NULL;
2241
2242   ret = &pi->prstatus.pr_flttrace;
2243 #else
2244   {
2245     static fltset_t flttrace;
2246
2247     if (ioctl (pi->ctl_fd, PIOCGFAULT, &flttrace) >= 0)
2248       ret = &flttrace;
2249   }
2250 #endif
2251   if (save && ret)
2252     memcpy (save, ret, sizeof (fltset_t));
2253
2254   return ret;
2255 }
2256
2257 /*
2258  * Function: proc_get_traced_sysentry
2259  *
2260  * returns the set of syscalls that are traced /debugged on entry.
2261  * Will also copy the syscall set if 'save' is non-zero.
2262  */
2263
2264 sysset_t *
2265 proc_get_traced_sysentry (procinfo *pi, sysset_t *save)
2266 {
2267   sysset_t *ret = NULL;
2268
2269   /*
2270    * We should never have to apply this operation to any procinfo
2271    * except the one for the main process.  If that ever changes
2272    * for any reason, then take out the following clause and 
2273    * replace it with one that makes sure the ctl_fd is open.
2274    */
2275   
2276   if (pi->tid != 0)
2277     pi = find_procinfo_or_die (pi->pid, 0);
2278
2279 #ifdef NEW_PROC_API
2280   if (!pi->status_valid)
2281     if (!proc_get_status (pi))
2282       return NULL;
2283
2284 #ifndef DYNAMIC_SYSCALLS
2285   ret = &pi->prstatus.pr_sysentry;
2286 #else /* DYNAMIC_SYSCALLS */
2287   {
2288     static sysset_t *sysentry;
2289     size_t size;
2290
2291     if (!sysentry)
2292       sysentry = sysset_t_alloc (pi);
2293     ret = sysentry;
2294     if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
2295       return NULL;
2296     if (pi->prstatus.pr_sysentry_offset == 0)
2297       {
2298         gdb_premptysysset (sysentry);
2299       }
2300     else
2301       {
2302         int rsize;
2303
2304         if (lseek (pi->status_fd, (off_t) pi->prstatus.pr_sysentry_offset,
2305                    SEEK_SET)
2306             != (off_t) pi->prstatus.pr_sysentry_offset)
2307           return NULL;
2308         size = sysset_t_size (pi);
2309         gdb_premptysysset (sysentry);
2310         rsize = read (pi->status_fd, sysentry, size);
2311         if (rsize < 0)
2312           return NULL;
2313       }
2314   }
2315 #endif /* DYNAMIC_SYSCALLS */
2316 #else /* !NEW_PROC_API */
2317   {
2318     static sysset_t sysentry;
2319
2320     if (ioctl (pi->ctl_fd, PIOCGENTRY, &sysentry) >= 0)
2321       ret = &sysentry;
2322   }
2323 #endif /* NEW_PROC_API */
2324   if (save && ret)
2325     memcpy (save, ret, sysset_t_size (pi));
2326
2327   return ret;
2328 }
2329
2330 /*
2331  * Function: proc_get_traced_sysexit
2332  *
2333  * returns the set of syscalls that are traced /debugged on exit.
2334  * Will also copy the syscall set if 'save' is non-zero.
2335  */
2336
2337 sysset_t *
2338 proc_get_traced_sysexit (procinfo *pi, sysset_t *save)
2339 {
2340   sysset_t * ret = NULL;
2341
2342   /*
2343    * We should never have to apply this operation to any procinfo
2344    * except the one for the main process.  If that ever changes
2345    * for any reason, then take out the following clause and 
2346    * replace it with one that makes sure the ctl_fd is open.
2347    */
2348   
2349   if (pi->tid != 0)
2350     pi = find_procinfo_or_die (pi->pid, 0);
2351
2352 #ifdef NEW_PROC_API
2353   if (!pi->status_valid)
2354     if (!proc_get_status (pi))
2355       return NULL;
2356
2357 #ifndef DYNAMIC_SYSCALLS
2358   ret = &pi->prstatus.pr_sysexit;
2359 #else /* DYNAMIC_SYSCALLS */
2360   {
2361     static sysset_t *sysexit;
2362     size_t size;
2363
2364     if (!sysexit)
2365       sysexit = sysset_t_alloc (pi);
2366     ret = sysexit;
2367     if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
2368       return NULL;
2369     if (pi->prstatus.pr_sysexit_offset == 0)
2370       {
2371         gdb_premptysysset (sysexit);
2372       }
2373     else
2374       {
2375         int rsize;
2376
2377         if (lseek (pi->status_fd, (off_t) pi->prstatus.pr_sysexit_offset, SEEK_SET)
2378             != (off_t) pi->prstatus.pr_sysexit_offset)
2379           return NULL;
2380         size = sysset_t_size (pi);
2381         gdb_premptysysset (sysexit);
2382         rsize = read (pi->status_fd, sysexit, size);
2383         if (rsize < 0)
2384           return NULL;
2385       }
2386   }
2387 #endif /* DYNAMIC_SYSCALLS */
2388 #else
2389   {
2390     static sysset_t sysexit;
2391
2392     if (ioctl (pi->ctl_fd, PIOCGEXIT, &sysexit) >= 0)
2393       ret = &sysexit;
2394   }
2395 #endif
2396   if (save && ret)
2397     memcpy (save, ret, sysset_t_size (pi));
2398
2399   return ret;
2400 }
2401
2402 /*
2403  * Function: proc_clear_current_fault
2404  *
2405  * The current fault (if any) is cleared; the associated signal
2406  * will not be sent to the process or LWP when it resumes.
2407  * Returns non-zero for success,  zero for failure.
2408  */
2409
2410 int
2411 proc_clear_current_fault (procinfo *pi)
2412 {
2413   int win;
2414
2415   /*
2416    * We should never have to apply this operation to any procinfo
2417    * except the one for the main process.  If that ever changes
2418    * for any reason, then take out the following clause and 
2419    * replace it with one that makes sure the ctl_fd is open.
2420    */
2421   
2422   if (pi->tid != 0)
2423     pi = find_procinfo_or_die (pi->pid, 0);
2424
2425 #ifdef NEW_PROC_API
2426   {
2427     procfs_ctl_t cmd = PCCFAULT;
2428     win = (write (pi->ctl_fd, (void *) &cmd, sizeof (cmd)) == sizeof (cmd));
2429   }
2430 #else
2431   win = (ioctl (pi->ctl_fd, PIOCCFAULT, 0) >= 0);
2432 #endif
2433
2434   return win;
2435 }
2436
2437 /*
2438  * Function: proc_set_current_signal
2439  *
2440  * Set the "current signal" that will be delivered next to the process.
2441  * NOTE: semantics are different from those of KILL.
2442  * This signal will be delivered to the process or LWP
2443  * immediately when it is resumed (even if the signal is held/blocked);
2444  * it will NOT immediately cause another event of interest, and will NOT
2445  * first trap back to the debugger.
2446  *
2447  * Returns non-zero for success,  zero for failure.
2448  */
2449
2450 int
2451 proc_set_current_signal (procinfo *pi, int signo)
2452 {
2453   int win;
2454   struct {
2455     procfs_ctl_t cmd;
2456     /* Use char array to avoid alignment issues.  */
2457     char sinfo[sizeof (gdb_siginfo_t)];
2458   } arg;
2459   gdb_siginfo_t *mysinfo;
2460
2461   /*
2462    * We should never have to apply this operation to any procinfo
2463    * except the one for the main process.  If that ever changes
2464    * for any reason, then take out the following clause and 
2465    * replace it with one that makes sure the ctl_fd is open.
2466    */
2467   
2468   if (pi->tid != 0)
2469     pi = find_procinfo_or_die (pi->pid, 0);
2470
2471 #ifdef PROCFS_DONT_PIOCSSIG_CURSIG
2472   /* With Alpha OSF/1 procfs, the kernel gets really confused if it
2473    * receives a PIOCSSIG with a signal identical to the current signal,
2474    * it messes up the current signal. Work around the kernel bug. 
2475    */
2476   if (signo > 0 &&
2477       signo == proc_cursig (pi))
2478     return 1;           /* I assume this is a success? */
2479 #endif
2480
2481   /* The pointer is just a type alias.  */
2482   mysinfo = (gdb_siginfo_t *) &arg.sinfo;
2483   mysinfo->si_signo = signo;
2484   mysinfo->si_code  = 0;
2485   mysinfo->si_pid   = getpid ();       /* ?why? */
2486   mysinfo->si_uid   = getuid ();       /* ?why? */
2487
2488 #ifdef NEW_PROC_API
2489   arg.cmd = PCSSIG;
2490   win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg))  == sizeof (arg));
2491 #else
2492   win = (ioctl (pi->ctl_fd, PIOCSSIG, (void *) &arg.sinfo) >= 0);
2493 #endif
2494
2495   return win;
2496 }
2497
2498 /*
2499  * Function: proc_clear_current_signal
2500  *
2501  * The current signal (if any) is cleared, and
2502  * is not sent to the process or LWP when it resumes.
2503  * Returns non-zero for success,  zero for failure.
2504  */
2505
2506 int
2507 proc_clear_current_signal (procinfo *pi)
2508 {
2509   int win;
2510
2511   /*
2512    * We should never have to apply this operation to any procinfo
2513    * except the one for the main process.  If that ever changes
2514    * for any reason, then take out the following clause and 
2515    * replace it with one that makes sure the ctl_fd is open.
2516    */
2517   
2518   if (pi->tid != 0)
2519     pi = find_procinfo_or_die (pi->pid, 0);
2520
2521 #ifdef NEW_PROC_API
2522   {
2523     struct {
2524       procfs_ctl_t cmd;
2525       /* Use char array to avoid alignment issues.  */
2526       char sinfo[sizeof (gdb_siginfo_t)];
2527     } arg;
2528     gdb_siginfo_t *mysinfo;
2529
2530     arg.cmd = PCSSIG;
2531     /* The pointer is just a type alias.  */
2532     mysinfo = (gdb_siginfo_t *) &arg.sinfo;
2533     mysinfo->si_signo = 0;
2534     mysinfo->si_code  = 0;
2535     mysinfo->si_errno = 0;
2536     mysinfo->si_pid   = getpid ();       /* ?why? */
2537     mysinfo->si_uid   = getuid ();       /* ?why? */
2538
2539     win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
2540   }
2541 #else
2542   win = (ioctl (pi->ctl_fd, PIOCSSIG, 0) >= 0);
2543 #endif
2544
2545   return win;
2546 }
2547
2548 /*
2549  * Function: proc_get_gregs
2550  *
2551  * Get the general registers for the process or LWP.
2552  * Returns non-zero for success, zero for failure.
2553  */
2554
2555 gdb_gregset_t *
2556 proc_get_gregs (procinfo *pi)
2557 {
2558   if (!pi->status_valid || !pi->gregs_valid)
2559     if (!proc_get_status (pi))
2560       return NULL;
2561
2562   /*
2563    * OK, sorry about the ifdef's.
2564    * There's three cases instead of two, because 
2565    * in this instance Unixware and Solaris/RW differ.
2566    */
2567
2568 #ifdef NEW_PROC_API
2569 #ifdef UNIXWARE         /* ugh, a true architecture dependency */
2570   return &pi->prstatus.pr_lwp.pr_context.uc_mcontext.gregs;
2571 #else   /* not Unixware */
2572   return &pi->prstatus.pr_lwp.pr_reg;
2573 #endif  /* Unixware */
2574 #else   /* not NEW_PROC_API */
2575   return &pi->prstatus.pr_reg;
2576 #endif  /* NEW_PROC_API */
2577 }
2578
2579 /*
2580  * Function: proc_get_fpregs
2581  *
2582  * Get the floating point registers for the process or LWP.
2583  * Returns non-zero for success, zero for failure.
2584  */
2585
2586 gdb_fpregset_t *
2587 proc_get_fpregs (procinfo *pi)
2588 {
2589 #ifdef NEW_PROC_API
2590   if (!pi->status_valid || !pi->fpregs_valid)
2591     if (!proc_get_status (pi))
2592       return NULL;
2593
2594 #ifdef UNIXWARE         /* a true architecture dependency */
2595   return &pi->prstatus.pr_lwp.pr_context.uc_mcontext.fpregs;
2596 #else
2597   return &pi->prstatus.pr_lwp.pr_fpreg;
2598 #endif  /* Unixware */
2599
2600 #else   /* not NEW_PROC_API */
2601   if (pi->fpregs_valid)
2602     return &pi->fpregset;       /* already got 'em */
2603   else
2604     {
2605       if (pi->ctl_fd == 0 &&
2606           open_procinfo_files (pi, FD_CTL) == 0)
2607         {
2608           return NULL;
2609         }
2610       else
2611         {
2612 #ifdef PIOCTGFPREG
2613           struct {
2614             long pr_count;
2615             tid_t pr_error_thread;
2616             tfpregset_t thread_1;
2617           } thread_fpregs;
2618
2619           thread_fpregs.pr_count = 1;
2620           thread_fpregs.thread_1.tid = pi->tid;
2621
2622           if (pi->tid == 0 &&
2623               ioctl (pi->ctl_fd, PIOCGFPREG, &pi->fpregset) >= 0)
2624             {
2625               pi->fpregs_valid = 1;
2626               return &pi->fpregset;     /* got 'em now! */
2627             }
2628           else if (pi->tid != 0 &&
2629                    ioctl (pi->ctl_fd, PIOCTGFPREG, &thread_fpregs) >= 0)
2630             {
2631               memcpy (&pi->fpregset, &thread_fpregs.thread_1.pr_fpregs,
2632                       sizeof (pi->fpregset));
2633               pi->fpregs_valid = 1;
2634               return &pi->fpregset;     /* got 'em now! */
2635             }
2636           else
2637             {
2638               return NULL;
2639             }
2640 #else
2641           if (ioctl (pi->ctl_fd, PIOCGFPREG, &pi->fpregset) >= 0)
2642             {
2643               pi->fpregs_valid = 1;
2644               return &pi->fpregset;     /* got 'em now! */
2645             }
2646           else
2647             {
2648               return NULL;
2649             }
2650 #endif
2651         }
2652     }
2653 #endif
2654 }
2655
2656 /*
2657  * Function: proc_set_gregs
2658  *
2659  * Write the general registers back to the process or LWP.
2660  * Returns non-zero for success, zero for failure.
2661  */
2662
2663 int
2664 proc_set_gregs (procinfo *pi)
2665 {
2666   gdb_gregset_t *gregs;
2667   int win;
2668
2669   if ((gregs = proc_get_gregs (pi)) == NULL)
2670     return 0;   /* get_regs has already warned */
2671
2672   if (pi->ctl_fd == 0 &&
2673       open_procinfo_files (pi, FD_CTL) == 0)
2674     {
2675       return 0;
2676     }
2677   else
2678     {
2679 #ifdef NEW_PROC_API
2680       struct {
2681         procfs_ctl_t cmd;
2682         /* Use char array to avoid alignment issues.  */
2683         char gregs[sizeof (gdb_gregset_t)];
2684       } arg;
2685
2686       arg.cmd   = PCSREG;
2687       memcpy (&arg.gregs, gregs, sizeof (arg.gregs));
2688       win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
2689 #else
2690       win = (ioctl (pi->ctl_fd, PIOCSREG, gregs) >= 0);
2691 #endif
2692     }
2693
2694   /* Policy: writing the regs invalidates our cache. */
2695   pi->gregs_valid = 0;
2696   return win;
2697 }
2698
2699 /*
2700  * Function: proc_set_fpregs
2701  *
2702  * Modify the floating point register set of the process or LWP.
2703  * Returns non-zero for success, zero for failure.
2704  */
2705
2706 int
2707 proc_set_fpregs (procinfo *pi)
2708 {
2709   gdb_fpregset_t *fpregs;
2710   int win;
2711
2712   if ((fpregs = proc_get_fpregs (pi)) == NULL)
2713     return 0;           /* get_fpregs has already warned */
2714
2715   if (pi->ctl_fd == 0 &&
2716       open_procinfo_files (pi, FD_CTL) == 0)
2717     {
2718       return 0;
2719     }
2720   else
2721     {
2722 #ifdef NEW_PROC_API
2723       struct {
2724         procfs_ctl_t cmd;
2725         /* Use char array to avoid alignment issues.  */
2726         char fpregs[sizeof (gdb_fpregset_t)];
2727       } arg;
2728
2729       arg.cmd   = PCSFPREG;
2730       memcpy (&arg.fpregs, fpregs, sizeof (arg.fpregs));
2731       win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
2732 #else
2733 #ifdef PIOCTSFPREG
2734       if (pi->tid == 0)
2735         win = (ioctl (pi->ctl_fd, PIOCSFPREG, fpregs) >= 0);
2736       else
2737         {
2738           struct {
2739             long pr_count;
2740             tid_t pr_error_thread;
2741             tfpregset_t thread_1;
2742           } thread_fpregs;
2743
2744           thread_fpregs.pr_count = 1;
2745           thread_fpregs.thread_1.tid = pi->tid;
2746           memcpy (&thread_fpregs.thread_1.pr_fpregs, fpregs,
2747                   sizeof (*fpregs));
2748           win = (ioctl (pi->ctl_fd, PIOCTSFPREG, &thread_fpregs) >= 0);
2749         }
2750 #else
2751       win = (ioctl (pi->ctl_fd, PIOCSFPREG, fpregs) >= 0);
2752 #endif  /* osf PIOCTSFPREG */
2753 #endif  /* NEW_PROC_API */
2754     }
2755
2756   /* Policy: writing the regs invalidates our cache. */
2757   pi->fpregs_valid = 0;
2758   return win;
2759 }
2760
2761 /*
2762  * Function: proc_kill
2763  *
2764  * Send a signal to the proc or lwp with the semantics of "kill()".
2765  * Returns non-zero for success,  zero for failure.
2766  */
2767
2768 int
2769 proc_kill (procinfo *pi, int signo)
2770 {
2771   int win;
2772
2773   /*
2774    * We might conceivably apply this operation to an LWP, and
2775    * the LWP's ctl file descriptor might not be open.
2776    */
2777
2778   if (pi->ctl_fd == 0 &&
2779       open_procinfo_files (pi, FD_CTL) == 0)
2780     {
2781       return 0;
2782     }
2783   else
2784     {
2785 #ifdef NEW_PROC_API
2786       procfs_ctl_t cmd[2];
2787
2788       cmd[0] = PCKILL;
2789       cmd[1] = signo;
2790       win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
2791 #else   /* ioctl method */
2792       /* FIXME: do I need the Alpha OSF fixups present in
2793          procfs.c/unconditionally_kill_inferior?  Perhaps only for SIGKILL? */
2794       win = (ioctl (pi->ctl_fd, PIOCKILL, &signo) >= 0);
2795 #endif
2796   }
2797
2798   return win;
2799 }
2800
2801 /*
2802  * Function: proc_parent_pid
2803  *
2804  * Find the pid of the process that started this one.
2805  * Returns the parent process pid, or zero.
2806  */
2807
2808 int
2809 proc_parent_pid (procinfo *pi)
2810 {
2811   /*
2812    * We should never have to apply this operation to any procinfo
2813    * except the one for the main process.  If that ever changes
2814    * for any reason, then take out the following clause and 
2815    * replace it with one that makes sure the ctl_fd is open.
2816    */
2817   
2818   if (pi->tid != 0)
2819     pi = find_procinfo_or_die (pi->pid, 0);
2820
2821   if (!pi->status_valid)
2822     if (!proc_get_status (pi))
2823       return 0;
2824
2825   return pi->prstatus.pr_ppid;
2826 }
2827
2828
2829 /*
2830  * Function: proc_set_watchpoint
2831  *
2832  */
2833
2834 int
2835 proc_set_watchpoint (procinfo *pi, CORE_ADDR addr, int len, int wflags)
2836 {
2837 #if !defined (TARGET_HAS_HARDWARE_WATCHPOINTS)  
2838   return 0;
2839 #else
2840 /* Horrible hack!  Detect Solaris 2.5, because this doesn't work on 2.5 */
2841 #if defined (PIOCOPENLWP) || defined (UNIXWARE) /* Solaris 2.5: bail out */
2842   return 0;
2843 #else
2844   struct {
2845     procfs_ctl_t cmd;
2846     char watch[sizeof (prwatch_t)];
2847   } arg;
2848   prwatch_t *pwatch;
2849
2850   pwatch            = (prwatch_t *) &arg.watch;
2851   pwatch->pr_vaddr  = address_to_host_pointer (addr);
2852   pwatch->pr_size   = len;
2853   pwatch->pr_wflags = wflags;
2854 #if defined(NEW_PROC_API) && defined (PCWATCH)
2855   arg.cmd = PCWATCH;
2856   return (write (pi->ctl_fd, &arg, sizeof (arg)) == sizeof (arg));
2857 #else
2858 #if defined (PIOCSWATCH)
2859   return (ioctl (pi->ctl_fd, PIOCSWATCH, pwatch) >= 0);
2860 #else
2861   return 0;     /* Fail */
2862 #endif
2863 #endif
2864 #endif
2865 #endif
2866 }
2867
2868 /*
2869  * Function: proc_iterate_over_mappings
2870  *
2871  * Given a pointer to a function, call that function once for every
2872  * mapped address space in the process.  The callback function 
2873  * receives an open file descriptor for the file corresponding to
2874  * that mapped address space (if there is one), and the base address
2875  * of the mapped space.  Quit when the callback function returns a
2876  * nonzero value, or at teh end of the mappings.
2877  *
2878  * Returns: the first non-zero return value of the callback function,
2879  * or zero.
2880  */
2881
2882 int
2883 proc_iterate_over_mappings (int (*func) (int, CORE_ADDR))
2884 {
2885   struct prmap *map;
2886   procinfo *pi;
2887 #ifndef NEW_PROC_API    /* avoid compiler warning */
2888   int nmaps = 0;
2889   int i;
2890 #else
2891   int map_fd;
2892   char pathname[MAX_PROC_NAME_SIZE];
2893 #endif
2894   int funcstat = 0;
2895   int fd;
2896
2897   pi = find_procinfo_or_die (PIDGET (inferior_ptid), 0);
2898
2899 #ifdef NEW_PROC_API
2900   /* Open map fd.  */
2901   sprintf (pathname, "/proc/%d/map", pi->pid);
2902   if ((map_fd = open_with_retry (pathname, O_RDONLY)) < 0)
2903     proc_error (pi, "proc_iterate_over_mappings (open)", __LINE__);
2904
2905   /* Make sure it gets closed again.  */
2906   make_cleanup_close (map_fd);
2907
2908   /* Allocate space for mapping (lifetime only for this function). */
2909   map = alloca (sizeof (struct prmap));
2910
2911   /* Now read the mappings from the file, 
2912      open a file descriptor for those that have a name, 
2913      and call the callback function.  */
2914   while (read (map_fd, 
2915                (void *) map, 
2916                sizeof (struct prmap)) == sizeof (struct prmap))
2917     {
2918       char name[MAX_PROC_NAME_SIZE + sizeof (map->pr_mapname)];
2919
2920       if (map->pr_vaddr == 0 && map->pr_size == 0)
2921         break;          /* sanity */
2922
2923       if (map->pr_mapname[0] == 0)
2924         {
2925           fd = -1;      /* no map file */
2926         }
2927       else
2928         {
2929           sprintf (name, "/proc/%d/object/%s", pi->pid, map->pr_mapname);
2930           /* Note: caller's responsibility to close this fd!  */
2931           fd = open_with_retry (name, O_RDONLY);
2932           /* Note: we don't test the above call for failure;
2933              we just pass the FD on as given.  Sometimes there is 
2934              no file, so the ioctl may return failure, but that's
2935              not a problem.  */
2936         }
2937
2938       /* Stop looping if the callback returns non-zero.  */
2939       if ((funcstat = (*func) (fd, (CORE_ADDR) map->pr_vaddr)) != 0)
2940         break;
2941     }  
2942 #else
2943   /* Get the number of mapping entries.  */
2944   if (ioctl (pi->ctl_fd, PIOCNMAP, &nmaps) < 0)
2945     proc_error (pi, "proc_iterate_over_mappings (PIOCNMAP)", __LINE__);
2946
2947   /* Allocate space for mappings (lifetime only this function).  */
2948   map = (struct prmap *) alloca ((nmaps + 1) * sizeof (struct prmap));
2949
2950   /* Read in all the mappings.  */
2951   if (ioctl (pi->ctl_fd, PIOCMAP, map) < 0)
2952     proc_error (pi, "proc_iterate_over_mappings (PIOCMAP)", __LINE__);
2953
2954   /* Now loop through the mappings, open an fd for each, and
2955      call the callback function.  */
2956   for (i = 0; 
2957        i < nmaps && map[i].pr_size != 0; 
2958        i++)
2959     {
2960       /* Note: caller's responsibility to close this fd!  */
2961       fd = ioctl (pi->ctl_fd, PIOCOPENM, &map[i].pr_vaddr);
2962       /* Note: we don't test the above call for failure;
2963          we just pass the FD on as given.  Sometimes there is 
2964          no file, so the ioctl may return failure, but that's
2965          not a problem.  */
2966
2967       /* Stop looping if the callback returns non-zero.  */
2968       funcstat = (*func) (fd, host_pointer_to_address (map[i].pr_vaddr));
2969       if (funcstat != 0)
2970         break;
2971     }
2972 #endif
2973
2974   return funcstat;
2975 }
2976
2977 #ifdef TM_I386SOL2_H            /* Is it hokey to use this? */
2978
2979 #include <sys/sysi86.h>
2980
2981 /*
2982  * Function: proc_get_LDT_entry
2983  *
2984  * Inputs:
2985  *   procinfo *pi;
2986  *   int key;
2987  *
2988  * The 'key' is actually the value of the lower 16 bits of
2989  * the GS register for the LWP that we're interested in.
2990  *
2991  * Return: matching ssh struct (LDT entry).
2992  */
2993
2994 struct ssd *
2995 proc_get_LDT_entry (procinfo *pi, int key)
2996 {
2997   static struct ssd *ldt_entry = NULL;
2998 #ifdef NEW_PROC_API
2999   char pathname[MAX_PROC_NAME_SIZE];
3000   struct cleanup *old_chain = NULL;
3001   int  fd;
3002
3003   /* Allocate space for one LDT entry.
3004      This alloc must persist, because we return a pointer to it.  */
3005   if (ldt_entry == NULL)
3006     ldt_entry = (struct ssd *) xmalloc (sizeof (struct ssd));
3007
3008   /* Open the file descriptor for the LDT table.  */
3009   sprintf (pathname, "/proc/%d/ldt", pi->pid);
3010   if ((fd = open_with_retry (pathname, O_RDONLY)) < 0)
3011     {
3012       proc_warn (pi, "proc_get_LDT_entry (open)", __LINE__);
3013       return NULL;
3014     }
3015   /* Make sure it gets closed again! */
3016   old_chain = make_cleanup_close (fd);
3017
3018   /* Now 'read' thru the table, find a match and return it.  */
3019   while (read (fd, ldt_entry, sizeof (struct ssd)) == sizeof (struct ssd))
3020     {
3021       if (ldt_entry->sel == 0 &&
3022           ldt_entry->bo  == 0 &&
3023           ldt_entry->acc1 == 0 &&
3024           ldt_entry->acc2 == 0)
3025         break;  /* end of table */
3026       /* If key matches, return this entry. */
3027       if (ldt_entry->sel == key)
3028         return ldt_entry;
3029     }
3030   /* Loop ended, match not found. */
3031   return NULL;
3032 #else
3033   int nldt, i;
3034   static int nalloc = 0;
3035
3036   /* Get the number of LDT entries.  */
3037   if (ioctl (pi->ctl_fd, PIOCNLDT, &nldt) < 0)
3038     {
3039       proc_warn (pi, "proc_get_LDT_entry (PIOCNLDT)", __LINE__);
3040       return NULL;
3041     }
3042
3043   /* Allocate space for the number of LDT entries. */
3044   /* This alloc has to persist, 'cause we return a pointer to it. */
3045   if (nldt > nalloc)
3046     {
3047       ldt_entry = (struct ssd *) 
3048         xrealloc (ldt_entry, (nldt + 1) * sizeof (struct ssd));
3049       nalloc = nldt;
3050     }
3051   
3052   /* Read the whole table in one gulp.  */
3053   if (ioctl (pi->ctl_fd, PIOCLDT, ldt_entry) < 0)
3054     {
3055       proc_warn (pi, "proc_get_LDT_entry (PIOCLDT)", __LINE__);
3056       return NULL;
3057     }
3058
3059   /* Search the table and return the (first) entry matching 'key'. */
3060   for (i = 0; i < nldt; i++)
3061     if (ldt_entry[i].sel == key)
3062       return &ldt_entry[i];
3063
3064   /* Loop ended, match not found. */
3065   return NULL;
3066 #endif
3067 }
3068
3069 #endif /* TM_I386SOL2_H */
3070
3071 /* =============== END, non-thread part of /proc  "MODULE" =============== */
3072
3073 /* =================== Thread "MODULE" =================== */
3074
3075 /* NOTE: you'll see more ifdefs and duplication of functions here,
3076    since there is a different way to do threads on every OS.  */
3077
3078 /*
3079  * Function: proc_get_nthreads 
3080  *
3081  * Return the number of threads for the process 
3082  */
3083
3084 #if defined (PIOCNTHR) && defined (PIOCTLIST)
3085 /*
3086  * OSF version
3087  */
3088 int 
3089 proc_get_nthreads (procinfo *pi)
3090 {
3091   int nthreads = 0;
3092
3093   if (ioctl (pi->ctl_fd, PIOCNTHR, &nthreads) < 0)
3094     proc_warn (pi, "procfs: PIOCNTHR failed", __LINE__);
3095
3096   return nthreads;
3097 }
3098
3099 #else
3100 #if defined (SYS_lwpcreate) || defined (SYS_lwp_create) /* FIXME: multiple */
3101 /*
3102  * Solaris and Unixware version
3103  */
3104 int
3105 proc_get_nthreads (procinfo *pi)
3106 {
3107   if (!pi->status_valid)
3108     if (!proc_get_status (pi))
3109       return 0;
3110
3111   /*
3112    * NEW_PROC_API: only works for the process procinfo, 
3113    * because the LWP procinfos do not get prstatus filled in.
3114    */
3115 #ifdef NEW_PROC_API  
3116   if (pi->tid != 0)     /* find the parent process procinfo */
3117     pi = find_procinfo_or_die (pi->pid, 0);
3118 #endif
3119   return pi->prstatus.pr_nlwp;
3120 }
3121
3122 #else
3123 /*
3124  * Default version
3125  */
3126 int
3127 proc_get_nthreads (procinfo *pi)
3128 {
3129   return 0;
3130 }
3131 #endif
3132 #endif
3133
3134 /*
3135  * Function: proc_get_current_thread (LWP version)
3136  *
3137  * Return the ID of the thread that had an event of interest.
3138  * (ie. the one that hit a breakpoint or other traced event).
3139  * All other things being equal, this should be the ID of a
3140  * thread that is currently executing.
3141  */
3142
3143 #if defined (SYS_lwpcreate) || defined (SYS_lwp_create) /* FIXME: multiple */
3144 /*
3145  * Solaris and Unixware version
3146  */
3147 int
3148 proc_get_current_thread (procinfo *pi)
3149 {
3150   /*
3151    * Note: this should be applied to the root procinfo for the process,
3152    * not to the procinfo for an LWP.  If applied to the procinfo for
3153    * an LWP, it will simply return that LWP's ID.  In that case, 
3154    * find the parent process procinfo.
3155    */
3156   
3157   if (pi->tid != 0)
3158     pi = find_procinfo_or_die (pi->pid, 0);
3159
3160   if (!pi->status_valid)
3161     if (!proc_get_status (pi))
3162       return 0;
3163
3164 #ifdef NEW_PROC_API
3165   return pi->prstatus.pr_lwp.pr_lwpid;
3166 #else
3167   return pi->prstatus.pr_who;
3168 #endif
3169 }
3170
3171 #else
3172 #if defined (PIOCNTHR) && defined (PIOCTLIST)
3173 /*
3174  * OSF version
3175  */
3176 int 
3177 proc_get_current_thread (procinfo *pi)
3178 {
3179 #if 0   /* FIXME: not ready for prime time? */
3180   return pi->prstatus.pr_tid;
3181 #else
3182   return 0;
3183 #endif
3184 }
3185
3186 #else
3187 /*
3188  * Default version
3189  */
3190 int 
3191 proc_get_current_thread (procinfo *pi)
3192 {
3193   return 0;
3194 }
3195
3196 #endif
3197 #endif
3198
3199 /*
3200  * Function: proc_update_threads 
3201  *
3202  * Discover the IDs of all the threads within the process, and
3203  * create a procinfo for each of them (chained to the parent).
3204  *
3205  * This unfortunately requires a different method on every OS.
3206  *
3207  * Return: non-zero for success, zero for failure.
3208  */
3209
3210 int
3211 proc_delete_dead_threads (procinfo *parent, procinfo *thread, void *ignore)
3212 {
3213   if (thread && parent) /* sanity */
3214     {
3215       thread->status_valid = 0;
3216       if (!proc_get_status (thread))
3217         destroy_one_procinfo (&parent->thread_list, thread);
3218     }
3219   return 0;     /* keep iterating */
3220 }
3221
3222 #if defined (PIOCLSTATUS)
3223 /*
3224  * Solaris 2.5 (ioctl) version
3225  */
3226 int
3227 proc_update_threads (procinfo *pi)
3228 {
3229   gdb_prstatus_t *prstatus;
3230   struct cleanup *old_chain = NULL;
3231   procinfo *thread;
3232   int nlwp, i;
3233
3234   /*
3235    * We should never have to apply this operation to any procinfo
3236    * except the one for the main process.  If that ever changes
3237    * for any reason, then take out the following clause and 
3238    * replace it with one that makes sure the ctl_fd is open.
3239    */
3240   
3241   if (pi->tid != 0)
3242     pi = find_procinfo_or_die (pi->pid, 0);
3243
3244   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
3245
3246   if ((nlwp = proc_get_nthreads (pi)) <= 1)
3247     return 1;   /* Process is not multi-threaded; nothing to do.  */
3248
3249   prstatus = xmalloc (sizeof (gdb_prstatus_t) * (nlwp + 1));
3250
3251   old_chain = make_cleanup (xfree, prstatus);
3252   if (ioctl (pi->ctl_fd, PIOCLSTATUS, prstatus) < 0)
3253     proc_error (pi, "update_threads (PIOCLSTATUS)", __LINE__);
3254
3255   /* Skip element zero, which represents the process as a whole. */
3256   for (i = 1; i < nlwp + 1; i++)
3257     {
3258       if ((thread = create_procinfo (pi->pid, prstatus[i].pr_who)) == NULL)
3259         proc_error (pi, "update_threads, create_procinfo", __LINE__);
3260
3261       memcpy (&thread->prstatus, &prstatus[i], sizeof (*prstatus));
3262       thread->status_valid = 1;
3263     }
3264   pi->threads_valid = 1;
3265   do_cleanups (old_chain);
3266   return 1;
3267 }
3268 #else
3269 #ifdef NEW_PROC_API
3270 /*
3271  * Unixware and Solaris 6 (and later) version
3272  */
3273 static void
3274 do_closedir_cleanup (void *dir)
3275 {
3276   closedir (dir);
3277 }
3278
3279 int
3280 proc_update_threads (procinfo *pi)
3281 {
3282   char pathname[MAX_PROC_NAME_SIZE + 16];
3283   struct dirent *direntry;
3284   struct cleanup *old_chain = NULL;
3285   procinfo *thread;
3286   DIR *dirp;
3287   int lwpid;
3288
3289   /*
3290    * We should never have to apply this operation to any procinfo
3291    * except the one for the main process.  If that ever changes
3292    * for any reason, then take out the following clause and 
3293    * replace it with one that makes sure the ctl_fd is open.
3294    */
3295   
3296   if (pi->tid != 0)
3297     pi = find_procinfo_or_die (pi->pid, 0);
3298
3299   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
3300
3301   /*
3302    * Unixware
3303    *
3304    * Note: this brute-force method is the only way I know of 
3305    * to accomplish this task on Unixware.  This method will 
3306    * also work on Solaris 2.6 and 2.7.  There is a much simpler
3307    * and more elegant way to do this on Solaris, but the margins
3308    * of this manuscript are too small to write it here...  ;-)
3309    */
3310
3311   strcpy (pathname, pi->pathname);
3312   strcat (pathname, "/lwp");
3313   if ((dirp = opendir (pathname)) == NULL)
3314     proc_error (pi, "update_threads, opendir", __LINE__);
3315
3316   old_chain = make_cleanup (do_closedir_cleanup, dirp);
3317   while ((direntry = readdir (dirp)) != NULL)
3318     if (direntry->d_name[0] != '.')             /* skip '.' and '..' */
3319       {
3320         lwpid = atoi (&direntry->d_name[0]);
3321         if ((thread = create_procinfo (pi->pid, lwpid)) == NULL)
3322           proc_error (pi, "update_threads, create_procinfo", __LINE__);
3323       }
3324   pi->threads_valid = 1;
3325   do_cleanups (old_chain);
3326   return 1;
3327 }
3328 #else
3329 #ifdef PIOCTLIST
3330 /*
3331  * OSF version
3332  */
3333 int 
3334 proc_update_threads (procinfo *pi)
3335 {
3336   int nthreads, i;
3337   tid_t *threads;
3338
3339   /*
3340    * We should never have to apply this operation to any procinfo
3341    * except the one for the main process.  If that ever changes
3342    * for any reason, then take out the following clause and 
3343    * replace it with one that makes sure the ctl_fd is open.
3344    */
3345   
3346   if (pi->tid != 0)
3347     pi = find_procinfo_or_die (pi->pid, 0);
3348
3349   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
3350
3351   nthreads = proc_get_nthreads (pi);
3352   if (nthreads < 2)
3353     return 0;           /* nothing to do for 1 or fewer threads */
3354
3355   threads = xmalloc (nthreads * sizeof (tid_t));
3356   
3357   if (ioctl (pi->ctl_fd, PIOCTLIST, threads) < 0)
3358     proc_error (pi, "procfs: update_threads (PIOCTLIST)", __LINE__);
3359
3360   for (i = 0; i < nthreads; i++)
3361     {
3362       if (!find_procinfo (pi->pid, threads[i]))
3363         if (!create_procinfo  (pi->pid, threads[i]))
3364           proc_error (pi, "update_threads, create_procinfo", __LINE__);
3365     }
3366   pi->threads_valid = 1;
3367   return 1;
3368 }
3369 #else
3370 /*
3371  * Default version
3372  */
3373 int
3374 proc_update_threads (procinfo *pi)
3375 {
3376   return 0;
3377 }
3378 #endif  /* OSF PIOCTLIST */
3379 #endif  /* NEW_PROC_API   */
3380 #endif  /* SOL 2.5 PIOCLSTATUS */
3381
3382 /*
3383  * Function: proc_iterate_over_threads
3384  *
3385  * Description:
3386  *   Given a pointer to a function, call that function once
3387  *   for each lwp in the procinfo list, until the function
3388  *   returns non-zero, in which event return the value
3389  *   returned by the function.
3390  *
3391  * Note: this function does NOT call update_threads.
3392  * If you want to discover new threads first, you must
3393  * call that function explicitly.  This function just makes
3394  * a quick pass over the currently-known procinfos. 
3395  * 
3396  * Arguments:
3397  *   pi         - parent process procinfo
3398  *   func       - per-thread function
3399  *   ptr        - opaque parameter for function.
3400  *
3401  * Return:
3402  *   First non-zero return value from the callee, or zero.
3403  */
3404
3405 int
3406 proc_iterate_over_threads (procinfo *pi,
3407                            int (*func) (procinfo *, procinfo *, void *),
3408                            void *ptr)
3409 {
3410   procinfo *thread, *next;
3411   int retval = 0;
3412
3413   /*
3414    * We should never have to apply this operation to any procinfo
3415    * except the one for the main process.  If that ever changes
3416    * for any reason, then take out the following clause and 
3417    * replace it with one that makes sure the ctl_fd is open.
3418    */
3419   
3420   if (pi->tid != 0)
3421     pi = find_procinfo_or_die (pi->pid, 0);
3422
3423   for (thread = pi->thread_list; thread != NULL; thread = next)
3424     {
3425       next = thread->next;      /* in case thread is destroyed */
3426       if ((retval = (*func) (pi, thread, ptr)) != 0)
3427         break;
3428     }
3429
3430   return retval;
3431 }
3432
3433 /* =================== END, Thread "MODULE" =================== */
3434
3435 /* =================== END, /proc  "MODULE" =================== */
3436
3437 /* ===================  GDB  "MODULE" =================== */
3438
3439 /*
3440  * Here are all of the gdb target vector functions and their friends.
3441  */
3442
3443 static ptid_t do_attach (ptid_t ptid);
3444 static void do_detach (int signo);
3445 static int register_gdb_signals (procinfo *, gdb_sigset_t *);
3446
3447 /*
3448  * Function: procfs_debug_inferior
3449  *
3450  * Sets up the inferior to be debugged.
3451  * Registers to trace signals, hardware faults, and syscalls.
3452  * Note: does not set RLC flag: caller may want to customize that.
3453  *
3454  * Returns: zero for success (note! unlike most functions in this module)
3455  *   On failure, returns the LINE NUMBER where it failed!
3456  */
3457
3458 static int
3459 procfs_debug_inferior (procinfo *pi)
3460 {
3461   fltset_t traced_faults;
3462   gdb_sigset_t traced_signals;
3463   sysset_t *traced_syscall_entries;
3464   sysset_t *traced_syscall_exits;
3465   int status;
3466
3467 #ifdef PROCFS_DONT_TRACE_FAULTS
3468   /* On some systems (OSF), we don't trace hardware faults.
3469      Apparently it's enough that we catch them as signals.
3470      Wonder why we don't just do that in general? */
3471   premptyset (&traced_faults);          /* don't trace faults. */
3472 #else
3473   /* Register to trace hardware faults in the child. */
3474   prfillset (&traced_faults);           /* trace all faults... */
3475   prdelset  (&traced_faults, FLTPAGE);  /* except page fault.  */
3476 #endif
3477   if (!proc_set_traced_faults  (pi, &traced_faults))
3478     return __LINE__;
3479
3480   /* Register to trace selected signals in the child. */
3481   premptyset (&traced_signals);
3482   if (!register_gdb_signals (pi, &traced_signals))
3483     return __LINE__;
3484
3485
3486   /* Register to trace the 'exit' system call (on entry).  */
3487   traced_syscall_entries = sysset_t_alloc (pi);
3488   gdb_premptysysset (traced_syscall_entries);
3489 #ifdef SYS_exit
3490   gdb_praddsysset (traced_syscall_entries, SYS_exit);
3491 #endif
3492 #ifdef SYS_lwpexit
3493   gdb_praddsysset (traced_syscall_entries, SYS_lwpexit);        /* And _lwp_exit... */
3494 #endif
3495 #ifdef SYS_lwp_exit
3496   gdb_praddsysset (traced_syscall_entries, SYS_lwp_exit);
3497 #endif
3498 #ifdef DYNAMIC_SYSCALLS
3499   {
3500     int callnum = find_syscall (pi, "_exit");
3501     if (callnum >= 0)
3502       gdb_praddsysset (traced_syscall_entries, callnum);
3503   }
3504 #endif
3505
3506   status = proc_set_traced_sysentry (pi, traced_syscall_entries);
3507   xfree (traced_syscall_entries);
3508   if (!status)
3509     return __LINE__;
3510
3511 #ifdef PRFS_STOPEXEC    /* defined on OSF */
3512   /* OSF method for tracing exec syscalls.  Quoting:
3513      Under Alpha OSF/1 we have to use a PIOCSSPCACT ioctl to trace
3514      exits from exec system calls because of the user level loader.  */
3515   /* FIXME: make nice and maybe move into an access function. */
3516   {
3517     int prfs_flags;
3518
3519     if (ioctl (pi->ctl_fd, PIOCGSPCACT, &prfs_flags) < 0)
3520       return __LINE__;
3521
3522     prfs_flags |= PRFS_STOPEXEC;
3523
3524     if (ioctl (pi->ctl_fd, PIOCSSPCACT, &prfs_flags) < 0)
3525       return __LINE__;
3526   }
3527 #else /* not PRFS_STOPEXEC */
3528   /* Everyone else's (except OSF) method for tracing exec syscalls */
3529   /* GW: Rationale...
3530      Not all systems with /proc have all the exec* syscalls with the same
3531      names.  On the SGI, for example, there is no SYS_exec, but there
3532      *is* a SYS_execv.  So, we try to account for that. */
3533
3534   traced_syscall_exits = sysset_t_alloc (pi);
3535   gdb_premptysysset (traced_syscall_exits);
3536 #ifdef SYS_exec
3537   gdb_praddsysset (traced_syscall_exits, SYS_exec);
3538 #endif
3539 #ifdef SYS_execve
3540   gdb_praddsysset (traced_syscall_exits, SYS_execve);
3541 #endif
3542 #ifdef SYS_execv
3543   gdb_praddsysset (traced_syscall_exits, SYS_execv);
3544 #endif
3545
3546 #ifdef SYS_lwpcreate
3547   gdb_praddsysset (traced_syscall_exits, SYS_lwpcreate);
3548   gdb_praddsysset (traced_syscall_exits, SYS_lwpexit);
3549 #endif
3550
3551 #ifdef SYS_lwp_create   /* FIXME: once only, please */
3552   gdb_praddsysset (traced_syscall_exits, SYS_lwp_create);
3553   gdb_praddsysset (traced_syscall_exits, SYS_lwp_exit);
3554 #endif
3555
3556 #ifdef DYNAMIC_SYSCALLS
3557   {
3558     int callnum = find_syscall (pi, "execve");
3559     if (callnum >= 0)
3560       gdb_praddsysset (traced_syscall_exits, callnum);
3561     callnum = find_syscall (pi, "ra_execve");
3562     if (callnum >= 0)
3563       gdb_praddsysset (traced_syscall_exits, callnum);
3564   }
3565 #endif
3566
3567   status = proc_set_traced_sysexit (pi, traced_syscall_exits);
3568   xfree (traced_syscall_exits);
3569   if (!status)
3570     return __LINE__;
3571
3572 #endif /* PRFS_STOPEXEC */
3573   return 0;
3574 }
3575
3576 static void 
3577 procfs_attach (char *args, int from_tty)
3578 {
3579   char *exec_file;
3580   int   pid;
3581
3582   if (!args)
3583     error_no_arg ("process-id to attach");
3584
3585   pid = atoi (args);
3586   if (pid == getpid ())
3587     error ("Attaching GDB to itself is not a good idea...");
3588
3589   if (from_tty)
3590     {
3591       exec_file = get_exec_file (0);
3592
3593       if (exec_file)
3594         printf_filtered ("Attaching to program `%s', %s\n", 
3595                          exec_file, target_pid_to_str (pid_to_ptid (pid)));
3596       else
3597         printf_filtered ("Attaching to %s\n",
3598                          target_pid_to_str (pid_to_ptid (pid)));
3599
3600       fflush (stdout);
3601     }
3602   inferior_ptid = do_attach (pid_to_ptid (pid));
3603   push_target (&procfs_ops);
3604 }
3605
3606 static void 
3607 procfs_detach (char *args, int from_tty)
3608 {
3609   char *exec_file;
3610   int   signo = 0;
3611
3612   if (from_tty)
3613     {
3614       exec_file = get_exec_file (0);
3615       if (exec_file == 0)
3616         exec_file = "";
3617       printf_filtered ("Detaching from program: %s %s\n",
3618               exec_file, target_pid_to_str (inferior_ptid));
3619       fflush (stdout);
3620     }
3621   if (args)
3622     signo = atoi (args);
3623   
3624   do_detach (signo);
3625   inferior_ptid = null_ptid;
3626   unpush_target (&procfs_ops);          /* Pop out of handling an inferior */
3627 }
3628
3629 static ptid_t
3630 do_attach (ptid_t ptid)
3631 {
3632   procinfo *pi;
3633   int fail;
3634
3635   if ((pi = create_procinfo (PIDGET (ptid), 0)) == NULL)
3636     perror ("procfs: out of memory in 'attach'");
3637
3638   if (!open_procinfo_files (pi, FD_CTL))
3639     {
3640       fprintf_filtered (gdb_stderr, "procfs:%d -- ", __LINE__);
3641       sprintf (errmsg, "do_attach: couldn't open /proc file for process %d", 
3642                PIDGET (ptid));
3643       dead_procinfo (pi, errmsg, NOKILL);
3644     }
3645
3646   /* Stop the process (if it isn't already stopped).  */
3647   if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
3648     {
3649       pi->was_stopped = 1;
3650       proc_prettyprint_why (proc_why (pi), proc_what (pi), 1);
3651     }
3652   else
3653     {
3654       pi->was_stopped = 0;
3655       /* Set the process to run again when we close it.  */
3656       if (!proc_set_run_on_last_close (pi))
3657         dead_procinfo (pi, "do_attach: couldn't set RLC.", NOKILL);
3658
3659       /* Now stop the process. */
3660       if (!proc_stop_process (pi))
3661         dead_procinfo (pi, "do_attach: couldn't stop the process.", NOKILL);
3662       pi->ignore_next_sigstop = 1;
3663     }
3664   /* Save some of the /proc state to be restored if we detach.  */
3665   if (!proc_get_traced_faults   (pi, &pi->saved_fltset))
3666     dead_procinfo (pi, "do_attach: couldn't save traced faults.", NOKILL);
3667   if (!proc_get_traced_signals  (pi, &pi->saved_sigset))
3668     dead_procinfo (pi, "do_attach: couldn't save traced signals.", NOKILL);
3669   if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
3670     dead_procinfo (pi, "do_attach: couldn't save traced syscall entries.",
3671                    NOKILL);
3672   if (!proc_get_traced_sysexit  (pi, pi->saved_exitset))
3673     dead_procinfo (pi, "do_attach: couldn't save traced syscall exits.", 
3674                    NOKILL);
3675   if (!proc_get_held_signals    (pi, &pi->saved_sighold))
3676     dead_procinfo (pi, "do_attach: couldn't save held signals.", NOKILL);
3677
3678   if ((fail = procfs_debug_inferior (pi)) != 0)
3679     dead_procinfo (pi, "do_attach: failed in procfs_debug_inferior", NOKILL);
3680
3681   /* Let GDB know that the inferior was attached.  */
3682   attach_flag = 1;
3683   return MERGEPID (pi->pid, proc_get_current_thread (pi));
3684 }
3685
3686 static void
3687 do_detach (int signo)
3688 {
3689   procinfo *pi;
3690
3691   /* Find procinfo for the main process */
3692   pi = find_procinfo_or_die (PIDGET (inferior_ptid), 0); /* FIXME: threads */
3693   if (signo)
3694     if (!proc_set_current_signal (pi, signo))
3695       proc_warn (pi, "do_detach, set_current_signal", __LINE__);
3696
3697   if (!proc_set_traced_signals (pi, &pi->saved_sigset))
3698     proc_warn (pi, "do_detach, set_traced_signal", __LINE__);
3699
3700   if (!proc_set_traced_faults (pi, &pi->saved_fltset))
3701     proc_warn (pi, "do_detach, set_traced_faults", __LINE__);
3702
3703   if (!proc_set_traced_sysentry (pi, pi->saved_entryset))
3704     proc_warn (pi, "do_detach, set_traced_sysentry", __LINE__);
3705
3706   if (!proc_set_traced_sysexit (pi, pi->saved_exitset))
3707     proc_warn (pi, "do_detach, set_traced_sysexit", __LINE__);
3708
3709   if (!proc_set_held_signals (pi, &pi->saved_sighold))
3710     proc_warn (pi, "do_detach, set_held_signals", __LINE__);
3711
3712   if (signo || (proc_flags (pi) & (PR_STOPPED | PR_ISTOP)))
3713     if (signo || !(pi->was_stopped) ||
3714         query ("Was stopped when attached, make it runnable again? "))
3715       {
3716         /* Clear any pending signal.  */
3717         if (!proc_clear_current_fault (pi))
3718           proc_warn (pi, "do_detach, clear_current_fault", __LINE__);
3719
3720         if (!proc_set_run_on_last_close (pi))
3721           proc_warn (pi, "do_detach, set_rlc", __LINE__);
3722       }
3723
3724   attach_flag = 0;
3725   destroy_procinfo (pi);
3726 }
3727
3728 /*
3729  * fetch_registers
3730  *
3731  * Since the /proc interface cannot give us individual registers,
3732  * we pay no attention to the (regno) argument, and just fetch them all.
3733  * This results in the possibility that we will do unnecessarily many
3734  * fetches, since we may be called repeatedly for individual registers.
3735  * So we cache the results, and mark the cache invalid when the process
3736  * is resumed.
3737  */
3738
3739 static void
3740 procfs_fetch_registers (int regno)
3741 {
3742   gdb_fpregset_t *fpregs;
3743   gdb_gregset_t  *gregs;
3744   procinfo       *pi;
3745   int            pid;
3746   int            tid;
3747
3748   pid = PIDGET (inferior_ptid);
3749   tid = TIDGET (inferior_ptid);
3750
3751   /* First look up procinfo for the main process. */
3752   pi  = find_procinfo_or_die (pid, 0);
3753
3754   /* If the event thread is not the same as GDB's requested thread 
3755      (ie. inferior_ptid), then look up procinfo for the requested 
3756      thread.  */
3757   if ((tid != 0) && 
3758       (tid != proc_get_current_thread (pi)))
3759     pi = find_procinfo_or_die (pid, tid);
3760
3761   if (pi == NULL)
3762     error ("procfs: fetch_registers failed to find procinfo for %s", 
3763            target_pid_to_str (inferior_ptid));
3764
3765   if ((gregs = proc_get_gregs (pi)) == NULL)
3766     proc_error (pi, "fetch_registers, get_gregs", __LINE__);
3767
3768   supply_gregset (gregs);
3769
3770   if (FP0_REGNUM >= 0)  /* need floating point? */
3771     {
3772       if ((regno >= 0 && regno < FP0_REGNUM) ||
3773           regno == PC_REGNUM  ||
3774           (NPC_REGNUM >= 0 && regno == NPC_REGNUM) ||
3775           regno == FP_REGNUM  ||
3776           regno == SP_REGNUM)
3777         return;                 /* not a floating point register */
3778
3779       if ((fpregs = proc_get_fpregs (pi)) == NULL)
3780         proc_error (pi, "fetch_registers, get_fpregs", __LINE__);
3781
3782       supply_fpregset (fpregs);
3783     }
3784 }
3785
3786 /* Get ready to modify the registers array.  On machines which store
3787    individual registers, this doesn't need to do anything.  On
3788    machines which store all the registers in one fell swoop, such as
3789    /proc, this makes sure that registers contains all the registers
3790    from the program being debugged.  */
3791
3792 static void
3793 procfs_prepare_to_store (void)
3794 {
3795 #ifdef CHILD_PREPARE_TO_STORE
3796   CHILD_PREPARE_TO_STORE ();
3797 #endif
3798 }
3799
3800 /*
3801  * store_registers
3802  *
3803  * Since the /proc interface will not read individual registers, 
3804  * we will cache these requests until the process is resumed, and
3805  * only then write them back to the inferior process.
3806  *
3807  * FIXME: is that a really bad idea?  Have to think about cases
3808  * where writing one register might affect the value of others, etc.
3809  */
3810
3811 static void
3812 procfs_store_registers (int regno)
3813 {
3814   gdb_fpregset_t *fpregs;
3815   gdb_gregset_t  *gregs;
3816   procinfo       *pi;
3817   int            pid;
3818   int            tid;
3819
3820   pid = PIDGET (inferior_ptid);
3821   tid = TIDGET (inferior_ptid);
3822
3823   /* First find procinfo for main process */
3824   pi  = find_procinfo_or_die (pid, 0);
3825
3826   /* If current lwp for process is not the same as requested thread
3827      (ie. inferior_ptid), then find procinfo for the requested thread.  */
3828
3829   if ((tid != 0) && 
3830       (tid != proc_get_current_thread (pi)))
3831     pi = find_procinfo_or_die (pid, tid);
3832
3833   if (pi == NULL)
3834     error ("procfs: store_registers: failed to find procinfo for %s",
3835            target_pid_to_str (inferior_ptid));
3836
3837   if ((gregs = proc_get_gregs (pi)) == NULL)
3838     proc_error (pi, "store_registers, get_gregs", __LINE__);
3839
3840   fill_gregset (gregs, regno);
3841   if (!proc_set_gregs (pi))
3842     proc_error (pi, "store_registers, set_gregs", __LINE__);
3843
3844   if (FP0_REGNUM >= 0)          /* need floating point? */
3845     {
3846       if ((regno >= 0 && regno < FP0_REGNUM) ||
3847           regno == PC_REGNUM  ||
3848           (NPC_REGNUM >= 0 && regno == NPC_REGNUM) ||
3849           regno == FP_REGNUM  ||
3850           regno == SP_REGNUM)
3851         return;                 /* not a floating point register */
3852
3853       if ((fpregs = proc_get_fpregs (pi)) == NULL)
3854         proc_error (pi, "store_registers, get_fpregs", __LINE__);
3855
3856       fill_fpregset (fpregs, regno);
3857       if (!proc_set_fpregs (pi))
3858         proc_error (pi, "store_registers, set_fpregs", __LINE__);
3859     }
3860 }
3861
3862 static int
3863 syscall_is_lwp_exit (procinfo *pi, int scall)
3864 {
3865
3866 #ifdef SYS_lwp_exit
3867   if (scall == SYS_lwp_exit)
3868     return 1;
3869 #endif
3870 #ifdef SYS_lwpexit
3871   if (scall == SYS_lwpexit)
3872     return 1;
3873 #endif
3874   return 0;
3875 }
3876
3877 static int
3878 syscall_is_exit (procinfo *pi, int scall)
3879 {
3880 #ifdef SYS_exit
3881   if (scall == SYS_exit)
3882     return 1;
3883 #endif
3884 #ifdef DYNAMIC_SYSCALLS
3885   if (find_syscall (pi, "_exit") == scall)
3886     return 1;
3887 #endif
3888   return 0;
3889 }
3890
3891 static int
3892 syscall_is_exec (procinfo *pi, int scall)
3893 {
3894 #ifdef SYS_exec
3895   if (scall == SYS_exec)
3896     return 1;
3897 #endif
3898 #ifdef SYS_execv
3899   if (scall == SYS_execv)
3900     return 1;
3901 #endif
3902 #ifdef SYS_execve
3903   if (scall == SYS_execve)
3904     return 1;
3905 #endif
3906 #ifdef DYNAMIC_SYSCALLS
3907   if (find_syscall (pi, "_execve"))
3908     return 1;
3909   if (find_syscall (pi, "ra_execve"))
3910     return 1;
3911 #endif
3912   return 0;
3913 }
3914
3915 static int
3916 syscall_is_lwp_create (procinfo *pi, int scall)
3917 {
3918 #ifdef SYS_lwp_create
3919   if (scall == SYS_lwp_create)
3920     return 1;
3921 #endif
3922 #ifdef SYS_lwpcreate
3923   if (scall == SYS_lwpcreate)
3924     return 1;
3925 #endif
3926   return 0;
3927 }
3928
3929 /*
3930  * Function: target_wait
3931  *
3932  * Retrieve the next stop event from the child process.
3933  * If child has not stopped yet, wait for it to stop.
3934  * Translate /proc eventcodes (or possibly wait eventcodes)
3935  * into gdb internal event codes.
3936  *
3937  * Return: id of process (and possibly thread) that incurred the event.
3938  *         event codes are returned thru a pointer parameter.
3939  */
3940
3941 static ptid_t
3942 procfs_wait (ptid_t ptid, struct target_waitstatus *status)
3943 {
3944   /* First cut: loosely based on original version 2.1 */
3945   procinfo *pi;
3946   int       wstat;
3947   int       temp_tid;
3948   ptid_t    retval, temp_ptid;
3949   int       why, what, flags;
3950   int       retry = 0;
3951
3952 wait_again:
3953
3954   retry++;
3955   wstat    = 0;
3956   retval   = pid_to_ptid (-1);
3957
3958   /* Find procinfo for main process */
3959   pi = find_procinfo_or_die (PIDGET (inferior_ptid), 0);
3960   if (pi)
3961     {
3962       /* We must assume that the status is stale now... */
3963       pi->status_valid = 0;
3964       pi->gregs_valid  = 0;
3965       pi->fpregs_valid = 0;
3966
3967 #if 0   /* just try this out... */
3968       flags = proc_flags (pi);
3969       why   = proc_why (pi);
3970       if ((flags & PR_STOPPED) && (why == PR_REQUESTED))
3971         pi->status_valid = 0;   /* re-read again, IMMEDIATELY... */
3972 #endif
3973       /* If child is not stopped, wait for it to stop.  */
3974       if (!(proc_flags (pi) & (PR_STOPPED | PR_ISTOP)) &&
3975           !proc_wait_for_stop (pi))
3976         {
3977           /* wait_for_stop failed: has the child terminated? */
3978           if (errno == ENOENT)
3979             {
3980               int wait_retval;
3981
3982               /* /proc file not found; presumably child has terminated. */
3983               wait_retval = wait (&wstat); /* "wait" for the child's exit  */
3984
3985               if (wait_retval != PIDGET (inferior_ptid)) /* wrong child? */
3986                 error ("procfs: couldn't stop process %d: wait returned %d\n",
3987                        PIDGET (inferior_ptid), wait_retval);
3988               /* FIXME: might I not just use waitpid?
3989                  Or try find_procinfo to see if I know about this child? */
3990               retval = pid_to_ptid (wait_retval);
3991             }
3992           else if (errno == EINTR)
3993             goto wait_again;
3994           else
3995             {
3996               /* Unknown error from wait_for_stop. */
3997               proc_error (pi, "target_wait (wait_for_stop)", __LINE__);
3998             }
3999         }
4000       else
4001         {
4002           /* This long block is reached if either:
4003              a) the child was already stopped, or
4004              b) we successfully waited for the child with wait_for_stop.
4005              This block will analyze the /proc status, and translate it
4006              into a waitstatus for GDB.
4007
4008              If we actually had to call wait because the /proc file
4009              is gone (child terminated), then we skip this block, 
4010              because we already have a waitstatus.  */
4011
4012           flags = proc_flags (pi);
4013           why   = proc_why (pi);
4014           what  = proc_what (pi);
4015
4016           if (flags & (PR_STOPPED | PR_ISTOP))
4017             {
4018 #ifdef PR_ASYNC
4019               /* If it's running async (for single_thread control),
4020                  set it back to normal again.  */
4021               if (flags & PR_ASYNC)
4022                 if (!proc_unset_async (pi))
4023                   proc_error (pi, "target_wait, unset_async", __LINE__);
4024 #endif
4025
4026               if (info_verbose)
4027                 proc_prettyprint_why (why, what, 1);
4028
4029               /* The 'pid' we will return to GDB is composed of
4030                  the process ID plus the lwp ID.  */
4031               retval = MERGEPID (pi->pid, proc_get_current_thread (pi));
4032
4033               switch (why) {
4034               case PR_SIGNALLED:
4035                 wstat = (what << 8) | 0177;
4036                 break;
4037               case PR_SYSENTRY:
4038                 if (syscall_is_lwp_exit (pi, what))
4039                   {
4040                     printf_filtered ("[%s exited]\n",
4041                                      target_pid_to_str (retval));
4042                     delete_thread (retval);
4043                     status->kind = TARGET_WAITKIND_SPURIOUS;
4044                     return retval;
4045                   }
4046                 else if (syscall_is_exit (pi, what))
4047                   {
4048                     /* Handle SYS_exit call only */
4049                     /* Stopped at entry to SYS_exit.
4050                        Make it runnable, resume it, then use 
4051                        the wait system call to get its exit code.
4052                        Proc_run_process always clears the current 
4053                        fault and signal.
4054                        Then return its exit status.  */
4055                     pi->status_valid = 0;
4056                     wstat = 0;
4057                     /* FIXME: what we should do is return 
4058                        TARGET_WAITKIND_SPURIOUS.  */
4059                     if (!proc_run_process (pi, 0, 0))
4060                       proc_error (pi, "target_wait, run_process", __LINE__);
4061                     if (attach_flag)
4062                       {
4063                         /* Don't call wait: simulate waiting for exit, 
4064                            return a "success" exit code.  Bogus: what if
4065                            it returns something else?  */
4066                         wstat = 0;
4067                         retval = inferior_ptid;  /* ? ? ? */
4068                       }
4069                     else
4070                       {
4071                         int temp = wait (&wstat);
4072
4073                         /* FIXME: shouldn't I make sure I get the right
4074                            event from the right process?  If (for
4075                            instance) I have killed an earlier inferior
4076                            process but failed to clean up after it
4077                            somehow, I could get its termination event
4078                            here.  */
4079
4080                         /* If wait returns -1, that's what we return to GDB. */
4081                         if (temp < 0)
4082                           retval = pid_to_ptid (temp);
4083                       }
4084                   }
4085                 else
4086                   {
4087                     printf_filtered ("procfs: trapped on entry to ");
4088                     proc_prettyprint_syscall (proc_what (pi), 0);
4089                     printf_filtered ("\n");
4090 #ifndef PIOCSSPCACT
4091                     {
4092                       long i, nsysargs, *sysargs;
4093
4094                       if ((nsysargs = proc_nsysarg (pi)) > 0 &&
4095                           (sysargs  = proc_sysargs (pi)) != NULL)
4096                         {
4097                           printf_filtered ("%ld syscall arguments:\n", nsysargs);
4098                           for (i = 0; i < nsysargs; i++)
4099                             printf_filtered ("#%ld: 0x%08lx\n", 
4100                                              i, sysargs[i]);
4101                         }
4102
4103                     }
4104 #endif
4105                     if (status)
4106                       {
4107                         /* How to exit gracefully, returning "unknown event" */
4108                         status->kind = TARGET_WAITKIND_SPURIOUS;
4109                         return inferior_ptid;
4110                       }
4111                     else
4112                       {
4113                         /* How to keep going without returning to wfi: */
4114                         target_resume (ptid, 0, TARGET_SIGNAL_0);
4115                         goto wait_again;
4116                       }
4117                   }
4118                 break;
4119               case PR_SYSEXIT:
4120                 if (syscall_is_exec (pi, what))
4121                   {
4122                     /* Hopefully this is our own "fork-child" execing
4123                        the real child.  Hoax this event into a trap, and
4124                        GDB will see the child about to execute its start
4125                        address. */
4126                     wstat = (SIGTRAP << 8) | 0177;
4127                   }
4128                 else if (syscall_is_lwp_create (pi, what))
4129                   {
4130                     /*
4131                      * This syscall is somewhat like fork/exec.
4132                      * We will get the event twice: once for the parent LWP,
4133                      * and once for the child.  We should already know about
4134                      * the parent LWP, but the child will be new to us.  So,
4135                      * whenever we get this event, if it represents a new
4136                      * thread, simply add the thread to the list.
4137                      */
4138
4139                     /* If not in procinfo list, add it.  */
4140                     temp_tid = proc_get_current_thread (pi);
4141                     if (!find_procinfo (pi->pid, temp_tid))
4142                       create_procinfo  (pi->pid, temp_tid);
4143
4144                     temp_ptid = MERGEPID (pi->pid, temp_tid);
4145                     /* If not in GDB's thread list, add it.  */
4146                     if (!in_thread_list (temp_ptid))
4147                       {
4148                         printf_filtered ("[New %s]\n",
4149                                          target_pid_to_str (temp_ptid));
4150                         add_thread (temp_ptid);
4151                       }
4152                     /* Return to WFI, but tell it to immediately resume. */
4153                     status->kind = TARGET_WAITKIND_SPURIOUS;
4154                     return inferior_ptid;
4155                   }
4156                 else if (syscall_is_lwp_exit (pi, what))
4157                   {
4158                     printf_filtered ("[%s exited]\n",
4159                                      target_pid_to_str (retval));
4160                     delete_thread (retval);
4161                     status->kind = TARGET_WAITKIND_SPURIOUS;
4162                     return retval;
4163                   }
4164                 else if (0)
4165                   {
4166                     /* FIXME:  Do we need to handle SYS_sproc,
4167                        SYS_fork, or SYS_vfork here?  The old procfs
4168                        seemed to use this event to handle threads on
4169                        older (non-LWP) systems, where I'm assuming
4170                        that threads were actually separate processes. 
4171                        Irix, maybe?  Anyway, low priority for now.  */
4172                   }
4173                 else
4174                   {
4175                     printf_filtered ("procfs: trapped on exit from ");
4176                     proc_prettyprint_syscall (proc_what (pi), 0);
4177                     printf_filtered ("\n");
4178 #ifndef PIOCSSPCACT
4179                     {
4180                       long i, nsysargs, *sysargs;
4181
4182                       if ((nsysargs = proc_nsysarg (pi)) > 0 &&
4183                           (sysargs  = proc_sysargs (pi)) != NULL)
4184                         {
4185                           printf_filtered ("%ld syscall arguments:\n", nsysargs);
4186                           for (i = 0; i < nsysargs; i++)
4187                             printf_filtered ("#%ld: 0x%08lx\n", 
4188                                              i, sysargs[i]);
4189                         }
4190                     }
4191 #endif
4192                     status->kind = TARGET_WAITKIND_SPURIOUS;
4193                     return inferior_ptid;
4194                   }
4195                 break;
4196               case PR_REQUESTED:
4197 #if 0   /* FIXME */
4198                 wstat = (SIGSTOP << 8) | 0177;
4199                 break;
4200 #else
4201                 if (retry < 5)
4202                   {
4203                     printf_filtered ("Retry #%d:\n", retry);
4204                     pi->status_valid = 0;
4205                     goto wait_again;
4206                   }
4207                 else
4208                   {
4209                     /* If not in procinfo list, add it.  */
4210                     temp_tid = proc_get_current_thread (pi);
4211                     if (!find_procinfo (pi->pid, temp_tid))
4212                       create_procinfo  (pi->pid, temp_tid);
4213
4214                     /* If not in GDB's thread list, add it.  */
4215                     temp_ptid = MERGEPID (pi->pid, temp_tid);
4216                     if (!in_thread_list (temp_ptid))
4217                       {
4218                         printf_filtered ("[New %s]\n", 
4219                                          target_pid_to_str (temp_ptid));
4220                         add_thread (temp_ptid);
4221                       }
4222
4223                     status->kind = TARGET_WAITKIND_STOPPED;
4224                     status->value.sig = 0;
4225                     return retval;
4226                   }
4227 #endif
4228               case PR_JOBCONTROL:
4229                 wstat = (what << 8) | 0177;
4230                 break;
4231               case PR_FAULTED:
4232                 switch (what) { /* FIXME: FAULTED_USE_SIGINFO */
4233 #ifdef FLTWATCH
4234                 case FLTWATCH:
4235                   wstat = (SIGTRAP << 8) | 0177;
4236                   break;
4237 #endif
4238 #ifdef FLTKWATCH
4239                 case FLTKWATCH:
4240                   wstat = (SIGTRAP << 8) | 0177;
4241                   break;
4242 #endif
4243                   /* FIXME: use si_signo where possible. */
4244                 case FLTPRIV:
4245 #if (FLTILL != FLTPRIV)         /* avoid "duplicate case" error */
4246                 case FLTILL:
4247 #endif
4248                   wstat = (SIGILL << 8) | 0177;
4249                   break;
4250                 case FLTBPT:
4251 #if (FLTTRACE != FLTBPT)        /* avoid "duplicate case" error */
4252                 case FLTTRACE:
4253 #endif
4254                   wstat = (SIGTRAP << 8) | 0177;
4255                   break;
4256                 case FLTSTACK:
4257                 case FLTACCESS:
4258 #if (FLTBOUNDS != FLTSTACK)     /* avoid "duplicate case" error */
4259                 case FLTBOUNDS:
4260 #endif
4261                   wstat = (SIGSEGV << 8) | 0177;
4262                   break;
4263                 case FLTIOVF:
4264                 case FLTIZDIV:
4265 #if (FLTFPE != FLTIOVF)         /* avoid "duplicate case" error */
4266                 case FLTFPE:
4267 #endif
4268                   wstat = (SIGFPE << 8) | 0177;
4269                   break;
4270                 case FLTPAGE:           /* Recoverable page fault */
4271                 default:         /* FIXME: use si_signo if possible for fault */
4272                   retval = pid_to_ptid (-1);
4273                   printf_filtered ("procfs:%d -- ", __LINE__);
4274                   printf_filtered ("child stopped for unknown reason:\n");
4275                   proc_prettyprint_why (why, what, 1);
4276                   error ("... giving up...");
4277                   break;
4278                 }
4279                 break;  /* case PR_FAULTED: */
4280               default:  /* switch (why) unmatched */
4281                 printf_filtered ("procfs:%d -- ", __LINE__);
4282                 printf_filtered ("child stopped for unknown reason:\n");
4283                 proc_prettyprint_why (why, what, 1);
4284                 error ("... giving up...");
4285                 break;
4286               }
4287               /*
4288                * Got this far without error:
4289                * If retval isn't in the threads database, add it.
4290                */
4291               if (PIDGET (retval) > 0 &&
4292                   !ptid_equal (retval, inferior_ptid) &&
4293                   !in_thread_list (retval))
4294                 {
4295                   /*
4296                    * We have a new thread.  
4297                    * We need to add it both to GDB's list and to our own.
4298                    * If we don't create a procinfo, resume may be unhappy 
4299                    * later.
4300                    */
4301                   printf_filtered ("[New %s]\n", target_pid_to_str (retval));
4302                   add_thread (retval);
4303                   if (find_procinfo (PIDGET (retval), TIDGET (retval)) == NULL)
4304                     create_procinfo (PIDGET (retval), TIDGET (retval));
4305
4306                   /* In addition, it's possible that this is the first
4307                    * new thread we've seen, in which case we may not 
4308                    * have created entries for inferior_ptid yet.
4309                    */
4310                   if (TIDGET (inferior_ptid) != 0)
4311                     {
4312                       if (!in_thread_list (inferior_ptid))
4313                         add_thread (inferior_ptid);
4314                       if (find_procinfo (PIDGET (inferior_ptid), 
4315                                          TIDGET (inferior_ptid)) == NULL)
4316                         create_procinfo (PIDGET (inferior_ptid), 
4317                                          TIDGET (inferior_ptid));
4318                     }
4319                 }
4320             }
4321           else  /* flags do not indicate STOPPED */
4322             {
4323               /* surely this can't happen... */
4324               printf_filtered ("procfs:%d -- process not stopped.\n",
4325                                __LINE__);
4326               proc_prettyprint_flags (flags, 1);
4327               error ("procfs: ...giving up...");
4328             }
4329         }
4330
4331       if (status)
4332         store_waitstatus (status, wstat);
4333     }
4334
4335   return retval;
4336 }
4337
4338 /* Transfer LEN bytes between GDB address MYADDR and target address
4339    MEMADDR.  If DOWRITE is non-zero, transfer them to the target,
4340    otherwise transfer them from the target.  TARGET is unused.
4341
4342    The return value is 0 if an error occurred or no bytes were
4343    transferred.  Otherwise, it will be a positive value which
4344    indicates the number of bytes transferred between gdb and the
4345    target.  (Note that the interface also makes provisions for
4346    negative values, but this capability isn't implemented here.) */
4347
4348 static int
4349 procfs_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len, int dowrite,
4350                     struct mem_attrib *attrib, struct target_ops *target)
4351 {
4352   procinfo *pi;
4353   int nbytes = 0;
4354
4355   /* Find procinfo for main process */
4356   pi = find_procinfo_or_die (PIDGET (inferior_ptid), 0);
4357   if (pi->as_fd == 0 &&
4358       open_procinfo_files (pi, FD_AS) == 0)
4359     {
4360       proc_warn (pi, "xfer_memory, open_proc_files", __LINE__);
4361       return 0;
4362     }
4363
4364   if (lseek (pi->as_fd, (off_t) memaddr, SEEK_SET) == (off_t) memaddr)
4365     {
4366       if (dowrite)
4367         {
4368 #ifdef NEW_PROC_API
4369           PROCFS_NOTE ("write memory: ");
4370 #else
4371           PROCFS_NOTE ("write memory: \n");
4372 #endif
4373           nbytes = write (pi->as_fd, myaddr, len);
4374         }
4375       else
4376         {
4377           PROCFS_NOTE ("read  memory: \n");
4378           nbytes = read (pi->as_fd, myaddr, len);
4379         }
4380       if (nbytes < 0)
4381         {
4382           nbytes = 0;
4383         }
4384     }
4385   return nbytes;
4386 }
4387
4388 /*
4389  * Function: invalidate_cache
4390  *
4391  * Called by target_resume before making child runnable.
4392  * Mark cached registers and status's invalid.
4393  * If there are "dirty" caches that need to be written back
4394  * to the child process, do that.
4395  *
4396  * File descriptors are also cached.  
4397  * As they are a limited resource, we cannot hold onto them indefinitely.
4398  * However, as they are expensive to open, we don't want to throw them
4399  * away indescriminately either.  As a compromise, we will keep the
4400  * file descriptors for the parent process, but discard any file
4401  * descriptors we may have accumulated for the threads.
4402  *
4403  * Return value:
4404  * As this function is called by iterate_over_threads, it always 
4405  * returns zero (so that iterate_over_threads will keep iterating).
4406  */
4407
4408
4409 static int
4410 invalidate_cache (procinfo *parent, procinfo *pi, void *ptr)
4411 {
4412   /*
4413    * About to run the child; invalidate caches and do any other cleanup.
4414    */
4415
4416 #if 0
4417   if (pi->gregs_dirty)
4418     if (parent == NULL ||
4419         proc_get_current_thread (parent) != pi->tid)
4420       if (!proc_set_gregs (pi)) /* flush gregs cache */
4421         proc_warn (pi, "target_resume, set_gregs",
4422                    __LINE__);
4423   if (FP0_REGNUM >= 0)
4424     if (pi->fpregs_dirty)
4425       if (parent == NULL ||
4426           proc_get_current_thread (parent) != pi->tid)
4427         if (!proc_set_fpregs (pi))      /* flush fpregs cache */
4428           proc_warn (pi, "target_resume, set_fpregs", 
4429                      __LINE__);
4430 #endif
4431
4432   if (parent != NULL)
4433     {
4434       /* The presence of a parent indicates that this is an LWP.
4435          Close any file descriptors that it might have open.  
4436          We don't do this to the master (parent) procinfo.  */
4437
4438       close_procinfo_files (pi);
4439     }
4440   pi->gregs_valid   = 0;
4441   pi->fpregs_valid  = 0;
4442 #if 0
4443   pi->gregs_dirty   = 0;
4444   pi->fpregs_dirty  = 0;
4445 #endif
4446   pi->status_valid  = 0;
4447   pi->threads_valid = 0;
4448
4449   return 0;
4450 }
4451
4452 #if 0
4453 /*
4454  * Function: make_signal_thread_runnable
4455  *
4456  * A callback function for iterate_over_threads.
4457  * Find the asynchronous signal thread, and make it runnable.
4458  * See if that helps matters any.
4459  */
4460
4461 static int
4462 make_signal_thread_runnable (procinfo *process, procinfo *pi, void *ptr)
4463 {
4464 #ifdef PR_ASLWP
4465   if (proc_flags (pi) & PR_ASLWP)
4466     {
4467       if (!proc_run_process (pi, 0, -1))
4468         proc_error (pi, "make_signal_thread_runnable", __LINE__);
4469       return 1;
4470     }
4471 #endif
4472   return 0;
4473 }
4474 #endif
4475
4476 /*
4477  * Function: target_resume
4478  *
4479  * Make the child process runnable.  Normally we will then call
4480  * procfs_wait and wait for it to stop again (unles gdb is async).
4481  *
4482  * Arguments:
4483  *  step:  if true, then arrange for the child to stop again 
4484  *         after executing a single instruction.
4485  *  signo: if zero, then cancel any pending signal.
4486  *         If non-zero, then arrange for the indicated signal 
4487  *         to be delivered to the child when it runs.
4488  *  pid:   if -1, then allow any child thread to run.
4489  *         if non-zero, then allow only the indicated thread to run.
4490  *******   (not implemented yet)
4491  */
4492
4493 static void
4494 procfs_resume (ptid_t ptid, int step, enum target_signal signo)
4495 {
4496   procinfo *pi, *thread;
4497   int native_signo;
4498
4499   /* 2.1: 
4500      prrun.prflags |= PRSVADDR;
4501      prrun.pr_vaddr = $PC;         set resume address 
4502      prrun.prflags |= PRSTRACE;    trace signals in pr_trace (all)
4503      prrun.prflags |= PRSFAULT;    trace faults in pr_fault (all but PAGE) 
4504      prrun.prflags |= PRCFAULT;    clear current fault.
4505
4506      PRSTRACE and PRSFAULT can be done by other means
4507         (proc_trace_signals, proc_trace_faults)
4508      PRSVADDR is unnecessary.
4509      PRCFAULT may be replaced by a PIOCCFAULT call (proc_clear_current_fault)
4510      This basically leaves PRSTEP and PRCSIG.
4511      PRCSIG is like PIOCSSIG (proc_clear_current_signal).
4512      So basically PR_STEP is the sole argument that must be passed
4513      to proc_run_process (for use in the prrun struct by ioctl). */
4514
4515   /* Find procinfo for main process */
4516   pi = find_procinfo_or_die (PIDGET (inferior_ptid), 0);
4517
4518   /* First cut: ignore pid argument */
4519   errno = 0;
4520
4521   /* Convert signal to host numbering.  */
4522   if (signo == 0 ||
4523       (signo == TARGET_SIGNAL_STOP && pi->ignore_next_sigstop))
4524     native_signo = 0;
4525   else
4526     native_signo = target_signal_to_host (signo);
4527
4528   pi->ignore_next_sigstop = 0;
4529
4530   /* Running the process voids all cached registers and status. */
4531   /* Void the threads' caches first */
4532   proc_iterate_over_threads (pi, invalidate_cache, NULL); 
4533   /* Void the process procinfo's caches.  */
4534   invalidate_cache (NULL, pi, NULL);
4535
4536   if (PIDGET (ptid) != -1)
4537     {
4538       /* Resume a specific thread, presumably suppressing the others. */
4539       thread = find_procinfo (PIDGET (ptid), TIDGET (ptid));
4540       if (thread != NULL)
4541         {
4542           if (thread->tid != 0)
4543             {
4544               /* We're to resume a specific thread, and not the others.
4545                * Set the child process's PR_ASYNC flag.
4546                */
4547 #ifdef PR_ASYNC
4548               if (!proc_set_async (pi))
4549                 proc_error (pi, "target_resume, set_async", __LINE__);
4550 #endif
4551 #if 0
4552               proc_iterate_over_threads (pi, 
4553                                          make_signal_thread_runnable,
4554                                          NULL);
4555 #endif
4556               pi = thread;      /* substitute the thread's procinfo for run */
4557             }
4558         }
4559     }
4560
4561   if (!proc_run_process (pi, step, native_signo))
4562     {
4563       if (errno == EBUSY)
4564         warning ("resume: target already running.  Pretend to resume, and hope for the best!\n");
4565       else
4566         proc_error (pi, "target_resume", __LINE__);
4567     }
4568 }
4569
4570 /*
4571  * Function: register_gdb_signals
4572  *
4573  * Traverse the list of signals that GDB knows about 
4574  * (see "handle" command), and arrange for the target
4575  * to be stopped or not, according to these settings.
4576  *
4577  * Returns non-zero for success, zero for failure.
4578  */
4579
4580 static int
4581 register_gdb_signals (procinfo *pi, gdb_sigset_t *signals)
4582 {
4583   int signo;
4584
4585   for (signo = 0; signo < NSIG; signo ++)
4586     if (signal_stop_state  (target_signal_from_host (signo)) == 0 &&
4587         signal_print_state (target_signal_from_host (signo)) == 0 &&
4588         signal_pass_state  (target_signal_from_host (signo)) == 1)
4589       prdelset (signals, signo);
4590     else
4591       praddset (signals, signo);
4592
4593   return proc_set_traced_signals (pi, signals);
4594 }
4595
4596 /*
4597  * Function: target_notice_signals
4598  *
4599  * Set up to trace signals in the child process.
4600  */
4601
4602 static void
4603 procfs_notice_signals (ptid_t ptid)
4604 {
4605   gdb_sigset_t signals;
4606   procinfo *pi = find_procinfo_or_die (PIDGET (ptid), 0);
4607
4608   if (proc_get_traced_signals (pi, &signals) &&
4609       register_gdb_signals    (pi, &signals))
4610     return;
4611   else
4612     proc_error (pi, "notice_signals", __LINE__);
4613 }
4614
4615 /*
4616  * Function: target_files_info
4617  *
4618  * Print status information about the child process.
4619  */
4620
4621 static void
4622 procfs_files_info (struct target_ops *ignore)
4623 {
4624   printf_filtered ("\tUsing the running image of %s %s via /proc.\n",
4625                    attach_flag? "attached": "child", 
4626                    target_pid_to_str (inferior_ptid));
4627 }
4628
4629 /*
4630  * Function: target_open
4631  *
4632  * A dummy: you don't open procfs.
4633  */
4634
4635 static void
4636 procfs_open (char *args, int from_tty)
4637 {
4638   error ("Use the \"run\" command to start a Unix child process.");
4639 }
4640
4641 /*
4642  * Function: target_can_run
4643  *
4644  * This tells GDB that this target vector can be invoked 
4645  * for "run" or "attach".
4646  */
4647
4648 int procfs_suppress_run = 0;    /* Non-zero if procfs should pretend not to
4649                                    be a runnable target.  Used by targets
4650                                    that can sit atop procfs, such as solaris
4651                                    thread support.  */
4652
4653
4654 static int
4655 procfs_can_run (void)
4656 {
4657   /* This variable is controlled by modules that sit atop procfs that
4658      may layer their own process structure atop that provided here.
4659      sol-thread.c does this because of the Solaris two-level thread
4660      model.  */
4661   
4662   /* NOTE: possibly obsolete -- use the thread_stratum approach instead. */
4663
4664   return !procfs_suppress_run;
4665 }
4666
4667 /*
4668  * Function: target_stop
4669  *
4670  * Stop the child process asynchronously, as when the
4671  * gdb user types control-c or presses a "stop" button.
4672  *
4673  * Works by sending kill(SIGINT) to the child's process group.
4674  */
4675
4676 static void
4677 procfs_stop (void)
4678 {
4679   extern pid_t inferior_process_group;
4680
4681   kill (-inferior_process_group, SIGINT);
4682 }
4683
4684 /*
4685  * Function: unconditionally_kill_inferior
4686  *
4687  * Make it die.  Wait for it to die.  Clean up after it.
4688  * Note: this should only be applied to the real process, 
4689  * not to an LWP, because of the check for parent-process.
4690  * If we need this to work for an LWP, it needs some more logic.
4691  */
4692
4693 static void
4694 unconditionally_kill_inferior (procinfo *pi)
4695 {
4696   int parent_pid;
4697
4698   parent_pid = proc_parent_pid (pi);
4699 #ifdef PROCFS_NEED_CLEAR_CURSIG_FOR_KILL
4700   /* FIXME: use access functions */
4701   /* Alpha OSF/1-3.x procfs needs a clear of the current signal
4702      before the PIOCKILL, otherwise it might generate a corrupted core
4703      file for the inferior.  */
4704   if (ioctl (pi->ctl_fd, PIOCSSIG, NULL) < 0)
4705     {
4706       printf_filtered ("unconditionally_kill: SSIG failed!\n");
4707     }
4708 #endif
4709 #ifdef PROCFS_NEED_PIOCSSIG_FOR_KILL
4710   /* Alpha OSF/1-2.x procfs needs a PIOCSSIG call with a SIGKILL signal
4711      to kill the inferior, otherwise it might remain stopped with a
4712      pending SIGKILL.
4713      We do not check the result of the PIOCSSIG, the inferior might have
4714      died already.  */
4715   {
4716     gdb_siginfo_t newsiginfo;
4717
4718     memset ((char *) &newsiginfo, 0, sizeof (newsiginfo));
4719     newsiginfo.si_signo = SIGKILL;
4720     newsiginfo.si_code = 0;
4721     newsiginfo.si_errno = 0;
4722     newsiginfo.si_pid = getpid ();
4723     newsiginfo.si_uid = getuid ();
4724     /* FIXME: use proc_set_current_signal */
4725     ioctl (pi->ctl_fd, PIOCSSIG, &newsiginfo);
4726   }
4727 #else /* PROCFS_NEED_PIOCSSIG_FOR_KILL */
4728   if (!proc_kill (pi, SIGKILL))
4729     proc_error (pi, "unconditionally_kill, proc_kill", __LINE__);
4730 #endif /* PROCFS_NEED_PIOCSSIG_FOR_KILL */
4731   destroy_procinfo (pi);
4732
4733   /* If pi is GDB's child, wait for it to die.  */
4734   if (parent_pid == getpid ())
4735     /* FIXME: should we use waitpid to make sure we get the right event?  
4736        Should we check the returned event?  */
4737     {
4738 #if 0
4739       int status, ret;
4740
4741       ret = waitpid (pi->pid, &status, 0);
4742 #else
4743       wait (NULL);
4744 #endif
4745     }
4746 }
4747
4748 /*
4749  * Function: target_kill_inferior
4750  *
4751  * We're done debugging it, and we want it to go away.
4752  * Then we want GDB to forget all about it.
4753  */
4754
4755 static void 
4756 procfs_kill_inferior (void)
4757 {
4758   if (!ptid_equal (inferior_ptid, null_ptid)) /* ? */
4759     {
4760       /* Find procinfo for main process */
4761       procinfo *pi = find_procinfo (PIDGET (inferior_ptid), 0);
4762
4763       if (pi)
4764         unconditionally_kill_inferior (pi);
4765       target_mourn_inferior ();
4766     }
4767 }
4768
4769 /*
4770  * Function: target_mourn_inferior
4771  *
4772  * Forget we ever debugged this thing!
4773  */
4774
4775 static void 
4776 procfs_mourn_inferior (void)
4777 {
4778   procinfo *pi;
4779
4780   if (!ptid_equal (inferior_ptid, null_ptid))
4781     {
4782       /* Find procinfo for main process */
4783       pi = find_procinfo (PIDGET (inferior_ptid), 0);
4784       if (pi)
4785         destroy_procinfo (pi);
4786     }
4787   unpush_target (&procfs_ops);
4788   generic_mourn_inferior ();
4789 }
4790
4791 /*
4792  * Function: init_inferior
4793  *
4794  * When GDB forks to create a runnable inferior process, 
4795  * this function is called on the parent side of the fork.
4796  * It's job is to do whatever is necessary to make the child
4797  * ready to be debugged, and then wait for the child to synchronize.
4798  */
4799
4800 static void 
4801 procfs_init_inferior (int pid)
4802 {
4803   procinfo *pi;
4804   gdb_sigset_t signals;
4805   int fail;
4806
4807   /* This routine called on the parent side (GDB side)
4808      after GDB forks the inferior.  */
4809
4810   push_target (&procfs_ops);
4811
4812   if ((pi = create_procinfo (pid, 0)) == NULL)
4813     perror ("procfs: out of memory in 'init_inferior'");
4814
4815   if (!open_procinfo_files (pi, FD_CTL))
4816     proc_error (pi, "init_inferior, open_proc_files", __LINE__);
4817
4818   /*
4819     xmalloc                     // done
4820     open_procinfo_files         // done
4821     link list                   // done
4822     prfillset (trace)
4823     procfs_notice_signals
4824     prfillset (fault)
4825     prdelset (FLTPAGE)
4826     PIOCWSTOP
4827     PIOCSFAULT
4828     */
4829
4830   /* If not stopped yet, wait for it to stop. */
4831   if (!(proc_flags (pi) & PR_STOPPED) &&
4832       !(proc_wait_for_stop (pi)))
4833     dead_procinfo (pi, "init_inferior: wait_for_stop failed", KILL);
4834
4835   /* Save some of the /proc state to be restored if we detach.  */
4836   /* FIXME: Why?  In case another debugger was debugging it?
4837      We're it's parent, for Ghu's sake! */
4838   if (!proc_get_traced_signals  (pi, &pi->saved_sigset))
4839     proc_error (pi, "init_inferior, get_traced_signals", __LINE__);
4840   if (!proc_get_held_signals    (pi, &pi->saved_sighold))
4841     proc_error (pi, "init_inferior, get_held_signals", __LINE__);
4842   if (!proc_get_traced_faults   (pi, &pi->saved_fltset))
4843     proc_error (pi, "init_inferior, get_traced_faults", __LINE__);
4844   if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
4845     proc_error (pi, "init_inferior, get_traced_sysentry", __LINE__);
4846   if (!proc_get_traced_sysexit  (pi, pi->saved_exitset))
4847     proc_error (pi, "init_inferior, get_traced_sysexit", __LINE__);
4848
4849   /* Register to trace selected signals in the child. */
4850   prfillset (&signals);
4851   if (!register_gdb_signals (pi, &signals))
4852     proc_error (pi, "init_inferior, register_signals", __LINE__);
4853
4854   if ((fail = procfs_debug_inferior (pi)) != 0)
4855     proc_error (pi, "init_inferior (procfs_debug_inferior)", fail);
4856
4857   /* FIXME: logically, we should really be turning OFF run-on-last-close,
4858      and possibly even turning ON kill-on-last-close at this point.  But
4859      I can't make that change without careful testing which I don't have
4860      time to do right now...  */
4861   /* Turn on run-on-last-close flag so that the child
4862      will die if GDB goes away for some reason.  */
4863   if (!proc_set_run_on_last_close (pi))
4864     proc_error (pi, "init_inferior, set_RLC", __LINE__);
4865
4866   /* The 'process ID' we return to GDB is composed of
4867      the actual process ID plus the lwp ID. */
4868   inferior_ptid = MERGEPID (pi->pid, proc_get_current_thread (pi));
4869
4870 #ifdef START_INFERIOR_TRAPS_EXPECTED
4871   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
4872 #else
4873   /* One trap to exec the shell, one to exec the program being debugged.  */
4874   startup_inferior (2);
4875 #endif /* START_INFERIOR_TRAPS_EXPECTED */
4876 }
4877
4878 /*
4879  * Function: set_exec_trap
4880  *
4881  * When GDB forks to create a new process, this function is called
4882  * on the child side of the fork before GDB exec's the user program.
4883  * Its job is to make the child minimally debuggable, so that the
4884  * parent GDB process can connect to the child and take over.
4885  * This function should do only the minimum to make that possible,
4886  * and to synchronize with the parent process.  The parent process
4887  * should take care of the details.
4888  */
4889
4890 static void
4891 procfs_set_exec_trap (void)
4892 {
4893   /* This routine called on the child side (inferior side)
4894      after GDB forks the inferior.  It must use only local variables,
4895      because it may be sharing data space with its parent.  */
4896
4897   procinfo *pi;
4898   sysset_t *exitset;
4899
4900   if ((pi = create_procinfo (getpid (), 0)) == NULL)
4901     perror_with_name ("procfs: create_procinfo failed in child.");
4902
4903   if (open_procinfo_files (pi, FD_CTL) == 0)
4904     {
4905       proc_warn (pi, "set_exec_trap, open_proc_files", __LINE__);
4906       gdb_flush (gdb_stderr);
4907       /* no need to call "dead_procinfo", because we're going to exit. */
4908       _exit (127);
4909     }
4910
4911 #ifdef PRFS_STOPEXEC    /* defined on OSF */
4912   /* OSF method for tracing exec syscalls.  Quoting:
4913      Under Alpha OSF/1 we have to use a PIOCSSPCACT ioctl to trace
4914      exits from exec system calls because of the user level loader.  */
4915   /* FIXME: make nice and maybe move into an access function. */
4916   {
4917     int prfs_flags;
4918
4919     if (ioctl (pi->ctl_fd, PIOCGSPCACT, &prfs_flags) < 0)
4920       {
4921         proc_warn (pi, "set_exec_trap (PIOCGSPCACT)", __LINE__);
4922         gdb_flush (gdb_stderr);
4923         _exit (127);
4924       }
4925     prfs_flags |= PRFS_STOPEXEC;
4926
4927     if (ioctl (pi->ctl_fd, PIOCSSPCACT, &prfs_flags) < 0)
4928       {
4929         proc_warn (pi, "set_exec_trap (PIOCSSPCACT)", __LINE__);
4930         gdb_flush (gdb_stderr);
4931         _exit (127);
4932       }
4933   }
4934 #else /* not PRFS_STOPEXEC */
4935   /* Everyone else's (except OSF) method for tracing exec syscalls */
4936   /* GW: Rationale...
4937      Not all systems with /proc have all the exec* syscalls with the same
4938      names.  On the SGI, for example, there is no SYS_exec, but there
4939      *is* a SYS_execv.  So, we try to account for that. */
4940
4941   exitset = sysset_t_alloc (pi);
4942   gdb_premptysysset (exitset);
4943 #ifdef SYS_exec
4944   gdb_praddsysset (exitset, SYS_exec);
4945 #endif
4946 #ifdef SYS_execve
4947   gdb_praddsysset (exitset, SYS_execve);
4948 #endif
4949 #ifdef SYS_execv
4950   gdb_praddsysset (exitset, SYS_execv);
4951 #endif
4952 #ifdef DYNAMIC_SYSCALLS
4953   {
4954     int callnum = find_syscall (pi, "execve");
4955
4956     if (callnum >= 0)
4957       gdb_praddsysset (exitset, callnum);
4958
4959     callnum = find_syscall (pi, "ra_execve");
4960     if (callnum >= 0)
4961       gdb_praddsysset (exitset, callnum);
4962   }
4963 #endif /* DYNAMIC_SYSCALLS */
4964
4965   if (!proc_set_traced_sysexit (pi, exitset))
4966     {
4967       proc_warn (pi, "set_exec_trap, set_traced_sysexit", __LINE__);
4968       gdb_flush (gdb_stderr);
4969       _exit (127);
4970     }
4971 #endif /* PRFS_STOPEXEC */
4972
4973   /* FIXME: should this be done in the parent instead? */
4974   /* Turn off inherit on fork flag so that all grand-children
4975      of gdb start with tracing flags cleared.  */
4976   if (!proc_unset_inherit_on_fork (pi))
4977     proc_warn (pi, "set_exec_trap, unset_inherit", __LINE__);
4978
4979   /* Turn off run on last close flag, so that the child process
4980      cannot run away just because we close our handle on it.
4981      We want it to wait for the parent to attach.  */
4982   if (!proc_unset_run_on_last_close (pi))
4983     proc_warn (pi, "set_exec_trap, unset_RLC", __LINE__);
4984
4985   /* FIXME: No need to destroy the procinfo -- 
4986      we have our own address space, and we're about to do an exec! */
4987   /*destroy_procinfo (pi);*/
4988 }
4989
4990 /*
4991  * Function: create_inferior
4992  *
4993  * This function is called BEFORE gdb forks the inferior process.
4994  * Its only real responsibility is to set things up for the fork, 
4995  * and tell GDB which two functions to call after the fork (one
4996  * for the parent, and one for the child).
4997  * 
4998  * This function does a complicated search for a unix shell program,
4999  * which it then uses to parse arguments and environment variables
5000  * to be sent to the child.  I wonder whether this code could not
5001  * be abstracted out and shared with other unix targets such as
5002  * infptrace?
5003  */
5004
5005 static void
5006 procfs_create_inferior (char *exec_file, char *allargs, char **env)
5007 {
5008   char *shell_file = getenv ("SHELL");
5009   char *tryname;
5010   if (shell_file != NULL && strchr (shell_file, '/') == NULL)
5011     {
5012
5013       /* We will be looking down the PATH to find shell_file.  If we
5014          just do this the normal way (via execlp, which operates by
5015          attempting an exec for each element of the PATH until it
5016          finds one which succeeds), then there will be an exec for
5017          each failed attempt, each of which will cause a PR_SYSEXIT
5018          stop, and we won't know how to distinguish the PR_SYSEXIT's
5019          for these failed execs with the ones for successful execs
5020          (whether the exec has succeeded is stored at that time in the
5021          carry bit or some such architecture-specific and
5022          non-ABI-specified place).
5023
5024          So I can't think of anything better than to search the PATH
5025          now.  This has several disadvantages: (1) There is a race
5026          condition; if we find a file now and it is deleted before we
5027          exec it, we lose, even if the deletion leaves a valid file
5028          further down in the PATH, (2) there is no way to know exactly
5029          what an executable (in the sense of "capable of being
5030          exec'd") file is.  Using access() loses because it may lose
5031          if the caller is the superuser; failing to use it loses if
5032          there are ACLs or some such.  */
5033
5034       char *p;
5035       char *p1;
5036       /* FIXME-maybe: might want "set path" command so user can change what
5037          path is used from within GDB.  */
5038       char *path = getenv ("PATH");
5039       int len;
5040       struct stat statbuf;
5041
5042       if (path == NULL)
5043         path = "/bin:/usr/bin";
5044
5045       tryname = alloca (strlen (path) + strlen (shell_file) + 2);
5046       for (p = path; p != NULL; p = p1 ? p1 + 1: NULL)
5047         {
5048           p1 = strchr (p, ':');
5049           if (p1 != NULL)
5050             len = p1 - p;
5051           else
5052             len = strlen (p);
5053           strncpy (tryname, p, len);
5054           tryname[len] = '\0';
5055           strcat (tryname, "/");
5056           strcat (tryname, shell_file);
5057           if (access (tryname, X_OK) < 0)
5058             continue;
5059           if (stat (tryname, &statbuf) < 0)
5060             continue;
5061           if (!S_ISREG (statbuf.st_mode))
5062             /* We certainly need to reject directories.  I'm not quite
5063                as sure about FIFOs, sockets, etc., but I kind of doubt
5064                that people want to exec() these things.  */
5065             continue;
5066           break;
5067         }
5068       if (p == NULL)
5069         /* Not found.  This must be an error rather than merely passing
5070            the file to execlp(), because execlp() would try all the
5071            exec()s, causing GDB to get confused.  */
5072         error ("procfs:%d -- Can't find shell %s in PATH",
5073                __LINE__, shell_file);
5074
5075       shell_file = tryname;
5076     }
5077
5078   fork_inferior (exec_file, allargs, env, procfs_set_exec_trap, 
5079                  procfs_init_inferior, NULL, shell_file);
5080
5081   /* We are at the first instruction we care about.  */
5082   /* Pedal to the metal... */
5083
5084   proceed ((CORE_ADDR) -1, TARGET_SIGNAL_0, 0);
5085 }
5086
5087 /*
5088  * Function: notice_thread
5089  *
5090  * Callback for find_new_threads.
5091  * Calls "add_thread".
5092  */
5093
5094 static int
5095 procfs_notice_thread (procinfo *pi, procinfo *thread, void *ptr)
5096 {
5097   ptid_t gdb_threadid = MERGEPID (pi->pid, thread->tid);
5098
5099   if (!in_thread_list (gdb_threadid))
5100     add_thread (gdb_threadid);
5101
5102   return 0;
5103 }
5104
5105 /*
5106  * Function: target_find_new_threads
5107  *
5108  * Query all the threads that the target knows about, 
5109  * and give them back to GDB to add to its list.
5110  */
5111
5112 void
5113 procfs_find_new_threads (void)
5114 {
5115   procinfo *pi;
5116
5117   /* Find procinfo for main process */
5118   pi = find_procinfo_or_die (PIDGET (inferior_ptid), 0);
5119   proc_update_threads (pi);
5120   proc_iterate_over_threads (pi, procfs_notice_thread, NULL);
5121 }
5122
5123 /* 
5124  * Function: target_thread_alive
5125  *
5126  * Return true if the thread is still 'alive'.
5127  *
5128  * This guy doesn't really seem to be doing his job.
5129  * Got to investigate how to tell when a thread is really gone.
5130  */
5131
5132 static int
5133 procfs_thread_alive (ptid_t ptid)
5134 {
5135   int proc, thread;
5136   procinfo *pi;
5137
5138   proc    = PIDGET (ptid);
5139   thread  = TIDGET (ptid);
5140   /* If I don't know it, it ain't alive! */
5141   if ((pi = find_procinfo (proc, thread)) == NULL)
5142     return 0;
5143
5144   /* If I can't get its status, it ain't alive!
5145      What's more, I need to forget about it!  */
5146   if (!proc_get_status (pi))
5147     {
5148       destroy_procinfo (pi);
5149       return 0;
5150     }
5151   /* I couldn't have got its status if it weren't alive, so it's alive.  */
5152   return 1;
5153 }
5154
5155 /*
5156  * Function: target_pid_to_str
5157  *
5158  * Return a string to be used to identify the thread in 
5159  * the "info threads" display.
5160  */
5161
5162 char *
5163 procfs_pid_to_str (ptid_t ptid)
5164 {
5165   static char buf[80];
5166   int proc, thread;
5167   procinfo *pi;
5168
5169   proc    = PIDGET (ptid);
5170   thread  = TIDGET (ptid);
5171   pi      = find_procinfo (proc, thread);
5172
5173   if (thread == 0)
5174     sprintf (buf, "Process %d", proc);
5175   else
5176     sprintf (buf, "LWP %d", thread);
5177   return &buf[0];
5178 }
5179
5180 /*
5181  * Function: procfs_set_watchpoint
5182  * Insert a watchpoint
5183  */
5184
5185 int 
5186 procfs_set_watchpoint (ptid_t ptid, CORE_ADDR addr, int len, int rwflag,
5187                        int after)
5188 {
5189 #ifndef UNIXWARE
5190 #ifndef AIX5
5191   int       pflags = 0;
5192   procinfo *pi; 
5193
5194   pi = find_procinfo_or_die (PIDGET (ptid) == -1 ? 
5195                              PIDGET (inferior_ptid) : PIDGET (ptid), 0);
5196
5197   /* Translate from GDB's flags to /proc's */
5198   if (len > 0)  /* len == 0 means delete watchpoint */
5199     {
5200       switch (rwflag) {         /* FIXME: need an enum! */
5201       case hw_write:            /* default watchpoint (write) */
5202         pflags = WRITE_WATCHFLAG;
5203         break;
5204       case hw_read:             /* read watchpoint */
5205         pflags = READ_WATCHFLAG;
5206         break;
5207       case hw_access:           /* access watchpoint */
5208         pflags = READ_WATCHFLAG | WRITE_WATCHFLAG;
5209         break;
5210       case hw_execute:          /* execution HW breakpoint */
5211         pflags = EXEC_WATCHFLAG;
5212         break;
5213       default:                  /* Something weird.  Return error. */
5214         return -1;
5215       }
5216       if (after)                /* Stop after r/w access is completed. */
5217         pflags |= AFTER_WATCHFLAG;
5218     }
5219
5220   if (!proc_set_watchpoint (pi, addr, len, pflags))
5221     {
5222       if (errno == E2BIG)       /* Typical error for no resources */
5223         return -1;              /* fail */
5224       /* GDB may try to remove the same watchpoint twice.
5225          If a remove request returns no match, don't error.  */
5226       if (errno == ESRCH && len == 0)
5227         return 0;               /* ignore */
5228       proc_error (pi, "set_watchpoint", __LINE__);
5229     }
5230 #endif /* AIX5 */
5231 #endif /* UNIXWARE */
5232   return 0;
5233 }
5234
5235 /*
5236  * Function: stopped_by_watchpoint
5237  *
5238  * Returns non-zero if process is stopped on a hardware watchpoint fault,
5239  * else returns zero.
5240  */
5241
5242 int
5243 procfs_stopped_by_watchpoint (ptid_t ptid)
5244 {
5245   procinfo *pi;
5246
5247   pi = find_procinfo_or_die (PIDGET (ptid) == -1 ? 
5248                              PIDGET (inferior_ptid) : PIDGET (ptid), 0);
5249
5250   if (!pi)      /* If no process, then not stopped by watchpoint!  */
5251     return 0;
5252
5253   if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
5254     {
5255       if (proc_why (pi) == PR_FAULTED)
5256         {       
5257 #ifdef FLTWATCH
5258           if (proc_what (pi) == FLTWATCH)
5259             return 1;
5260 #endif
5261 #ifdef FLTKWATCH
5262           if (proc_what (pi) == FLTKWATCH)
5263             return 1;
5264 #endif
5265         }
5266     }
5267   return 0;
5268 }
5269
5270 #ifdef TM_I386SOL2_H
5271 /*
5272  * Function: procfs_find_LDT_entry 
5273  *
5274  * Input:
5275  *   ptid_t ptid;       // The GDB-style pid-plus-LWP.
5276  *
5277  * Return:
5278  *   pointer to the corresponding LDT entry.
5279  */
5280
5281 struct ssd *
5282 procfs_find_LDT_entry (ptid_t ptid)
5283 {
5284   gdb_gregset_t *gregs;
5285   int            key;
5286   procinfo      *pi;
5287
5288   /* Find procinfo for the lwp. */
5289   if ((pi = find_procinfo (PIDGET (ptid), TIDGET (ptid))) == NULL)
5290     {
5291       warning ("procfs_find_LDT_entry: could not find procinfo for %d:%d.",
5292                PIDGET (ptid), TIDGET (ptid));
5293       return NULL;
5294     }
5295   /* get its general registers. */
5296   if ((gregs = proc_get_gregs (pi)) == NULL)
5297     {
5298       warning ("procfs_find_LDT_entry: could not read gregs for %d:%d.",
5299                PIDGET (ptid), TIDGET (ptid));
5300       return NULL;
5301     }
5302   /* Now extract the GS register's lower 16 bits. */
5303   key = (*gregs)[GS] & 0xffff;
5304
5305   /* Find the matching entry and return it. */
5306   return proc_get_LDT_entry (pi, key);
5307 }
5308 #endif /* TM_I386SOL2_H */
5309
5310 /*
5311  * Function: mappingflags
5312  *
5313  * Returns an ascii representation of a memory mapping's flags.
5314  */
5315
5316 static char *
5317 mappingflags (flags)
5318      long flags;
5319 {
5320   static char asciiflags[8];
5321
5322   strcpy (asciiflags, "-------");
5323 #if defined (MA_PHYS)
5324   if (flags & MA_PHYS)
5325     asciiflags[0] = 'd';
5326 #endif
5327   if (flags & MA_STACK)
5328     asciiflags[1] = 's';
5329   if (flags & MA_BREAK)
5330     asciiflags[2] = 'b';
5331   if (flags & MA_SHARED)
5332     asciiflags[3] = 's';
5333   if (flags & MA_READ)
5334     asciiflags[4] = 'r';
5335   if (flags & MA_WRITE)
5336     asciiflags[5] = 'w';
5337   if (flags & MA_EXEC)
5338     asciiflags[6] = 'x';
5339   return (asciiflags);
5340 }
5341
5342 /*
5343  * Function: info_proc_mappings
5344  *
5345  * Implement the "info proc mappings" subcommand.
5346  */
5347
5348 static void
5349 info_proc_mappings (procinfo *pi, int summary)
5350 {
5351   char *header_fmt_string, *data_fmt_string;
5352   char pathname[MAX_PROC_NAME_SIZE];
5353   struct prmap *prmaps;
5354   struct prmap *prmap;
5355   int map_fd;
5356   int nmap;
5357 #ifdef NEW_PROC_API
5358   struct stat sbuf;
5359 #endif
5360
5361   if (TARGET_PTR_BIT == 32)
5362     {
5363       header_fmt_string = "\t%10s %10s %10s %10s %7s\n";
5364       data_fmt_string   = "\t%#10lx %#10lx %#10x %#10x %7s\n";
5365     }
5366   else
5367     {
5368       header_fmt_string = "  %18s %18s %10s %10s %7s\n";
5369       data_fmt_string   = "  %#18lx %#18lx %#10x %#10x %7s\n";
5370     }
5371
5372   if (summary)
5373     return;     /* No output for summary mode. */
5374
5375   /* Get the number of mappings, allocate space, 
5376      and read the mappings into prmaps.  */
5377 #ifdef NEW_PROC_API
5378   /* Open map fd. */
5379   sprintf (pathname, "/proc/%d/map", pi->pid);
5380   if ((map_fd = open (pathname, O_RDONLY)) < 0)
5381     return;             /* Can't open map file. */
5382   /* Make sure it gets closed again. */
5383   make_cleanup_close (map_fd);
5384
5385   /* Use stat to determine the file size, and compute 
5386      the number of prmap_t objects it contains.  */
5387   if (fstat (map_fd, &sbuf) != 0)
5388     return;             /* Can't stat file.  */
5389
5390   nmap = sbuf.st_size / sizeof (prmap_t);
5391   prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
5392   if (read (map_fd, (char *) prmaps, nmap * sizeof (*prmaps))
5393       != (nmap * sizeof (*prmaps)))
5394     return;             /* Can't read file. */
5395 #else
5396   /* Use ioctl command PIOCNMAP to get number of mappings.  */
5397   if (ioctl (pi->ctl_fd, PIOCNMAP, &nmap) != 0)
5398     return;     /* Can't get number of mappings.  */
5399   prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
5400   if (ioctl (pi->ctl_fd, PIOCMAP, prmaps) != 0)
5401     return;     /* Can't read mappings. */
5402 #endif
5403
5404   printf_filtered ("Mapped address spaces:\n\n");
5405   printf_filtered (header_fmt_string, 
5406                    "Start Addr",
5407                    "  End Addr",
5408                    "      Size",
5409                    "    Offset",
5410                    "Flags");
5411
5412   for (prmap = prmaps; nmap > 0; prmap++, nmap--)
5413     {
5414       printf_filtered (data_fmt_string, 
5415                        (unsigned long) prmap->pr_vaddr,
5416                        (unsigned long) prmap->pr_vaddr
5417                        + prmap->pr_size - 1,
5418                        prmap->pr_size,
5419 #ifdef PCAGENT          /* Gross hack: only defined on Solaris 2.6+ */
5420                        (unsigned int) prmap->pr_offset, 
5421 #else
5422                        prmap->pr_off,
5423 #endif
5424                        mappingflags (prmap->pr_mflags));
5425     }
5426   printf_filtered ("\n");
5427 }
5428
5429 /*
5430  * Function: info_proc_cmd
5431  *
5432  * Implement the "info proc" command.
5433  */
5434
5435 static void
5436 info_proc_cmd (char *args, int from_tty)
5437 {
5438   struct cleanup *old_chain;
5439   procinfo *process  = NULL;
5440   procinfo *thread   = NULL;
5441   char    **argv     = NULL;
5442   char     *tmp      = NULL;
5443   int       pid      = 0;
5444   int       tid      = 0;
5445   int       mappings = 0;
5446
5447   old_chain = make_cleanup (null_cleanup, 0);
5448   if (args)
5449     {
5450       if ((argv = buildargv (args)) == NULL)
5451         nomem (0);
5452       else
5453         make_cleanup_freeargv (argv);
5454     }
5455   while (argv != NULL && *argv != NULL)
5456     {
5457       if (isdigit (argv[0][0]))
5458         {
5459           pid = strtoul (argv[0], &tmp, 10);
5460           if (*tmp == '/')
5461             tid = strtoul (++tmp, NULL, 10);
5462         }
5463       else if (argv[0][0] == '/')
5464         {
5465           tid = strtoul (argv[0] + 1, NULL, 10);
5466         }
5467       else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
5468         {
5469           mappings = 1;
5470         }
5471       else
5472         {
5473           /* [...] */
5474         }
5475       argv++;
5476     }
5477   if (pid == 0)
5478     pid = PIDGET (inferior_ptid);
5479   if (pid == 0)
5480     error ("No current process: you must name one.");
5481   else
5482     {
5483       /* Have pid, will travel.
5484          First see if it's a process we're already debugging. */
5485       process = find_procinfo (pid, 0);
5486        if (process == NULL)
5487          {
5488            /* No.  So open a procinfo for it, but 
5489               remember to close it again when finished.  */
5490            process = create_procinfo (pid, 0);
5491            make_cleanup (do_destroy_procinfo_cleanup, process);
5492            if (!open_procinfo_files (process, FD_CTL))
5493              proc_error (process, "info proc, open_procinfo_files", __LINE__);
5494          }
5495     }
5496   if (tid != 0)
5497     thread = create_procinfo (pid, tid);
5498
5499   if (process)
5500     {
5501       printf_filtered ("process %d flags:\n", process->pid);
5502       proc_prettyprint_flags (proc_flags (process), 1);
5503       if (proc_flags (process) & (PR_STOPPED | PR_ISTOP))
5504         proc_prettyprint_why (proc_why (process), proc_what (process), 1);
5505       if (proc_get_nthreads (process) > 1)
5506         printf_filtered ("Process has %d threads.\n", 
5507                          proc_get_nthreads (process));
5508     }
5509   if (thread)
5510     {
5511       printf_filtered ("thread %d flags:\n", thread->tid);
5512       proc_prettyprint_flags (proc_flags (thread), 1);
5513       if (proc_flags (thread) & (PR_STOPPED | PR_ISTOP))
5514         proc_prettyprint_why (proc_why (thread), proc_what (thread), 1);
5515     }
5516
5517   if (mappings)
5518     {
5519       info_proc_mappings (process, 0);
5520     }
5521
5522   do_cleanups (old_chain);
5523 }
5524
5525 static void
5526 proc_trace_syscalls (char *args, int from_tty, int entry_or_exit, int mode)
5527 {
5528   procinfo *pi;
5529   sysset_t *sysset;
5530   int       syscallnum = 0;
5531
5532   if (PIDGET (inferior_ptid) <= 0)
5533     error ("you must be debugging a process to use this command.");
5534
5535   if (args == NULL || args[0] == 0)
5536     error_no_arg ("system call to trace");
5537
5538   pi = find_procinfo_or_die (PIDGET (inferior_ptid), 0);
5539   if (isdigit (args[0]))
5540     {
5541       syscallnum = atoi (args);
5542       if (entry_or_exit == PR_SYSENTRY)
5543         sysset = proc_get_traced_sysentry (pi, NULL);
5544       else
5545         sysset = proc_get_traced_sysexit (pi, NULL);
5546
5547       if (sysset == NULL)
5548         proc_error (pi, "proc-trace, get_traced_sysset", __LINE__);
5549
5550       if (mode == FLAG_SET)
5551         gdb_praddsysset (sysset, syscallnum);
5552       else
5553         gdb_prdelsysset (sysset, syscallnum);
5554
5555       if (entry_or_exit == PR_SYSENTRY)
5556         {
5557           if (!proc_set_traced_sysentry (pi, sysset))
5558             proc_error (pi, "proc-trace, set_traced_sysentry", __LINE__);
5559         }
5560       else
5561         {
5562           if (!proc_set_traced_sysexit (pi, sysset))
5563             proc_error (pi, "proc-trace, set_traced_sysexit", __LINE__);
5564         }
5565     }
5566 }
5567
5568 static void 
5569 proc_trace_sysentry_cmd (char *args, int from_tty)
5570 {
5571   proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_SET);
5572 }
5573
5574 static void 
5575 proc_trace_sysexit_cmd (char *args, int from_tty)
5576 {
5577   proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_SET);
5578 }
5579
5580 static void 
5581 proc_untrace_sysentry_cmd (char *args, int from_tty)
5582 {
5583   proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_RESET);
5584 }
5585
5586 static void 
5587 proc_untrace_sysexit_cmd (char *args, int from_tty)
5588 {
5589   proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_RESET);
5590 }
5591
5592
5593 void
5594 _initialize_procfs (void)
5595 {
5596   init_procfs_ops ();
5597   add_target (&procfs_ops);
5598   add_info ("proc", info_proc_cmd, 
5599             "Show /proc process information about any running process.\n\
5600 Specify process id, or use the program being debugged by default.\n\
5601 Specify keyword 'mappings' for detailed info on memory mappings.");
5602   add_com ("proc-trace-entry", no_class, proc_trace_sysentry_cmd, 
5603            "Give a trace of entries into the syscall.");
5604   add_com ("proc-trace-exit", no_class, proc_trace_sysexit_cmd, 
5605            "Give a trace of exits from the syscall.");
5606   add_com ("proc-untrace-entry", no_class, proc_untrace_sysentry_cmd, 
5607            "Cancel a trace of entries into the syscall.");
5608   add_com ("proc-untrace-exit", no_class, proc_untrace_sysexit_cmd, 
5609            "Cancel a trace of exits from the syscall.");
5610 }
5611
5612 /* =================== END, GDB  "MODULE" =================== */
5613
5614
5615
5616 /* miscelaneous stubs:                                             */
5617 /* The following satisfy a few random symbols mostly created by    */
5618 /* the solaris threads implementation, which I will chase down     */
5619 /* later.        */
5620
5621 /*
5622  * Return a pid for which we guarantee
5623  * we will be able to find a 'live' procinfo.
5624  */
5625
5626 ptid_t
5627 procfs_first_available (void)
5628 {
5629   return pid_to_ptid (procinfo_list ? procinfo_list->pid : -1);
5630 }