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