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