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