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