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