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