OSDN Git Service

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