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