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