GDB (API)
/home/stan/gdb/src/gdb/procfs.c
Go to the documentation of this file.
00001 /* Machine independent support for SVR4 /proc (process file system) for GDB.
00002 
00003    Copyright (C) 1999-2013 Free Software Foundation, Inc.
00004 
00005    Written by Michael Snyder at Cygnus Solutions.
00006    Based on work by Fred Fish, Stu Grossman, Geoff Noer, and others.
00007 
00008    This file is part of GDB.
00009 
00010    This program is free software; you can redistribute it and/or modify
00011    it under the terms of the GNU General Public License as published by
00012    the Free Software Foundation; either version 3 of the License, or
00013    (at your option) any later version.
00014 
00015    This program is distributed in the hope that it will be useful,
00016    but WITHOUT ANY WARRANTY; without even the implied warranty of
00017    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00018    GNU General Public License for more details.
00019 
00020    You should have received a copy of the GNU General Public License
00021    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00022 
00023 #include "defs.h"
00024 #include "inferior.h"
00025 #include "target.h"
00026 #include "gdbcore.h"
00027 #include "elf-bfd.h"            /* for elfcore_write_* */
00028 #include "gdbcmd.h"
00029 #include "gdbthread.h"
00030 #include "regcache.h"
00031 #include "inf-child.h"
00032 
00033 #if defined (NEW_PROC_API)
00034 #define _STRUCTURED_PROC 1      /* Should be done by configure script.  */
00035 #endif
00036 
00037 #include <sys/procfs.h>
00038 #ifdef HAVE_SYS_FAULT_H
00039 #include <sys/fault.h>
00040 #endif
00041 #ifdef HAVE_SYS_SYSCALL_H
00042 #include <sys/syscall.h>
00043 #endif
00044 #include <sys/errno.h>
00045 #include "gdb_wait.h"
00046 #include <signal.h>
00047 #include <ctype.h>
00048 #include "gdb_bfd.h"
00049 #include "gdb_string.h"
00050 #include "gdb_assert.h"
00051 #include "inflow.h"
00052 #include "auxv.h"
00053 #include "procfs.h"
00054 #include "observer.h"
00055 
00056 /* This module provides the interface between GDB and the
00057    /proc file system, which is used on many versions of Unix
00058    as a means for debuggers to control other processes.
00059 
00060    Examples of the systems that use this interface are:
00061 
00062      Irix
00063      Solaris
00064      OSF
00065      AIX5
00066 
00067    /proc works by imitating a file system: you open a simulated file
00068    that represents the process you wish to interact with, and perform
00069    operations on that "file" in order to examine or change the state
00070    of the other process.
00071 
00072    The most important thing to know about /proc and this module is
00073    that there are two very different interfaces to /proc:
00074 
00075      One that uses the ioctl system call, and another that uses read
00076      and write system calls.
00077 
00078    This module has to support both /proc interfaces.  This means that
00079    there are two different ways of doing every basic operation.
00080 
00081    In order to keep most of the code simple and clean, I have defined
00082    an interface "layer" which hides all these system calls.  An ifdef
00083    (NEW_PROC_API) determines which interface we are using, and most or
00084    all occurrances of this ifdef should be confined to this interface
00085    layer.  */
00086 
00087 /* Determine which /proc API we are using: The ioctl API defines
00088    PIOCSTATUS, while the read/write (multiple fd) API never does.  */
00089 
00090 #ifdef NEW_PROC_API
00091 #include <sys/types.h>
00092 #include "gdb_dirent.h" /* opendir/readdir, for listing the LWP's */
00093 #endif
00094 
00095 #include <fcntl.h>      /* for O_RDONLY */
00096 #include <unistd.h>     /* for "X_OK" */
00097 #include "gdb_stat.h"   /* for struct stat */
00098 
00099 /* Note: procfs-utils.h must be included after the above system header
00100    files, because it redefines various system calls using macros.
00101    This may be incompatible with the prototype declarations.  */
00102 
00103 #include "proc-utils.h"
00104 
00105 /* Prototypes for supply_gregset etc.  */
00106 #include "gregset.h"
00107 
00108 /* =================== TARGET_OPS "MODULE" =================== */
00109 
00110 /* This module defines the GDB target vector and its methods.  */
00111 
00112 static void procfs_attach (struct target_ops *, char *, int);
00113 static void procfs_detach (struct target_ops *, char *, int);
00114 static void procfs_resume (struct target_ops *,
00115                            ptid_t, int, enum gdb_signal);
00116 static void procfs_stop (ptid_t);
00117 static void procfs_files_info (struct target_ops *);
00118 static void procfs_fetch_registers (struct target_ops *,
00119                                     struct regcache *, int);
00120 static void procfs_store_registers (struct target_ops *,
00121                                     struct regcache *, int);
00122 static void procfs_pass_signals (int, unsigned char *);
00123 static void procfs_kill_inferior (struct target_ops *ops);
00124 static void procfs_mourn_inferior (struct target_ops *ops);
00125 static void procfs_create_inferior (struct target_ops *, char *,
00126                                     char *, char **, int);
00127 static ptid_t procfs_wait (struct target_ops *,
00128                            ptid_t, struct target_waitstatus *, int);
00129 static int procfs_xfer_memory (CORE_ADDR, gdb_byte *, int, int,
00130                                struct mem_attrib *attrib,
00131                                struct target_ops *);
00132 static LONGEST procfs_xfer_partial (struct target_ops *ops,
00133                                     enum target_object object,
00134                                     const char *annex,
00135                                     gdb_byte *readbuf,
00136                                     const gdb_byte *writebuf,
00137                                     ULONGEST offset, LONGEST len);
00138 
00139 static int procfs_thread_alive (struct target_ops *ops, ptid_t);
00140 
00141 static void procfs_find_new_threads (struct target_ops *ops);
00142 static char *procfs_pid_to_str (struct target_ops *, ptid_t);
00143 
00144 static int proc_find_memory_regions (find_memory_region_ftype, void *);
00145 
00146 static char * procfs_make_note_section (bfd *, int *);
00147 
00148 static int procfs_can_use_hw_breakpoint (int, int, int);
00149 
00150 static void procfs_info_proc (struct target_ops *, char *,
00151                               enum info_proc_what);
00152 
00153 #if defined (PR_MODEL_NATIVE) && (PR_MODEL_NATIVE == PR_MODEL_LP64)
00154 /* When GDB is built as 64-bit application on Solaris, the auxv data
00155    is presented in 64-bit format.  We need to provide a custom parser
00156    to handle that.  */
00157 static int
00158 procfs_auxv_parse (struct target_ops *ops, gdb_byte **readptr,
00159                    gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
00160 {
00161   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
00162   gdb_byte *ptr = *readptr;
00163 
00164   if (endptr == ptr)
00165     return 0;
00166 
00167   if (endptr - ptr < 8 * 2)
00168     return -1;
00169 
00170   *typep = extract_unsigned_integer (ptr, 4, byte_order);
00171   ptr += 8;
00172   /* The size of data is always 64-bit.  If the application is 32-bit,
00173      it will be zero extended, as expected.  */
00174   *valp = extract_unsigned_integer (ptr, 8, byte_order);
00175   ptr += 8;
00176 
00177   *readptr = ptr;
00178   return 1;
00179 }
00180 #endif
00181 
00182 struct target_ops *
00183 procfs_target (void)
00184 {
00185   struct target_ops *t = inf_child_target ();
00186 
00187   t->to_shortname = "procfs";
00188   t->to_longname = "Unix /proc child process";
00189   t->to_doc =
00190     "Unix /proc child process (started by the \"run\" command).";
00191   t->to_create_inferior = procfs_create_inferior;
00192   t->to_kill = procfs_kill_inferior;
00193   t->to_mourn_inferior = procfs_mourn_inferior;
00194   t->to_attach = procfs_attach;
00195   t->to_detach = procfs_detach;
00196   t->to_wait = procfs_wait;
00197   t->to_resume = procfs_resume;
00198   t->to_fetch_registers = procfs_fetch_registers;
00199   t->to_store_registers = procfs_store_registers;
00200   t->to_xfer_partial = procfs_xfer_partial;
00201   t->deprecated_xfer_memory = procfs_xfer_memory;
00202   t->to_pass_signals = procfs_pass_signals;
00203   t->to_files_info = procfs_files_info;
00204   t->to_stop = procfs_stop;
00205 
00206   t->to_find_new_threads = procfs_find_new_threads;
00207   t->to_thread_alive = procfs_thread_alive;
00208   t->to_pid_to_str = procfs_pid_to_str;
00209 
00210   t->to_has_thread_control = tc_schedlock;
00211   t->to_find_memory_regions = proc_find_memory_regions;
00212   t->to_make_corefile_notes = procfs_make_note_section;
00213   t->to_info_proc = procfs_info_proc;
00214 
00215 #if defined(PR_MODEL_NATIVE) && (PR_MODEL_NATIVE == PR_MODEL_LP64)
00216   t->to_auxv_parse = procfs_auxv_parse;
00217 #endif
00218 
00219   t->to_magic = OPS_MAGIC;
00220 
00221   return t;
00222 }
00223 
00224 /* =================== END, TARGET_OPS "MODULE" =================== */
00225 
00226 /* World Unification:
00227 
00228    Put any typedefs, defines etc. here that are required for the
00229    unification of code that handles different versions of /proc.  */
00230 
00231 #ifdef NEW_PROC_API             /* Solaris 7 && 8 method for watchpoints */
00232 #ifdef WA_READ
00233      enum { READ_WATCHFLAG  = WA_READ,
00234             WRITE_WATCHFLAG = WA_WRITE,
00235             EXEC_WATCHFLAG  = WA_EXEC,
00236             AFTER_WATCHFLAG = WA_TRAPAFTER
00237      };
00238 #endif
00239 #else                           /* Irix method for watchpoints */
00240      enum { READ_WATCHFLAG  = MA_READ,
00241             WRITE_WATCHFLAG = MA_WRITE,
00242             EXEC_WATCHFLAG  = MA_EXEC,
00243             AFTER_WATCHFLAG = 0         /* trapafter not implemented */
00244      };
00245 #endif
00246 
00247 /* gdb_sigset_t */
00248 #ifdef HAVE_PR_SIGSET_T
00249 typedef pr_sigset_t gdb_sigset_t;
00250 #else
00251 typedef sigset_t gdb_sigset_t;
00252 #endif
00253 
00254 /* sigaction */
00255 #ifdef HAVE_PR_SIGACTION64_T
00256 typedef pr_sigaction64_t gdb_sigaction_t;
00257 #else
00258 typedef struct sigaction gdb_sigaction_t;
00259 #endif
00260 
00261 /* siginfo */
00262 #ifdef HAVE_PR_SIGINFO64_T
00263 typedef pr_siginfo64_t gdb_siginfo_t;
00264 #else
00265 typedef siginfo_t gdb_siginfo_t;
00266 #endif
00267 
00268 /* On mips-irix, praddset and prdelset are defined in such a way that
00269    they return a value, which causes GCC to emit a -Wunused error
00270    because the returned value is not used.  Prevent this warning
00271    by casting the return value to void.  On sparc-solaris, this issue
00272    does not exist because the definition of these macros already include
00273    that cast to void.  */
00274 #define gdb_praddset(sp, flag) ((void) praddset (sp, flag))
00275 #define gdb_prdelset(sp, flag) ((void) prdelset (sp, flag))
00276 
00277 /* gdb_premptysysset */
00278 #ifdef premptysysset
00279 #define gdb_premptysysset premptysysset
00280 #else
00281 #define gdb_premptysysset premptyset
00282 #endif
00283 
00284 /* praddsysset */
00285 #ifdef praddsysset
00286 #define gdb_praddsysset praddsysset
00287 #else
00288 #define gdb_praddsysset gdb_praddset
00289 #endif
00290 
00291 /* prdelsysset */
00292 #ifdef prdelsysset
00293 #define gdb_prdelsysset prdelsysset
00294 #else
00295 #define gdb_prdelsysset gdb_prdelset
00296 #endif
00297 
00298 /* prissyssetmember */
00299 #ifdef prissyssetmember
00300 #define gdb_pr_issyssetmember prissyssetmember
00301 #else
00302 #define gdb_pr_issyssetmember prismember
00303 #endif
00304 
00305 /* As a feature test, saying ``#if HAVE_PRSYSENT_T'' everywhere isn't
00306    as intuitively descriptive as it could be, so we'll define
00307    DYNAMIC_SYSCALLS to mean the same thing.  Anyway, at the time of
00308    this writing, this feature is only found on AIX5 systems and
00309    basically means that the set of syscalls is not fixed.  I.e,
00310    there's no nice table that one can #include to get all of the
00311    syscall numbers.  Instead, they're stored in /proc/PID/sysent
00312    for each process.  We are at least guaranteed that they won't
00313    change over the lifetime of the process.  But each process could
00314    (in theory) have different syscall numbers.  */
00315 #ifdef HAVE_PRSYSENT_T
00316 #define DYNAMIC_SYSCALLS
00317 #endif
00318 
00319 
00320 
00321 /* =================== STRUCT PROCINFO "MODULE" =================== */
00322 
00323      /* FIXME: this comment will soon be out of date W.R.T. threads.  */
00324 
00325 /* The procinfo struct is a wrapper to hold all the state information
00326    concerning a /proc process.  There should be exactly one procinfo
00327    for each process, and since GDB currently can debug only one
00328    process at a time, that means there should be only one procinfo.
00329    All of the LWP's of a process can be accessed indirectly thru the
00330    single process procinfo.
00331 
00332    However, against the day when GDB may debug more than one process,
00333    this data structure is kept in a list (which for now will hold no
00334    more than one member), and many functions will have a pointer to a
00335    procinfo as an argument.
00336 
00337    There will be a separate procinfo structure for use by the (not yet
00338    implemented) "info proc" command, so that we can print useful
00339    information about any random process without interfering with the
00340    inferior's procinfo information.  */
00341 
00342 #ifdef NEW_PROC_API
00343 /* format strings for /proc paths */
00344 # ifndef CTL_PROC_NAME_FMT
00345 #  define MAIN_PROC_NAME_FMT   "/proc/%d"
00346 #  define CTL_PROC_NAME_FMT    "/proc/%d/ctl"
00347 #  define AS_PROC_NAME_FMT     "/proc/%d/as"
00348 #  define MAP_PROC_NAME_FMT    "/proc/%d/map"
00349 #  define STATUS_PROC_NAME_FMT "/proc/%d/status"
00350 #  define MAX_PROC_NAME_SIZE sizeof("/proc/99999/lwp/8096/lstatus")
00351 # endif
00352 /* the name of the proc status struct depends on the implementation */
00353 typedef pstatus_t   gdb_prstatus_t;
00354 typedef lwpstatus_t gdb_lwpstatus_t;
00355 #else /* ! NEW_PROC_API */
00356 /* format strings for /proc paths */
00357 # ifndef CTL_PROC_NAME_FMT
00358 #  define MAIN_PROC_NAME_FMT   "/proc/%05d"
00359 #  define CTL_PROC_NAME_FMT    "/proc/%05d"
00360 #  define AS_PROC_NAME_FMT     "/proc/%05d"
00361 #  define MAP_PROC_NAME_FMT    "/proc/%05d"
00362 #  define STATUS_PROC_NAME_FMT "/proc/%05d"
00363 #  define MAX_PROC_NAME_SIZE sizeof("/proc/ttttppppp")
00364 # endif
00365 /* The name of the proc status struct depends on the implementation.  */
00366 typedef prstatus_t gdb_prstatus_t;
00367 typedef prstatus_t gdb_lwpstatus_t;
00368 #endif /* NEW_PROC_API */
00369 
00370 typedef struct procinfo {
00371   struct procinfo *next;
00372   int pid;                      /* Process ID    */
00373   int tid;                      /* Thread/LWP id */
00374 
00375   /* process state */
00376   int was_stopped;
00377   int ignore_next_sigstop;
00378 
00379   /* The following four fd fields may be identical, or may contain
00380      several different fd's, depending on the version of /proc
00381      (old ioctl or new read/write).  */
00382 
00383   int ctl_fd;                   /* File descriptor for /proc control file */
00384 
00385   /* The next three file descriptors are actually only needed in the
00386      read/write, multiple-file-descriptor implemenation
00387      (NEW_PROC_API).  However, to avoid a bunch of #ifdefs in the
00388      code, we will use them uniformly by (in the case of the ioctl
00389      single-file-descriptor implementation) filling them with copies
00390      of the control fd.  */
00391   int status_fd;                /* File descriptor for /proc status file */
00392   int as_fd;                    /* File descriptor for /proc as file */
00393 
00394   char pathname[MAX_PROC_NAME_SIZE];    /* Pathname to /proc entry */
00395 
00396   fltset_t saved_fltset;        /* Saved traced hardware fault set */
00397   gdb_sigset_t saved_sigset;    /* Saved traced signal set */
00398   gdb_sigset_t saved_sighold;   /* Saved held signal set */
00399   sysset_t *saved_exitset;      /* Saved traced system call exit set */
00400   sysset_t *saved_entryset;     /* Saved traced system call entry set */
00401 
00402   gdb_prstatus_t prstatus;      /* Current process status info */
00403 
00404 #ifndef NEW_PROC_API
00405   gdb_fpregset_t fpregset;      /* Current floating point registers */
00406 #endif
00407 
00408 #ifdef DYNAMIC_SYSCALLS
00409   int num_syscalls;             /* Total number of syscalls */
00410   char **syscall_names;         /* Syscall number to name map */
00411 #endif
00412 
00413   struct procinfo *thread_list;
00414 
00415   int status_valid : 1;
00416   int gregs_valid  : 1;
00417   int fpregs_valid : 1;
00418   int threads_valid: 1;
00419 } procinfo;
00420 
00421 static char errmsg[128];        /* shared error msg buffer */
00422 
00423 /* Function prototypes for procinfo module: */
00424 
00425 static procinfo *find_procinfo_or_die (int pid, int tid);
00426 static procinfo *find_procinfo (int pid, int tid);
00427 static procinfo *create_procinfo (int pid, int tid);
00428 static void destroy_procinfo (procinfo * p);
00429 static void do_destroy_procinfo_cleanup (void *);
00430 static void dead_procinfo (procinfo * p, char *msg, int killp);
00431 static int open_procinfo_files (procinfo * p, int which);
00432 static void close_procinfo_files (procinfo * p);
00433 static int sysset_t_size (procinfo *p);
00434 static sysset_t *sysset_t_alloc (procinfo * pi);
00435 #ifdef DYNAMIC_SYSCALLS
00436 static void load_syscalls (procinfo *pi);
00437 static void free_syscalls (procinfo *pi);
00438 static int find_syscall (procinfo *pi, char *name);
00439 #endif /* DYNAMIC_SYSCALLS */
00440 
00441 static int iterate_over_mappings
00442   (procinfo *pi, find_memory_region_ftype child_func, void *data,
00443    int (*func) (struct prmap *map, find_memory_region_ftype child_func,
00444                 void *data));
00445 
00446 /* The head of the procinfo list: */
00447 static procinfo * procinfo_list;
00448 
00449 /* Search the procinfo list.  Return a pointer to procinfo, or NULL if
00450    not found.  */
00451 
00452 static procinfo *
00453 find_procinfo (int pid, int tid)
00454 {
00455   procinfo *pi;
00456 
00457   for (pi = procinfo_list; pi; pi = pi->next)
00458     if (pi->pid == pid)
00459       break;
00460 
00461   if (pi)
00462     if (tid)
00463       {
00464         /* Don't check threads_valid.  If we're updating the
00465            thread_list, we want to find whatever threads are already
00466            here.  This means that in general it is the caller's
00467            responsibility to check threads_valid and update before
00468            calling find_procinfo, if the caller wants to find a new
00469            thread.  */
00470 
00471         for (pi = pi->thread_list; pi; pi = pi->next)
00472           if (pi->tid == tid)
00473             break;
00474       }
00475 
00476   return pi;
00477 }
00478 
00479 /* Calls find_procinfo, but errors on failure.  */
00480 
00481 static procinfo *
00482 find_procinfo_or_die (int pid, int tid)
00483 {
00484   procinfo *pi = find_procinfo (pid, tid);
00485 
00486   if (pi == NULL)
00487     {
00488       if (tid)
00489         error (_("procfs: couldn't find pid %d "
00490                  "(kernel thread %d) in procinfo list."),
00491                pid, tid);
00492       else
00493         error (_("procfs: couldn't find pid %d in procinfo list."), pid);
00494     }
00495   return pi;
00496 }
00497 
00498 /* Wrapper for `open'.  The appropriate open call is attempted; if
00499    unsuccessful, it will be retried as many times as needed for the
00500    EAGAIN and EINTR conditions.
00501 
00502    For other conditions, retry the open a limited number of times.  In
00503    addition, a short sleep is imposed prior to retrying the open.  The
00504    reason for this sleep is to give the kernel a chance to catch up
00505    and create the file in question in the event that GDB "wins" the
00506    race to open a file before the kernel has created it.  */
00507 
00508 static int
00509 open_with_retry (const char *pathname, int flags)
00510 {
00511   int retries_remaining, status;
00512 
00513   retries_remaining = 2;
00514 
00515   while (1)
00516     {
00517       status = open (pathname, flags);
00518 
00519       if (status >= 0 || retries_remaining == 0)
00520         break;
00521       else if (errno != EINTR && errno != EAGAIN)
00522         {
00523           retries_remaining--;
00524           sleep (1);
00525         }
00526     }
00527 
00528   return status;
00529 }
00530 
00531 /* Open the file descriptor for the process or LWP.  If NEW_PROC_API
00532    is defined, we only open the control file descriptor; the others
00533    are opened lazily as needed.  Otherwise (if not NEW_PROC_API),
00534    there is only one real file descriptor, but we keep multiple copies
00535    of it so that the code that uses them does not have to be #ifdef'd.
00536    Returns the file descriptor, or zero for failure.  */
00537 
00538 enum { FD_CTL, FD_STATUS, FD_AS };
00539 
00540 static int
00541 open_procinfo_files (procinfo *pi, int which)
00542 {
00543 #ifdef NEW_PROC_API
00544   char tmp[MAX_PROC_NAME_SIZE];
00545 #endif
00546   int  fd;
00547 
00548   /* This function is getting ALMOST long enough to break up into
00549      several.  Here is some rationale:
00550 
00551      NEW_PROC_API (Solaris 2.6, Solaris 2.7):
00552      There are several file descriptors that may need to be open
00553        for any given process or LWP.  The ones we're intereted in are:
00554          - control       (ctl)    write-only    change the state
00555          - status        (status) read-only     query the state
00556          - address space (as)     read/write    access memory
00557          - map           (map)    read-only     virtual addr map
00558        Most of these are opened lazily as they are needed.
00559        The pathnames for the 'files' for an LWP look slightly
00560        different from those of a first-class process:
00561          Pathnames for a process (<proc-id>):
00562            /proc/<proc-id>/ctl
00563            /proc/<proc-id>/status
00564            /proc/<proc-id>/as
00565            /proc/<proc-id>/map
00566          Pathnames for an LWP (lwp-id):
00567            /proc/<proc-id>/lwp/<lwp-id>/lwpctl
00568            /proc/<proc-id>/lwp/<lwp-id>/lwpstatus
00569        An LWP has no map or address space file descriptor, since
00570        the memory map and address space are shared by all LWPs.
00571 
00572      Everyone else (Solaris 2.5, Irix, OSF)
00573        There is only one file descriptor for each process or LWP.
00574        For convenience, we copy the same file descriptor into all
00575        three fields of the procinfo struct (ctl_fd, status_fd, and
00576        as_fd, see NEW_PROC_API above) so that code that uses them
00577        doesn't need any #ifdef's.
00578          Pathname for all:
00579            /proc/<proc-id>
00580 
00581        Solaris 2.5 LWP's:
00582          Each LWP has an independent file descriptor, but these
00583          are not obtained via the 'open' system call like the rest:
00584          instead, they're obtained thru an ioctl call (PIOCOPENLWP)
00585          to the file descriptor of the parent process.
00586 
00587        OSF threads:
00588          These do not even have their own independent file descriptor.
00589          All operations are carried out on the file descriptor of the
00590          parent process.  Therefore we just call open again for each
00591          thread, getting a new handle for the same 'file'.  */
00592 
00593 #ifdef NEW_PROC_API
00594   /* In this case, there are several different file descriptors that
00595      we might be asked to open.  The control file descriptor will be
00596      opened early, but the others will be opened lazily as they are
00597      needed.  */
00598 
00599   strcpy (tmp, pi->pathname);
00600   switch (which) {      /* Which file descriptor to open?  */
00601   case FD_CTL:
00602     if (pi->tid)
00603       strcat (tmp, "/lwpctl");
00604     else
00605       strcat (tmp, "/ctl");
00606     fd = open_with_retry (tmp, O_WRONLY);
00607     if (fd < 0)
00608       return 0;         /* fail */
00609     pi->ctl_fd = fd;
00610     break;
00611   case FD_AS:
00612     if (pi->tid)
00613       return 0;         /* There is no 'as' file descriptor for an lwp.  */
00614     strcat (tmp, "/as");
00615     fd = open_with_retry (tmp, O_RDWR);
00616     if (fd < 0)
00617       return 0;         /* fail */
00618     pi->as_fd = fd;
00619     break;
00620   case FD_STATUS:
00621     if (pi->tid)
00622       strcat (tmp, "/lwpstatus");
00623     else
00624       strcat (tmp, "/status");
00625     fd = open_with_retry (tmp, O_RDONLY);
00626     if (fd < 0)
00627       return 0;         /* fail */
00628     pi->status_fd = fd;
00629     break;
00630   default:
00631     return 0;           /* unknown file descriptor */
00632   }
00633 #else  /* not NEW_PROC_API */
00634   /* In this case, there is only one file descriptor for each procinfo
00635      (ie. each process or LWP).  In fact, only the file descriptor for
00636      the process can actually be opened by an 'open' system call.  The
00637      ones for the LWPs have to be obtained thru an IOCTL call on the
00638      process's file descriptor.
00639 
00640      For convenience, we copy each procinfo's single file descriptor
00641      into all of the fields occupied by the several file descriptors
00642      of the NEW_PROC_API implementation.  That way, the code that uses
00643      them can be written without ifdefs.  */
00644 
00645 
00646 #ifdef PIOCTSTATUS      /* OSF */
00647   /* Only one FD; just open it.  */
00648   if ((fd = open_with_retry (pi->pathname, O_RDWR)) < 0)
00649     return 0;
00650 #else                   /* Sol 2.5, Irix, other?  */
00651   if (pi->tid == 0)     /* Master procinfo for the process */
00652     {
00653       fd = open_with_retry (pi->pathname, O_RDWR);
00654       if (fd < 0)
00655         return 0;       /* fail */
00656     }
00657   else                  /* LWP thread procinfo */
00658     {
00659 #ifdef PIOCOPENLWP      /* Sol 2.5, thread/LWP */
00660       procinfo *process;
00661       int lwpid = pi->tid;
00662 
00663       /* Find the procinfo for the entire process.  */
00664       if ((process = find_procinfo (pi->pid, 0)) == NULL)
00665         return 0;       /* fail */
00666 
00667       /* Now obtain the file descriptor for the LWP.  */
00668       if ((fd = ioctl (process->ctl_fd, PIOCOPENLWP, &lwpid)) < 0)
00669         return 0;       /* fail */
00670 #else                   /* Irix, other?  */
00671       return 0;         /* Don't know how to open threads.  */
00672 #endif  /* Sol 2.5 PIOCOPENLWP */
00673     }
00674 #endif  /* OSF     PIOCTSTATUS */
00675   pi->ctl_fd = pi->as_fd = pi->status_fd = fd;
00676 #endif  /* NEW_PROC_API */
00677 
00678   return 1;             /* success */
00679 }
00680 
00681 /* Allocate a data structure and link it into the procinfo list.
00682    First tries to find a pre-existing one (FIXME: why?).  Returns the
00683    pointer to new procinfo struct.  */
00684 
00685 static procinfo *
00686 create_procinfo (int pid, int tid)
00687 {
00688   procinfo *pi, *parent = NULL;
00689 
00690   if ((pi = find_procinfo (pid, tid)))
00691     return pi;                  /* Already exists, nothing to do.  */
00692 
00693   /* Find parent before doing malloc, to save having to cleanup.  */
00694   if (tid != 0)
00695     parent = find_procinfo_or_die (pid, 0);     /* FIXME: should I
00696                                                    create it if it
00697                                                    doesn't exist yet?  */
00698 
00699   pi = (procinfo *) xmalloc (sizeof (procinfo));
00700   memset (pi, 0, sizeof (procinfo));
00701   pi->pid = pid;
00702   pi->tid = tid;
00703 
00704 #ifdef DYNAMIC_SYSCALLS
00705   load_syscalls (pi);
00706 #endif
00707 
00708   pi->saved_entryset = sysset_t_alloc (pi);
00709   pi->saved_exitset = sysset_t_alloc (pi);
00710 
00711   /* Chain into list.  */
00712   if (tid == 0)
00713     {
00714       sprintf (pi->pathname, MAIN_PROC_NAME_FMT, pid);
00715       pi->next = procinfo_list;
00716       procinfo_list = pi;
00717     }
00718   else
00719     {
00720 #ifdef NEW_PROC_API
00721       sprintf (pi->pathname, "/proc/%05d/lwp/%d", pid, tid);
00722 #else
00723       sprintf (pi->pathname, MAIN_PROC_NAME_FMT, pid);
00724 #endif
00725       pi->next = parent->thread_list;
00726       parent->thread_list = pi;
00727     }
00728   return pi;
00729 }
00730 
00731 /* Close all file descriptors associated with the procinfo.  */
00732 
00733 static void
00734 close_procinfo_files (procinfo *pi)
00735 {
00736   if (pi->ctl_fd > 0)
00737     close (pi->ctl_fd);
00738 #ifdef NEW_PROC_API
00739   if (pi->as_fd > 0)
00740     close (pi->as_fd);
00741   if (pi->status_fd > 0)
00742     close (pi->status_fd);
00743 #endif
00744   pi->ctl_fd = pi->as_fd = pi->status_fd = 0;
00745 }
00746 
00747 /* Destructor function.  Close, unlink and deallocate the object.  */
00748 
00749 static void
00750 destroy_one_procinfo (procinfo **list, procinfo *pi)
00751 {
00752   procinfo *ptr;
00753 
00754   /* Step one: unlink the procinfo from its list.  */
00755   if (pi == *list)
00756     *list = pi->next;
00757   else
00758     for (ptr = *list; ptr; ptr = ptr->next)
00759       if (ptr->next == pi)
00760         {
00761           ptr->next =  pi->next;
00762           break;
00763         }
00764 
00765   /* Step two: close any open file descriptors.  */
00766   close_procinfo_files (pi);
00767 
00768   /* Step three: free the memory.  */
00769 #ifdef DYNAMIC_SYSCALLS
00770   free_syscalls (pi);
00771 #endif
00772   xfree (pi->saved_entryset);
00773   xfree (pi->saved_exitset);
00774   xfree (pi);
00775 }
00776 
00777 static void
00778 destroy_procinfo (procinfo *pi)
00779 {
00780   procinfo *tmp;
00781 
00782   if (pi->tid != 0)     /* Destroy a thread procinfo.  */
00783     {
00784       tmp = find_procinfo (pi->pid, 0); /* Find the parent process.  */
00785       destroy_one_procinfo (&tmp->thread_list, pi);
00786     }
00787   else                  /* Destroy a process procinfo and all its threads.  */
00788     {
00789       /* First destroy the children, if any; */
00790       while (pi->thread_list != NULL)
00791         destroy_one_procinfo (&pi->thread_list, pi->thread_list);
00792       /* Then destroy the parent.  Genocide!!!  */
00793       destroy_one_procinfo (&procinfo_list, pi);
00794     }
00795 }
00796 
00797 static void
00798 do_destroy_procinfo_cleanup (void *pi)
00799 {
00800   destroy_procinfo (pi);
00801 }
00802 
00803 enum { NOKILL, KILL };
00804 
00805 /* To be called on a non_recoverable error for a procinfo.  Prints
00806    error messages, optionally sends a SIGKILL to the process, then
00807    destroys the data structure.  */
00808 
00809 static void
00810 dead_procinfo (procinfo *pi, char *msg, int kill_p)
00811 {
00812   char procfile[80];
00813 
00814   if (pi->pathname)
00815     {
00816       print_sys_errmsg (pi->pathname, errno);
00817     }
00818   else
00819     {
00820       sprintf (procfile, "process %d", pi->pid);
00821       print_sys_errmsg (procfile, errno);
00822     }
00823   if (kill_p == KILL)
00824     kill (pi->pid, SIGKILL);
00825 
00826   destroy_procinfo (pi);
00827   error ("%s", msg);
00828 }
00829 
00830 /* Returns the (complete) size of a sysset_t struct.  Normally, this
00831    is just sizeof (sysset_t), but in the case of Monterey/64, the
00832    actual size of sysset_t isn't known until runtime.  */
00833 
00834 static int
00835 sysset_t_size (procinfo * pi)
00836 {
00837 #ifndef DYNAMIC_SYSCALLS
00838   return sizeof (sysset_t);
00839 #else
00840   return sizeof (sysset_t) - sizeof (uint64_t)
00841     + sizeof (uint64_t) * ((pi->num_syscalls + (8 * sizeof (uint64_t) - 1))
00842                            / (8 * sizeof (uint64_t)));
00843 #endif
00844 }
00845 
00846 /* Allocate and (partially) initialize a sysset_t struct.  */
00847 
00848 static sysset_t *
00849 sysset_t_alloc (procinfo * pi)
00850 {
00851   sysset_t *ret;
00852   int size = sysset_t_size (pi);
00853 
00854   ret = xmalloc (size);
00855 #ifdef DYNAMIC_SYSCALLS
00856   ret->pr_size = ((pi->num_syscalls + (8 * sizeof (uint64_t) - 1))
00857                   / (8 * sizeof (uint64_t)));
00858 #endif
00859   return ret;
00860 }
00861 
00862 #ifdef DYNAMIC_SYSCALLS
00863 
00864 /* Extract syscall numbers and names from /proc/<pid>/sysent.  Initialize
00865    pi->num_syscalls with the number of syscalls and pi->syscall_names
00866    with the names.  (Certain numbers may be skipped in which case the
00867    names for these numbers will be left as NULL.)  */
00868 
00869 #define MAX_SYSCALL_NAME_LENGTH 256
00870 #define MAX_SYSCALLS 65536
00871 
00872 static void
00873 load_syscalls (procinfo *pi)
00874 {
00875   char pathname[MAX_PROC_NAME_SIZE];
00876   int sysent_fd;
00877   prsysent_t header;
00878   prsyscall_t *syscalls;
00879   int i, size, maxcall;
00880   struct cleanup *cleanups;
00881 
00882   pi->num_syscalls = 0;
00883   pi->syscall_names = 0;
00884 
00885   /* Open the file descriptor for the sysent file.  */
00886   sprintf (pathname, "/proc/%d/sysent", pi->pid);
00887   sysent_fd = open_with_retry (pathname, O_RDONLY);
00888   if (sysent_fd < 0)
00889     {
00890       error (_("load_syscalls: Can't open /proc/%d/sysent"), pi->pid);
00891     }
00892   cleanups = make_cleanup_close (sysent_fd);
00893 
00894   size = sizeof header - sizeof (prsyscall_t);
00895   if (read (sysent_fd, &header, size) != size)
00896     {
00897       error (_("load_syscalls: Error reading /proc/%d/sysent"), pi->pid);
00898     }
00899 
00900   if (header.pr_nsyscalls == 0)
00901     {
00902       error (_("load_syscalls: /proc/%d/sysent contains no syscalls!"),
00903              pi->pid);
00904     }
00905 
00906   size = header.pr_nsyscalls * sizeof (prsyscall_t);
00907   syscalls = xmalloc (size);
00908   make_cleanup (free_current_contents, &syscalls);
00909 
00910   if (read (sysent_fd, syscalls, size) != size)
00911     error (_("load_syscalls: Error reading /proc/%d/sysent"), pi->pid);
00912 
00913   /* Find maximum syscall number.  This may not be the same as
00914      pr_nsyscalls since that value refers to the number of entries
00915      in the table.  (Also, the docs indicate that some system
00916      call numbers may be skipped.)  */
00917 
00918   maxcall = syscalls[0].pr_number;
00919 
00920   for (i = 1; i <  header.pr_nsyscalls; i++)
00921     if (syscalls[i].pr_number > maxcall
00922         && syscalls[i].pr_nameoff > 0
00923         && syscalls[i].pr_number < MAX_SYSCALLS)
00924       maxcall = syscalls[i].pr_number;
00925 
00926   pi->num_syscalls = maxcall+1;
00927   pi->syscall_names = xmalloc (pi->num_syscalls * sizeof (char *));
00928 
00929   for (i = 0; i < pi->num_syscalls; i++)
00930     pi->syscall_names[i] = NULL;
00931 
00932   /* Read the syscall names in.  */
00933   for (i = 0; i < header.pr_nsyscalls; i++)
00934     {
00935       char namebuf[MAX_SYSCALL_NAME_LENGTH];
00936       int nread;
00937       int callnum;
00938 
00939       if (syscalls[i].pr_number >= MAX_SYSCALLS
00940           || syscalls[i].pr_number < 0
00941           || syscalls[i].pr_nameoff <= 0
00942           || (lseek (sysent_fd, (off_t) syscalls[i].pr_nameoff, SEEK_SET)
00943                                        != (off_t) syscalls[i].pr_nameoff))
00944         continue;
00945 
00946       nread = read (sysent_fd, namebuf, sizeof namebuf);
00947       if (nread <= 0)
00948         continue;
00949 
00950       callnum = syscalls[i].pr_number;
00951 
00952       if (pi->syscall_names[callnum] != NULL)
00953         {
00954           /* FIXME: Generate warning.  */
00955           continue;
00956         }
00957 
00958       namebuf[nread-1] = '\0';
00959       size = strlen (namebuf) + 1;
00960       pi->syscall_names[callnum] = xmalloc (size);
00961       strncpy (pi->syscall_names[callnum], namebuf, size-1);
00962       pi->syscall_names[callnum][size-1] = '\0';
00963     }
00964 
00965   do_cleanups (cleanups);
00966 }
00967 
00968 /* Free the space allocated for the syscall names from the procinfo
00969    structure.  */
00970 
00971 static void
00972 free_syscalls (procinfo *pi)
00973 {
00974   if (pi->syscall_names)
00975     {
00976       int i;
00977 
00978       for (i = 0; i < pi->num_syscalls; i++)
00979         if (pi->syscall_names[i] != NULL)
00980           xfree (pi->syscall_names[i]);
00981 
00982       xfree (pi->syscall_names);
00983       pi->syscall_names = 0;
00984     }
00985 }
00986 
00987 /* Given a name, look up (and return) the corresponding syscall number.
00988    If no match is found, return -1.  */
00989 
00990 static int
00991 find_syscall (procinfo *pi, char *name)
00992 {
00993   int i;
00994 
00995   for (i = 0; i < pi->num_syscalls; i++)
00996     {
00997       if (pi->syscall_names[i] && strcmp (name, pi->syscall_names[i]) == 0)
00998         return i;
00999     }
01000   return -1;
01001 }
01002 #endif
01003 
01004 /* =================== END, STRUCT PROCINFO "MODULE" =================== */
01005 
01006 /* ===================  /proc  "MODULE" =================== */
01007 
01008 /* This "module" is the interface layer between the /proc system API
01009    and the gdb target vector functions.  This layer consists of access
01010    functions that encapsulate each of the basic operations that we
01011    need to use from the /proc API.
01012 
01013    The main motivation for this layer is to hide the fact that there
01014    are two very different implementations of the /proc API.  Rather
01015    than have a bunch of #ifdefs all thru the gdb target vector
01016    functions, we do our best to hide them all in here.  */
01017 
01018 static long proc_flags (procinfo * pi);
01019 static int proc_why (procinfo * pi);
01020 static int proc_what (procinfo * pi);
01021 static int proc_set_current_signal (procinfo * pi, int signo);
01022 static int proc_get_current_thread (procinfo * pi);
01023 static int proc_iterate_over_threads
01024   (procinfo * pi,
01025    int (*func) (procinfo *, procinfo *, void *),
01026    void *ptr);
01027 
01028 static void
01029 proc_warn (procinfo *pi, char *func, int line)
01030 {
01031   sprintf (errmsg, "procfs: %s line %d, %s", func, line, pi->pathname);
01032   print_sys_errmsg (errmsg, errno);
01033 }
01034 
01035 static void
01036 proc_error (procinfo *pi, char *func, int line)
01037 {
01038   sprintf (errmsg, "procfs: %s line %d, %s", func, line, pi->pathname);
01039   perror_with_name (errmsg);
01040 }
01041 
01042 /* Updates the status struct in the procinfo.  There is a 'valid'
01043    flag, to let other functions know when this function needs to be
01044    called (so the status is only read when it is needed).  The status
01045    file descriptor is also only opened when it is needed.  Returns
01046    non-zero for success, zero for failure.  */
01047 
01048 static int
01049 proc_get_status (procinfo *pi)
01050 {
01051   /* Status file descriptor is opened "lazily".  */
01052   if (pi->status_fd == 0 &&
01053       open_procinfo_files (pi, FD_STATUS) == 0)
01054     {
01055       pi->status_valid = 0;
01056       return 0;
01057     }
01058 
01059 #ifdef NEW_PROC_API
01060   if (lseek (pi->status_fd, 0, SEEK_SET) < 0)
01061     pi->status_valid = 0;                       /* fail */
01062   else
01063     {
01064       /* Sigh... I have to read a different data structure,
01065          depending on whether this is a main process or an LWP.  */
01066       if (pi->tid)
01067         pi->status_valid = (read (pi->status_fd,
01068                                   (char *) &pi->prstatus.pr_lwp,
01069                                   sizeof (lwpstatus_t))
01070                             == sizeof (lwpstatus_t));
01071       else
01072         {
01073           pi->status_valid = (read (pi->status_fd,
01074                                     (char *) &pi->prstatus,
01075                                     sizeof (gdb_prstatus_t))
01076                               == sizeof (gdb_prstatus_t));
01077         }
01078     }
01079 #else   /* ioctl method */
01080 #ifdef PIOCTSTATUS      /* osf */
01081   if (pi->tid == 0)     /* main process */
01082     {
01083       /* Just read the danged status.  Now isn't that simple?  */
01084       pi->status_valid =
01085         (ioctl (pi->status_fd, PIOCSTATUS, &pi->prstatus) >= 0);
01086     }
01087   else
01088     {
01089       int win;
01090       struct {
01091         long pr_count;
01092         tid_t pr_error_thread;
01093         struct prstatus status;
01094       } thread_status;
01095 
01096       thread_status.pr_count = 1;
01097       thread_status.status.pr_tid = pi->tid;
01098       win = (ioctl (pi->status_fd, PIOCTSTATUS, &thread_status) >= 0);
01099       if (win)
01100         {
01101           memcpy (&pi->prstatus, &thread_status.status,
01102                   sizeof (pi->prstatus));
01103           pi->status_valid = 1;
01104         }
01105     }
01106 #else
01107   /* Just read the danged status.  Now isn't that simple?  */
01108   pi->status_valid = (ioctl (pi->status_fd, PIOCSTATUS, &pi->prstatus) >= 0);
01109 #endif
01110 #endif
01111 
01112   if (pi->status_valid)
01113     {
01114       PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
01115                                 proc_why (pi),
01116                                 proc_what (pi),
01117                                 proc_get_current_thread (pi));
01118     }
01119 
01120   /* The status struct includes general regs, so mark them valid too.  */
01121   pi->gregs_valid  = pi->status_valid;
01122 #ifdef NEW_PROC_API
01123   /* In the read/write multiple-fd model, the status struct includes
01124      the fp regs too, so mark them valid too.  */
01125   pi->fpregs_valid = pi->status_valid;
01126 #endif
01127   return pi->status_valid;      /* True if success, false if failure.  */
01128 }
01129 
01130 /* Returns the process flags (pr_flags field).  */
01131 
01132 static long
01133 proc_flags (procinfo *pi)
01134 {
01135   if (!pi->status_valid)
01136     if (!proc_get_status (pi))
01137       return 0; /* FIXME: not a good failure value (but what is?)  */
01138 
01139 #ifdef NEW_PROC_API
01140   return pi->prstatus.pr_lwp.pr_flags;
01141 #else
01142   return pi->prstatus.pr_flags;
01143 #endif
01144 }
01145 
01146 /* Returns the pr_why field (why the process stopped).  */
01147 
01148 static int
01149 proc_why (procinfo *pi)
01150 {
01151   if (!pi->status_valid)
01152     if (!proc_get_status (pi))
01153       return 0; /* FIXME: not a good failure value (but what is?)  */
01154 
01155 #ifdef NEW_PROC_API
01156   return pi->prstatus.pr_lwp.pr_why;
01157 #else
01158   return pi->prstatus.pr_why;
01159 #endif
01160 }
01161 
01162 /* Returns the pr_what field (details of why the process stopped).  */
01163 
01164 static int
01165 proc_what (procinfo *pi)
01166 {
01167   if (!pi->status_valid)
01168     if (!proc_get_status (pi))
01169       return 0; /* FIXME: not a good failure value (but what is?)  */
01170 
01171 #ifdef NEW_PROC_API
01172   return pi->prstatus.pr_lwp.pr_what;
01173 #else
01174   return pi->prstatus.pr_what;
01175 #endif
01176 }
01177 
01178 /* This function is only called when PI is stopped by a watchpoint.
01179    Assuming the OS supports it, write to *ADDR the data address which
01180    triggered it and return 1.  Return 0 if it is not possible to know
01181    the address.  */
01182 
01183 static int
01184 proc_watchpoint_address (procinfo *pi, CORE_ADDR *addr)
01185 {
01186   if (!pi->status_valid)
01187     if (!proc_get_status (pi))
01188       return 0;
01189 
01190 #ifdef NEW_PROC_API
01191   *addr = (CORE_ADDR) gdbarch_pointer_to_address (target_gdbarch (),
01192             builtin_type (target_gdbarch ())->builtin_data_ptr,
01193             (gdb_byte *) &pi->prstatus.pr_lwp.pr_info.si_addr);
01194 #else
01195   *addr = (CORE_ADDR) gdbarch_pointer_to_address (target_gdbarch (),
01196             builtin_type (target_gdbarch ())->builtin_data_ptr,
01197             (gdb_byte *) &pi->prstatus.pr_info.si_addr);
01198 #endif
01199   return 1;
01200 }
01201 
01202 #ifndef PIOCSSPCACT     /* The following is not supported on OSF.  */
01203 
01204 /* Returns the pr_nsysarg field (number of args to the current
01205    syscall).  */
01206 
01207 static int
01208 proc_nsysarg (procinfo *pi)
01209 {
01210   if (!pi->status_valid)
01211     if (!proc_get_status (pi))
01212       return 0;
01213 
01214 #ifdef NEW_PROC_API
01215   return pi->prstatus.pr_lwp.pr_nsysarg;
01216 #else
01217   return pi->prstatus.pr_nsysarg;
01218 #endif
01219 }
01220 
01221 /* Returns the pr_sysarg field (pointer to the arguments of current
01222    syscall).  */
01223 
01224 static long *
01225 proc_sysargs (procinfo *pi)
01226 {
01227   if (!pi->status_valid)
01228     if (!proc_get_status (pi))
01229       return NULL;
01230 
01231 #ifdef NEW_PROC_API
01232   return (long *) &pi->prstatus.pr_lwp.pr_sysarg;
01233 #else
01234   return (long *) &pi->prstatus.pr_sysarg;
01235 #endif
01236 }
01237 #endif /* PIOCSSPCACT */
01238 
01239 #ifdef PROCFS_DONT_PIOCSSIG_CURSIG
01240 /* Returns the pr_cursig field (current signal).  */
01241 
01242 static long
01243 proc_cursig (struct procinfo *pi)
01244 {
01245   if (!pi->status_valid)
01246     if (!proc_get_status (pi))
01247       return 0; /* FIXME: not a good failure value (but what is?)  */
01248 
01249 #ifdef NEW_PROC_API
01250   return pi->prstatus.pr_lwp.pr_cursig;
01251 #else
01252   return pi->prstatus.pr_cursig;
01253 #endif
01254 }
01255 #endif /* PROCFS_DONT_PIOCSSIG_CURSIG */
01256 
01257 /* === I appologize for the messiness of this function.
01258    === This is an area where the different versions of
01259    === /proc are more inconsistent than usual.
01260 
01261    Set or reset any of the following process flags:
01262       PR_FORK   -- forked child will inherit trace flags
01263       PR_RLC    -- traced process runs when last /proc file closed.
01264       PR_KLC    -- traced process is killed when last /proc file closed.
01265       PR_ASYNC  -- LWP's get to run/stop independently.
01266 
01267    There are three methods for doing this function:
01268    1) Newest: read/write [PCSET/PCRESET/PCUNSET]
01269       [Sol6, Sol7, UW]
01270    2) Middle: PIOCSET/PIOCRESET
01271       [Irix, Sol5]
01272    3) Oldest: PIOCSFORK/PIOCRFORK/PIOCSRLC/PIOCRRLC
01273       [OSF, Sol5]
01274 
01275    Note: Irix does not define PR_ASYNC.
01276    Note: OSF  does not define PR_KLC.
01277    Note: OSF  is the only one that can ONLY use the oldest method.
01278 
01279    Arguments:
01280       pi   -- the procinfo
01281       flag -- one of PR_FORK, PR_RLC, or PR_ASYNC
01282       mode -- 1 for set, 0 for reset.
01283 
01284    Returns non-zero for success, zero for failure.  */
01285 
01286 enum { FLAG_RESET, FLAG_SET };
01287 
01288 static int
01289 proc_modify_flag (procinfo *pi, long flag, long mode)
01290 {
01291   long win = 0;         /* default to fail */
01292 
01293   /* These operations affect the process as a whole, and applying them
01294      to an individual LWP has the same meaning as applying them to the
01295      main process.  Therefore, if we're ever called with a pointer to
01296      an LWP's procinfo, let's substitute the process's procinfo and
01297      avoid opening the LWP's file descriptor unnecessarily.  */
01298 
01299   if (pi->pid != 0)
01300     pi = find_procinfo_or_die (pi->pid, 0);
01301 
01302 #ifdef NEW_PROC_API     /* Newest method: Newer Solarii.  */
01303   /* First normalize the PCUNSET/PCRESET command opcode
01304      (which for no obvious reason has a different definition
01305      from one operating system to the next...)  */
01306 #ifdef  PCUNSET
01307 #define GDBRESET PCUNSET
01308 #else
01309 #ifdef  PCRESET
01310 #define GDBRESET PCRESET
01311 #endif
01312 #endif
01313   {
01314     procfs_ctl_t arg[2];
01315 
01316     if (mode == FLAG_SET)       /* Set the flag (RLC, FORK, or ASYNC).  */
01317       arg[0] = PCSET;
01318     else                        /* Reset the flag.  */
01319       arg[0] = GDBRESET;
01320 
01321     arg[1] = flag;
01322     win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
01323   }
01324 #else
01325 #ifdef PIOCSET          /* Irix/Sol5 method */
01326   if (mode == FLAG_SET) /* Set the flag (hopefully RLC, FORK, or ASYNC).  */
01327     {
01328       win = (ioctl (pi->ctl_fd, PIOCSET, &flag)   >= 0);
01329     }
01330   else                  /* Reset the flag.  */
01331     {
01332       win = (ioctl (pi->ctl_fd, PIOCRESET, &flag) >= 0);
01333     }
01334 
01335 #else
01336 #ifdef PIOCSRLC         /* Oldest method: OSF */
01337   switch (flag) {
01338   case PR_RLC:
01339     if (mode == FLAG_SET)       /* Set run-on-last-close */
01340       {
01341         win = (ioctl (pi->ctl_fd, PIOCSRLC, NULL) >= 0);
01342       }
01343     else                        /* Clear run-on-last-close */
01344       {
01345         win = (ioctl (pi->ctl_fd, PIOCRRLC, NULL) >= 0);
01346       }
01347     break;
01348   case PR_FORK:
01349     if (mode == FLAG_SET)       /* Set inherit-on-fork */
01350       {
01351         win = (ioctl (pi->ctl_fd, PIOCSFORK, NULL) >= 0);
01352       }
01353     else                        /* Clear inherit-on-fork */
01354       {
01355         win = (ioctl (pi->ctl_fd, PIOCRFORK, NULL) >= 0);
01356       }
01357     break;
01358   default:
01359     win = 0;            /* Fail -- unknown flag (can't do PR_ASYNC).  */
01360     break;
01361   }
01362 #endif
01363 #endif
01364 #endif
01365 #undef GDBRESET
01366   /* The above operation renders the procinfo's cached pstatus
01367      obsolete.  */
01368   pi->status_valid = 0;
01369 
01370   if (!win)
01371     warning (_("procfs: modify_flag failed to turn %s %s"),
01372              flag == PR_FORK  ? "PR_FORK"  :
01373              flag == PR_RLC   ? "PR_RLC"   :
01374 #ifdef PR_ASYNC
01375              flag == PR_ASYNC ? "PR_ASYNC" :
01376 #endif
01377 #ifdef PR_KLC
01378              flag == PR_KLC   ? "PR_KLC"   :
01379 #endif
01380              "<unknown flag>",
01381              mode == FLAG_RESET ? "off" : "on");
01382 
01383   return win;
01384 }
01385 
01386 /* Set the run_on_last_close flag.  Process with all threads will
01387    become runnable when debugger closes all /proc fds.  Returns
01388    non-zero for success, zero for failure.  */
01389 
01390 static int
01391 proc_set_run_on_last_close (procinfo *pi)
01392 {
01393   return proc_modify_flag (pi, PR_RLC, FLAG_SET);
01394 }
01395 
01396 /* Reset the run_on_last_close flag.  The process will NOT become
01397    runnable when debugger closes its file handles.  Returns non-zero
01398    for success, zero for failure.  */
01399 
01400 static int
01401 proc_unset_run_on_last_close (procinfo *pi)
01402 {
01403   return proc_modify_flag (pi, PR_RLC, FLAG_RESET);
01404 }
01405 
01406 /* Reset inherit_on_fork flag.  If the process forks a child while we
01407    are registered for events in the parent, then we will NOT recieve
01408    events from the child.  Returns non-zero for success, zero for
01409    failure.  */
01410 
01411 static int
01412 proc_unset_inherit_on_fork (procinfo *pi)
01413 {
01414   return proc_modify_flag (pi, PR_FORK, FLAG_RESET);
01415 }
01416 
01417 #ifdef PR_ASYNC
01418 /* Set PR_ASYNC flag.  If one LWP stops because of a debug event
01419    (signal etc.), the remaining LWPs will continue to run.  Returns
01420    non-zero for success, zero for failure.  */
01421 
01422 static int
01423 proc_set_async (procinfo *pi)
01424 {
01425   return proc_modify_flag (pi, PR_ASYNC, FLAG_SET);
01426 }
01427 
01428 /* Reset PR_ASYNC flag.  If one LWP stops because of a debug event
01429    (signal etc.), then all other LWPs will stop as well.  Returns
01430    non-zero for success, zero for failure.  */
01431 
01432 static int
01433 proc_unset_async (procinfo *pi)
01434 {
01435   return proc_modify_flag (pi, PR_ASYNC, FLAG_RESET);
01436 }
01437 #endif /* PR_ASYNC */
01438 
01439 /* Request the process/LWP to stop.  Does not wait.  Returns non-zero
01440    for success, zero for failure.  */
01441 
01442 static int
01443 proc_stop_process (procinfo *pi)
01444 {
01445   int win;
01446 
01447   /* We might conceivably apply this operation to an LWP, and the
01448      LWP's ctl file descriptor might not be open.  */
01449 
01450   if (pi->ctl_fd == 0 &&
01451       open_procinfo_files (pi, FD_CTL) == 0)
01452     return 0;
01453   else
01454     {
01455 #ifdef NEW_PROC_API
01456       procfs_ctl_t cmd = PCSTOP;
01457 
01458       win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
01459 #else   /* ioctl method */
01460       win = (ioctl (pi->ctl_fd, PIOCSTOP, &pi->prstatus) >= 0);
01461       /* Note: the call also reads the prstatus.  */
01462       if (win)
01463         {
01464           pi->status_valid = 1;
01465           PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
01466                                     proc_why (pi),
01467                                     proc_what (pi),
01468                                     proc_get_current_thread (pi));
01469         }
01470 #endif
01471     }
01472 
01473   return win;
01474 }
01475 
01476 /* Wait for the process or LWP to stop (block until it does).  Returns
01477    non-zero for success, zero for failure.  */
01478 
01479 static int
01480 proc_wait_for_stop (procinfo *pi)
01481 {
01482   int win;
01483 
01484   /* We should never have to apply this operation to any procinfo
01485      except the one for the main process.  If that ever changes for
01486      any reason, then take out the following clause and replace it
01487      with one that makes sure the ctl_fd is open.  */
01488 
01489   if (pi->tid != 0)
01490     pi = find_procinfo_or_die (pi->pid, 0);
01491 
01492 #ifdef NEW_PROC_API
01493   {
01494     procfs_ctl_t cmd = PCWSTOP;
01495 
01496     win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
01497     /* We been runnin' and we stopped -- need to update status.  */
01498     pi->status_valid = 0;
01499   }
01500 #else   /* ioctl method */
01501   win = (ioctl (pi->ctl_fd, PIOCWSTOP, &pi->prstatus) >= 0);
01502   /* Above call also refreshes the prstatus.  */
01503   if (win)
01504     {
01505       pi->status_valid = 1;
01506       PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
01507                                 proc_why (pi),
01508                                 proc_what (pi),
01509                                 proc_get_current_thread (pi));
01510     }
01511 #endif
01512 
01513   return win;
01514 }
01515 
01516 /* Make the process or LWP runnable.
01517 
01518    Options (not all are implemented):
01519      - single-step
01520      - clear current fault
01521      - clear current signal
01522      - abort the current system call
01523      - stop as soon as finished with system call
01524      - (ioctl): set traced signal set
01525      - (ioctl): set held   signal set
01526      - (ioctl): set traced fault  set
01527      - (ioctl): set start pc (vaddr)
01528 
01529    Always clears the current fault.  PI is the process or LWP to
01530    operate on.  If STEP is true, set the process or LWP to trap after
01531    one instruction.  If SIGNO is zero, clear the current signal if
01532    any; if non-zero, set the current signal to this one.  Returns
01533    non-zero for success, zero for failure.  */
01534 
01535 static int
01536 proc_run_process (procinfo *pi, int step, int signo)
01537 {
01538   int win;
01539   int runflags;
01540 
01541   /* We will probably have to apply this operation to individual
01542      threads, so make sure the control file descriptor is open.  */
01543 
01544   if (pi->ctl_fd == 0 &&
01545       open_procinfo_files (pi, FD_CTL) == 0)
01546     {
01547       return 0;
01548     }
01549 
01550   runflags    = PRCFAULT;       /* Always clear current fault.  */
01551   if (step)
01552     runflags |= PRSTEP;
01553   if (signo == 0)
01554     runflags |= PRCSIG;
01555   else if (signo != -1)         /* -1 means do nothing W.R.T. signals.  */
01556     proc_set_current_signal (pi, signo);
01557 
01558 #ifdef NEW_PROC_API
01559   {
01560     procfs_ctl_t cmd[2];
01561 
01562     cmd[0]  = PCRUN;
01563     cmd[1]  = runflags;
01564     win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
01565   }
01566 #else   /* ioctl method */
01567   {
01568     prrun_t prrun;
01569 
01570     memset (&prrun, 0, sizeof (prrun));
01571     prrun.pr_flags  = runflags;
01572     win = (ioctl (pi->ctl_fd, PIOCRUN, &prrun) >= 0);
01573   }
01574 #endif
01575 
01576   return win;
01577 }
01578 
01579 /* Register to trace signals in the process or LWP.  Returns non-zero
01580    for success, zero for failure.  */
01581 
01582 static int
01583 proc_set_traced_signals (procinfo *pi, gdb_sigset_t *sigset)
01584 {
01585   int win;
01586 
01587   /* We should never have to apply this operation to any procinfo
01588      except the one for the main process.  If that ever changes for
01589      any reason, then take out the following clause and replace it
01590      with one that makes sure the ctl_fd is open.  */
01591 
01592   if (pi->tid != 0)
01593     pi = find_procinfo_or_die (pi->pid, 0);
01594 
01595 #ifdef NEW_PROC_API
01596   {
01597     struct {
01598       procfs_ctl_t cmd;
01599       /* Use char array to avoid alignment issues.  */
01600       char sigset[sizeof (gdb_sigset_t)];
01601     } arg;
01602 
01603     arg.cmd = PCSTRACE;
01604     memcpy (&arg.sigset, sigset, sizeof (gdb_sigset_t));
01605 
01606     win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
01607   }
01608 #else   /* ioctl method */
01609   win = (ioctl (pi->ctl_fd, PIOCSTRACE, sigset) >= 0);
01610 #endif
01611   /* The above operation renders the procinfo's cached pstatus obsolete.  */
01612   pi->status_valid = 0;
01613 
01614   if (!win)
01615     warning (_("procfs: set_traced_signals failed"));
01616   return win;
01617 }
01618 
01619 /* Register to trace hardware faults in the process or LWP.  Returns
01620    non-zero for success, zero for failure.  */
01621 
01622 static int
01623 proc_set_traced_faults (procinfo *pi, fltset_t *fltset)
01624 {
01625   int win;
01626 
01627   /* We should never have to apply this operation to any procinfo
01628      except the one for the main process.  If that ever changes for
01629      any reason, then take out the following clause and replace it
01630      with one that makes sure the ctl_fd is open.  */
01631 
01632   if (pi->tid != 0)
01633     pi = find_procinfo_or_die (pi->pid, 0);
01634 
01635 #ifdef NEW_PROC_API
01636   {
01637     struct {
01638       procfs_ctl_t cmd;
01639       /* Use char array to avoid alignment issues.  */
01640       char fltset[sizeof (fltset_t)];
01641     } arg;
01642 
01643     arg.cmd = PCSFAULT;
01644     memcpy (&arg.fltset, fltset, sizeof (fltset_t));
01645 
01646     win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
01647   }
01648 #else   /* ioctl method */
01649   win = (ioctl (pi->ctl_fd, PIOCSFAULT, fltset) >= 0);
01650 #endif
01651   /* The above operation renders the procinfo's cached pstatus obsolete.  */
01652   pi->status_valid = 0;
01653 
01654   return win;
01655 }
01656 
01657 /* Register to trace entry to system calls in the process or LWP.
01658    Returns non-zero for success, zero for failure.  */
01659 
01660 static int
01661 proc_set_traced_sysentry (procinfo *pi, sysset_t *sysset)
01662 {
01663   int win;
01664 
01665   /* We should never have to apply this operation to any procinfo
01666      except the one for the main process.  If that ever changes for
01667      any reason, then take out the following clause and replace it
01668      with one that makes sure the ctl_fd is open.  */
01669 
01670   if (pi->tid != 0)
01671     pi = find_procinfo_or_die (pi->pid, 0);
01672 
01673 #ifdef NEW_PROC_API
01674   {
01675     struct gdb_proc_ctl_pcsentry {
01676       procfs_ctl_t cmd;
01677       /* Use char array to avoid alignment issues.  */
01678       char sysset[sizeof (sysset_t)];
01679     } *argp;
01680     int argp_size = sizeof (struct gdb_proc_ctl_pcsentry)
01681                   - sizeof (sysset_t)
01682                   + sysset_t_size (pi);
01683 
01684     argp = xmalloc (argp_size);
01685 
01686     argp->cmd = PCSENTRY;
01687     memcpy (&argp->sysset, sysset, sysset_t_size (pi));
01688 
01689     win = (write (pi->ctl_fd, (char *) argp, argp_size) == argp_size);
01690     xfree (argp);
01691   }
01692 #else   /* ioctl method */
01693   win = (ioctl (pi->ctl_fd, PIOCSENTRY, sysset) >= 0);
01694 #endif
01695   /* The above operation renders the procinfo's cached pstatus
01696      obsolete.  */
01697   pi->status_valid = 0;
01698 
01699   return win;
01700 }
01701 
01702 /* Register to trace exit from system calls in the process or LWP.
01703    Returns non-zero for success, zero for failure.  */
01704 
01705 static int
01706 proc_set_traced_sysexit (procinfo *pi, sysset_t *sysset)
01707 {
01708   int win;
01709 
01710   /* We should never have to apply this operation to any procinfo
01711      except the one for the main process.  If that ever changes for
01712      any reason, then take out the following clause and replace it
01713      with one that makes sure the ctl_fd is open.  */
01714 
01715   if (pi->tid != 0)
01716     pi = find_procinfo_or_die (pi->pid, 0);
01717 
01718 #ifdef NEW_PROC_API
01719   {
01720     struct gdb_proc_ctl_pcsexit {
01721       procfs_ctl_t cmd;
01722       /* Use char array to avoid alignment issues.  */
01723       char sysset[sizeof (sysset_t)];
01724     } *argp;
01725     int argp_size = sizeof (struct gdb_proc_ctl_pcsexit)
01726                   - sizeof (sysset_t)
01727                   + sysset_t_size (pi);
01728 
01729     argp = xmalloc (argp_size);
01730 
01731     argp->cmd = PCSEXIT;
01732     memcpy (&argp->sysset, sysset, sysset_t_size (pi));
01733 
01734     win = (write (pi->ctl_fd, (char *) argp, argp_size) == argp_size);
01735     xfree (argp);
01736   }
01737 #else   /* ioctl method */
01738   win = (ioctl (pi->ctl_fd, PIOCSEXIT, sysset) >= 0);
01739 #endif
01740   /* The above operation renders the procinfo's cached pstatus
01741      obsolete.  */
01742   pi->status_valid = 0;
01743 
01744   return win;
01745 }
01746 
01747 /* Specify the set of blocked / held signals in the process or LWP.
01748    Returns non-zero for success, zero for failure.  */
01749 
01750 static int
01751 proc_set_held_signals (procinfo *pi, gdb_sigset_t *sighold)
01752 {
01753   int win;
01754 
01755   /* We should never have to apply this operation to any procinfo
01756      except the one for the main process.  If that ever changes for
01757      any reason, then take out the following clause and replace it
01758      with one that makes sure the ctl_fd is open.  */
01759 
01760   if (pi->tid != 0)
01761     pi = find_procinfo_or_die (pi->pid, 0);
01762 
01763 #ifdef NEW_PROC_API
01764   {
01765     struct {
01766       procfs_ctl_t cmd;
01767       /* Use char array to avoid alignment issues.  */
01768       char hold[sizeof (gdb_sigset_t)];
01769     } arg;
01770 
01771     arg.cmd  = PCSHOLD;
01772     memcpy (&arg.hold, sighold, sizeof (gdb_sigset_t));
01773     win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
01774   }
01775 #else
01776   win = (ioctl (pi->ctl_fd, PIOCSHOLD, sighold) >= 0);
01777 #endif
01778   /* The above operation renders the procinfo's cached pstatus
01779      obsolete.  */
01780   pi->status_valid = 0;
01781 
01782   return win;
01783 }
01784 
01785 /* Returns the set of signals that are held / blocked.  Will also copy
01786    the sigset if SAVE is non-zero.  */
01787 
01788 static gdb_sigset_t *
01789 proc_get_held_signals (procinfo *pi, gdb_sigset_t *save)
01790 {
01791   gdb_sigset_t *ret = NULL;
01792 
01793   /* We should never have to apply this operation to any procinfo
01794      except the one for the main process.  If that ever changes for
01795      any reason, then take out the following clause and replace it
01796      with one that makes sure the ctl_fd is open.  */
01797 
01798   if (pi->tid != 0)
01799     pi = find_procinfo_or_die (pi->pid, 0);
01800 
01801 #ifdef NEW_PROC_API
01802   if (!pi->status_valid)
01803     if (!proc_get_status (pi))
01804       return NULL;
01805 
01806   ret = &pi->prstatus.pr_lwp.pr_lwphold;
01807 #else  /* not NEW_PROC_API */
01808   {
01809     static gdb_sigset_t sigheld;
01810 
01811     if (ioctl (pi->ctl_fd, PIOCGHOLD, &sigheld) >= 0)
01812       ret = &sigheld;
01813   }
01814 #endif /* NEW_PROC_API */
01815   if (save && ret)
01816     memcpy (save, ret, sizeof (gdb_sigset_t));
01817 
01818   return ret;
01819 }
01820 
01821 /* Returns the set of signals that are traced / debugged.  Will also
01822    copy the sigset if SAVE is non-zero.  */
01823 
01824 static gdb_sigset_t *
01825 proc_get_traced_signals (procinfo *pi, gdb_sigset_t *save)
01826 {
01827   gdb_sigset_t *ret = NULL;
01828 
01829   /* We should never have to apply this operation to any procinfo
01830      except the one for the main process.  If that ever changes for
01831      any reason, then take out the following clause and replace it
01832      with one that makes sure the ctl_fd is open.  */
01833 
01834   if (pi->tid != 0)
01835     pi = find_procinfo_or_die (pi->pid, 0);
01836 
01837 #ifdef NEW_PROC_API
01838   if (!pi->status_valid)
01839     if (!proc_get_status (pi))
01840       return NULL;
01841 
01842   ret = &pi->prstatus.pr_sigtrace;
01843 #else
01844   {
01845     static gdb_sigset_t sigtrace;
01846 
01847     if (ioctl (pi->ctl_fd, PIOCGTRACE, &sigtrace) >= 0)
01848       ret = &sigtrace;
01849   }
01850 #endif
01851   if (save && ret)
01852     memcpy (save, ret, sizeof (gdb_sigset_t));
01853 
01854   return ret;
01855 }
01856 
01857 /* Returns the set of hardware faults that are traced /debugged.  Will
01858    also copy the faultset if SAVE is non-zero.  */
01859 
01860 static fltset_t *
01861 proc_get_traced_faults (procinfo *pi, fltset_t *save)
01862 {
01863   fltset_t *ret = NULL;
01864 
01865   /* We should never have to apply this operation to any procinfo
01866      except the one for the main process.  If that ever changes for
01867      any reason, then take out the following clause and replace it
01868      with one that makes sure the ctl_fd is open.  */
01869 
01870   if (pi->tid != 0)
01871     pi = find_procinfo_or_die (pi->pid, 0);
01872 
01873 #ifdef NEW_PROC_API
01874   if (!pi->status_valid)
01875     if (!proc_get_status (pi))
01876       return NULL;
01877 
01878   ret = &pi->prstatus.pr_flttrace;
01879 #else
01880   {
01881     static fltset_t flttrace;
01882 
01883     if (ioctl (pi->ctl_fd, PIOCGFAULT, &flttrace) >= 0)
01884       ret = &flttrace;
01885   }
01886 #endif
01887   if (save && ret)
01888     memcpy (save, ret, sizeof (fltset_t));
01889 
01890   return ret;
01891 }
01892 
01893 /* Returns the set of syscalls that are traced /debugged on entry.
01894    Will also copy the syscall set if SAVE is non-zero.  */
01895 
01896 static sysset_t *
01897 proc_get_traced_sysentry (procinfo *pi, sysset_t *save)
01898 {
01899   sysset_t *ret = NULL;
01900 
01901   /* We should never have to apply this operation to any procinfo
01902      except the one for the main process.  If that ever changes for
01903      any reason, then take out the following clause and replace it
01904      with one that makes sure the ctl_fd is open.  */
01905 
01906   if (pi->tid != 0)
01907     pi = find_procinfo_or_die (pi->pid, 0);
01908 
01909 #ifdef NEW_PROC_API
01910   if (!pi->status_valid)
01911     if (!proc_get_status (pi))
01912       return NULL;
01913 
01914 #ifndef DYNAMIC_SYSCALLS
01915   ret = &pi->prstatus.pr_sysentry;
01916 #else /* DYNAMIC_SYSCALLS */
01917   {
01918     static sysset_t *sysentry;
01919     size_t size;
01920 
01921     if (!sysentry)
01922       sysentry = sysset_t_alloc (pi);
01923     ret = sysentry;
01924     if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
01925       return NULL;
01926     if (pi->prstatus.pr_sysentry_offset == 0)
01927       {
01928         gdb_premptysysset (sysentry);
01929       }
01930     else
01931       {
01932         int rsize;
01933 
01934         if (lseek (pi->status_fd, (off_t) pi->prstatus.pr_sysentry_offset,
01935                    SEEK_SET)
01936             != (off_t) pi->prstatus.pr_sysentry_offset)
01937           return NULL;
01938         size = sysset_t_size (pi);
01939         gdb_premptysysset (sysentry);
01940         rsize = read (pi->status_fd, sysentry, size);
01941         if (rsize < 0)
01942           return NULL;
01943       }
01944   }
01945 #endif /* DYNAMIC_SYSCALLS */
01946 #else /* !NEW_PROC_API */
01947   {
01948     static sysset_t sysentry;
01949 
01950     if (ioctl (pi->ctl_fd, PIOCGENTRY, &sysentry) >= 0)
01951       ret = &sysentry;
01952   }
01953 #endif /* NEW_PROC_API */
01954   if (save && ret)
01955     memcpy (save, ret, sysset_t_size (pi));
01956 
01957   return ret;
01958 }
01959 
01960 /* Returns the set of syscalls that are traced /debugged on exit.
01961    Will also copy the syscall set if SAVE is non-zero.  */
01962 
01963 static sysset_t *
01964 proc_get_traced_sysexit (procinfo *pi, sysset_t *save)
01965 {
01966   sysset_t * ret = NULL;
01967 
01968   /* We should never have to apply this operation to any procinfo
01969      except the one for the main process.  If that ever changes for
01970      any reason, then take out the following clause and replace it
01971      with one that makes sure the ctl_fd is open.  */
01972 
01973   if (pi->tid != 0)
01974     pi = find_procinfo_or_die (pi->pid, 0);
01975 
01976 #ifdef NEW_PROC_API
01977   if (!pi->status_valid)
01978     if (!proc_get_status (pi))
01979       return NULL;
01980 
01981 #ifndef DYNAMIC_SYSCALLS
01982   ret = &pi->prstatus.pr_sysexit;
01983 #else /* DYNAMIC_SYSCALLS */
01984   {
01985     static sysset_t *sysexit;
01986     size_t size;
01987 
01988     if (!sysexit)
01989       sysexit = sysset_t_alloc (pi);
01990     ret = sysexit;
01991     if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
01992       return NULL;
01993     if (pi->prstatus.pr_sysexit_offset == 0)
01994       {
01995         gdb_premptysysset (sysexit);
01996       }
01997     else
01998       {
01999         int rsize;
02000 
02001         if (lseek (pi->status_fd, (off_t) pi->prstatus.pr_sysexit_offset,
02002                    SEEK_SET)
02003             != (off_t) pi->prstatus.pr_sysexit_offset)
02004           return NULL;
02005         size = sysset_t_size (pi);
02006         gdb_premptysysset (sysexit);
02007         rsize = read (pi->status_fd, sysexit, size);
02008         if (rsize < 0)
02009           return NULL;
02010       }
02011   }
02012 #endif /* DYNAMIC_SYSCALLS */
02013 #else
02014   {
02015     static sysset_t sysexit;
02016 
02017     if (ioctl (pi->ctl_fd, PIOCGEXIT, &sysexit) >= 0)
02018       ret = &sysexit;
02019   }
02020 #endif
02021   if (save && ret)
02022     memcpy (save, ret, sysset_t_size (pi));
02023 
02024   return ret;
02025 }
02026 
02027 /* The current fault (if any) is cleared; the associated signal will
02028    not be sent to the process or LWP when it resumes.  Returns
02029    non-zero for success, zero for failure.  */
02030 
02031 static int
02032 proc_clear_current_fault (procinfo *pi)
02033 {
02034   int win;
02035 
02036   /* We should never have to apply this operation to any procinfo
02037      except the one for the main process.  If that ever changes for
02038      any reason, then take out the following clause and replace it
02039      with one that makes sure the ctl_fd is open.  */
02040 
02041   if (pi->tid != 0)
02042     pi = find_procinfo_or_die (pi->pid, 0);
02043 
02044 #ifdef NEW_PROC_API
02045   {
02046     procfs_ctl_t cmd = PCCFAULT;
02047 
02048     win = (write (pi->ctl_fd, (void *) &cmd, sizeof (cmd)) == sizeof (cmd));
02049   }
02050 #else
02051   win = (ioctl (pi->ctl_fd, PIOCCFAULT, 0) >= 0);
02052 #endif
02053 
02054   return win;
02055 }
02056 
02057 /* Set the "current signal" that will be delivered next to the
02058    process.  NOTE: semantics are different from those of KILL.  This
02059    signal will be delivered to the process or LWP immediately when it
02060    is resumed (even if the signal is held/blocked); it will NOT
02061    immediately cause another event of interest, and will NOT first
02062    trap back to the debugger.  Returns non-zero for success, zero for
02063    failure.  */
02064 
02065 static int
02066 proc_set_current_signal (procinfo *pi, int signo)
02067 {
02068   int win;
02069   struct {
02070     procfs_ctl_t cmd;
02071     /* Use char array to avoid alignment issues.  */
02072     char sinfo[sizeof (gdb_siginfo_t)];
02073   } arg;
02074   gdb_siginfo_t mysinfo;
02075   ptid_t wait_ptid;
02076   struct target_waitstatus wait_status;
02077 
02078   /* We should never have to apply this operation to any procinfo
02079      except the one for the main process.  If that ever changes for
02080      any reason, then take out the following clause and replace it
02081      with one that makes sure the ctl_fd is open.  */
02082 
02083   if (pi->tid != 0)
02084     pi = find_procinfo_or_die (pi->pid, 0);
02085 
02086 #ifdef PROCFS_DONT_PIOCSSIG_CURSIG
02087   /* With Alpha OSF/1 procfs, the kernel gets really confused if it
02088      receives a PIOCSSIG with a signal identical to the current
02089      signal, it messes up the current signal.  Work around the kernel
02090      bug.  */
02091   if (signo > 0 &&
02092       signo == proc_cursig (pi))
02093     return 1;           /* I assume this is a success?  */
02094 #endif
02095 
02096   /* The pointer is just a type alias.  */
02097   get_last_target_status (&wait_ptid, &wait_status);
02098   if (ptid_equal (wait_ptid, inferior_ptid)
02099       && wait_status.kind == TARGET_WAITKIND_STOPPED
02100       && wait_status.value.sig == gdb_signal_from_host (signo)
02101       && proc_get_status (pi)
02102 #ifdef NEW_PROC_API
02103       && pi->prstatus.pr_lwp.pr_info.si_signo == signo
02104 #else
02105       && pi->prstatus.pr_info.si_signo == signo
02106 #endif
02107       )
02108     /* Use the siginfo associated with the signal being
02109        redelivered.  */
02110 #ifdef NEW_PROC_API
02111     memcpy (arg.sinfo, &pi->prstatus.pr_lwp.pr_info, sizeof (gdb_siginfo_t));
02112 #else
02113     memcpy (arg.sinfo, &pi->prstatus.pr_info, sizeof (gdb_siginfo_t));
02114 #endif
02115   else
02116     {
02117       mysinfo.si_signo = signo;
02118       mysinfo.si_code  = 0;
02119       mysinfo.si_pid   = getpid ();       /* ?why? */
02120       mysinfo.si_uid   = getuid ();       /* ?why? */
02121       memcpy (arg.sinfo, &mysinfo, sizeof (gdb_siginfo_t));
02122     }
02123 
02124 #ifdef NEW_PROC_API
02125   arg.cmd = PCSSIG;
02126   win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg))  == sizeof (arg));
02127 #else
02128   win = (ioctl (pi->ctl_fd, PIOCSSIG, (void *) &arg.sinfo) >= 0);
02129 #endif
02130 
02131   return win;
02132 }
02133 
02134 /* The current signal (if any) is cleared, and is not sent to the
02135    process or LWP when it resumes.  Returns non-zero for success, zero
02136    for failure.  */
02137 
02138 static int
02139 proc_clear_current_signal (procinfo *pi)
02140 {
02141   int win;
02142 
02143   /* We should never have to apply this operation to any procinfo
02144      except the one for the main process.  If that ever changes for
02145      any reason, then take out the following clause and replace it
02146      with one that makes sure the ctl_fd is open.  */
02147 
02148   if (pi->tid != 0)
02149     pi = find_procinfo_or_die (pi->pid, 0);
02150 
02151 #ifdef NEW_PROC_API
02152   {
02153     struct {
02154       procfs_ctl_t cmd;
02155       /* Use char array to avoid alignment issues.  */
02156       char sinfo[sizeof (gdb_siginfo_t)];
02157     } arg;
02158     gdb_siginfo_t mysinfo;
02159 
02160     arg.cmd = PCSSIG;
02161     /* The pointer is just a type alias.  */
02162     mysinfo.si_signo = 0;
02163     mysinfo.si_code  = 0;
02164     mysinfo.si_errno = 0;
02165     mysinfo.si_pid   = getpid ();       /* ?why? */
02166     mysinfo.si_uid   = getuid ();       /* ?why? */
02167     memcpy (arg.sinfo, &mysinfo, sizeof (gdb_siginfo_t));
02168 
02169     win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
02170   }
02171 #else
02172   win = (ioctl (pi->ctl_fd, PIOCSSIG, 0) >= 0);
02173 #endif
02174 
02175   return win;
02176 }
02177 
02178 /* Return the general-purpose registers for the process or LWP
02179    corresponding to PI.  Upon failure, return NULL.  */
02180 
02181 static gdb_gregset_t *
02182 proc_get_gregs (procinfo *pi)
02183 {
02184   if (!pi->status_valid || !pi->gregs_valid)
02185     if (!proc_get_status (pi))
02186       return NULL;
02187 
02188 #ifdef NEW_PROC_API
02189   return &pi->prstatus.pr_lwp.pr_reg;
02190 #else
02191   return &pi->prstatus.pr_reg;
02192 #endif
02193 }
02194 
02195 /* Return the general-purpose registers for the process or LWP
02196    corresponding to PI.  Upon failure, return NULL.  */
02197 
02198 static gdb_fpregset_t *
02199 proc_get_fpregs (procinfo *pi)
02200 {
02201 #ifdef NEW_PROC_API
02202   if (!pi->status_valid || !pi->fpregs_valid)
02203     if (!proc_get_status (pi))
02204       return NULL;
02205 
02206   return &pi->prstatus.pr_lwp.pr_fpreg;
02207 
02208 #else  /* not NEW_PROC_API */
02209   if (pi->fpregs_valid)
02210     return &pi->fpregset;       /* Already got 'em.  */
02211   else
02212     {
02213       if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
02214         {
02215           return NULL;
02216         }
02217       else
02218         {
02219 # ifdef PIOCTGFPREG
02220           struct {
02221             long pr_count;
02222             tid_t pr_error_thread;
02223             tfpregset_t thread_1;
02224           } thread_fpregs;
02225 
02226           thread_fpregs.pr_count = 1;
02227           thread_fpregs.thread_1.tid = pi->tid;
02228 
02229           if (pi->tid == 0
02230               && ioctl (pi->ctl_fd, PIOCGFPREG, &pi->fpregset) >= 0)
02231             {
02232               pi->fpregs_valid = 1;
02233               return &pi->fpregset; /* Got 'em now!  */
02234             }
02235           else if (pi->tid != 0
02236                    && ioctl (pi->ctl_fd, PIOCTGFPREG, &thread_fpregs) >= 0)
02237             {
02238               memcpy (&pi->fpregset, &thread_fpregs.thread_1.pr_fpregs,
02239                       sizeof (pi->fpregset));
02240               pi->fpregs_valid = 1;
02241               return &pi->fpregset; /* Got 'em now!  */
02242             }
02243           else
02244             {
02245               return NULL;
02246             }
02247 # else
02248           if (ioctl (pi->ctl_fd, PIOCGFPREG, &pi->fpregset) >= 0)
02249             {
02250               pi->fpregs_valid = 1;
02251               return &pi->fpregset; /* Got 'em now!  */
02252             }
02253           else
02254             {
02255               return NULL;
02256             }
02257 # endif
02258         }
02259     }
02260 #endif /* NEW_PROC_API */
02261 }
02262 
02263 /* Write the general-purpose registers back to the process or LWP
02264    corresponding to PI.  Return non-zero for success, zero for
02265    failure.  */
02266 
02267 static int
02268 proc_set_gregs (procinfo *pi)
02269 {
02270   gdb_gregset_t *gregs;
02271   int win;
02272 
02273   gregs = proc_get_gregs (pi);
02274   if (gregs == NULL)
02275     return 0;                   /* proc_get_regs has already warned.  */
02276 
02277   if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
02278     {
02279       return 0;
02280     }
02281   else
02282     {
02283 #ifdef NEW_PROC_API
02284       struct {
02285         procfs_ctl_t cmd;
02286         /* Use char array to avoid alignment issues.  */
02287         char gregs[sizeof (gdb_gregset_t)];
02288       } arg;
02289 
02290       arg.cmd = PCSREG;
02291       memcpy (&arg.gregs, gregs, sizeof (arg.gregs));
02292       win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
02293 #else
02294       win = (ioctl (pi->ctl_fd, PIOCSREG, gregs) >= 0);
02295 #endif
02296     }
02297 
02298   /* Policy: writing the registers invalidates our cache.  */
02299   pi->gregs_valid = 0;
02300   return win;
02301 }
02302 
02303 /* Write the floating-pointer registers back to the process or LWP
02304    corresponding to PI.  Return non-zero for success, zero for
02305    failure.  */
02306 
02307 static int
02308 proc_set_fpregs (procinfo *pi)
02309 {
02310   gdb_fpregset_t *fpregs;
02311   int win;
02312 
02313   fpregs = proc_get_fpregs (pi);
02314   if (fpregs == NULL)
02315     return 0;                   /* proc_get_fpregs has already warned.  */
02316 
02317   if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
02318     {
02319       return 0;
02320     }
02321   else
02322     {
02323 #ifdef NEW_PROC_API
02324       struct {
02325         procfs_ctl_t cmd;
02326         /* Use char array to avoid alignment issues.  */
02327         char fpregs[sizeof (gdb_fpregset_t)];
02328       } arg;
02329 
02330       arg.cmd = PCSFPREG;
02331       memcpy (&arg.fpregs, fpregs, sizeof (arg.fpregs));
02332       win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
02333 #else
02334 # ifdef PIOCTSFPREG
02335       if (pi->tid == 0)
02336         win = (ioctl (pi->ctl_fd, PIOCSFPREG, fpregs) >= 0);
02337       else
02338         {
02339           struct {
02340             long pr_count;
02341             tid_t pr_error_thread;
02342             tfpregset_t thread_1;
02343           } thread_fpregs;
02344 
02345           thread_fpregs.pr_count = 1;
02346           thread_fpregs.thread_1.tid = pi->tid;
02347           memcpy (&thread_fpregs.thread_1.pr_fpregs, fpregs,
02348                   sizeof (*fpregs));
02349           win = (ioctl (pi->ctl_fd, PIOCTSFPREG, &thread_fpregs) >= 0);
02350         }
02351 # else
02352       win = (ioctl (pi->ctl_fd, PIOCSFPREG, fpregs) >= 0);
02353 # endif
02354 #endif /* NEW_PROC_API */
02355     }
02356 
02357   /* Policy: writing the registers invalidates our cache.  */
02358   pi->fpregs_valid = 0;
02359   return win;
02360 }
02361 
02362 /* Send a signal to the proc or lwp with the semantics of "kill()".
02363    Returns non-zero for success, zero for failure.  */
02364 
02365 static int
02366 proc_kill (procinfo *pi, int signo)
02367 {
02368   int win;
02369 
02370   /* We might conceivably apply this operation to an LWP, and the
02371      LWP's ctl file descriptor might not be open.  */
02372 
02373   if (pi->ctl_fd == 0 &&
02374       open_procinfo_files (pi, FD_CTL) == 0)
02375     {
02376       return 0;
02377     }
02378   else
02379     {
02380 #ifdef NEW_PROC_API
02381       procfs_ctl_t cmd[2];
02382 
02383       cmd[0] = PCKILL;
02384       cmd[1] = signo;
02385       win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
02386 #else   /* ioctl method */
02387       /* FIXME: do I need the Alpha OSF fixups present in
02388          procfs.c/unconditionally_kill_inferior?  Perhaps only for SIGKILL?  */
02389       win = (ioctl (pi->ctl_fd, PIOCKILL, &signo) >= 0);
02390 #endif
02391   }
02392 
02393   return win;
02394 }
02395 
02396 /* Find the pid of the process that started this one.  Returns the
02397    parent process pid, or zero.  */
02398 
02399 static int
02400 proc_parent_pid (procinfo *pi)
02401 {
02402   /* We should never have to apply this operation to any procinfo
02403      except the one for the main process.  If that ever changes for
02404      any reason, then take out the following clause and replace it
02405      with one that makes sure the ctl_fd is open.  */
02406 
02407   if (pi->tid != 0)
02408     pi = find_procinfo_or_die (pi->pid, 0);
02409 
02410   if (!pi->status_valid)
02411     if (!proc_get_status (pi))
02412       return 0;
02413 
02414   return pi->prstatus.pr_ppid;
02415 }
02416 
02417 /* Convert a target address (a.k.a. CORE_ADDR) into a host address
02418    (a.k.a void pointer)!  */
02419 
02420 #if (defined (PCWATCH) || defined (PIOCSWATCH)) \
02421     && !(defined (PIOCOPENLWP))
02422 static void *
02423 procfs_address_to_host_pointer (CORE_ADDR addr)
02424 {
02425   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
02426   void *ptr;
02427 
02428   gdb_assert (sizeof (ptr) == TYPE_LENGTH (ptr_type));
02429   gdbarch_address_to_pointer (target_gdbarch (), ptr_type,
02430                               (gdb_byte *) &ptr, addr);
02431   return ptr;
02432 }
02433 #endif
02434 
02435 static int
02436 proc_set_watchpoint (procinfo *pi, CORE_ADDR addr, int len, int wflags)
02437 {
02438 #if !defined (PCWATCH) && !defined (PIOCSWATCH)
02439   /* If neither or these is defined, we can't support watchpoints.
02440      This just avoids possibly failing to compile the below on such
02441      systems.  */
02442   return 0;
02443 #else
02444 /* Horrible hack!  Detect Solaris 2.5, because this doesn't work on 2.5.  */
02445 #if defined (PIOCOPENLWP)       /* Solaris 2.5: bail out.  */
02446   return 0;
02447 #else
02448   struct {
02449     procfs_ctl_t cmd;
02450     char watch[sizeof (prwatch_t)];
02451   } arg;
02452   prwatch_t pwatch;
02453 
02454   /* NOTE: cagney/2003-02-01: Even more horrible hack.  Need to
02455      convert a target address into something that can be stored in a
02456      native data structure.  */
02457 #ifdef PCAGENT  /* Horrible hack: only defined on Solaris 2.6+ */
02458   pwatch.pr_vaddr  = (uintptr_t) procfs_address_to_host_pointer (addr);
02459 #else
02460   pwatch.pr_vaddr  = (caddr_t) procfs_address_to_host_pointer (addr);
02461 #endif
02462   pwatch.pr_size   = len;
02463   pwatch.pr_wflags = wflags;
02464 #if defined(NEW_PROC_API) && defined (PCWATCH)
02465   arg.cmd = PCWATCH;
02466   memcpy (arg.watch, &pwatch, sizeof (prwatch_t));
02467   return (write (pi->ctl_fd, &arg, sizeof (arg)) == sizeof (arg));
02468 #else
02469 #if defined (PIOCSWATCH)
02470   return (ioctl (pi->ctl_fd, PIOCSWATCH, &pwatch) >= 0);
02471 #else
02472   return 0;     /* Fail */
02473 #endif
02474 #endif
02475 #endif
02476 #endif
02477 }
02478 
02479 #if (defined(__i386__) || defined(__x86_64__)) && defined (sun)
02480 
02481 #include <sys/sysi86.h>
02482 
02483 /* The KEY is actually the value of the lower 16 bits of the GS
02484    register for the LWP that we're interested in.  Returns the
02485    matching ssh struct (LDT entry).  */
02486 
02487 static struct ssd *
02488 proc_get_LDT_entry (procinfo *pi, int key)
02489 {
02490   static struct ssd *ldt_entry = NULL;
02491 #ifdef NEW_PROC_API
02492   char pathname[MAX_PROC_NAME_SIZE];
02493   struct cleanup *old_chain = NULL;
02494   int  fd;
02495 
02496   /* Allocate space for one LDT entry.
02497      This alloc must persist, because we return a pointer to it.  */
02498   if (ldt_entry == NULL)
02499     ldt_entry = (struct ssd *) xmalloc (sizeof (struct ssd));
02500 
02501   /* Open the file descriptor for the LDT table.  */
02502   sprintf (pathname, "/proc/%d/ldt", pi->pid);
02503   if ((fd = open_with_retry (pathname, O_RDONLY)) < 0)
02504     {
02505       proc_warn (pi, "proc_get_LDT_entry (open)", __LINE__);
02506       return NULL;
02507     }
02508   /* Make sure it gets closed again!  */
02509   old_chain = make_cleanup_close (fd);
02510 
02511   /* Now 'read' thru the table, find a match and return it.  */
02512   while (read (fd, ldt_entry, sizeof (struct ssd)) == sizeof (struct ssd))
02513     {
02514       if (ldt_entry->sel == 0 &&
02515           ldt_entry->bo  == 0 &&
02516           ldt_entry->acc1 == 0 &&
02517           ldt_entry->acc2 == 0)
02518         break;  /* end of table */
02519       /* If key matches, return this entry.  */
02520       if (ldt_entry->sel == key)
02521         return ldt_entry;
02522     }
02523   /* Loop ended, match not found.  */
02524   return NULL;
02525 #else
02526   int nldt, i;
02527   static int nalloc = 0;
02528 
02529   /* Get the number of LDT entries.  */
02530   if (ioctl (pi->ctl_fd, PIOCNLDT, &nldt) < 0)
02531     {
02532       proc_warn (pi, "proc_get_LDT_entry (PIOCNLDT)", __LINE__);
02533       return NULL;
02534     }
02535 
02536   /* Allocate space for the number of LDT entries.  */
02537   /* This alloc has to persist, 'cause we return a pointer to it.  */
02538   if (nldt > nalloc)
02539     {
02540       ldt_entry = (struct ssd *)
02541         xrealloc (ldt_entry, (nldt + 1) * sizeof (struct ssd));
02542       nalloc = nldt;
02543     }
02544 
02545   /* Read the whole table in one gulp.  */
02546   if (ioctl (pi->ctl_fd, PIOCLDT, ldt_entry) < 0)
02547     {
02548       proc_warn (pi, "proc_get_LDT_entry (PIOCLDT)", __LINE__);
02549       return NULL;
02550     }
02551 
02552   /* Search the table and return the (first) entry matching 'key'.  */
02553   for (i = 0; i < nldt; i++)
02554     if (ldt_entry[i].sel == key)
02555       return &ldt_entry[i];
02556 
02557   /* Loop ended, match not found.  */
02558   return NULL;
02559 #endif
02560 }
02561 
02562 /* Returns the pointer to the LDT entry of PTID.  */
02563 
02564 struct ssd *
02565 procfs_find_LDT_entry (ptid_t ptid)
02566 {
02567   gdb_gregset_t *gregs;
02568   int            key;
02569   procinfo      *pi;
02570 
02571   /* Find procinfo for the lwp.  */
02572   if ((pi = find_procinfo (ptid_get_pid (ptid), ptid_get_lwp (ptid))) == NULL)
02573     {
02574       warning (_("procfs_find_LDT_entry: could not find procinfo for %d:%ld."),
02575                ptid_get_pid (ptid), ptid_get_lwp (ptid));
02576       return NULL;
02577     }
02578   /* get its general registers.  */
02579   if ((gregs = proc_get_gregs (pi)) == NULL)
02580     {
02581       warning (_("procfs_find_LDT_entry: could not read gregs for %d:%ld."),
02582                ptid_get_pid (ptid), ptid_get_lwp (ptid));
02583       return NULL;
02584     }
02585   /* Now extract the GS register's lower 16 bits.  */
02586   key = (*gregs)[GS] & 0xffff;
02587 
02588   /* Find the matching entry and return it.  */
02589   return proc_get_LDT_entry (pi, key);
02590 }
02591 
02592 #endif
02593 
02594 /* =============== END, non-thread part of /proc  "MODULE" =============== */
02595 
02596 /* =================== Thread "MODULE" =================== */
02597 
02598 /* NOTE: you'll see more ifdefs and duplication of functions here,
02599    since there is a different way to do threads on every OS.  */
02600 
02601 /* Returns the number of threads for the process.  */
02602 
02603 #if defined (PIOCNTHR) && defined (PIOCTLIST)
02604 /* OSF version */
02605 static int
02606 proc_get_nthreads (procinfo *pi)
02607 {
02608   int nthreads = 0;
02609 
02610   if (ioctl (pi->ctl_fd, PIOCNTHR, &nthreads) < 0)
02611     proc_warn (pi, "procfs: PIOCNTHR failed", __LINE__);
02612 
02613   return nthreads;
02614 }
02615 
02616 #else
02617 #if defined (SYS_lwpcreate) || defined (SYS_lwp_create) /* FIXME: multiple */
02618 /* Solaris version */
02619 static int
02620 proc_get_nthreads (procinfo *pi)
02621 {
02622   if (!pi->status_valid)
02623     if (!proc_get_status (pi))
02624       return 0;
02625 
02626   /* NEW_PROC_API: only works for the process procinfo, because the
02627      LWP procinfos do not get prstatus filled in.  */
02628 #ifdef NEW_PROC_API
02629   if (pi->tid != 0)     /* Find the parent process procinfo.  */
02630     pi = find_procinfo_or_die (pi->pid, 0);
02631 #endif
02632   return pi->prstatus.pr_nlwp;
02633 }
02634 
02635 #else
02636 /* Default version */
02637 static int
02638 proc_get_nthreads (procinfo *pi)
02639 {
02640   return 0;
02641 }
02642 #endif
02643 #endif
02644 
02645 /* LWP version.
02646 
02647    Return the ID of the thread that had an event of interest.
02648    (ie. the one that hit a breakpoint or other traced event).  All
02649    other things being equal, this should be the ID of a thread that is
02650    currently executing.  */
02651 
02652 #if defined (SYS_lwpcreate) || defined (SYS_lwp_create) /* FIXME: multiple */
02653 /* Solaris version */
02654 static int
02655 proc_get_current_thread (procinfo *pi)
02656 {
02657   /* Note: this should be applied to the root procinfo for the
02658      process, not to the procinfo for an LWP.  If applied to the
02659      procinfo for an LWP, it will simply return that LWP's ID.  In
02660      that case, find the parent process procinfo.  */
02661 
02662   if (pi->tid != 0)
02663     pi = find_procinfo_or_die (pi->pid, 0);
02664 
02665   if (!pi->status_valid)
02666     if (!proc_get_status (pi))
02667       return 0;
02668 
02669 #ifdef NEW_PROC_API
02670   return pi->prstatus.pr_lwp.pr_lwpid;
02671 #else
02672   return pi->prstatus.pr_who;
02673 #endif
02674 }
02675 
02676 #else
02677 #if defined (PIOCNTHR) && defined (PIOCTLIST)
02678 /* OSF version */
02679 static int
02680 proc_get_current_thread (procinfo *pi)
02681 {
02682 #if 0   /* FIXME: not ready for prime time?  */
02683   return pi->prstatus.pr_tid;
02684 #else
02685   return 0;
02686 #endif
02687 }
02688 
02689 #else
02690 /* Default version */
02691 static int
02692 proc_get_current_thread (procinfo *pi)
02693 {
02694   return 0;
02695 }
02696 
02697 #endif
02698 #endif
02699 
02700 /* Discover the IDs of all the threads within the process, and create
02701    a procinfo for each of them (chained to the parent).  This
02702    unfortunately requires a different method on every OS.  Returns
02703    non-zero for success, zero for failure.  */
02704 
02705 static int
02706 proc_delete_dead_threads (procinfo *parent, procinfo *thread, void *ignore)
02707 {
02708   if (thread && parent) /* sanity */
02709     {
02710       thread->status_valid = 0;
02711       if (!proc_get_status (thread))
02712         destroy_one_procinfo (&parent->thread_list, thread);
02713     }
02714   return 0;     /* keep iterating */
02715 }
02716 
02717 #if defined (PIOCLSTATUS)
02718 /* Solaris 2.5 (ioctl) version */
02719 static int
02720 proc_update_threads (procinfo *pi)
02721 {
02722   gdb_prstatus_t *prstatus;
02723   struct cleanup *old_chain = NULL;
02724   procinfo *thread;
02725   int nlwp, i;
02726 
02727   /* We should never have to apply this operation to any procinfo
02728      except the one for the main process.  If that ever changes for
02729      any reason, then take out the following clause and replace it
02730      with one that makes sure the ctl_fd is open.  */
02731 
02732   if (pi->tid != 0)
02733     pi = find_procinfo_or_die (pi->pid, 0);
02734 
02735   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
02736 
02737   if ((nlwp = proc_get_nthreads (pi)) <= 1)
02738     return 1;   /* Process is not multi-threaded; nothing to do.  */
02739 
02740   prstatus = xmalloc (sizeof (gdb_prstatus_t) * (nlwp + 1));
02741 
02742   old_chain = make_cleanup (xfree, prstatus);
02743   if (ioctl (pi->ctl_fd, PIOCLSTATUS, prstatus) < 0)
02744     proc_error (pi, "update_threads (PIOCLSTATUS)", __LINE__);
02745 
02746   /* Skip element zero, which represents the process as a whole.  */
02747   for (i = 1; i < nlwp + 1; i++)
02748     {
02749       if ((thread = create_procinfo (pi->pid, prstatus[i].pr_who)) == NULL)
02750         proc_error (pi, "update_threads, create_procinfo", __LINE__);
02751 
02752       memcpy (&thread->prstatus, &prstatus[i], sizeof (*prstatus));
02753       thread->status_valid = 1;
02754     }
02755   pi->threads_valid = 1;
02756   do_cleanups (old_chain);
02757   return 1;
02758 }
02759 #else
02760 #ifdef NEW_PROC_API
02761 /* Solaris 6 (and later) version.  */
02762 static void
02763 do_closedir_cleanup (void *dir)
02764 {
02765   closedir (dir);
02766 }
02767 
02768 static int
02769 proc_update_threads (procinfo *pi)
02770 {
02771   char pathname[MAX_PROC_NAME_SIZE + 16];
02772   struct dirent *direntry;
02773   struct cleanup *old_chain = NULL;
02774   procinfo *thread;
02775   DIR *dirp;
02776   int lwpid;
02777 
02778   /* We should never have to apply this operation to any procinfo
02779      except the one for the main process.  If that ever changes for
02780      any reason, then take out the following clause and replace it
02781      with one that makes sure the ctl_fd is open.  */
02782 
02783   if (pi->tid != 0)
02784     pi = find_procinfo_or_die (pi->pid, 0);
02785 
02786   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
02787 
02788   /* Note: this brute-force method was originally devised for Unixware
02789      (support removed since), and will also work on Solaris 2.6 and
02790      2.7.  The original comment mentioned the existence of a much
02791      simpler and more elegant way to do this on Solaris, but didn't
02792      point out what that was.  */
02793 
02794   strcpy (pathname, pi->pathname);
02795   strcat (pathname, "/lwp");
02796   if ((dirp = opendir (pathname)) == NULL)
02797     proc_error (pi, "update_threads, opendir", __LINE__);
02798 
02799   old_chain = make_cleanup (do_closedir_cleanup, dirp);
02800   while ((direntry = readdir (dirp)) != NULL)
02801     if (direntry->d_name[0] != '.')             /* skip '.' and '..' */
02802       {
02803         lwpid = atoi (&direntry->d_name[0]);
02804         if ((thread = create_procinfo (pi->pid, lwpid)) == NULL)
02805           proc_error (pi, "update_threads, create_procinfo", __LINE__);
02806       }
02807   pi->threads_valid = 1;
02808   do_cleanups (old_chain);
02809   return 1;
02810 }
02811 #else
02812 #ifdef PIOCTLIST
02813 /* OSF version */
02814 static int
02815 proc_update_threads (procinfo *pi)
02816 {
02817   int nthreads, i;
02818   tid_t *threads;
02819 
02820   /* We should never have to apply this operation to any procinfo
02821      except the one for the main process.  If that ever changes for
02822      any reason, then take out the following clause and replace it
02823      with one that makes sure the ctl_fd is open.  */
02824 
02825   if (pi->tid != 0)
02826     pi = find_procinfo_or_die (pi->pid, 0);
02827 
02828   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
02829 
02830   nthreads = proc_get_nthreads (pi);
02831   if (nthreads < 2)
02832     return 0;           /* Nothing to do for 1 or fewer threads.  */
02833 
02834   threads = xmalloc (nthreads * sizeof (tid_t));
02835 
02836   if (ioctl (pi->ctl_fd, PIOCTLIST, threads) < 0)
02837     proc_error (pi, "procfs: update_threads (PIOCTLIST)", __LINE__);
02838 
02839   for (i = 0; i < nthreads; i++)
02840     {
02841       if (!find_procinfo (pi->pid, threads[i]))
02842         if (!create_procinfo  (pi->pid, threads[i]))
02843           proc_error (pi, "update_threads, create_procinfo", __LINE__);
02844     }
02845   pi->threads_valid = 1;
02846   return 1;
02847 }
02848 #else
02849 /* Default version */
02850 static int
02851 proc_update_threads (procinfo *pi)
02852 {
02853   return 0;
02854 }
02855 #endif  /* OSF PIOCTLIST */
02856 #endif  /* NEW_PROC_API   */
02857 #endif  /* SOL 2.5 PIOCLSTATUS */
02858 
02859 /* Given a pointer to a function, call that function once for each lwp
02860    in the procinfo list, until the function returns non-zero, in which
02861    event return the value returned by the function.
02862 
02863    Note: this function does NOT call update_threads.  If you want to
02864    discover new threads first, you must call that function explicitly.
02865    This function just makes a quick pass over the currently-known
02866    procinfos.
02867 
02868    PI is the parent process procinfo.  FUNC is the per-thread
02869    function.  PTR is an opaque parameter for function.  Returns the
02870    first non-zero return value from the callee, or zero.  */
02871 
02872 static int
02873 proc_iterate_over_threads (procinfo *pi,
02874                            int (*func) (procinfo *, procinfo *, void *),
02875                            void *ptr)
02876 {
02877   procinfo *thread, *next;
02878   int retval = 0;
02879 
02880   /* We should never have to apply this operation to any procinfo
02881      except the one for the main process.  If that ever changes for
02882      any reason, then take out the following clause and replace it
02883      with one that makes sure the ctl_fd is open.  */
02884 
02885   if (pi->tid != 0)
02886     pi = find_procinfo_or_die (pi->pid, 0);
02887 
02888   for (thread = pi->thread_list; thread != NULL; thread = next)
02889     {
02890       next = thread->next;      /* In case thread is destroyed.  */
02891       if ((retval = (*func) (pi, thread, ptr)) != 0)
02892         break;
02893     }
02894 
02895   return retval;
02896 }
02897 
02898 /* =================== END, Thread "MODULE" =================== */
02899 
02900 /* =================== END, /proc  "MODULE" =================== */
02901 
02902 /* ===================  GDB  "MODULE" =================== */
02903 
02904 /* Here are all of the gdb target vector functions and their
02905    friends.  */
02906 
02907 static ptid_t do_attach (ptid_t ptid);
02908 static void do_detach (int signo);
02909 static void proc_trace_syscalls_1 (procinfo *pi, int syscallnum,
02910                                    int entry_or_exit, int mode, int from_tty);
02911 
02912 /* On mips-irix, we need to insert a breakpoint at __dbx_link during
02913    the startup phase.  The following two variables are used to record
02914    the address of the breakpoint, and the code that was replaced by
02915    a breakpoint.  */
02916 static int dbx_link_bpt_addr = 0;
02917 static void *dbx_link_bpt;
02918 
02919 /* Sets up the inferior to be debugged.  Registers to trace signals,
02920    hardware faults, and syscalls.  Note: does not set RLC flag: caller
02921    may want to customize that.  Returns zero for success (note!
02922    unlike most functions in this module); on failure, returns the LINE
02923    NUMBER where it failed!  */
02924 
02925 static int
02926 procfs_debug_inferior (procinfo *pi)
02927 {
02928   fltset_t traced_faults;
02929   gdb_sigset_t traced_signals;
02930   sysset_t *traced_syscall_entries;
02931   sysset_t *traced_syscall_exits;
02932   int status;
02933 
02934 #ifdef PROCFS_DONT_TRACE_FAULTS
02935   /* On some systems (OSF), we don't trace hardware faults.
02936      Apparently it's enough that we catch them as signals.
02937      Wonder why we don't just do that in general?  */
02938   premptyset (&traced_faults);          /* don't trace faults.  */
02939 #else
02940   /* Register to trace hardware faults in the child.  */
02941   prfillset (&traced_faults);           /* trace all faults...  */
02942   gdb_prdelset  (&traced_faults, FLTPAGE);      /* except page fault.  */
02943 #endif
02944   if (!proc_set_traced_faults  (pi, &traced_faults))
02945     return __LINE__;
02946 
02947   /* Initially, register to trace all signals in the child.  */
02948   prfillset (&traced_signals);
02949   if (!proc_set_traced_signals (pi, &traced_signals))
02950     return __LINE__;
02951 
02952 
02953   /* Register to trace the 'exit' system call (on entry).  */
02954   traced_syscall_entries = sysset_t_alloc (pi);
02955   gdb_premptysysset (traced_syscall_entries);
02956 #ifdef SYS_exit
02957   gdb_praddsysset (traced_syscall_entries, SYS_exit);
02958 #endif
02959 #ifdef SYS_lwpexit
02960   gdb_praddsysset (traced_syscall_entries, SYS_lwpexit);/* And _lwp_exit...  */
02961 #endif
02962 #ifdef SYS_lwp_exit
02963   gdb_praddsysset (traced_syscall_entries, SYS_lwp_exit);
02964 #endif
02965 #ifdef DYNAMIC_SYSCALLS
02966   {
02967     int callnum = find_syscall (pi, "_exit");
02968 
02969     if (callnum >= 0)
02970       gdb_praddsysset (traced_syscall_entries, callnum);
02971   }
02972 #endif
02973 
02974   status = proc_set_traced_sysentry (pi, traced_syscall_entries);
02975   xfree (traced_syscall_entries);
02976   if (!status)
02977     return __LINE__;
02978 
02979 #ifdef PRFS_STOPEXEC    /* defined on OSF */
02980   /* OSF method for tracing exec syscalls.  Quoting:
02981      Under Alpha OSF/1 we have to use a PIOCSSPCACT ioctl to trace
02982      exits from exec system calls because of the user level loader.  */
02983   /* FIXME: make nice and maybe move into an access function.  */
02984   {
02985     int prfs_flags;
02986 
02987     if (ioctl (pi->ctl_fd, PIOCGSPCACT, &prfs_flags) < 0)
02988       return __LINE__;
02989 
02990     prfs_flags |= PRFS_STOPEXEC;
02991 
02992     if (ioctl (pi->ctl_fd, PIOCSSPCACT, &prfs_flags) < 0)
02993       return __LINE__;
02994   }
02995 #else /* not PRFS_STOPEXEC */
02996   /* Everyone else's (except OSF) method for tracing exec syscalls.  */
02997   /* GW: Rationale...
02998      Not all systems with /proc have all the exec* syscalls with the same
02999      names.  On the SGI, for example, there is no SYS_exec, but there
03000      *is* a SYS_execv.  So, we try to account for that.  */
03001 
03002   traced_syscall_exits = sysset_t_alloc (pi);
03003   gdb_premptysysset (traced_syscall_exits);
03004 #ifdef SYS_exec
03005   gdb_praddsysset (traced_syscall_exits, SYS_exec);
03006 #endif
03007 #ifdef SYS_execve
03008   gdb_praddsysset (traced_syscall_exits, SYS_execve);
03009 #endif
03010 #ifdef SYS_execv
03011   gdb_praddsysset (traced_syscall_exits, SYS_execv);
03012 #endif
03013 
03014 #ifdef SYS_lwpcreate
03015   gdb_praddsysset (traced_syscall_exits, SYS_lwpcreate);
03016   gdb_praddsysset (traced_syscall_exits, SYS_lwpexit);
03017 #endif
03018 
03019 #ifdef SYS_lwp_create   /* FIXME: once only, please.  */
03020   gdb_praddsysset (traced_syscall_exits, SYS_lwp_create);
03021   gdb_praddsysset (traced_syscall_exits, SYS_lwp_exit);
03022 #endif
03023 
03024 #ifdef DYNAMIC_SYSCALLS
03025   {
03026     int callnum = find_syscall (pi, "execve");
03027 
03028     if (callnum >= 0)
03029       gdb_praddsysset (traced_syscall_exits, callnum);
03030     callnum = find_syscall (pi, "ra_execve");
03031     if (callnum >= 0)
03032       gdb_praddsysset (traced_syscall_exits, callnum);
03033   }
03034 #endif
03035 
03036   status = proc_set_traced_sysexit (pi, traced_syscall_exits);
03037   xfree (traced_syscall_exits);
03038   if (!status)
03039     return __LINE__;
03040 
03041 #endif /* PRFS_STOPEXEC */
03042   return 0;
03043 }
03044 
03045 static void
03046 procfs_attach (struct target_ops *ops, char *args, int from_tty)
03047 {
03048   char *exec_file;
03049   int   pid;
03050 
03051   pid = parse_pid_to_attach (args);
03052 
03053   if (pid == getpid ())
03054     error (_("Attaching GDB to itself is not a good idea..."));
03055 
03056   if (from_tty)
03057     {
03058       exec_file = get_exec_file (0);
03059 
03060       if (exec_file)
03061         printf_filtered (_("Attaching to program `%s', %s\n"),
03062                          exec_file, target_pid_to_str (pid_to_ptid (pid)));
03063       else
03064         printf_filtered (_("Attaching to %s\n"),
03065                          target_pid_to_str (pid_to_ptid (pid)));
03066 
03067       fflush (stdout);
03068     }
03069   inferior_ptid = do_attach (pid_to_ptid (pid));
03070   push_target (ops);
03071 }
03072 
03073 static void
03074 procfs_detach (struct target_ops *ops, char *args, int from_tty)
03075 {
03076   int sig = 0;
03077   int pid = ptid_get_pid (inferior_ptid);
03078 
03079   if (args)
03080     sig = atoi (args);
03081 
03082   if (from_tty)
03083     {
03084       char *exec_file;
03085 
03086       exec_file = get_exec_file (0);
03087       if (exec_file == NULL)
03088         exec_file = "";
03089 
03090       printf_filtered (_("Detaching from program: %s, %s\n"), exec_file,
03091                        target_pid_to_str (pid_to_ptid (pid)));
03092       gdb_flush (gdb_stdout);
03093     }
03094 
03095   do_detach (sig);
03096 
03097   inferior_ptid = null_ptid;
03098   detach_inferior (pid);
03099   unpush_target (ops);
03100 }
03101 
03102 static ptid_t
03103 do_attach (ptid_t ptid)
03104 {
03105   procinfo *pi;
03106   struct inferior *inf;
03107   int fail;
03108   int lwpid;
03109 
03110   if ((pi = create_procinfo (ptid_get_pid (ptid), 0)) == NULL)
03111     perror (_("procfs: out of memory in 'attach'"));
03112 
03113   if (!open_procinfo_files (pi, FD_CTL))
03114     {
03115       fprintf_filtered (gdb_stderr, "procfs:%d -- ", __LINE__);
03116       sprintf (errmsg, "do_attach: couldn't open /proc file for process %d",
03117                ptid_get_pid (ptid));
03118       dead_procinfo (pi, errmsg, NOKILL);
03119     }
03120 
03121   /* Stop the process (if it isn't already stopped).  */
03122   if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
03123     {
03124       pi->was_stopped = 1;
03125       proc_prettyprint_why (proc_why (pi), proc_what (pi), 1);
03126     }
03127   else
03128     {
03129       pi->was_stopped = 0;
03130       /* Set the process to run again when we close it.  */
03131       if (!proc_set_run_on_last_close (pi))
03132         dead_procinfo (pi, "do_attach: couldn't set RLC.", NOKILL);
03133 
03134       /* Now stop the process.  */
03135       if (!proc_stop_process (pi))
03136         dead_procinfo (pi, "do_attach: couldn't stop the process.", NOKILL);
03137       pi->ignore_next_sigstop = 1;
03138     }
03139   /* Save some of the /proc state to be restored if we detach.  */
03140   if (!proc_get_traced_faults   (pi, &pi->saved_fltset))
03141     dead_procinfo (pi, "do_attach: couldn't save traced faults.", NOKILL);
03142   if (!proc_get_traced_signals  (pi, &pi->saved_sigset))
03143     dead_procinfo (pi, "do_attach: couldn't save traced signals.", NOKILL);
03144   if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
03145     dead_procinfo (pi, "do_attach: couldn't save traced syscall entries.",
03146                    NOKILL);
03147   if (!proc_get_traced_sysexit  (pi, pi->saved_exitset))
03148     dead_procinfo (pi, "do_attach: couldn't save traced syscall exits.",
03149                    NOKILL);
03150   if (!proc_get_held_signals    (pi, &pi->saved_sighold))
03151     dead_procinfo (pi, "do_attach: couldn't save held signals.", NOKILL);
03152 
03153   if ((fail = procfs_debug_inferior (pi)) != 0)
03154     dead_procinfo (pi, "do_attach: failed in procfs_debug_inferior", NOKILL);
03155 
03156   inf = current_inferior ();
03157   inferior_appeared (inf, pi->pid);
03158   /* Let GDB know that the inferior was attached.  */
03159   inf->attach_flag = 1;
03160 
03161   /* Create a procinfo for the current lwp.  */
03162   lwpid = proc_get_current_thread (pi);
03163   create_procinfo (pi->pid, lwpid);
03164 
03165   /* Add it to gdb's thread list.  */
03166   ptid = ptid_build (pi->pid, lwpid, 0);
03167   add_thread (ptid);
03168 
03169   return ptid;
03170 }
03171 
03172 static void
03173 do_detach (int signo)
03174 {
03175   procinfo *pi;
03176 
03177   /* Find procinfo for the main process.  */
03178   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid),
03179                              0); /* FIXME: threads */
03180   if (signo)
03181     if (!proc_set_current_signal (pi, signo))
03182       proc_warn (pi, "do_detach, set_current_signal", __LINE__);
03183 
03184   if (!proc_set_traced_signals (pi, &pi->saved_sigset))
03185     proc_warn (pi, "do_detach, set_traced_signal", __LINE__);
03186 
03187   if (!proc_set_traced_faults (pi, &pi->saved_fltset))
03188     proc_warn (pi, "do_detach, set_traced_faults", __LINE__);
03189 
03190   if (!proc_set_traced_sysentry (pi, pi->saved_entryset))
03191     proc_warn (pi, "do_detach, set_traced_sysentry", __LINE__);
03192 
03193   if (!proc_set_traced_sysexit (pi, pi->saved_exitset))
03194     proc_warn (pi, "do_detach, set_traced_sysexit", __LINE__);
03195 
03196   if (!proc_set_held_signals (pi, &pi->saved_sighold))
03197     proc_warn (pi, "do_detach, set_held_signals", __LINE__);
03198 
03199   if (signo || (proc_flags (pi) & (PR_STOPPED | PR_ISTOP)))
03200     if (signo || !(pi->was_stopped) ||
03201         query (_("Was stopped when attached, make it runnable again? ")))
03202       {
03203         /* Clear any pending signal.  */
03204         if (!proc_clear_current_fault (pi))
03205           proc_warn (pi, "do_detach, clear_current_fault", __LINE__);
03206 
03207         if (signo == 0 && !proc_clear_current_signal (pi))
03208           proc_warn (pi, "do_detach, clear_current_signal", __LINE__);
03209 
03210         if (!proc_set_run_on_last_close (pi))
03211           proc_warn (pi, "do_detach, set_rlc", __LINE__);
03212       }
03213 
03214   destroy_procinfo (pi);
03215 }
03216 
03217 /* Fetch register REGNUM from the inferior.  If REGNUM is -1, do this
03218    for all registers.
03219 
03220    ??? Is the following note still relevant?  We can't get individual
03221    registers with the PT_GETREGS ptrace(2) request either, yet we
03222    don't bother with caching at all in that case.
03223 
03224    NOTE: Since the /proc interface cannot give us individual
03225    registers, we pay no attention to REGNUM, and just fetch them all.
03226    This results in the possibility that we will do unnecessarily many
03227    fetches, since we may be called repeatedly for individual
03228    registers.  So we cache the results, and mark the cache invalid
03229    when the process is resumed.  */
03230 
03231 static void
03232 procfs_fetch_registers (struct target_ops *ops,
03233                         struct regcache *regcache, int regnum)
03234 {
03235   gdb_gregset_t *gregs;
03236   procinfo *pi;
03237   int pid = ptid_get_pid (inferior_ptid);
03238   int tid = ptid_get_lwp (inferior_ptid);
03239   struct gdbarch *gdbarch = get_regcache_arch (regcache);
03240 
03241   pi = find_procinfo_or_die (pid, tid);
03242 
03243   if (pi == NULL)
03244     error (_("procfs: fetch_registers failed to find procinfo for %s"),
03245            target_pid_to_str (inferior_ptid));
03246 
03247   gregs = proc_get_gregs (pi);
03248   if (gregs == NULL)
03249     proc_error (pi, "fetch_registers, get_gregs", __LINE__);
03250 
03251   supply_gregset (regcache, (const gdb_gregset_t *) gregs);
03252 
03253   if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU?  */
03254     {
03255       gdb_fpregset_t *fpregs;
03256 
03257       if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
03258           || regnum == gdbarch_pc_regnum (gdbarch)
03259           || regnum == gdbarch_sp_regnum (gdbarch))
03260         return;                 /* Not a floating point register.  */
03261 
03262       fpregs = proc_get_fpregs (pi);
03263       if (fpregs == NULL)
03264         proc_error (pi, "fetch_registers, get_fpregs", __LINE__);
03265 
03266       supply_fpregset (regcache, (const gdb_fpregset_t *) fpregs);
03267     }
03268 }
03269 
03270 /* Store register REGNUM back into the inferior.  If REGNUM is -1, do
03271    this for all registers.
03272 
03273    NOTE: Since the /proc interface will not read individual registers,
03274    we will cache these requests until the process is resumed, and only
03275    then write them back to the inferior process.
03276 
03277    FIXME: is that a really bad idea?  Have to think about cases where
03278    writing one register might affect the value of others, etc.  */
03279 
03280 static void
03281 procfs_store_registers (struct target_ops *ops,
03282                         struct regcache *regcache, int regnum)
03283 {
03284   gdb_gregset_t *gregs;
03285   procinfo *pi;
03286   int pid = ptid_get_pid (inferior_ptid);
03287   int tid = ptid_get_lwp (inferior_ptid);
03288   struct gdbarch *gdbarch = get_regcache_arch (regcache);
03289 
03290   pi = find_procinfo_or_die (pid, tid);
03291 
03292   if (pi == NULL)
03293     error (_("procfs: store_registers: failed to find procinfo for %s"),
03294            target_pid_to_str (inferior_ptid));
03295 
03296   gregs = proc_get_gregs (pi);
03297   if (gregs == NULL)
03298     proc_error (pi, "store_registers, get_gregs", __LINE__);
03299 
03300   fill_gregset (regcache, gregs, regnum);
03301   if (!proc_set_gregs (pi))
03302     proc_error (pi, "store_registers, set_gregs", __LINE__);
03303 
03304   if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU?  */
03305     {
03306       gdb_fpregset_t *fpregs;
03307 
03308       if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
03309           || regnum == gdbarch_pc_regnum (gdbarch)
03310           || regnum == gdbarch_sp_regnum (gdbarch))
03311         return;                 /* Not a floating point register.  */
03312 
03313       fpregs = proc_get_fpregs (pi);
03314       if (fpregs == NULL)
03315         proc_error (pi, "store_registers, get_fpregs", __LINE__);
03316 
03317       fill_fpregset (regcache, fpregs, regnum);
03318       if (!proc_set_fpregs (pi))
03319         proc_error (pi, "store_registers, set_fpregs", __LINE__);
03320     }
03321 }
03322 
03323 static int
03324 syscall_is_lwp_exit (procinfo *pi, int scall)
03325 {
03326 #ifdef SYS_lwp_exit
03327   if (scall == SYS_lwp_exit)
03328     return 1;
03329 #endif
03330 #ifdef SYS_lwpexit
03331   if (scall == SYS_lwpexit)
03332     return 1;
03333 #endif
03334   return 0;
03335 }
03336 
03337 static int
03338 syscall_is_exit (procinfo *pi, int scall)
03339 {
03340 #ifdef SYS_exit
03341   if (scall == SYS_exit)
03342     return 1;
03343 #endif
03344 #ifdef DYNAMIC_SYSCALLS
03345   if (find_syscall (pi, "_exit") == scall)
03346     return 1;
03347 #endif
03348   return 0;
03349 }
03350 
03351 static int
03352 syscall_is_exec (procinfo *pi, int scall)
03353 {
03354 #ifdef SYS_exec
03355   if (scall == SYS_exec)
03356     return 1;
03357 #endif
03358 #ifdef SYS_execv
03359   if (scall == SYS_execv)
03360     return 1;
03361 #endif
03362 #ifdef SYS_execve
03363   if (scall == SYS_execve)
03364     return 1;
03365 #endif
03366 #ifdef DYNAMIC_SYSCALLS
03367   if (find_syscall (pi, "_execve"))
03368     return 1;
03369   if (find_syscall (pi, "ra_execve"))
03370     return 1;
03371 #endif
03372   return 0;
03373 }
03374 
03375 static int
03376 syscall_is_lwp_create (procinfo *pi, int scall)
03377 {
03378 #ifdef SYS_lwp_create
03379   if (scall == SYS_lwp_create)
03380     return 1;
03381 #endif
03382 #ifdef SYS_lwpcreate
03383   if (scall == SYS_lwpcreate)
03384     return 1;
03385 #endif
03386   return 0;
03387 }
03388 
03389 /* Remove the breakpoint that we inserted in __dbx_link().
03390    Does nothing if the breakpoint hasn't been inserted or has already
03391    been removed.  */
03392 
03393 static void
03394 remove_dbx_link_breakpoint (void)
03395 {
03396   if (dbx_link_bpt_addr == 0)
03397     return;
03398 
03399   if (deprecated_remove_raw_breakpoint (target_gdbarch (), dbx_link_bpt) != 0)
03400     warning (_("Unable to remove __dbx_link breakpoint."));
03401 
03402   dbx_link_bpt_addr = 0;
03403   dbx_link_bpt = NULL;
03404 }
03405 
03406 #ifdef SYS_syssgi
03407 /* Return the address of the __dbx_link() function in the file
03408    refernced by ABFD by scanning its symbol table.  Return 0 if
03409    the symbol was not found.  */
03410 
03411 static CORE_ADDR
03412 dbx_link_addr (bfd *abfd)
03413 {
03414   long storage_needed;
03415   asymbol **symbol_table;
03416   long number_of_symbols;
03417   long i;
03418 
03419   storage_needed = bfd_get_symtab_upper_bound (abfd);
03420   if (storage_needed <= 0)
03421     return 0;
03422 
03423   symbol_table = (asymbol **) xmalloc (storage_needed);
03424   make_cleanup (xfree, symbol_table);
03425 
03426   number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
03427 
03428   for (i = 0; i < number_of_symbols; i++)
03429     {
03430       asymbol *sym = symbol_table[i];
03431 
03432       if ((sym->flags & BSF_GLOBAL)
03433           && sym->name != NULL && strcmp (sym->name, "__dbx_link") == 0)
03434         return (sym->value + sym->section->vma);
03435     }
03436 
03437   /* Symbol not found, return NULL.  */
03438   return 0;
03439 }
03440 
03441 /* Search the symbol table of the file referenced by FD for a symbol
03442    named __dbx_link().  If found, then insert a breakpoint at this location,
03443    and return nonzero.  Return zero otherwise.  */
03444 
03445 static int
03446 insert_dbx_link_bpt_in_file (int fd, CORE_ADDR ignored)
03447 {
03448   bfd *abfd;
03449   long storage_needed;
03450   CORE_ADDR sym_addr;
03451 
03452   abfd = gdb_bfd_fdopenr ("unamed", 0, fd);
03453   if (abfd == NULL)
03454     {
03455       warning (_("Failed to create a bfd: %s."), bfd_errmsg (bfd_get_error ()));
03456       return 0;
03457     }
03458 
03459   if (!bfd_check_format (abfd, bfd_object))
03460     {
03461       /* Not the correct format, so we can not possibly find the dbx_link
03462          symbol in it.  */
03463       gdb_bfd_unref (abfd);
03464       return 0;
03465     }
03466 
03467   sym_addr = dbx_link_addr (abfd);
03468   if (sym_addr != 0)
03469     {
03470       /* Insert the breakpoint.  */
03471       dbx_link_bpt_addr = sym_addr;
03472       dbx_link_bpt = deprecated_insert_raw_breakpoint (target_gdbarch (), NULL,
03473                                                        sym_addr);
03474       if (dbx_link_bpt == NULL)
03475         {
03476           warning (_("Failed to insert dbx_link breakpoint."));
03477           gdb_bfd_unref (abfd);
03478           return 0;
03479         }
03480       gdb_bfd_unref (abfd);
03481       return 1;
03482     }
03483 
03484   gdb_bfd_unref (abfd);
03485   return 0;
03486 }
03487 
03488 /* Calls the supplied callback function once for each mapped address
03489    space in the process.  The callback function receives an open file
03490    descriptor for the file corresponding to that mapped address space
03491    (if there is one), and the base address of the mapped space.  Quit
03492    when the callback function returns a nonzero value, or at teh end
03493    of the mappings.  Returns the first non-zero return value of the
03494    callback function, or zero.  */
03495 
03496 static int
03497 solib_mappings_callback (struct prmap *map, int (*func) (int, CORE_ADDR),
03498                          void *data)
03499 {
03500   procinfo *pi = data;
03501   int fd;
03502 
03503 #ifdef NEW_PROC_API
03504   char name[MAX_PROC_NAME_SIZE + sizeof (map->pr_mapname)];
03505 
03506   if (map->pr_vaddr == 0 && map->pr_size == 0)
03507     return -1;          /* sanity */
03508 
03509   if (map->pr_mapname[0] == 0)
03510     {
03511       fd = -1;  /* no map file */
03512     }
03513   else
03514     {
03515       sprintf (name, "/proc/%d/object/%s", pi->pid, map->pr_mapname);
03516       /* Note: caller's responsibility to close this fd!  */
03517       fd = open_with_retry (name, O_RDONLY);
03518       /* Note: we don't test the above call for failure;
03519          we just pass the FD on as given.  Sometimes there is
03520          no file, so the open may return failure, but that's
03521          not a problem.  */
03522     }
03523 #else
03524   fd = ioctl (pi->ctl_fd, PIOCOPENM, &map->pr_vaddr);
03525   /* Note: we don't test the above call for failure;
03526      we just pass the FD on as given.  Sometimes there is
03527      no file, so the ioctl may return failure, but that's
03528      not a problem.  */
03529 #endif
03530   return (*func) (fd, (CORE_ADDR) map->pr_vaddr);
03531 }
03532 
03533 /* If the given memory region MAP contains a symbol named __dbx_link,
03534    insert a breakpoint at this location and return nonzero.  Return
03535    zero otherwise.  */
03536 
03537 static int
03538 insert_dbx_link_bpt_in_region (struct prmap *map,
03539                                find_memory_region_ftype child_func,
03540                                void *data)
03541 {
03542   procinfo *pi = (procinfo *) data;
03543 
03544   /* We know the symbol we're looking for is in a text region, so
03545      only look for it if the region is a text one.  */
03546   if (map->pr_mflags & MA_EXEC)
03547     return solib_mappings_callback (map, insert_dbx_link_bpt_in_file, pi);
03548 
03549   return 0;
03550 }
03551 
03552 /* Search all memory regions for a symbol named __dbx_link.  If found,
03553    insert a breakpoint at its location, and return nonzero.  Return zero
03554    otherwise.  */
03555 
03556 static int
03557 insert_dbx_link_breakpoint (procinfo *pi)
03558 {
03559   return iterate_over_mappings (pi, NULL, pi, insert_dbx_link_bpt_in_region);
03560 }
03561 #endif
03562 
03563 /* Retrieve the next stop event from the child process.  If child has
03564    not stopped yet, wait for it to stop.  Translate /proc eventcodes
03565    (or possibly wait eventcodes) into gdb internal event codes.
03566    Returns the id of process (and possibly thread) that incurred the
03567    event.  Event codes are returned through a pointer parameter.  */
03568 
03569 static ptid_t
03570 procfs_wait (struct target_ops *ops,
03571              ptid_t ptid, struct target_waitstatus *status, int options)
03572 {
03573   /* First cut: loosely based on original version 2.1.  */
03574   procinfo *pi;
03575   int       wstat;
03576   int       temp_tid;
03577   ptid_t    retval, temp_ptid;
03578   int       why, what, flags;
03579   int       retry = 0;
03580 
03581 wait_again:
03582 
03583   retry++;
03584   wstat    = 0;
03585   retval   = pid_to_ptid (-1);
03586 
03587   /* Find procinfo for main process.  */
03588   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
03589   if (pi)
03590     {
03591       /* We must assume that the status is stale now...  */
03592       pi->status_valid = 0;
03593       pi->gregs_valid  = 0;
03594       pi->fpregs_valid = 0;
03595 
03596 #if 0   /* just try this out...  */
03597       flags = proc_flags (pi);
03598       why   = proc_why (pi);
03599       if ((flags & PR_STOPPED) && (why == PR_REQUESTED))
03600         pi->status_valid = 0;   /* re-read again, IMMEDIATELY...  */
03601 #endif
03602       /* If child is not stopped, wait for it to stop.  */
03603       if (!(proc_flags (pi) & (PR_STOPPED | PR_ISTOP)) &&
03604           !proc_wait_for_stop (pi))
03605         {
03606           /* wait_for_stop failed: has the child terminated?  */
03607           if (errno == ENOENT)
03608             {
03609               int wait_retval;
03610 
03611               /* /proc file not found; presumably child has terminated.  */
03612               wait_retval = wait (&wstat); /* "wait" for the child's exit.  */
03613 
03614               /* Wrong child?  */
03615               if (wait_retval != ptid_get_pid (inferior_ptid))
03616                 error (_("procfs: couldn't stop "
03617                          "process %d: wait returned %d."),
03618                        ptid_get_pid (inferior_ptid), wait_retval);
03619               /* FIXME: might I not just use waitpid?
03620                  Or try find_procinfo to see if I know about this child?  */
03621               retval = pid_to_ptid (wait_retval);
03622             }
03623           else if (errno == EINTR)
03624             goto wait_again;
03625           else
03626             {
03627               /* Unknown error from wait_for_stop.  */
03628               proc_error (pi, "target_wait (wait_for_stop)", __LINE__);
03629             }
03630         }
03631       else
03632         {
03633           /* This long block is reached if either:
03634              a) the child was already stopped, or
03635              b) we successfully waited for the child with wait_for_stop.
03636              This block will analyze the /proc status, and translate it
03637              into a waitstatus for GDB.
03638 
03639              If we actually had to call wait because the /proc file
03640              is gone (child terminated), then we skip this block,
03641              because we already have a waitstatus.  */
03642 
03643           flags = proc_flags (pi);
03644           why   = proc_why (pi);
03645           what  = proc_what (pi);
03646 
03647           if (flags & (PR_STOPPED | PR_ISTOP))
03648             {
03649 #ifdef PR_ASYNC
03650               /* If it's running async (for single_thread control),
03651                  set it back to normal again.  */
03652               if (flags & PR_ASYNC)
03653                 if (!proc_unset_async (pi))
03654                   proc_error (pi, "target_wait, unset_async", __LINE__);
03655 #endif
03656 
03657               if (info_verbose)
03658                 proc_prettyprint_why (why, what, 1);
03659 
03660               /* The 'pid' we will return to GDB is composed of
03661                  the process ID plus the lwp ID.  */
03662               retval = ptid_build (pi->pid, proc_get_current_thread (pi), 0);
03663 
03664               switch (why) {
03665               case PR_SIGNALLED:
03666                 wstat = (what << 8) | 0177;
03667                 break;
03668               case PR_SYSENTRY:
03669                 if (syscall_is_lwp_exit (pi, what))
03670                   {
03671                     if (print_thread_events)
03672                       printf_unfiltered (_("[%s exited]\n"),
03673                                          target_pid_to_str (retval));
03674                     delete_thread (retval);
03675                     status->kind = TARGET_WAITKIND_SPURIOUS;
03676                     return retval;
03677                   }
03678                 else if (syscall_is_exit (pi, what))
03679                   {
03680                     struct inferior *inf;
03681 
03682                     /* Handle SYS_exit call only.  */
03683                     /* Stopped at entry to SYS_exit.
03684                        Make it runnable, resume it, then use
03685                        the wait system call to get its exit code.
03686                        Proc_run_process always clears the current
03687                        fault and signal.
03688                        Then return its exit status.  */
03689                     pi->status_valid = 0;
03690                     wstat = 0;
03691                     /* FIXME: what we should do is return
03692                        TARGET_WAITKIND_SPURIOUS.  */
03693                     if (!proc_run_process (pi, 0, 0))
03694                       proc_error (pi, "target_wait, run_process", __LINE__);
03695 
03696                     inf = find_inferior_pid (pi->pid);
03697                     if (inf->attach_flag)
03698                       {
03699                         /* Don't call wait: simulate waiting for exit,
03700                            return a "success" exit code.  Bogus: what if
03701                            it returns something else?  */
03702                         wstat = 0;
03703                         retval = inferior_ptid;  /* ? ? ? */
03704                       }
03705                     else
03706                       {
03707                         int temp = wait (&wstat);
03708 
03709                         /* FIXME: shouldn't I make sure I get the right
03710                            event from the right process?  If (for
03711                            instance) I have killed an earlier inferior
03712                            process but failed to clean up after it
03713                            somehow, I could get its termination event
03714                            here.  */
03715 
03716                         /* If wait returns -1, that's what we return
03717                            to GDB.  */
03718                         if (temp < 0)
03719                           retval = pid_to_ptid (temp);
03720                       }
03721                   }
03722                 else
03723                   {
03724                     printf_filtered (_("procfs: trapped on entry to "));
03725                     proc_prettyprint_syscall (proc_what (pi), 0);
03726                     printf_filtered ("\n");
03727 #ifndef PIOCSSPCACT
03728                     {
03729                       long i, nsysargs, *sysargs;
03730 
03731                       if ((nsysargs = proc_nsysarg (pi)) > 0 &&
03732                           (sysargs  = proc_sysargs (pi)) != NULL)
03733                         {
03734                           printf_filtered (_("%ld syscall arguments:\n"),
03735                                            nsysargs);
03736                           for (i = 0; i < nsysargs; i++)
03737                             printf_filtered ("#%ld: 0x%08lx\n",
03738                                              i, sysargs[i]);
03739                         }
03740 
03741                     }
03742 #endif
03743                     if (status)
03744                       {
03745                         /* How to exit gracefully, returning "unknown
03746                            event".  */
03747                         status->kind = TARGET_WAITKIND_SPURIOUS;
03748                         return inferior_ptid;
03749                       }
03750                     else
03751                       {
03752                         /* How to keep going without returning to wfi: */
03753                         target_resume (ptid, 0, GDB_SIGNAL_0);
03754                         goto wait_again;
03755                       }
03756                   }
03757                 break;
03758               case PR_SYSEXIT:
03759                 if (syscall_is_exec (pi, what))
03760                   {
03761                     /* Hopefully this is our own "fork-child" execing
03762                        the real child.  Hoax this event into a trap, and
03763                        GDB will see the child about to execute its start
03764                        address.  */
03765                     wstat = (SIGTRAP << 8) | 0177;
03766                   }
03767 #ifdef SYS_syssgi
03768                 else if (what == SYS_syssgi)
03769                   {
03770                     /* see if we can break on dbx_link().  If yes, then
03771                        we no longer need the SYS_syssgi notifications.  */
03772                     if (insert_dbx_link_breakpoint (pi))
03773                       proc_trace_syscalls_1 (pi, SYS_syssgi, PR_SYSEXIT,
03774                                              FLAG_RESET, 0);
03775 
03776                     /* This is an internal event and should be transparent
03777                        to wfi, so resume the execution and wait again.  See
03778                        comment in procfs_init_inferior() for more details.  */
03779                     target_resume (ptid, 0, GDB_SIGNAL_0);
03780                     goto wait_again;
03781                   }
03782 #endif
03783                 else if (syscall_is_lwp_create (pi, what))
03784                   {
03785                     /* This syscall is somewhat like fork/exec.  We
03786                        will get the event twice: once for the parent
03787                        LWP, and once for the child.  We should already
03788                        know about the parent LWP, but the child will
03789                        be new to us.  So, whenever we get this event,
03790                        if it represents a new thread, simply add the
03791                        thread to the list.  */
03792 
03793                     /* If not in procinfo list, add it.  */
03794                     temp_tid = proc_get_current_thread (pi);
03795                     if (!find_procinfo (pi->pid, temp_tid))
03796                       create_procinfo  (pi->pid, temp_tid);
03797 
03798                     temp_ptid = ptid_build (pi->pid, temp_tid, 0);
03799                     /* If not in GDB's thread list, add it.  */
03800                     if (!in_thread_list (temp_ptid))
03801                       add_thread (temp_ptid);
03802 
03803                     /* Return to WFI, but tell it to immediately resume.  */
03804                     status->kind = TARGET_WAITKIND_SPURIOUS;
03805                     return inferior_ptid;
03806                   }
03807                 else if (syscall_is_lwp_exit (pi, what))
03808                   {
03809                     if (print_thread_events)
03810                       printf_unfiltered (_("[%s exited]\n"),
03811                                          target_pid_to_str (retval));
03812                     delete_thread (retval);
03813                     status->kind = TARGET_WAITKIND_SPURIOUS;
03814                     return retval;
03815                   }
03816                 else if (0)
03817                   {
03818                     /* FIXME:  Do we need to handle SYS_sproc,
03819                        SYS_fork, or SYS_vfork here?  The old procfs
03820                        seemed to use this event to handle threads on
03821                        older (non-LWP) systems, where I'm assuming
03822                        that threads were actually separate processes.
03823                        Irix, maybe?  Anyway, low priority for now.  */
03824                   }
03825                 else
03826                   {
03827                     printf_filtered (_("procfs: trapped on exit from "));
03828                     proc_prettyprint_syscall (proc_what (pi), 0);
03829                     printf_filtered ("\n");
03830 #ifndef PIOCSSPCACT
03831                     {
03832                       long i, nsysargs, *sysargs;
03833 
03834                       if ((nsysargs = proc_nsysarg (pi)) > 0 &&
03835                           (sysargs  = proc_sysargs (pi)) != NULL)
03836                         {
03837                           printf_filtered (_("%ld syscall arguments:\n"),
03838                                            nsysargs);
03839                           for (i = 0; i < nsysargs; i++)
03840                             printf_filtered ("#%ld: 0x%08lx\n",
03841                                              i, sysargs[i]);
03842                         }
03843                     }
03844 #endif
03845                     status->kind = TARGET_WAITKIND_SPURIOUS;
03846                     return inferior_ptid;
03847                   }
03848                 break;
03849               case PR_REQUESTED:
03850 #if 0   /* FIXME */
03851                 wstat = (SIGSTOP << 8) | 0177;
03852                 break;
03853 #else
03854                 if (retry < 5)
03855                   {
03856                     printf_filtered (_("Retry #%d:\n"), retry);
03857                     pi->status_valid = 0;
03858                     goto wait_again;
03859                   }
03860                 else
03861                   {
03862                     /* If not in procinfo list, add it.  */
03863                     temp_tid = proc_get_current_thread (pi);
03864                     if (!find_procinfo (pi->pid, temp_tid))
03865                       create_procinfo  (pi->pid, temp_tid);
03866 
03867                     /* If not in GDB's thread list, add it.  */
03868                     temp_ptid = ptid_build (pi->pid, temp_tid, 0);
03869                     if (!in_thread_list (temp_ptid))
03870                       add_thread (temp_ptid);
03871 
03872                     status->kind = TARGET_WAITKIND_STOPPED;
03873                     status->value.sig = 0;
03874                     return retval;
03875                   }
03876 #endif
03877               case PR_JOBCONTROL:
03878                 wstat = (what << 8) | 0177;
03879                 break;
03880               case PR_FAULTED:
03881                 switch (what) {
03882 #ifdef FLTWATCH
03883                 case FLTWATCH:
03884                   wstat = (SIGTRAP << 8) | 0177;
03885                   break;
03886 #endif
03887 #ifdef FLTKWATCH
03888                 case FLTKWATCH:
03889                   wstat = (SIGTRAP << 8) | 0177;
03890                   break;
03891 #endif
03892                   /* FIXME: use si_signo where possible.  */
03893                 case FLTPRIV:
03894 #if (FLTILL != FLTPRIV)         /* Avoid "duplicate case" error.  */
03895                 case FLTILL:
03896 #endif
03897                   wstat = (SIGILL << 8) | 0177;
03898                   break;
03899                 case FLTBPT:
03900 #if (FLTTRACE != FLTBPT)        /* Avoid "duplicate case" error.  */
03901                 case FLTTRACE:
03902 #endif
03903                   /* If we hit our __dbx_link() internal breakpoint,
03904                      then remove it.  See comments in procfs_init_inferior()
03905                      for more details.  */
03906                   if (dbx_link_bpt_addr != 0
03907                       && dbx_link_bpt_addr
03908                          == regcache_read_pc (get_current_regcache ()))
03909                     remove_dbx_link_breakpoint ();
03910 
03911                   wstat = (SIGTRAP << 8) | 0177;
03912                   break;
03913                 case FLTSTACK:
03914                 case FLTACCESS:
03915 #if (FLTBOUNDS != FLTSTACK)     /* Avoid "duplicate case" error.  */
03916                 case FLTBOUNDS:
03917 #endif
03918                   wstat = (SIGSEGV << 8) | 0177;
03919                   break;
03920                 case FLTIOVF:
03921                 case FLTIZDIV:
03922 #if (FLTFPE != FLTIOVF)         /* Avoid "duplicate case" error.  */
03923                 case FLTFPE:
03924 #endif
03925                   wstat = (SIGFPE << 8) | 0177;
03926                   break;
03927                 case FLTPAGE:   /* Recoverable page fault */
03928                 default:        /* FIXME: use si_signo if possible for
03929                                    fault.  */
03930                   retval = pid_to_ptid (-1);
03931                   printf_filtered ("procfs:%d -- ", __LINE__);
03932                   printf_filtered (_("child stopped for unknown reason:\n"));
03933                   proc_prettyprint_why (why, what, 1);
03934                   error (_("... giving up..."));
03935                   break;
03936                 }
03937                 break;  /* case PR_FAULTED: */
03938               default:  /* switch (why) unmatched */
03939                 printf_filtered ("procfs:%d -- ", __LINE__);
03940                 printf_filtered (_("child stopped for unknown reason:\n"));
03941                 proc_prettyprint_why (why, what, 1);
03942                 error (_("... giving up..."));
03943                 break;
03944               }
03945               /* Got this far without error: If retval isn't in the
03946                  threads database, add it.  */
03947               if (ptid_get_pid (retval) > 0 &&
03948                   !ptid_equal (retval, inferior_ptid) &&
03949                   !in_thread_list (retval))
03950                 {
03951                   /* We have a new thread.  We need to add it both to
03952                      GDB's list and to our own.  If we don't create a
03953                      procinfo, resume may be unhappy later.  */
03954                   add_thread (retval);
03955                   if (find_procinfo (ptid_get_pid (retval),
03956                                      ptid_get_lwp (retval)) == NULL)
03957                     create_procinfo (ptid_get_pid (retval),
03958                                      ptid_get_lwp (retval));
03959                 }
03960             }
03961           else  /* Flags do not indicate STOPPED.  */
03962             {
03963               /* surely this can't happen...  */
03964               printf_filtered ("procfs:%d -- process not stopped.\n",
03965                                __LINE__);
03966               proc_prettyprint_flags (flags, 1);
03967               error (_("procfs: ...giving up..."));
03968             }
03969         }
03970 
03971       if (status)
03972         store_waitstatus (status, wstat);
03973     }
03974 
03975   return retval;
03976 }
03977 
03978 /* Perform a partial transfer to/from the specified object.  For
03979    memory transfers, fall back to the old memory xfer functions.  */
03980 
03981 static LONGEST
03982 procfs_xfer_partial (struct target_ops *ops, enum target_object object,
03983                      const char *annex, gdb_byte *readbuf,
03984                      const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
03985 {
03986   switch (object)
03987     {
03988     case TARGET_OBJECT_MEMORY:
03989       if (readbuf)
03990         return (*ops->deprecated_xfer_memory) (offset, readbuf,
03991                                                len, 0/*read*/, NULL, ops);
03992       if (writebuf)
03993         return (*ops->deprecated_xfer_memory) (offset, (gdb_byte *) writebuf,
03994                                                len, 1/*write*/, NULL, ops);
03995       return -1;
03996 
03997 #ifdef NEW_PROC_API
03998     case TARGET_OBJECT_AUXV:
03999       return memory_xfer_auxv (ops, object, annex, readbuf, writebuf,
04000                                offset, len);
04001 #endif
04002 
04003     default:
04004       if (ops->beneath != NULL)
04005         return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
04006                                               readbuf, writebuf, offset, len);
04007       return -1;
04008     }
04009 }
04010 
04011 
04012 /* Transfer LEN bytes between GDB address MYADDR and target address
04013    MEMADDR.  If DOWRITE is non-zero, transfer them to the target,
04014    otherwise transfer them from the target.  TARGET is unused.
04015 
04016    The return value is 0 if an error occurred or no bytes were
04017    transferred.  Otherwise, it will be a positive value which
04018    indicates the number of bytes transferred between gdb and the
04019    target.  (Note that the interface also makes provisions for
04020    negative values, but this capability isn't implemented here.)  */
04021 
04022 static int
04023 procfs_xfer_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len, int dowrite,
04024                     struct mem_attrib *attrib, struct target_ops *target)
04025 {
04026   procinfo *pi;
04027   int nbytes = 0;
04028 
04029   /* Find procinfo for main process.  */
04030   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
04031   if (pi->as_fd == 0 &&
04032       open_procinfo_files (pi, FD_AS) == 0)
04033     {
04034       proc_warn (pi, "xfer_memory, open_proc_files", __LINE__);
04035       return 0;
04036     }
04037 
04038   if (lseek (pi->as_fd, (off_t) memaddr, SEEK_SET) == (off_t) memaddr)
04039     {
04040       if (dowrite)
04041         {
04042 #ifdef NEW_PROC_API
04043           PROCFS_NOTE ("write memory:\n");
04044 #else
04045           PROCFS_NOTE ("write memory:\n");
04046 #endif
04047           nbytes = write (pi->as_fd, myaddr, len);
04048         }
04049       else
04050         {
04051           PROCFS_NOTE ("read  memory:\n");
04052           nbytes = read (pi->as_fd, myaddr, len);
04053         }
04054       if (nbytes < 0)
04055         {
04056           nbytes = 0;
04057         }
04058     }
04059   return nbytes;
04060 }
04061 
04062 /* Called by target_resume before making child runnable.  Mark cached
04063    registers and status's invalid.  If there are "dirty" caches that
04064    need to be written back to the child process, do that.
04065 
04066    File descriptors are also cached.  As they are a limited resource,
04067    we cannot hold onto them indefinitely.  However, as they are
04068    expensive to open, we don't want to throw them away
04069    indescriminately either.  As a compromise, we will keep the file
04070    descriptors for the parent process, but discard any file
04071    descriptors we may have accumulated for the threads.
04072 
04073    As this function is called by iterate_over_threads, it always
04074    returns zero (so that iterate_over_threads will keep
04075    iterating).  */
04076 
04077 static int
04078 invalidate_cache (procinfo *parent, procinfo *pi, void *ptr)
04079 {
04080   /* About to run the child; invalidate caches and do any other
04081      cleanup.  */
04082 
04083 #if 0
04084   if (pi->gregs_dirty)
04085     if (parent == NULL ||
04086         proc_get_current_thread (parent) != pi->tid)
04087       if (!proc_set_gregs (pi)) /* flush gregs cache */
04088         proc_warn (pi, "target_resume, set_gregs",
04089                    __LINE__);
04090   if (gdbarch_fp0_regnum (target_gdbarch ()) >= 0)
04091     if (pi->fpregs_dirty)
04092       if (parent == NULL ||
04093           proc_get_current_thread (parent) != pi->tid)
04094         if (!proc_set_fpregs (pi))      /* flush fpregs cache */
04095           proc_warn (pi, "target_resume, set_fpregs",
04096                      __LINE__);
04097 #endif
04098 
04099   if (parent != NULL)
04100     {
04101       /* The presence of a parent indicates that this is an LWP.
04102          Close any file descriptors that it might have open.
04103          We don't do this to the master (parent) procinfo.  */
04104 
04105       close_procinfo_files (pi);
04106     }
04107   pi->gregs_valid   = 0;
04108   pi->fpregs_valid  = 0;
04109 #if 0
04110   pi->gregs_dirty   = 0;
04111   pi->fpregs_dirty  = 0;
04112 #endif
04113   pi->status_valid  = 0;
04114   pi->threads_valid = 0;
04115 
04116   return 0;
04117 }
04118 
04119 #if 0
04120 /* A callback function for iterate_over_threads.  Find the
04121    asynchronous signal thread, and make it runnable.  See if that
04122    helps matters any.  */
04123 
04124 static int
04125 make_signal_thread_runnable (procinfo *process, procinfo *pi, void *ptr)
04126 {
04127 #ifdef PR_ASLWP
04128   if (proc_flags (pi) & PR_ASLWP)
04129     {
04130       if (!proc_run_process (pi, 0, -1))
04131         proc_error (pi, "make_signal_thread_runnable", __LINE__);
04132       return 1;
04133     }
04134 #endif
04135   return 0;
04136 }
04137 #endif
04138 
04139 /* Make the child process runnable.  Normally we will then call
04140    procfs_wait and wait for it to stop again (unless gdb is async).
04141 
04142    If STEP is true, then arrange for the child to stop again after
04143    executing a single instruction.  If SIGNO is zero, then cancel any
04144    pending signal; if non-zero, then arrange for the indicated signal
04145    to be delivered to the child when it runs.  If PID is -1, then
04146    allow any child thread to run; if non-zero, then allow only the
04147    indicated thread to run.  (not implemented yet).  */
04148 
04149 static void
04150 procfs_resume (struct target_ops *ops,
04151                ptid_t ptid, int step, enum gdb_signal signo)
04152 {
04153   procinfo *pi, *thread;
04154   int native_signo;
04155 
04156   /* 2.1:
04157      prrun.prflags |= PRSVADDR;
04158      prrun.pr_vaddr = $PC;         set resume address
04159      prrun.prflags |= PRSTRACE;    trace signals in pr_trace (all)
04160      prrun.prflags |= PRSFAULT;    trace faults in pr_fault (all but PAGE)
04161      prrun.prflags |= PRCFAULT;    clear current fault.
04162 
04163      PRSTRACE and PRSFAULT can be done by other means
04164         (proc_trace_signals, proc_trace_faults)
04165      PRSVADDR is unnecessary.
04166      PRCFAULT may be replaced by a PIOCCFAULT call (proc_clear_current_fault)
04167      This basically leaves PRSTEP and PRCSIG.
04168      PRCSIG is like PIOCSSIG (proc_clear_current_signal).
04169      So basically PR_STEP is the sole argument that must be passed
04170      to proc_run_process (for use in the prrun struct by ioctl).  */
04171 
04172   /* Find procinfo for main process.  */
04173   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
04174 
04175   /* First cut: ignore pid argument.  */
04176   errno = 0;
04177 
04178   /* Convert signal to host numbering.  */
04179   if (signo == 0 ||
04180       (signo == GDB_SIGNAL_STOP && pi->ignore_next_sigstop))
04181     native_signo = 0;
04182   else
04183     native_signo = gdb_signal_to_host (signo);
04184 
04185   pi->ignore_next_sigstop = 0;
04186 
04187   /* Running the process voids all cached registers and status.  */
04188   /* Void the threads' caches first.  */
04189   proc_iterate_over_threads (pi, invalidate_cache, NULL);
04190   /* Void the process procinfo's caches.  */
04191   invalidate_cache (NULL, pi, NULL);
04192 
04193   if (ptid_get_pid (ptid) != -1)
04194     {
04195       /* Resume a specific thread, presumably suppressing the
04196          others.  */
04197       thread = find_procinfo (ptid_get_pid (ptid), ptid_get_lwp (ptid));
04198       if (thread != NULL)
04199         {
04200           if (thread->tid != 0)
04201             {
04202               /* We're to resume a specific thread, and not the
04203                  others.  Set the child process's PR_ASYNC flag.  */
04204 #ifdef PR_ASYNC
04205               if (!proc_set_async (pi))
04206                 proc_error (pi, "target_resume, set_async", __LINE__);
04207 #endif
04208 #if 0
04209               proc_iterate_over_threads (pi,
04210                                          make_signal_thread_runnable,
04211                                          NULL);
04212 #endif
04213               pi = thread;      /* Substitute the thread's procinfo
04214                                    for run.  */
04215             }
04216         }
04217     }
04218 
04219   if (!proc_run_process (pi, step, native_signo))
04220     {
04221       if (errno == EBUSY)
04222         warning (_("resume: target already running.  "
04223                    "Pretend to resume, and hope for the best!"));
04224       else
04225         proc_error (pi, "target_resume", __LINE__);
04226     }
04227 }
04228 
04229 /* Set up to trace signals in the child process.  */
04230 
04231 static void
04232 procfs_pass_signals (int numsigs, unsigned char *pass_signals)
04233 {
04234   gdb_sigset_t signals;
04235   procinfo *pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
04236   int signo;
04237 
04238   prfillset (&signals);
04239 
04240   for (signo = 0; signo < NSIG; signo++)
04241     {
04242       int target_signo = gdb_signal_from_host (signo);
04243       if (target_signo < numsigs && pass_signals[target_signo])
04244         gdb_prdelset (&signals, signo);
04245     }
04246 
04247   if (!proc_set_traced_signals (pi, &signals))
04248     proc_error (pi, "pass_signals", __LINE__);
04249 }
04250 
04251 /* Print status information about the child process.  */
04252 
04253 static void
04254 procfs_files_info (struct target_ops *ignore)
04255 {
04256   struct inferior *inf = current_inferior ();
04257 
04258   printf_filtered (_("\tUsing the running image of %s %s via /proc.\n"),
04259                    inf->attach_flag? "attached": "child",
04260                    target_pid_to_str (inferior_ptid));
04261 }
04262 
04263 /* Stop the child process asynchronously, as when the gdb user types
04264    control-c or presses a "stop" button.  Works by sending
04265    kill(SIGINT) to the child's process group.  */
04266 
04267 static void
04268 procfs_stop (ptid_t ptid)
04269 {
04270   kill (-inferior_process_group (), SIGINT);
04271 }
04272 
04273 /* Make it die.  Wait for it to die.  Clean up after it.  Note: this
04274    should only be applied to the real process, not to an LWP, because
04275    of the check for parent-process.  If we need this to work for an
04276    LWP, it needs some more logic.  */
04277 
04278 static void
04279 unconditionally_kill_inferior (procinfo *pi)
04280 {
04281   int parent_pid;
04282 
04283   parent_pid = proc_parent_pid (pi);
04284 #ifdef PROCFS_NEED_CLEAR_CURSIG_FOR_KILL
04285   /* FIXME: use access functions.  */
04286   /* Alpha OSF/1-3.x procfs needs a clear of the current signal
04287      before the PIOCKILL, otherwise it might generate a corrupted core
04288      file for the inferior.  */
04289   if (ioctl (pi->ctl_fd, PIOCSSIG, NULL) < 0)
04290     {
04291       printf_filtered ("unconditionally_kill: SSIG failed!\n");
04292     }
04293 #endif
04294 #ifdef PROCFS_NEED_PIOCSSIG_FOR_KILL
04295   /* Alpha OSF/1-2.x procfs needs a PIOCSSIG call with a SIGKILL signal
04296      to kill the inferior, otherwise it might remain stopped with a
04297      pending SIGKILL.
04298      We do not check the result of the PIOCSSIG, the inferior might have
04299      died already.  */
04300   {
04301     gdb_siginfo_t newsiginfo;
04302 
04303     memset ((char *) &newsiginfo, 0, sizeof (newsiginfo));
04304     newsiginfo.si_signo = SIGKILL;
04305     newsiginfo.si_code = 0;
04306     newsiginfo.si_errno = 0;
04307     newsiginfo.si_pid = getpid ();
04308     newsiginfo.si_uid = getuid ();
04309     /* FIXME: use proc_set_current_signal.  */
04310     ioctl (pi->ctl_fd, PIOCSSIG, &newsiginfo);
04311   }
04312 #else /* PROCFS_NEED_PIOCSSIG_FOR_KILL */
04313   if (!proc_kill (pi, SIGKILL))
04314     proc_error (pi, "unconditionally_kill, proc_kill", __LINE__);
04315 #endif /* PROCFS_NEED_PIOCSSIG_FOR_KILL */
04316   destroy_procinfo (pi);
04317 
04318   /* If pi is GDB's child, wait for it to die.  */
04319   if (parent_pid == getpid ())
04320     /* FIXME: should we use waitpid to make sure we get the right event?
04321        Should we check the returned event?  */
04322     {
04323 #if 0
04324       int status, ret;
04325 
04326       ret = waitpid (pi->pid, &status, 0);
04327 #else
04328       wait (NULL);
04329 #endif
04330     }
04331 }
04332 
04333 /* We're done debugging it, and we want it to go away.  Then we want
04334    GDB to forget all about it.  */
04335 
04336 static void
04337 procfs_kill_inferior (struct target_ops *ops)
04338 {
04339   if (!ptid_equal (inferior_ptid, null_ptid)) /* ? */
04340     {
04341       /* Find procinfo for main process.  */
04342       procinfo *pi = find_procinfo (ptid_get_pid (inferior_ptid), 0);
04343 
04344       if (pi)
04345         unconditionally_kill_inferior (pi);
04346       target_mourn_inferior ();
04347     }
04348 }
04349 
04350 /* Forget we ever debugged this thing!  */
04351 
04352 static void
04353 procfs_mourn_inferior (struct target_ops *ops)
04354 {
04355   procinfo *pi;
04356 
04357   if (!ptid_equal (inferior_ptid, null_ptid))
04358     {
04359       /* Find procinfo for main process.  */
04360       pi = find_procinfo (ptid_get_pid (inferior_ptid), 0);
04361       if (pi)
04362         destroy_procinfo (pi);
04363     }
04364   unpush_target (ops);
04365 
04366   if (dbx_link_bpt != NULL)
04367     {
04368       deprecated_remove_raw_breakpoint (target_gdbarch (), dbx_link_bpt);
04369       dbx_link_bpt_addr = 0;
04370       dbx_link_bpt = NULL;
04371     }
04372 
04373   generic_mourn_inferior ();
04374 }
04375 
04376 /* When GDB forks to create a runnable inferior process, this function
04377    is called on the parent side of the fork.  It's job is to do
04378    whatever is necessary to make the child ready to be debugged, and
04379    then wait for the child to synchronize.  */
04380 
04381 static void
04382 procfs_init_inferior (struct target_ops *ops, int pid)
04383 {
04384   procinfo *pi;
04385   gdb_sigset_t signals;
04386   int fail;
04387   int lwpid;
04388 
04389   /* This routine called on the parent side (GDB side)
04390      after GDB forks the inferior.  */
04391   push_target (ops);
04392 
04393   if ((pi = create_procinfo (pid, 0)) == NULL)
04394     perror (_("procfs: out of memory in 'init_inferior'"));
04395 
04396   if (!open_procinfo_files (pi, FD_CTL))
04397     proc_error (pi, "init_inferior, open_proc_files", __LINE__);
04398 
04399   /*
04400     xmalloc                     // done
04401     open_procinfo_files         // done
04402     link list                   // done
04403     prfillset (trace)
04404     procfs_notice_signals
04405     prfillset (fault)
04406     prdelset (FLTPAGE)
04407     PIOCWSTOP
04408     PIOCSFAULT
04409     */
04410 
04411   /* If not stopped yet, wait for it to stop.  */
04412   if (!(proc_flags (pi) & PR_STOPPED) &&
04413       !(proc_wait_for_stop (pi)))
04414     dead_procinfo (pi, "init_inferior: wait_for_stop failed", KILL);
04415 
04416   /* Save some of the /proc state to be restored if we detach.  */
04417   /* FIXME: Why?  In case another debugger was debugging it?
04418      We're it's parent, for Ghu's sake!  */
04419   if (!proc_get_traced_signals  (pi, &pi->saved_sigset))
04420     proc_error (pi, "init_inferior, get_traced_signals", __LINE__);
04421   if (!proc_get_held_signals    (pi, &pi->saved_sighold))
04422     proc_error (pi, "init_inferior, get_held_signals", __LINE__);
04423   if (!proc_get_traced_faults   (pi, &pi->saved_fltset))
04424     proc_error (pi, "init_inferior, get_traced_faults", __LINE__);
04425   if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
04426     proc_error (pi, "init_inferior, get_traced_sysentry", __LINE__);
04427   if (!proc_get_traced_sysexit  (pi, pi->saved_exitset))
04428     proc_error (pi, "init_inferior, get_traced_sysexit", __LINE__);
04429 
04430   if ((fail = procfs_debug_inferior (pi)) != 0)
04431     proc_error (pi, "init_inferior (procfs_debug_inferior)", fail);
04432 
04433   /* FIXME: logically, we should really be turning OFF run-on-last-close,
04434      and possibly even turning ON kill-on-last-close at this point.  But
04435      I can't make that change without careful testing which I don't have
04436      time to do right now...  */
04437   /* Turn on run-on-last-close flag so that the child
04438      will die if GDB goes away for some reason.  */
04439   if (!proc_set_run_on_last_close (pi))
04440     proc_error (pi, "init_inferior, set_RLC", __LINE__);
04441 
04442   /* We now have have access to the lwpid of the main thread/lwp.  */
04443   lwpid = proc_get_current_thread (pi);
04444 
04445   /* Create a procinfo for the main lwp.  */
04446   create_procinfo (pid, lwpid);
04447 
04448   /* We already have a main thread registered in the thread table at
04449      this point, but it didn't have any lwp info yet.  Notify the core
04450      about it.  This changes inferior_ptid as well.  */
04451   thread_change_ptid (pid_to_ptid (pid),
04452                       ptid_build (pid, lwpid, 0));
04453 
04454   /* Typically two, one trap to exec the shell, one to exec the
04455      program being debugged.  Defined by "inferior.h".  */
04456   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
04457 
04458 #ifdef SYS_syssgi
04459   /* On mips-irix, we need to stop the inferior early enough during
04460      the startup phase in order to be able to load the shared library
04461      symbols and insert the breakpoints that are located in these shared
04462      libraries.  Stopping at the program entry point is not good enough
04463      because the -init code is executed before the execution reaches
04464      that point.
04465 
04466      So what we need to do is to insert a breakpoint in the runtime
04467      loader (rld), more precisely in __dbx_link().  This procedure is
04468      called by rld once all shared libraries have been mapped, but before
04469      the -init code is executed.  Unfortuantely, this is not straightforward,
04470      as rld is not part of the executable we are running, and thus we need
04471      the inferior to run until rld itself has been mapped in memory.
04472 
04473      For this, we trace all syssgi() syscall exit events.  Each time
04474      we detect such an event, we iterate over each text memory maps,
04475      get its associated fd, and scan the symbol table for __dbx_link().
04476      When found, we know that rld has been mapped, and that we can insert
04477      the breakpoint at the symbol address.  Once the dbx_link() breakpoint
04478      has been inserted, the syssgi() notifications are no longer necessary,
04479      so they should be canceled.  */
04480   proc_trace_syscalls_1 (pi, SYS_syssgi, PR_SYSEXIT, FLAG_SET, 0);
04481 #endif
04482 }
04483 
04484 /* When GDB forks to create a new process, this function is called on
04485    the child side of the fork before GDB exec's the user program.  Its
04486    job is to make the child minimally debuggable, so that the parent
04487    GDB process can connect to the child and take over.  This function
04488    should do only the minimum to make that possible, and to
04489    synchronize with the parent process.  The parent process should
04490    take care of the details.  */
04491 
04492 static void
04493 procfs_set_exec_trap (void)
04494 {
04495   /* This routine called on the child side (inferior side)
04496      after GDB forks the inferior.  It must use only local variables,
04497      because it may be sharing data space with its parent.  */
04498 
04499   procinfo *pi;
04500   sysset_t *exitset;
04501 
04502   if ((pi = create_procinfo (getpid (), 0)) == NULL)
04503     perror_with_name (_("procfs: create_procinfo failed in child."));
04504 
04505   if (open_procinfo_files (pi, FD_CTL) == 0)
04506     {
04507       proc_warn (pi, "set_exec_trap, open_proc_files", __LINE__);
04508       gdb_flush (gdb_stderr);
04509       /* No need to call "dead_procinfo", because we're going to
04510          exit.  */
04511       _exit (127);
04512     }
04513 
04514 #ifdef PRFS_STOPEXEC    /* defined on OSF */
04515   /* OSF method for tracing exec syscalls.  Quoting:
04516      Under Alpha OSF/1 we have to use a PIOCSSPCACT ioctl to trace
04517      exits from exec system calls because of the user level loader.  */
04518   /* FIXME: make nice and maybe move into an access function.  */
04519   {
04520     int prfs_flags;
04521 
04522     if (ioctl (pi->ctl_fd, PIOCGSPCACT, &prfs_flags) < 0)
04523       {
04524         proc_warn (pi, "set_exec_trap (PIOCGSPCACT)", __LINE__);
04525         gdb_flush (gdb_stderr);
04526         _exit (127);
04527       }
04528     prfs_flags |= PRFS_STOPEXEC;
04529 
04530     if (ioctl (pi->ctl_fd, PIOCSSPCACT, &prfs_flags) < 0)
04531       {
04532         proc_warn (pi, "set_exec_trap (PIOCSSPCACT)", __LINE__);
04533         gdb_flush (gdb_stderr);
04534         _exit (127);
04535       }
04536   }
04537 #else /* not PRFS_STOPEXEC */
04538   /* Everyone else's (except OSF) method for tracing exec syscalls.  */
04539   /* GW: Rationale...
04540      Not all systems with /proc have all the exec* syscalls with the same
04541      names.  On the SGI, for example, there is no SYS_exec, but there
04542      *is* a SYS_execv.  So, we try to account for that.  */
04543 
04544   exitset = sysset_t_alloc (pi);
04545   gdb_premptysysset (exitset);
04546 #ifdef SYS_exec
04547   gdb_praddsysset (exitset, SYS_exec);
04548 #endif
04549 #ifdef SYS_execve
04550   gdb_praddsysset (exitset, SYS_execve);
04551 #endif
04552 #ifdef SYS_execv
04553   gdb_praddsysset (exitset, SYS_execv);
04554 #endif
04555 #ifdef DYNAMIC_SYSCALLS
04556   {
04557     int callnum = find_syscall (pi, "execve");
04558 
04559     if (callnum >= 0)
04560       gdb_praddsysset (exitset, callnum);
04561 
04562     callnum = find_syscall (pi, "ra_execve");
04563     if (callnum >= 0)
04564       gdb_praddsysset (exitset, callnum);
04565   }
04566 #endif /* DYNAMIC_SYSCALLS */
04567 
04568   if (!proc_set_traced_sysexit (pi, exitset))
04569     {
04570       proc_warn (pi, "set_exec_trap, set_traced_sysexit", __LINE__);
04571       gdb_flush (gdb_stderr);
04572       _exit (127);
04573     }
04574 #endif /* PRFS_STOPEXEC */
04575 
04576   /* FIXME: should this be done in the parent instead?  */
04577   /* Turn off inherit on fork flag so that all grand-children
04578      of gdb start with tracing flags cleared.  */
04579   if (!proc_unset_inherit_on_fork (pi))
04580     proc_warn (pi, "set_exec_trap, unset_inherit", __LINE__);
04581 
04582   /* Turn off run on last close flag, so that the child process
04583      cannot run away just because we close our handle on it.
04584      We want it to wait for the parent to attach.  */
04585   if (!proc_unset_run_on_last_close (pi))
04586     proc_warn (pi, "set_exec_trap, unset_RLC", __LINE__);
04587 
04588   /* FIXME: No need to destroy the procinfo --
04589      we have our own address space, and we're about to do an exec!  */
04590   /*destroy_procinfo (pi);*/
04591 }
04592 
04593 /* This function is called BEFORE gdb forks the inferior process.  Its
04594    only real responsibility is to set things up for the fork, and tell
04595    GDB which two functions to call after the fork (one for the parent,
04596    and one for the child).
04597 
04598    This function does a complicated search for a unix shell program,
04599    which it then uses to parse arguments and environment variables to
04600    be sent to the child.  I wonder whether this code could not be
04601    abstracted out and shared with other unix targets such as
04602    inf-ptrace?  */
04603 
04604 static void
04605 procfs_create_inferior (struct target_ops *ops, char *exec_file,
04606                         char *allargs, char **env, int from_tty)
04607 {
04608   char *shell_file = getenv ("SHELL");
04609   char *tryname;
04610   int pid;
04611 
04612   if (shell_file != NULL && strchr (shell_file, '/') == NULL)
04613     {
04614 
04615       /* We will be looking down the PATH to find shell_file.  If we
04616          just do this the normal way (via execlp, which operates by
04617          attempting an exec for each element of the PATH until it
04618          finds one which succeeds), then there will be an exec for
04619          each failed attempt, each of which will cause a PR_SYSEXIT
04620          stop, and we won't know how to distinguish the PR_SYSEXIT's
04621          for these failed execs with the ones for successful execs
04622          (whether the exec has succeeded is stored at that time in the
04623          carry bit or some such architecture-specific and
04624          non-ABI-specified place).
04625 
04626          So I can't think of anything better than to search the PATH
04627          now.  This has several disadvantages: (1) There is a race
04628          condition; if we find a file now and it is deleted before we
04629          exec it, we lose, even if the deletion leaves a valid file
04630          further down in the PATH, (2) there is no way to know exactly
04631          what an executable (in the sense of "capable of being
04632          exec'd") file is.  Using access() loses because it may lose
04633          if the caller is the superuser; failing to use it loses if
04634          there are ACLs or some such.  */
04635 
04636       char *p;
04637       char *p1;
04638       /* FIXME-maybe: might want "set path" command so user can change what
04639          path is used from within GDB.  */
04640       char *path = getenv ("PATH");
04641       int len;
04642       struct stat statbuf;
04643 
04644       if (path == NULL)
04645         path = "/bin:/usr/bin";
04646 
04647       tryname = alloca (strlen (path) + strlen (shell_file) + 2);
04648       for (p = path; p != NULL; p = p1 ? p1 + 1: NULL)
04649         {
04650           p1 = strchr (p, ':');
04651           if (p1 != NULL)
04652             len = p1 - p;
04653           else
04654             len = strlen (p);
04655           strncpy (tryname, p, len);
04656           tryname[len] = '\0';
04657           strcat (tryname, "/");
04658           strcat (tryname, shell_file);
04659           if (access (tryname, X_OK) < 0)
04660             continue;
04661           if (stat (tryname, &statbuf) < 0)
04662             continue;
04663           if (!S_ISREG (statbuf.st_mode))
04664             /* We certainly need to reject directories.  I'm not quite
04665                as sure about FIFOs, sockets, etc., but I kind of doubt
04666                that people want to exec() these things.  */
04667             continue;
04668           break;
04669         }
04670       if (p == NULL)
04671         /* Not found.  This must be an error rather than merely passing
04672            the file to execlp(), because execlp() would try all the
04673            exec()s, causing GDB to get confused.  */
04674         error (_("procfs:%d -- Can't find shell %s in PATH"),
04675                __LINE__, shell_file);
04676 
04677       shell_file = tryname;
04678     }
04679 
04680   pid = fork_inferior (exec_file, allargs, env, procfs_set_exec_trap,
04681                        NULL, NULL, shell_file, NULL);
04682 
04683   procfs_init_inferior (ops, pid);
04684 }
04685 
04686 /* An observer for the "inferior_created" event.  */
04687 
04688 static void
04689 procfs_inferior_created (struct target_ops *ops, int from_tty)
04690 {
04691 #ifdef SYS_syssgi
04692   /* Make sure to cancel the syssgi() syscall-exit notifications.
04693      They should normally have been removed by now, but they may still
04694      be activated if the inferior doesn't use shared libraries, or if
04695      we didn't locate __dbx_link, or if we never stopped in __dbx_link.
04696      See procfs_init_inferior() for more details.
04697 
04698      Since these notifications are only ever enabled when we spawned
04699      the inferior ourselves, there is nothing to do when the inferior
04700      was created by attaching to an already running process, or when
04701      debugging a core file.  */
04702   if (current_inferior ()->attach_flag || !target_can_run (&current_target))
04703     return;
04704 
04705   proc_trace_syscalls_1 (find_procinfo_or_die (ptid_get_pid (inferior_ptid),
04706                          0), SYS_syssgi, PR_SYSEXIT, FLAG_RESET, 0);
04707 #endif
04708 }
04709 
04710 /* Callback for find_new_threads.  Calls "add_thread".  */
04711 
04712 static int
04713 procfs_notice_thread (procinfo *pi, procinfo *thread, void *ptr)
04714 {
04715   ptid_t gdb_threadid = ptid_build (pi->pid, thread->tid, 0);
04716 
04717   if (!in_thread_list (gdb_threadid) || is_exited (gdb_threadid))
04718     add_thread (gdb_threadid);
04719 
04720   return 0;
04721 }
04722 
04723 /* Query all the threads that the target knows about, and give them
04724    back to GDB to add to its list.  */
04725 
04726 static void
04727 procfs_find_new_threads (struct target_ops *ops)
04728 {
04729   procinfo *pi;
04730 
04731   /* Find procinfo for main process.  */
04732   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
04733   proc_update_threads (pi);
04734   proc_iterate_over_threads (pi, procfs_notice_thread, NULL);
04735 }
04736 
04737 /* Return true if the thread is still 'alive'.  This guy doesn't
04738    really seem to be doing his job.  Got to investigate how to tell
04739    when a thread is really gone.  */
04740 
04741 static int
04742 procfs_thread_alive (struct target_ops *ops, ptid_t ptid)
04743 {
04744   int proc, thread;
04745   procinfo *pi;
04746 
04747   proc    = ptid_get_pid (ptid);
04748   thread  = ptid_get_lwp (ptid);
04749   /* If I don't know it, it ain't alive!  */
04750   if ((pi = find_procinfo (proc, thread)) == NULL)
04751     return 0;
04752 
04753   /* If I can't get its status, it ain't alive!
04754      What's more, I need to forget about it!  */
04755   if (!proc_get_status (pi))
04756     {
04757       destroy_procinfo (pi);
04758       return 0;
04759     }
04760   /* I couldn't have got its status if it weren't alive, so it's
04761      alive.  */
04762   return 1;
04763 }
04764 
04765 /* Convert PTID to a string.  Returns the string in a static
04766    buffer.  */
04767 
04768 static char *
04769 procfs_pid_to_str (struct target_ops *ops, ptid_t ptid)
04770 {
04771   static char buf[80];
04772 
04773   if (ptid_get_lwp (ptid) == 0)
04774     sprintf (buf, "process %d", ptid_get_pid (ptid));
04775   else
04776     sprintf (buf, "LWP %ld", ptid_get_lwp (ptid));
04777 
04778   return buf;
04779 }
04780 
04781 /* Insert a watchpoint.  */
04782 
04783 static int
04784 procfs_set_watchpoint (ptid_t ptid, CORE_ADDR addr, int len, int rwflag,
04785                        int after)
04786 {
04787 #ifndef AIX5
04788   int       pflags = 0;
04789   procinfo *pi;
04790 
04791   pi = find_procinfo_or_die (ptid_get_pid (ptid) == -1 ?
04792                              ptid_get_pid (inferior_ptid) : ptid_get_pid (ptid),
04793                              0);
04794 
04795   /* Translate from GDB's flags to /proc's.  */
04796   if (len > 0)  /* len == 0 means delete watchpoint.  */
04797     {
04798       switch (rwflag) {         /* FIXME: need an enum!  */
04799       case hw_write:            /* default watchpoint (write) */
04800         pflags = WRITE_WATCHFLAG;
04801         break;
04802       case hw_read:             /* read watchpoint */
04803         pflags = READ_WATCHFLAG;
04804         break;
04805       case hw_access:           /* access watchpoint */
04806         pflags = READ_WATCHFLAG | WRITE_WATCHFLAG;
04807         break;
04808       case hw_execute:          /* execution HW breakpoint */
04809         pflags = EXEC_WATCHFLAG;
04810         break;
04811       default:                  /* Something weird.  Return error.  */
04812         return -1;
04813       }
04814       if (after)                /* Stop after r/w access is completed.  */
04815         pflags |= AFTER_WATCHFLAG;
04816     }
04817 
04818   if (!proc_set_watchpoint (pi, addr, len, pflags))
04819     {
04820       if (errno == E2BIG)       /* Typical error for no resources.  */
04821         return -1;              /* fail */
04822       /* GDB may try to remove the same watchpoint twice.
04823          If a remove request returns no match, don't error.  */
04824       if (errno == ESRCH && len == 0)
04825         return 0;               /* ignore */
04826       proc_error (pi, "set_watchpoint", __LINE__);
04827     }
04828 #endif /* AIX5 */
04829   return 0;
04830 }
04831 
04832 /* Return non-zero if we can set a hardware watchpoint of type TYPE.  TYPE
04833    is one of bp_hardware_watchpoint, bp_read_watchpoint, bp_write_watchpoint,
04834    or bp_hardware_watchpoint.  CNT is the number of watchpoints used so
04835    far.
04836 
04837    Note:  procfs_can_use_hw_breakpoint() is not yet used by all
04838    procfs.c targets due to the fact that some of them still define
04839    target_can_use_hardware_watchpoint.  */
04840 
04841 static int
04842 procfs_can_use_hw_breakpoint (int type, int cnt, int othertype)
04843 {
04844   /* Due to the way that proc_set_watchpoint() is implemented, host
04845      and target pointers must be of the same size.  If they are not,
04846      we can't use hardware watchpoints.  This limitation is due to the
04847      fact that proc_set_watchpoint() calls
04848      procfs_address_to_host_pointer(); a close inspection of
04849      procfs_address_to_host_pointer will reveal that an internal error
04850      will be generated when the host and target pointer sizes are
04851      different.  */
04852   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
04853 
04854   if (sizeof (void *) != TYPE_LENGTH (ptr_type))
04855     return 0;
04856 
04857   /* Other tests here???  */
04858 
04859   return 1;
04860 }
04861 
04862 /* Returns non-zero if process is stopped on a hardware watchpoint
04863    fault, else returns zero.  */
04864 
04865 static int
04866 procfs_stopped_by_watchpoint (void)
04867 {
04868   procinfo *pi;
04869 
04870   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
04871 
04872   if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
04873     {
04874       if (proc_why (pi) == PR_FAULTED)
04875         {
04876 #ifdef FLTWATCH
04877           if (proc_what (pi) == FLTWATCH)
04878             return 1;
04879 #endif
04880 #ifdef FLTKWATCH
04881           if (proc_what (pi) == FLTKWATCH)
04882             return 1;
04883 #endif
04884         }
04885     }
04886   return 0;
04887 }
04888 
04889 /* Returns 1 if the OS knows the position of the triggered watchpoint,
04890    and sets *ADDR to that address.  Returns 0 if OS cannot report that
04891    address.  This function is only called if
04892    procfs_stopped_by_watchpoint returned 1, thus no further checks are
04893    done.  The function also assumes that ADDR is not NULL.  */
04894 
04895 static int
04896 procfs_stopped_data_address (struct target_ops *targ, CORE_ADDR *addr)
04897 {
04898   procinfo *pi;
04899 
04900   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
04901   return proc_watchpoint_address (pi, addr);
04902 }
04903 
04904 static int
04905 procfs_insert_watchpoint (CORE_ADDR addr, int len, int type,
04906                           struct expression *cond)
04907 {
04908   if (!target_have_steppable_watchpoint
04909       && !gdbarch_have_nonsteppable_watchpoint (target_gdbarch ()))
04910     {
04911       /* When a hardware watchpoint fires off the PC will be left at
04912          the instruction following the one which caused the
04913          watchpoint.  It will *NOT* be necessary for GDB to step over
04914          the watchpoint.  */
04915       return procfs_set_watchpoint (inferior_ptid, addr, len, type, 1);
04916     }
04917   else
04918     {
04919       /* When a hardware watchpoint fires off the PC will be left at
04920          the instruction which caused the watchpoint.  It will be
04921          necessary for GDB to step over the watchpoint.  */
04922       return procfs_set_watchpoint (inferior_ptid, addr, len, type, 0);
04923     }
04924 }
04925 
04926 static int
04927 procfs_remove_watchpoint (CORE_ADDR addr, int len, int type,
04928                           struct expression *cond)
04929 {
04930   return procfs_set_watchpoint (inferior_ptid, addr, 0, 0, 0);
04931 }
04932 
04933 static int
04934 procfs_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
04935 {
04936   /* The man page for proc(4) on Solaris 2.6 and up says that the
04937      system can support "thousands" of hardware watchpoints, but gives
04938      no method for finding out how many; It doesn't say anything about
04939      the allowed size for the watched area either.  So we just tell
04940      GDB 'yes'.  */
04941   return 1;
04942 }
04943 
04944 void
04945 procfs_use_watchpoints (struct target_ops *t)
04946 {
04947   t->to_stopped_by_watchpoint = procfs_stopped_by_watchpoint;
04948   t->to_insert_watchpoint = procfs_insert_watchpoint;
04949   t->to_remove_watchpoint = procfs_remove_watchpoint;
04950   t->to_region_ok_for_hw_watchpoint = procfs_region_ok_for_hw_watchpoint;
04951   t->to_can_use_hw_breakpoint = procfs_can_use_hw_breakpoint;
04952   t->to_stopped_data_address = procfs_stopped_data_address;
04953 }
04954 
04955 /* Memory Mappings Functions: */
04956 
04957 /* Call a callback function once for each mapping, passing it the
04958    mapping, an optional secondary callback function, and some optional
04959    opaque data.  Quit and return the first non-zero value returned
04960    from the callback.
04961 
04962    PI is the procinfo struct for the process to be mapped.  FUNC is
04963    the callback function to be called by this iterator.  DATA is the
04964    optional opaque data to be passed to the callback function.
04965    CHILD_FUNC is the optional secondary function pointer to be passed
04966    to the child function.  Returns the first non-zero return value
04967    from the callback function, or zero.  */
04968 
04969 static int
04970 iterate_over_mappings (procinfo *pi, find_memory_region_ftype child_func,
04971                        void *data,
04972                        int (*func) (struct prmap *map,
04973                                     find_memory_region_ftype child_func,
04974                                     void *data))
04975 {
04976   char pathname[MAX_PROC_NAME_SIZE];
04977   struct prmap *prmaps;
04978   struct prmap *prmap;
04979   int funcstat;
04980   int map_fd;
04981   int nmap;
04982   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
04983 #ifdef NEW_PROC_API
04984   struct stat sbuf;
04985 #endif
04986 
04987   /* Get the number of mappings, allocate space,
04988      and read the mappings into prmaps.  */
04989 #ifdef NEW_PROC_API
04990   /* Open map fd.  */
04991   sprintf (pathname, "/proc/%d/map", pi->pid);
04992   if ((map_fd = open (pathname, O_RDONLY)) < 0)
04993     proc_error (pi, "iterate_over_mappings (open)", __LINE__);
04994 
04995   /* Make sure it gets closed again.  */
04996   make_cleanup_close (map_fd);
04997 
04998   /* Use stat to determine the file size, and compute
04999      the number of prmap_t objects it contains.  */
05000   if (fstat (map_fd, &sbuf) != 0)
05001     proc_error (pi, "iterate_over_mappings (fstat)", __LINE__);
05002 
05003   nmap = sbuf.st_size / sizeof (prmap_t);
05004   prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
05005   if (read (map_fd, (char *) prmaps, nmap * sizeof (*prmaps))
05006       != (nmap * sizeof (*prmaps)))
05007     proc_error (pi, "iterate_over_mappings (read)", __LINE__);
05008 #else
05009   /* Use ioctl command PIOCNMAP to get number of mappings.  */
05010   if (ioctl (pi->ctl_fd, PIOCNMAP, &nmap) != 0)
05011     proc_error (pi, "iterate_over_mappings (PIOCNMAP)", __LINE__);
05012 
05013   prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
05014   if (ioctl (pi->ctl_fd, PIOCMAP, prmaps) != 0)
05015     proc_error (pi, "iterate_over_mappings (PIOCMAP)", __LINE__);
05016 #endif
05017 
05018   for (prmap = prmaps; nmap > 0; prmap++, nmap--)
05019     if ((funcstat = (*func) (prmap, child_func, data)) != 0)
05020       {
05021         do_cleanups (cleanups);
05022         return funcstat;
05023       }
05024 
05025   do_cleanups (cleanups);
05026   return 0;
05027 }
05028 
05029 /* Implements the to_find_memory_regions method.  Calls an external
05030    function for each memory region.
05031    Returns the integer value returned by the callback.  */
05032 
05033 static int
05034 find_memory_regions_callback (struct prmap *map,
05035                               find_memory_region_ftype func, void *data)
05036 {
05037   return (*func) ((CORE_ADDR) map->pr_vaddr,
05038                   map->pr_size,
05039                   (map->pr_mflags & MA_READ) != 0,
05040                   (map->pr_mflags & MA_WRITE) != 0,
05041                   (map->pr_mflags & MA_EXEC) != 0,
05042                   1, /* MODIFIED is unknown, pass it as true.  */
05043                   data);
05044 }
05045 
05046 /* External interface.  Calls a callback function once for each
05047    mapped memory region in the child process, passing as arguments:
05048 
05049         CORE_ADDR virtual_address,
05050         unsigned long size,
05051         int read,       TRUE if region is readable by the child
05052         int write,      TRUE if region is writable by the child
05053         int execute     TRUE if region is executable by the child.
05054 
05055    Stops iterating and returns the first non-zero value returned by
05056    the callback.  */
05057 
05058 static int
05059 proc_find_memory_regions (find_memory_region_ftype func, void *data)
05060 {
05061   procinfo *pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
05062 
05063   return iterate_over_mappings (pi, func, data,
05064                                 find_memory_regions_callback);
05065 }
05066 
05067 /* Returns an ascii representation of a memory mapping's flags.  */
05068 
05069 static char *
05070 mappingflags (long flags)
05071 {
05072   static char asciiflags[8];
05073 
05074   strcpy (asciiflags, "-------");
05075 #if defined (MA_PHYS)
05076   if (flags & MA_PHYS)
05077     asciiflags[0] = 'd';
05078 #endif
05079   if (flags & MA_STACK)
05080     asciiflags[1] = 's';
05081   if (flags & MA_BREAK)
05082     asciiflags[2] = 'b';
05083   if (flags & MA_SHARED)
05084     asciiflags[3] = 's';
05085   if (flags & MA_READ)
05086     asciiflags[4] = 'r';
05087   if (flags & MA_WRITE)
05088     asciiflags[5] = 'w';
05089   if (flags & MA_EXEC)
05090     asciiflags[6] = 'x';
05091   return (asciiflags);
05092 }
05093 
05094 /* Callback function, does the actual work for 'info proc
05095    mappings'.  */
05096 
05097 static int
05098 info_mappings_callback (struct prmap *map, find_memory_region_ftype ignore,
05099                         void *unused)
05100 {
05101   unsigned int pr_off;
05102 
05103 #ifdef PCAGENT  /* Horrible hack: only defined on Solaris 2.6+ */
05104   pr_off = (unsigned int) map->pr_offset;
05105 #else
05106   pr_off = map->pr_off;
05107 #endif
05108 
05109   if (gdbarch_addr_bit (target_gdbarch ()) == 32)
05110     printf_filtered ("\t%#10lx %#10lx %#10lx %#10x %7s\n",
05111                      (unsigned long) map->pr_vaddr,
05112                      (unsigned long) map->pr_vaddr + map->pr_size - 1,
05113                      (unsigned long) map->pr_size,
05114                      pr_off,
05115                      mappingflags (map->pr_mflags));
05116   else
05117     printf_filtered ("  %#18lx %#18lx %#10lx %#10x %7s\n",
05118                      (unsigned long) map->pr_vaddr,
05119                      (unsigned long) map->pr_vaddr + map->pr_size - 1,
05120                      (unsigned long) map->pr_size,
05121                      pr_off,
05122                      mappingflags (map->pr_mflags));
05123 
05124   return 0;
05125 }
05126 
05127 /* Implement the "info proc mappings" subcommand.  */
05128 
05129 static void
05130 info_proc_mappings (procinfo *pi, int summary)
05131 {
05132   if (summary)
05133     return;     /* No output for summary mode.  */
05134 
05135   printf_filtered (_("Mapped address spaces:\n\n"));
05136   if (gdbarch_ptr_bit (target_gdbarch ()) == 32)
05137     printf_filtered ("\t%10s %10s %10s %10s %7s\n",
05138                      "Start Addr",
05139                      "  End Addr",
05140                      "      Size",
05141                      "    Offset",
05142                      "Flags");
05143   else
05144     printf_filtered ("  %18s %18s %10s %10s %7s\n",
05145                      "Start Addr",
05146                      "  End Addr",
05147                      "      Size",
05148                      "    Offset",
05149                      "Flags");
05150 
05151   iterate_over_mappings (pi, NULL, NULL, info_mappings_callback);
05152   printf_filtered ("\n");
05153 }
05154 
05155 /* Implement the "info proc" command.  */
05156 
05157 static void
05158 procfs_info_proc (struct target_ops *ops, char *args,
05159                   enum info_proc_what what)
05160 {
05161   struct cleanup *old_chain;
05162   procinfo *process  = NULL;
05163   procinfo *thread   = NULL;
05164   char    **argv     = NULL;
05165   char     *tmp      = NULL;
05166   int       pid      = 0;
05167   int       tid      = 0;
05168   int       mappings = 0;
05169 
05170   switch (what)
05171     {
05172     case IP_MINIMAL:
05173       break;
05174 
05175     case IP_MAPPINGS:
05176     case IP_ALL:
05177       mappings = 1;
05178       break;
05179 
05180     default:
05181       error (_("Not supported on this target."));
05182     }
05183 
05184   old_chain = make_cleanup (null_cleanup, 0);
05185   if (args)
05186     {
05187       argv = gdb_buildargv (args);
05188       make_cleanup_freeargv (argv);
05189     }
05190   while (argv != NULL && *argv != NULL)
05191     {
05192       if (isdigit (argv[0][0]))
05193         {
05194           pid = strtoul (argv[0], &tmp, 10);
05195           if (*tmp == '/')
05196             tid = strtoul (++tmp, NULL, 10);
05197         }
05198       else if (argv[0][0] == '/')
05199         {
05200           tid = strtoul (argv[0] + 1, NULL, 10);
05201         }
05202       argv++;
05203     }
05204   if (pid == 0)
05205     pid = ptid_get_pid (inferior_ptid);
05206   if (pid == 0)
05207     error (_("No current process: you must name one."));
05208   else
05209     {
05210       /* Have pid, will travel.
05211          First see if it's a process we're already debugging.  */
05212       process = find_procinfo (pid, 0);
05213        if (process == NULL)
05214          {
05215            /* No.  So open a procinfo for it, but
05216               remember to close it again when finished.  */
05217            process = create_procinfo (pid, 0);
05218            make_cleanup (do_destroy_procinfo_cleanup, process);
05219            if (!open_procinfo_files (process, FD_CTL))
05220              proc_error (process, "info proc, open_procinfo_files", __LINE__);
05221          }
05222     }
05223   if (tid != 0)
05224     thread = create_procinfo (pid, tid);
05225 
05226   if (process)
05227     {
05228       printf_filtered (_("process %d flags:\n"), process->pid);
05229       proc_prettyprint_flags (proc_flags (process), 1);
05230       if (proc_flags (process) & (PR_STOPPED | PR_ISTOP))
05231         proc_prettyprint_why (proc_why (process), proc_what (process), 1);
05232       if (proc_get_nthreads (process) > 1)
05233         printf_filtered ("Process has %d threads.\n",
05234                          proc_get_nthreads (process));
05235     }
05236   if (thread)
05237     {
05238       printf_filtered (_("thread %d flags:\n"), thread->tid);
05239       proc_prettyprint_flags (proc_flags (thread), 1);
05240       if (proc_flags (thread) & (PR_STOPPED | PR_ISTOP))
05241         proc_prettyprint_why (proc_why (thread), proc_what (thread), 1);
05242     }
05243 
05244   if (mappings)
05245     {
05246       info_proc_mappings (process, 0);
05247     }
05248 
05249   do_cleanups (old_chain);
05250 }
05251 
05252 /* Modify the status of the system call identified by SYSCALLNUM in
05253    the set of syscalls that are currently traced/debugged.
05254 
05255    If ENTRY_OR_EXIT is set to PR_SYSENTRY, then the entry syscalls set
05256    will be updated.  Otherwise, the exit syscalls set will be updated.
05257 
05258    If MODE is FLAG_SET, then traces will be enabled.  Otherwise, they
05259    will be disabled.  */
05260 
05261 static void
05262 proc_trace_syscalls_1 (procinfo *pi, int syscallnum, int entry_or_exit,
05263                        int mode, int from_tty)
05264 {
05265   sysset_t *sysset;
05266 
05267   if (entry_or_exit == PR_SYSENTRY)
05268     sysset = proc_get_traced_sysentry (pi, NULL);
05269   else
05270     sysset = proc_get_traced_sysexit (pi, NULL);
05271 
05272   if (sysset == NULL)
05273     proc_error (pi, "proc-trace, get_traced_sysset", __LINE__);
05274 
05275   if (mode == FLAG_SET)
05276     gdb_praddsysset (sysset, syscallnum);
05277   else
05278     gdb_prdelsysset (sysset, syscallnum);
05279 
05280   if (entry_or_exit == PR_SYSENTRY)
05281     {
05282       if (!proc_set_traced_sysentry (pi, sysset))
05283         proc_error (pi, "proc-trace, set_traced_sysentry", __LINE__);
05284     }
05285   else
05286     {
05287       if (!proc_set_traced_sysexit (pi, sysset))
05288         proc_error (pi, "proc-trace, set_traced_sysexit", __LINE__);
05289     }
05290 }
05291 
05292 static void
05293 proc_trace_syscalls (char *args, int from_tty, int entry_or_exit, int mode)
05294 {
05295   procinfo *pi;
05296 
05297   if (ptid_get_pid (inferior_ptid) <= 0)
05298     error (_("you must be debugging a process to use this command."));
05299 
05300   if (args == NULL || args[0] == 0)
05301     error_no_arg (_("system call to trace"));
05302 
05303   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
05304   if (isdigit (args[0]))
05305     {
05306       const int syscallnum = atoi (args);
05307 
05308       proc_trace_syscalls_1 (pi, syscallnum, entry_or_exit, mode, from_tty);
05309     }
05310 }
05311 
05312 static void
05313 proc_trace_sysentry_cmd (char *args, int from_tty)
05314 {
05315   proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_SET);
05316 }
05317 
05318 static void
05319 proc_trace_sysexit_cmd (char *args, int from_tty)
05320 {
05321   proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_SET);
05322 }
05323 
05324 static void
05325 proc_untrace_sysentry_cmd (char *args, int from_tty)
05326 {
05327   proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_RESET);
05328 }
05329 
05330 static void
05331 proc_untrace_sysexit_cmd (char *args, int from_tty)
05332 {
05333   proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_RESET);
05334 }
05335 
05336 
05337 /* Provide a prototype to silence -Wmissing-prototypes.  */
05338 extern void _initialize_procfs (void);
05339 
05340 void
05341 _initialize_procfs (void)
05342 {
05343   observer_attach_inferior_created (procfs_inferior_created);
05344 
05345   add_com ("proc-trace-entry", no_class, proc_trace_sysentry_cmd,
05346            _("Give a trace of entries into the syscall."));
05347   add_com ("proc-trace-exit", no_class, proc_trace_sysexit_cmd,
05348            _("Give a trace of exits from the syscall."));
05349   add_com ("proc-untrace-entry", no_class, proc_untrace_sysentry_cmd,
05350            _("Cancel a trace of entries into the syscall."));
05351   add_com ("proc-untrace-exit", no_class, proc_untrace_sysexit_cmd,
05352            _("Cancel a trace of exits from the syscall."));
05353 }
05354 
05355 /* =================== END, GDB  "MODULE" =================== */
05356 
05357 
05358 
05359 /* miscellaneous stubs: */
05360 
05361 /* The following satisfy a few random symbols mostly created by the
05362    solaris threads implementation, which I will chase down later.  */
05363 
05364 /* Return a pid for which we guarantee we will be able to find a
05365    'live' procinfo.  */
05366 
05367 ptid_t
05368 procfs_first_available (void)
05369 {
05370   return pid_to_ptid (procinfo_list ? procinfo_list->pid : -1);
05371 }
05372 
05373 /* ===================  GCORE .NOTE "MODULE" =================== */
05374 #if defined (PIOCOPENLWP) || defined (PCAGENT)
05375 /* gcore only implemented on solaris (so far) */
05376 
05377 static char *
05378 procfs_do_thread_registers (bfd *obfd, ptid_t ptid,
05379                             char *note_data, int *note_size,
05380                             enum gdb_signal stop_signal)
05381 {
05382   struct regcache *regcache = get_thread_regcache (ptid);
05383   gdb_gregset_t gregs;
05384   gdb_fpregset_t fpregs;
05385   unsigned long merged_pid;
05386   struct cleanup *old_chain;
05387 
05388   merged_pid = ptid_get_lwp (ptid) << 16 | ptid_get_pid (ptid);
05389 
05390   /* This part is the old method for fetching registers.
05391      It should be replaced by the newer one using regsets
05392      once it is implemented in this platform:
05393      gdbarch_regset_from_core_section() and regset->collect_regset().  */
05394 
05395   old_chain = save_inferior_ptid ();
05396   inferior_ptid = ptid;
05397   target_fetch_registers (regcache, -1);
05398 
05399   fill_gregset (regcache, &gregs, -1);
05400 #if defined (NEW_PROC_API)
05401   note_data = (char *) elfcore_write_lwpstatus (obfd,
05402                                                 note_data,
05403                                                 note_size,
05404                                                 merged_pid,
05405                                                 stop_signal,
05406                                                 &gregs);
05407 #else
05408   note_data = (char *) elfcore_write_prstatus (obfd,
05409                                                note_data,
05410                                                note_size,
05411                                                merged_pid,
05412                                                stop_signal,
05413                                                &gregs);
05414 #endif
05415   fill_fpregset (regcache, &fpregs, -1);
05416   note_data = (char *) elfcore_write_prfpreg (obfd,
05417                                               note_data,
05418                                               note_size,
05419                                               &fpregs,
05420                                               sizeof (fpregs));
05421 
05422   do_cleanups (old_chain);
05423 
05424   return note_data;
05425 }
05426 
05427 struct procfs_corefile_thread_data {
05428   bfd *obfd;
05429   char *note_data;
05430   int *note_size;
05431   enum gdb_signal stop_signal;
05432 };
05433 
05434 static int
05435 procfs_corefile_thread_callback (procinfo *pi, procinfo *thread, void *data)
05436 {
05437   struct procfs_corefile_thread_data *args = data;
05438 
05439   if (pi != NULL)
05440     {
05441       ptid_t ptid = ptid_build (pi->pid, thread->tid, 0);
05442 
05443       args->note_data = procfs_do_thread_registers (args->obfd, ptid,
05444                                                     args->note_data,
05445                                                     args->note_size,
05446                                                     args->stop_signal);
05447     }
05448   return 0;
05449 }
05450 
05451 static int
05452 find_signalled_thread (struct thread_info *info, void *data)
05453 {
05454   if (info->suspend.stop_signal != GDB_SIGNAL_0
05455       && ptid_get_pid (info->ptid) == ptid_get_pid (inferior_ptid))
05456     return 1;
05457 
05458   return 0;
05459 }
05460 
05461 static enum gdb_signal
05462 find_stop_signal (void)
05463 {
05464   struct thread_info *info =
05465     iterate_over_threads (find_signalled_thread, NULL);
05466 
05467   if (info)
05468     return info->suspend.stop_signal;
05469   else
05470     return GDB_SIGNAL_0;
05471 }
05472 
05473 static char *
05474 procfs_make_note_section (bfd *obfd, int *note_size)
05475 {
05476   struct cleanup *old_chain;
05477   gdb_gregset_t gregs;
05478   gdb_fpregset_t fpregs;
05479   char fname[16] = {'\0'};
05480   char psargs[80] = {'\0'};
05481   procinfo *pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
05482   char *note_data = NULL;
05483   char *inf_args;
05484   struct procfs_corefile_thread_data thread_args;
05485   gdb_byte *auxv;
05486   int auxv_len;
05487   enum gdb_signal stop_signal;
05488 
05489   if (get_exec_file (0))
05490     {
05491       strncpy (fname, lbasename (get_exec_file (0)), sizeof (fname));
05492       fname[sizeof (fname) - 1] = 0;
05493       strncpy (psargs, get_exec_file (0), sizeof (psargs));
05494       psargs[sizeof (psargs) - 1] = 0;
05495 
05496       inf_args = get_inferior_args ();
05497       if (inf_args && *inf_args &&
05498           strlen (inf_args) < ((int) sizeof (psargs) - (int) strlen (psargs)))
05499         {
05500           strncat (psargs, " ",
05501                    sizeof (psargs) - strlen (psargs));
05502           strncat (psargs, inf_args,
05503                    sizeof (psargs) - strlen (psargs));
05504         }
05505     }
05506 
05507   note_data = (char *) elfcore_write_prpsinfo (obfd,
05508                                                note_data,
05509                                                note_size,
05510                                                fname,
05511                                                psargs);
05512 
05513   stop_signal = find_stop_signal ();
05514 
05515 #ifdef NEW_PROC_API
05516   fill_gregset (get_current_regcache (), &gregs, -1);
05517   note_data = elfcore_write_pstatus (obfd, note_data, note_size,
05518                                      ptid_get_pid (inferior_ptid),
05519                                      stop_signal, &gregs);
05520 #endif
05521 
05522   thread_args.obfd = obfd;
05523   thread_args.note_data = note_data;
05524   thread_args.note_size = note_size;
05525   thread_args.stop_signal = stop_signal;
05526   proc_iterate_over_threads (pi, procfs_corefile_thread_callback,
05527                              &thread_args);
05528 
05529   /* There should be always at least one thread.  */
05530   gdb_assert (thread_args.note_data != note_data);
05531   note_data = thread_args.note_data;
05532 
05533   auxv_len = target_read_alloc (&current_target, TARGET_OBJECT_AUXV,
05534                                 NULL, &auxv);
05535   if (auxv_len > 0)
05536     {
05537       note_data = elfcore_write_note (obfd, note_data, note_size,
05538                                       "CORE", NT_AUXV, auxv, auxv_len);
05539       xfree (auxv);
05540     }
05541 
05542   make_cleanup (xfree, note_data);
05543   return note_data;
05544 }
05545 #else /* !Solaris */
05546 static char *
05547 procfs_make_note_section (bfd *obfd, int *note_size)
05548 {
05549   error (_("gcore not implemented for this host."));
05550   return NULL;  /* lint */
05551 }
05552 #endif /* Solaris */
05553 /* ===================  END GCORE .NOTE "MODULE" =================== */
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines