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