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