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