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