gdb/procfs.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Machine independent support for SVR4 /proc (process file system) for GDB.

  2.    Copyright (C) 1999-2015 Free Software Foundation, Inc.

  3.    Written by Michael Snyder at Cygnus Solutions.
  4.    Based on work by Fred Fish, Stu Grossman, Geoff Noer, and others.

  5.    This file is part of GDB.

  6.    This program is free software; you can redistribute it and/or modify
  7.    it under the terms of the GNU General Public License as published by
  8.    the Free Software Foundation; either version 3 of the License, or
  9.    (at your option) any later version.

  10.    This program is distributed in the hope that it will be useful,
  11.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13.    GNU General Public License for more details.

  14.    You should have received a copy of the GNU General Public License
  15.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  16. #include "defs.h"
  17. #include "inferior.h"
  18. #include "infrun.h"
  19. #include "target.h"
  20. #include "gdbcore.h"
  21. #include "elf-bfd.h"                /* for elfcore_write_* */
  22. #include "gdbcmd.h"
  23. #include "gdbthread.h"
  24. #include "regcache.h"
  25. #include "inf-child.h"

  26. #if defined (NEW_PROC_API)
  27. #define _STRUCTURED_PROC 1        /* Should be done by configure script.  */
  28. #endif

  29. #include <sys/procfs.h>
  30. #ifdef HAVE_SYS_FAULT_H
  31. #include <sys/fault.h>
  32. #endif
  33. #ifdef HAVE_SYS_SYSCALL_H
  34. #include <sys/syscall.h>
  35. #endif
  36. #include "gdb_wait.h"
  37. #include <signal.h>
  38. #include <ctype.h>
  39. #include "gdb_bfd.h"
  40. #include "inflow.h"
  41. #include "auxv.h"
  42. #include "procfs.h"
  43. #include "observer.h"

  44. /* This module provides the interface between GDB and the
  45.    /proc file system, which is used on many versions of Unix
  46.    as a means for debuggers to control other processes.

  47.    Examples of the systems that use this interface are:

  48.      Irix
  49.      Solaris
  50.      OSF
  51.      AIX5

  52.    /proc works by imitating a file system: you open a simulated file
  53.    that represents the process you wish to interact with, and perform
  54.    operations on that "file" in order to examine or change the state
  55.    of the other process.

  56.    The most important thing to know about /proc and this module is
  57.    that there are two very different interfaces to /proc:

  58.      One that uses the ioctl system call, and another that uses read
  59.      and write system calls.

  60.    This module has to support both /proc interfaces.  This means that
  61.    there are two different ways of doing every basic operation.

  62.    In order to keep most of the code simple and clean, I have defined
  63.    an interface "layer" which hides all these system calls.  An ifdef
  64.    (NEW_PROC_API) determines which interface we are using, and most or
  65.    all occurrances of this ifdef should be confined to this interface
  66.    layer.  */

  67. /* Determine which /proc API we are using: The ioctl API defines
  68.    PIOCSTATUS, while the read/write (multiple fd) API never does.  */

  69. #ifdef NEW_PROC_API
  70. #include <sys/types.h>
  71. #include <dirent.h>        /* opendir/readdir, for listing the LWP's */
  72. #endif

  73. #include <fcntl.h>        /* for O_RDONLY */
  74. #include <unistd.h>        /* for "X_OK" */
  75. #include <sys/stat.h>        /* for struct stat */

  76. /* Note: procfs-utils.h must be included after the above system header
  77.    files, because it redefines various system calls using macros.
  78.    This may be incompatible with the prototype declarations.  */

  79. #include "proc-utils.h"

  80. /* Prototypes for supply_gregset etc.  */
  81. #include "gregset.h"

  82. /* =================== TARGET_OPS "MODULE" =================== */

  83. /* This module defines the GDB target vector and its methods.  */

  84. static void procfs_attach (struct target_ops *, const char *, int);
  85. static void procfs_detach (struct target_ops *, const char *, int);
  86. static void procfs_resume (struct target_ops *,
  87.                            ptid_t, int, enum gdb_signal);
  88. static void procfs_stop (struct target_ops *self, ptid_t);
  89. static void procfs_files_info (struct target_ops *);
  90. static void procfs_fetch_registers (struct target_ops *,
  91.                                     struct regcache *, int);
  92. static void procfs_store_registers (struct target_ops *,
  93.                                     struct regcache *, int);
  94. static void procfs_pass_signals (struct target_ops *self,
  95.                                  int, unsigned char *);
  96. static void procfs_kill_inferior (struct target_ops *ops);
  97. static void procfs_mourn_inferior (struct target_ops *ops);
  98. static void procfs_create_inferior (struct target_ops *, char *,
  99.                                     char *, char **, int);
  100. static ptid_t procfs_wait (struct target_ops *,
  101.                            ptid_t, struct target_waitstatus *, int);
  102. static enum target_xfer_status procfs_xfer_memory (gdb_byte *,
  103.                                                    const gdb_byte *,
  104.                                                    ULONGEST, ULONGEST,
  105.                                                    ULONGEST *);
  106. static target_xfer_partial_ftype procfs_xfer_partial;

  107. static int procfs_thread_alive (struct target_ops *ops, ptid_t);

  108. static void procfs_update_thread_list (struct target_ops *ops);
  109. static char *procfs_pid_to_str (struct target_ops *, ptid_t);

  110. static int proc_find_memory_regions (struct target_ops *self,
  111.                                      find_memory_region_ftype, void *);

  112. static char * procfs_make_note_section (struct target_ops *self,
  113.                                         bfd *, int *);

  114. static int procfs_can_use_hw_breakpoint (struct target_ops *self,
  115.                                          int, int, int);

  116. static void procfs_info_proc (struct target_ops *, const char *,
  117.                               enum info_proc_what);

  118. #if defined (PR_MODEL_NATIVE) && (PR_MODEL_NATIVE == PR_MODEL_LP64)
  119. /* When GDB is built as 64-bit application on Solaris, the auxv data
  120.    is presented in 64-bit format.  We need to provide a custom parser
  121.    to handle that.  */
  122. static int
  123. procfs_auxv_parse (struct target_ops *ops, gdb_byte **readptr,
  124.                    gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
  125. {
  126.   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
  127.   gdb_byte *ptr = *readptr;

  128.   if (endptr == ptr)
  129.     return 0;

  130.   if (endptr - ptr < 8 * 2)
  131.     return -1;

  132.   *typep = extract_unsigned_integer (ptr, 4, byte_order);
  133.   ptr += 8;
  134.   /* The size of data is always 64-bit.  If the application is 32-bit,
  135.      it will be zero extended, as expected.  */
  136.   *valp = extract_unsigned_integer (ptr, 8, byte_order);
  137.   ptr += 8;

  138.   *readptr = ptr;
  139.   return 1;
  140. }
  141. #endif

  142. struct target_ops *
  143. procfs_target (void)
  144. {
  145.   struct target_ops *t = inf_child_target ();

  146.   t->to_create_inferior = procfs_create_inferior;
  147.   t->to_kill = procfs_kill_inferior;
  148.   t->to_mourn_inferior = procfs_mourn_inferior;
  149.   t->to_attach = procfs_attach;
  150.   t->to_detach = procfs_detach;
  151.   t->to_wait = procfs_wait;
  152.   t->to_resume = procfs_resume;
  153.   t->to_fetch_registers = procfs_fetch_registers;
  154.   t->to_store_registers = procfs_store_registers;
  155.   t->to_xfer_partial = procfs_xfer_partial;
  156.   t->to_pass_signals = procfs_pass_signals;
  157.   t->to_files_info = procfs_files_info;
  158.   t->to_stop = procfs_stop;

  159.   t->to_update_thread_list = procfs_update_thread_list;
  160.   t->to_thread_alive = procfs_thread_alive;
  161.   t->to_pid_to_str = procfs_pid_to_str;

  162.   t->to_has_thread_control = tc_schedlock;
  163.   t->to_find_memory_regions = proc_find_memory_regions;
  164.   t->to_make_corefile_notes = procfs_make_note_section;
  165.   t->to_info_proc = procfs_info_proc;

  166. #if defined(PR_MODEL_NATIVE) && (PR_MODEL_NATIVE == PR_MODEL_LP64)
  167.   t->to_auxv_parse = procfs_auxv_parse;
  168. #endif

  169.   t->to_magic = OPS_MAGIC;

  170.   return t;
  171. }

  172. /* =================== END, TARGET_OPS "MODULE" =================== */

  173. /* World Unification:

  174.    Put any typedefs, defines etc. here that are required for the
  175.    unification of code that handles different versions of /proc.  */

  176. #ifdef NEW_PROC_API                /* Solaris 7 && 8 method for watchpoints */
  177. #ifdef WA_READ
  178.      enum { READ_WATCHFLAG  = WA_READ,
  179.             WRITE_WATCHFLAG = WA_WRITE,
  180.             EXEC_WATCHFLAG  = WA_EXEC,
  181.             AFTER_WATCHFLAG = WA_TRAPAFTER
  182.      };
  183. #endif
  184. #else                                /* Irix method for watchpoints */
  185.      enum { READ_WATCHFLAG  = MA_READ,
  186.             WRITE_WATCHFLAG = MA_WRITE,
  187.             EXEC_WATCHFLAG  = MA_EXEC,
  188.             AFTER_WATCHFLAG = 0                /* trapafter not implemented */
  189.      };
  190. #endif

  191. /* gdb_sigset_t */
  192. #ifdef HAVE_PR_SIGSET_T
  193. typedef pr_sigset_t gdb_sigset_t;
  194. #else
  195. typedef sigset_t gdb_sigset_t;
  196. #endif

  197. /* sigaction */
  198. #ifdef HAVE_PR_SIGACTION64_T
  199. typedef pr_sigaction64_t gdb_sigaction_t;
  200. #else
  201. typedef struct sigaction gdb_sigaction_t;
  202. #endif

  203. /* siginfo */
  204. #ifdef HAVE_PR_SIGINFO64_T
  205. typedef pr_siginfo64_t gdb_siginfo_t;
  206. #else
  207. typedef siginfo_t gdb_siginfo_t;
  208. #endif

  209. /* On mips-irix, praddset and prdelset are defined in such a way that
  210.    they return a value, which causes GCC to emit a -Wunused error
  211.    because the returned value is not used.  Prevent this warning
  212.    by casting the return value to void.  On sparc-solaris, this issue
  213.    does not exist because the definition of these macros already include
  214.    that cast to void.  */
  215. #define gdb_praddset(sp, flag) ((void) praddset (sp, flag))
  216. #define gdb_prdelset(sp, flag) ((void) prdelset (sp, flag))

  217. /* gdb_premptysysset */
  218. #ifdef premptysysset
  219. #define gdb_premptysysset premptysysset
  220. #else
  221. #define gdb_premptysysset premptyset
  222. #endif

  223. /* praddsysset */
  224. #ifdef praddsysset
  225. #define gdb_praddsysset praddsysset
  226. #else
  227. #define gdb_praddsysset gdb_praddset
  228. #endif

  229. /* prdelsysset */
  230. #ifdef prdelsysset
  231. #define gdb_prdelsysset prdelsysset
  232. #else
  233. #define gdb_prdelsysset gdb_prdelset
  234. #endif

  235. /* prissyssetmember */
  236. #ifdef prissyssetmember
  237. #define gdb_pr_issyssetmember prissyssetmember
  238. #else
  239. #define gdb_pr_issyssetmember prismember
  240. #endif

  241. /* As a feature test, saying ``#if HAVE_PRSYSENT_T'' everywhere isn't
  242.    as intuitively descriptive as it could be, so we'll define
  243.    DYNAMIC_SYSCALLS to mean the same thing.  Anyway, at the time of
  244.    this writing, this feature is only found on AIX5 systems and
  245.    basically means that the set of syscalls is not fixed.  I.e,
  246.    there's no nice table that one can #include to get all of the
  247.    syscall numbers.  Instead, they're stored in /proc/PID/sysent
  248.    for each process.  We are at least guaranteed that they won't
  249.    change over the lifetime of the process.  But each process could
  250.    (in theory) have different syscall numbers.  */
  251. #ifdef HAVE_PRSYSENT_T
  252. #define DYNAMIC_SYSCALLS
  253. #endif



  254. /* =================== STRUCT PROCINFO "MODULE" =================== */

  255.      /* FIXME: this comment will soon be out of date W.R.T. threads.  */

  256. /* The procinfo struct is a wrapper to hold all the state information
  257.    concerning a /proc process.  There should be exactly one procinfo
  258.    for each process, and since GDB currently can debug only one
  259.    process at a time, that means there should be only one procinfo.
  260.    All of the LWP's of a process can be accessed indirectly thru the
  261.    single process procinfo.

  262.    However, against the day when GDB may debug more than one process,
  263.    this data structure is kept in a list (which for now will hold no
  264.    more than one member), and many functions will have a pointer to a
  265.    procinfo as an argument.

  266.    There will be a separate procinfo structure for use by the (not yet
  267.    implemented) "info proc" command, so that we can print useful
  268.    information about any random process without interfering with the
  269.    inferior's procinfo information.  */

  270. #ifdef NEW_PROC_API
  271. /* format strings for /proc paths */
  272. # ifndef CTL_PROC_NAME_FMT
  273. #  define MAIN_PROC_NAME_FMT   "/proc/%d"
  274. #  define CTL_PROC_NAME_FMT    "/proc/%d/ctl"
  275. #  define AS_PROC_NAME_FMT     "/proc/%d/as"
  276. #  define MAP_PROC_NAME_FMT    "/proc/%d/map"
  277. #  define STATUS_PROC_NAME_FMT "/proc/%d/status"
  278. #  define MAX_PROC_NAME_SIZE sizeof("/proc/99999/lwp/8096/lstatus")
  279. # endif
  280. /* the name of the proc status struct depends on the implementation */
  281. typedef pstatus_t   gdb_prstatus_t;
  282. typedef lwpstatus_t gdb_lwpstatus_t;
  283. #else /* ! NEW_PROC_API */
  284. /* format strings for /proc paths */
  285. # ifndef CTL_PROC_NAME_FMT
  286. #  define MAIN_PROC_NAME_FMT   "/proc/%05d"
  287. #  define CTL_PROC_NAME_FMT    "/proc/%05d"
  288. #  define AS_PROC_NAME_FMT     "/proc/%05d"
  289. #  define MAP_PROC_NAME_FMT    "/proc/%05d"
  290. #  define STATUS_PROC_NAME_FMT "/proc/%05d"
  291. #  define MAX_PROC_NAME_SIZE sizeof("/proc/ttttppppp")
  292. # endif
  293. /* The name of the proc status struct depends on the implementation.  */
  294. typedef prstatus_t gdb_prstatus_t;
  295. typedef prstatus_t gdb_lwpstatus_t;
  296. #endif /* NEW_PROC_API */

  297. typedef struct procinfo {
  298.   struct procinfo *next;
  299.   int pid;                        /* Process ID    */
  300.   int tid;                        /* Thread/LWP id */

  301.   /* process state */
  302.   int was_stopped;
  303.   int ignore_next_sigstop;

  304.   /* The following four fd fields may be identical, or may contain
  305.      several different fd's, depending on the version of /proc
  306.      (old ioctl or new read/write).  */

  307.   int ctl_fd;                        /* File descriptor for /proc control file */

  308.   /* The next three file descriptors are actually only needed in the
  309.      read/write, multiple-file-descriptor implemenation
  310.      (NEW_PROC_API).  However, to avoid a bunch of #ifdefs in the
  311.      code, we will use them uniformly by (in the case of the ioctl
  312.      single-file-descriptor implementation) filling them with copies
  313.      of the control fd.  */
  314.   int status_fd;                /* File descriptor for /proc status file */
  315.   int as_fd;                        /* File descriptor for /proc as file */

  316.   char pathname[MAX_PROC_NAME_SIZE];        /* Pathname to /proc entry */

  317.   fltset_t saved_fltset;        /* Saved traced hardware fault set */
  318.   gdb_sigset_t saved_sigset;        /* Saved traced signal set */
  319.   gdb_sigset_t saved_sighold;        /* Saved held signal set */
  320.   sysset_t *saved_exitset;        /* Saved traced system call exit set */
  321.   sysset_t *saved_entryset;        /* Saved traced system call entry set */

  322.   gdb_prstatus_t prstatus;        /* Current process status info */

  323. #ifndef NEW_PROC_API
  324.   gdb_fpregset_t fpregset;        /* Current floating point registers */
  325. #endif

  326. #ifdef DYNAMIC_SYSCALLS
  327.   int num_syscalls;                /* Total number of syscalls */
  328.   char **syscall_names;                /* Syscall number to name map */
  329. #endif

  330.   struct procinfo *thread_list;

  331.   int status_valid : 1;
  332.   int gregs_valid  : 1;
  333.   int fpregs_valid : 1;
  334.   int threads_valid: 1;
  335. } procinfo;

  336. static char errmsg[128];        /* shared error msg buffer */

  337. /* Function prototypes for procinfo module: */

  338. static procinfo *find_procinfo_or_die (int pid, int tid);
  339. static procinfo *find_procinfo (int pid, int tid);
  340. static procinfo *create_procinfo (int pid, int tid);
  341. static void destroy_procinfo (procinfo * p);
  342. static void do_destroy_procinfo_cleanup (void *);
  343. static void dead_procinfo (procinfo * p, char *msg, int killp);
  344. static int open_procinfo_files (procinfo * p, int which);
  345. static void close_procinfo_files (procinfo * p);
  346. static int sysset_t_size (procinfo *p);
  347. static sysset_t *sysset_t_alloc (procinfo * pi);
  348. #ifdef DYNAMIC_SYSCALLS
  349. static void load_syscalls (procinfo *pi);
  350. static void free_syscalls (procinfo *pi);
  351. static int find_syscall (procinfo *pi, char *name);
  352. #endif /* DYNAMIC_SYSCALLS */

  353. static int iterate_over_mappings
  354.   (procinfo *pi, find_memory_region_ftype child_func, void *data,
  355.    int (*func) (struct prmap *map, find_memory_region_ftype child_func,
  356.                 void *data));

  357. /* The head of the procinfo list: */
  358. static procinfo * procinfo_list;

  359. /* Search the procinfo list.  Return a pointer to procinfo, or NULL if
  360.    not found.  */

  361. static procinfo *
  362. find_procinfo (int pid, int tid)
  363. {
  364.   procinfo *pi;

  365.   for (pi = procinfo_list; pi; pi = pi->next)
  366.     if (pi->pid == pid)
  367.       break;

  368.   if (pi)
  369.     if (tid)
  370.       {
  371.         /* Don't check threads_valid.  If we're updating the
  372.            thread_list, we want to find whatever threads are already
  373.            here.  This means that in general it is the caller's
  374.            responsibility to check threads_valid and update before
  375.            calling find_procinfo, if the caller wants to find a new
  376.            thread.  */

  377.         for (pi = pi->thread_list; pi; pi = pi->next)
  378.           if (pi->tid == tid)
  379.             break;
  380.       }

  381.   return pi;
  382. }

  383. /* Calls find_procinfo, but errors on failure.  */

  384. static procinfo *
  385. find_procinfo_or_die (int pid, int tid)
  386. {
  387.   procinfo *pi = find_procinfo (pid, tid);

  388.   if (pi == NULL)
  389.     {
  390.       if (tid)
  391.         error (_("procfs: couldn't find pid %d "
  392.                  "(kernel thread %d) in procinfo list."),
  393.                pid, tid);
  394.       else
  395.         error (_("procfs: couldn't find pid %d in procinfo list."), pid);
  396.     }
  397.   return pi;
  398. }

  399. /* Wrapper for `open'.  The appropriate open call is attempted; if
  400.    unsuccessful, it will be retried as many times as needed for the
  401.    EAGAIN and EINTR conditions.

  402.    For other conditions, retry the open a limited number of times.  In
  403.    addition, a short sleep is imposed prior to retrying the open.  The
  404.    reason for this sleep is to give the kernel a chance to catch up
  405.    and create the file in question in the event that GDB "wins" the
  406.    race to open a file before the kernel has created it.  */

  407. static int
  408. open_with_retry (const char *pathname, int flags)
  409. {
  410.   int retries_remaining, status;

  411.   retries_remaining = 2;

  412.   while (1)
  413.     {
  414.       status = open (pathname, flags);

  415.       if (status >= 0 || retries_remaining == 0)
  416.         break;
  417.       else if (errno != EINTR && errno != EAGAIN)
  418.         {
  419.           retries_remaining--;
  420.           sleep (1);
  421.         }
  422.     }

  423.   return status;
  424. }

  425. /* Open the file descriptor for the process or LWP.  If NEW_PROC_API
  426.    is defined, we only open the control file descriptor; the others
  427.    are opened lazily as needed.  Otherwise (if not NEW_PROC_API),
  428.    there is only one real file descriptor, but we keep multiple copies
  429.    of it so that the code that uses them does not have to be #ifdef'd.
  430.    Returns the file descriptor, or zero for failure.  */

  431. enum { FD_CTL, FD_STATUS, FD_AS };

  432. static int
  433. open_procinfo_files (procinfo *pi, int which)
  434. {
  435. #ifdef NEW_PROC_API
  436.   char tmp[MAX_PROC_NAME_SIZE];
  437. #endif
  438.   int  fd;

  439.   /* This function is getting ALMOST long enough to break up into
  440.      several.  Here is some rationale:

  441.      NEW_PROC_API (Solaris 2.6, Solaris 2.7):
  442.      There are several file descriptors that may need to be open
  443.        for any given process or LWP.  The ones we're intereted in are:
  444.          - control         (ctl)          write-only        change the state
  445.          - status         (status) read-only        query the state
  446.          - address space (as)          read/write        access memory
  447.          - map                 (map)          read-only        virtual addr map
  448.        Most of these are opened lazily as they are needed.
  449.        The pathnames for the 'files' for an LWP look slightly
  450.        different from those of a first-class process:
  451.          Pathnames for a process (<proc-id>):
  452.            /proc/<proc-id>/ctl
  453.            /proc/<proc-id>/status
  454.            /proc/<proc-id>/as
  455.            /proc/<proc-id>/map
  456.          Pathnames for an LWP (lwp-id):
  457.            /proc/<proc-id>/lwp/<lwp-id>/lwpctl
  458.            /proc/<proc-id>/lwp/<lwp-id>/lwpstatus
  459.        An LWP has no map or address space file descriptor, since
  460.        the memory map and address space are shared by all LWPs.

  461.      Everyone else (Solaris 2.5, Irix, OSF)
  462.        There is only one file descriptor for each process or LWP.
  463.        For convenience, we copy the same file descriptor into all
  464.        three fields of the procinfo struct (ctl_fd, status_fd, and
  465.        as_fd, see NEW_PROC_API above) so that code that uses them
  466.        doesn't need any #ifdef's.
  467.          Pathname for all:
  468.            /proc/<proc-id>

  469.        Solaris 2.5 LWP's:
  470.          Each LWP has an independent file descriptor, but these
  471.          are not obtained via the 'open' system call like the rest:
  472.          instead, they're obtained thru an ioctl call (PIOCOPENLWP)
  473.          to the file descriptor of the parent process.

  474.        OSF threads:
  475.          These do not even have their own independent file descriptor.
  476.          All operations are carried out on the file descriptor of the
  477.          parent process.  Therefore we just call open again for each
  478.          thread, getting a new handle for the same 'file'.  */

  479. #ifdef NEW_PROC_API
  480.   /* In this case, there are several different file descriptors that
  481.      we might be asked to open.  The control file descriptor will be
  482.      opened early, but the others will be opened lazily as they are
  483.      needed.  */

  484.   strcpy (tmp, pi->pathname);
  485.   switch (which) {        /* Which file descriptor to open?  */
  486.   case FD_CTL:
  487.     if (pi->tid)
  488.       strcat (tmp, "/lwpctl");
  489.     else
  490.       strcat (tmp, "/ctl");
  491.     fd = open_with_retry (tmp, O_WRONLY);
  492.     if (fd < 0)
  493.       return 0;                /* fail */
  494.     pi->ctl_fd = fd;
  495.     break;
  496.   case FD_AS:
  497.     if (pi->tid)
  498.       return 0;                /* There is no 'as' file descriptor for an lwp.  */
  499.     strcat (tmp, "/as");
  500.     fd = open_with_retry (tmp, O_RDWR);
  501.     if (fd < 0)
  502.       return 0;                /* fail */
  503.     pi->as_fd = fd;
  504.     break;
  505.   case FD_STATUS:
  506.     if (pi->tid)
  507.       strcat (tmp, "/lwpstatus");
  508.     else
  509.       strcat (tmp, "/status");
  510.     fd = open_with_retry (tmp, O_RDONLY);
  511.     if (fd < 0)
  512.       return 0;                /* fail */
  513.     pi->status_fd = fd;
  514.     break;
  515.   default:
  516.     return 0;                /* unknown file descriptor */
  517.   }
  518. #else  /* not NEW_PROC_API */
  519.   /* In this case, there is only one file descriptor for each procinfo
  520.      (ie. each process or LWP).  In fact, only the file descriptor for
  521.      the process can actually be opened by an 'open' system call.  The
  522.      ones for the LWPs have to be obtained thru an IOCTL call on the
  523.      process's file descriptor.

  524.      For convenience, we copy each procinfo's single file descriptor
  525.      into all of the fields occupied by the several file descriptors
  526.      of the NEW_PROC_API implementation.  That way, the code that uses
  527.      them can be written without ifdefs.  */


  528. #ifdef PIOCTSTATUS        /* OSF */
  529.   /* Only one FD; just open it.  */
  530.   if ((fd = open_with_retry (pi->pathname, O_RDWR)) < 0)
  531.     return 0;
  532. #else                        /* Sol 2.5, Irix, other?  */
  533.   if (pi->tid == 0)        /* Master procinfo for the process */
  534.     {
  535.       fd = open_with_retry (pi->pathname, O_RDWR);
  536.       if (fd < 0)
  537.         return 0;        /* fail */
  538.     }
  539.   else                        /* LWP thread procinfo */
  540.     {
  541. #ifdef PIOCOPENLWP        /* Sol 2.5, thread/LWP */
  542.       procinfo *process;
  543.       int lwpid = pi->tid;

  544.       /* Find the procinfo for the entire process.  */
  545.       if ((process = find_procinfo (pi->pid, 0)) == NULL)
  546.         return 0;        /* fail */

  547.       /* Now obtain the file descriptor for the LWP.  */
  548.       if ((fd = ioctl (process->ctl_fd, PIOCOPENLWP, &lwpid)) < 0)
  549.         return 0;        /* fail */
  550. #else                        /* Irix, other?  */
  551.       return 0;                /* Don't know how to open threads.  */
  552. #endif        /* Sol 2.5 PIOCOPENLWP */
  553.     }
  554. #endif        /* OSF     PIOCTSTATUS */
  555.   pi->ctl_fd = pi->as_fd = pi->status_fd = fd;
  556. #endif        /* NEW_PROC_API */

  557.   return 1;                /* success */
  558. }

  559. /* Allocate a data structure and link it into the procinfo list.
  560.    First tries to find a pre-existing one (FIXME: why?).  Returns the
  561.    pointer to new procinfo struct.  */

  562. static procinfo *
  563. create_procinfo (int pid, int tid)
  564. {
  565.   procinfo *pi, *parent = NULL;

  566.   if ((pi = find_procinfo (pid, tid)))
  567.     return pi;                        /* Already exists, nothing to do.  */

  568.   /* Find parent before doing malloc, to save having to cleanup.  */
  569.   if (tid != 0)
  570.     parent = find_procinfo_or_die (pid, 0);        /* FIXME: should I
  571.                                                    create it if it
  572.                                                    doesn't exist yet?  */

  573.   pi = (procinfo *) xmalloc (sizeof (procinfo));
  574.   memset (pi, 0, sizeof (procinfo));
  575.   pi->pid = pid;
  576.   pi->tid = tid;

  577. #ifdef DYNAMIC_SYSCALLS
  578.   load_syscalls (pi);
  579. #endif

  580.   pi->saved_entryset = sysset_t_alloc (pi);
  581.   pi->saved_exitset = sysset_t_alloc (pi);

  582.   /* Chain into list.  */
  583.   if (tid == 0)
  584.     {
  585.       sprintf (pi->pathname, MAIN_PROC_NAME_FMT, pid);
  586.       pi->next = procinfo_list;
  587.       procinfo_list = pi;
  588.     }
  589.   else
  590.     {
  591. #ifdef NEW_PROC_API
  592.       sprintf (pi->pathname, "/proc/%05d/lwp/%d", pid, tid);
  593. #else
  594.       sprintf (pi->pathname, MAIN_PROC_NAME_FMT, pid);
  595. #endif
  596.       pi->next = parent->thread_list;
  597.       parent->thread_list = pi;
  598.     }
  599.   return pi;
  600. }

  601. /* Close all file descriptors associated with the procinfo.  */

  602. static void
  603. close_procinfo_files (procinfo *pi)
  604. {
  605.   if (pi->ctl_fd > 0)
  606.     close (pi->ctl_fd);
  607. #ifdef NEW_PROC_API
  608.   if (pi->as_fd > 0)
  609.     close (pi->as_fd);
  610.   if (pi->status_fd > 0)
  611.     close (pi->status_fd);
  612. #endif
  613.   pi->ctl_fd = pi->as_fd = pi->status_fd = 0;
  614. }

  615. /* Destructor function.  Close, unlink and deallocate the object.  */

  616. static void
  617. destroy_one_procinfo (procinfo **list, procinfo *pi)
  618. {
  619.   procinfo *ptr;

  620.   /* Step one: unlink the procinfo from its list.  */
  621.   if (pi == *list)
  622.     *list = pi->next;
  623.   else
  624.     for (ptr = *list; ptr; ptr = ptr->next)
  625.       if (ptr->next == pi)
  626.         {
  627.           ptr->next =  pi->next;
  628.           break;
  629.         }

  630.   /* Step two: close any open file descriptors.  */
  631.   close_procinfo_files (pi);

  632.   /* Step three: free the memory.  */
  633. #ifdef DYNAMIC_SYSCALLS
  634.   free_syscalls (pi);
  635. #endif
  636.   xfree (pi->saved_entryset);
  637.   xfree (pi->saved_exitset);
  638.   xfree (pi);
  639. }

  640. static void
  641. destroy_procinfo (procinfo *pi)
  642. {
  643.   procinfo *tmp;

  644.   if (pi->tid != 0)        /* Destroy a thread procinfo.  */
  645.     {
  646.       tmp = find_procinfo (pi->pid, 0);        /* Find the parent process.  */
  647.       destroy_one_procinfo (&tmp->thread_list, pi);
  648.     }
  649.   else                        /* Destroy a process procinfo and all its threads.  */
  650.     {
  651.       /* First destroy the children, if any; */
  652.       while (pi->thread_list != NULL)
  653.         destroy_one_procinfo (&pi->thread_list, pi->thread_list);
  654.       /* Then destroy the parent.  Genocide!!!  */
  655.       destroy_one_procinfo (&procinfo_list, pi);
  656.     }
  657. }

  658. static void
  659. do_destroy_procinfo_cleanup (void *pi)
  660. {
  661.   destroy_procinfo (pi);
  662. }

  663. enum { NOKILL, KILL };

  664. /* To be called on a non_recoverable error for a procinfo.  Prints
  665.    error messages, optionally sends a SIGKILL to the process, then
  666.    destroys the data structure.  */

  667. static void
  668. dead_procinfo (procinfo *pi, char *msg, int kill_p)
  669. {
  670.   char procfile[80];

  671.   if (pi->pathname)
  672.     {
  673.       print_sys_errmsg (pi->pathname, errno);
  674.     }
  675.   else
  676.     {
  677.       sprintf (procfile, "process %d", pi->pid);
  678.       print_sys_errmsg (procfile, errno);
  679.     }
  680.   if (kill_p == KILL)
  681.     kill (pi->pid, SIGKILL);

  682.   destroy_procinfo (pi);
  683.   error ("%s", msg);
  684. }

  685. /* Returns the (complete) size of a sysset_t struct.  Normally, this
  686.    is just sizeof (sysset_t), but in the case of Monterey/64, the
  687.    actual size of sysset_t isn't known until runtime.  */

  688. static int
  689. sysset_t_size (procinfo * pi)
  690. {
  691. #ifndef DYNAMIC_SYSCALLS
  692.   return sizeof (sysset_t);
  693. #else
  694.   return sizeof (sysset_t) - sizeof (uint64_t)
  695.     + sizeof (uint64_t) * ((pi->num_syscalls + (8 * sizeof (uint64_t) - 1))
  696.                            / (8 * sizeof (uint64_t)));
  697. #endif
  698. }

  699. /* Allocate and (partially) initialize a sysset_t struct.  */

  700. static sysset_t *
  701. sysset_t_alloc (procinfo * pi)
  702. {
  703.   sysset_t *ret;
  704.   int size = sysset_t_size (pi);

  705.   ret = xmalloc (size);
  706. #ifdef DYNAMIC_SYSCALLS
  707.   ret->pr_size = ((pi->num_syscalls + (8 * sizeof (uint64_t) - 1))
  708.                   / (8 * sizeof (uint64_t)));
  709. #endif
  710.   return ret;
  711. }

  712. #ifdef DYNAMIC_SYSCALLS

  713. /* Extract syscall numbers and names from /proc/<pid>/sysent.  Initialize
  714.    pi->num_syscalls with the number of syscalls and pi->syscall_names
  715.    with the names.  (Certain numbers may be skipped in which case the
  716.    names for these numbers will be left as NULL.)  */

  717. #define MAX_SYSCALL_NAME_LENGTH 256
  718. #define MAX_SYSCALLS 65536

  719. static void
  720. load_syscalls (procinfo *pi)
  721. {
  722.   char pathname[MAX_PROC_NAME_SIZE];
  723.   int sysent_fd;
  724.   prsysent_t header;
  725.   prsyscall_t *syscalls;
  726.   int i, size, maxcall;
  727.   struct cleanup *cleanups;

  728.   pi->num_syscalls = 0;
  729.   pi->syscall_names = 0;

  730.   /* Open the file descriptor for the sysent file.  */
  731.   sprintf (pathname, "/proc/%d/sysent", pi->pid);
  732.   sysent_fd = open_with_retry (pathname, O_RDONLY);
  733.   if (sysent_fd < 0)
  734.     {
  735.       error (_("load_syscalls: Can't open /proc/%d/sysent"), pi->pid);
  736.     }
  737.   cleanups = make_cleanup_close (sysent_fd);

  738.   size = sizeof header - sizeof (prsyscall_t);
  739.   if (read (sysent_fd, &header, size) != size)
  740.     {
  741.       error (_("load_syscalls: Error reading /proc/%d/sysent"), pi->pid);
  742.     }

  743.   if (header.pr_nsyscalls == 0)
  744.     {
  745.       error (_("load_syscalls: /proc/%d/sysent contains no syscalls!"),
  746.              pi->pid);
  747.     }

  748.   size = header.pr_nsyscalls * sizeof (prsyscall_t);
  749.   syscalls = xmalloc (size);
  750.   make_cleanup (free_current_contents, &syscalls);

  751.   if (read (sysent_fd, syscalls, size) != size)
  752.     error (_("load_syscalls: Error reading /proc/%d/sysent"), pi->pid);

  753.   /* Find maximum syscall number.  This may not be the same as
  754.      pr_nsyscalls since that value refers to the number of entries
  755.      in the table.  (Also, the docs indicate that some system
  756.      call numbers may be skipped.)  */

  757.   maxcall = syscalls[0].pr_number;

  758.   for (i = 1; iheader.pr_nsyscalls; i++)
  759.     if (syscalls[i].pr_number > maxcall
  760.         && syscalls[i].pr_nameoff > 0
  761.         && syscalls[i].pr_number < MAX_SYSCALLS)
  762.       maxcall = syscalls[i].pr_number;

  763.   pi->num_syscalls = maxcall+1;
  764.   pi->syscall_names = xmalloc (pi->num_syscalls * sizeof (char *));

  765.   for (i = 0; i < pi->num_syscalls; i++)
  766.     pi->syscall_names[i] = NULL;

  767.   /* Read the syscall names in.  */
  768.   for (i = 0; i < header.pr_nsyscalls; i++)
  769.     {
  770.       char namebuf[MAX_SYSCALL_NAME_LENGTH];
  771.       int nread;
  772.       int callnum;

  773.       if (syscalls[i].pr_number >= MAX_SYSCALLS
  774.           || syscalls[i].pr_number < 0
  775.           || syscalls[i].pr_nameoff <= 0
  776.           || (lseek (sysent_fd, (off_t) syscalls[i].pr_nameoff, SEEK_SET)
  777.                                        != (off_t) syscalls[i].pr_nameoff))
  778.         continue;

  779.       nread = read (sysent_fd, namebuf, sizeof namebuf);
  780.       if (nread <= 0)
  781.         continue;

  782.       callnum = syscalls[i].pr_number;

  783.       if (pi->syscall_names[callnum] != NULL)
  784.         {
  785.           /* FIXME: Generate warning.  */
  786.           continue;
  787.         }

  788.       namebuf[nread-1] = '\0';
  789.       size = strlen (namebuf) + 1;
  790.       pi->syscall_names[callnum] = xmalloc (size);
  791.       strncpy (pi->syscall_names[callnum], namebuf, size-1);
  792.       pi->syscall_names[callnum][size-1] = '\0';
  793.     }

  794.   do_cleanups (cleanups);
  795. }

  796. /* Free the space allocated for the syscall names from the procinfo
  797.    structure.  */

  798. static void
  799. free_syscalls (procinfo *pi)
  800. {
  801.   if (pi->syscall_names)
  802.     {
  803.       int i;

  804.       for (i = 0; i < pi->num_syscalls; i++)
  805.         if (pi->syscall_names[i] != NULL)
  806.           xfree (pi->syscall_names[i]);

  807.       xfree (pi->syscall_names);
  808.       pi->syscall_names = 0;
  809.     }
  810. }

  811. /* Given a name, look up (and return) the corresponding syscall number.
  812.    If no match is found, return -1.  */

  813. static int
  814. find_syscall (procinfo *pi, char *name)
  815. {
  816.   int i;

  817.   for (i = 0; i < pi->num_syscalls; i++)
  818.     {
  819.       if (pi->syscall_names[i] && strcmp (name, pi->syscall_names[i]) == 0)
  820.         return i;
  821.     }
  822.   return -1;
  823. }
  824. #endif

  825. /* =================== END, STRUCT PROCINFO "MODULE" =================== */

  826. /* ===================  /proc  "MODULE" =================== */

  827. /* This "module" is the interface layer between the /proc system API
  828.    and the gdb target vector functions.  This layer consists of access
  829.    functions that encapsulate each of the basic operations that we
  830.    need to use from the /proc API.

  831.    The main motivation for this layer is to hide the fact that there
  832.    are two very different implementations of the /proc API.  Rather
  833.    than have a bunch of #ifdefs all thru the gdb target vector
  834.    functions, we do our best to hide them all in here.  */

  835. static long proc_flags (procinfo * pi);
  836. static int proc_why (procinfo * pi);
  837. static int proc_what (procinfo * pi);
  838. static int proc_set_current_signal (procinfo * pi, int signo);
  839. static int proc_get_current_thread (procinfo * pi);
  840. static int proc_iterate_over_threads
  841.   (procinfo * pi,
  842.    int (*func) (procinfo *, procinfo *, void *),
  843.    void *ptr);

  844. static void
  845. proc_warn (procinfo *pi, char *func, int line)
  846. {
  847.   sprintf (errmsg, "procfs: %s line %d, %s", func, line, pi->pathname);
  848.   print_sys_errmsg (errmsg, errno);
  849. }

  850. static void
  851. proc_error (procinfo *pi, char *func, int line)
  852. {
  853.   sprintf (errmsg, "procfs: %s line %d, %s", func, line, pi->pathname);
  854.   perror_with_name (errmsg);
  855. }

  856. /* Updates the status struct in the procinfo.  There is a 'valid'
  857.    flag, to let other functions know when this function needs to be
  858.    called (so the status is only read when it is needed).  The status
  859.    file descriptor is also only opened when it is needed.  Returns
  860.    non-zero for success, zero for failure.  */

  861. static int
  862. proc_get_status (procinfo *pi)
  863. {
  864.   /* Status file descriptor is opened "lazily".  */
  865.   if (pi->status_fd == 0 &&
  866.       open_procinfo_files (pi, FD_STATUS) == 0)
  867.     {
  868.       pi->status_valid = 0;
  869.       return 0;
  870.     }

  871. #ifdef NEW_PROC_API
  872.   if (lseek (pi->status_fd, 0, SEEK_SET) < 0)
  873.     pi->status_valid = 0;                        /* fail */
  874.   else
  875.     {
  876.       /* Sigh... I have to read a different data structure,
  877.          depending on whether this is a main process or an LWP.  */
  878.       if (pi->tid)
  879.         pi->status_valid = (read (pi->status_fd,
  880.                                   (char *) &pi->prstatus.pr_lwp,
  881.                                   sizeof (lwpstatus_t))
  882.                             == sizeof (lwpstatus_t));
  883.       else
  884.         {
  885.           pi->status_valid = (read (pi->status_fd,
  886.                                     (char *) &pi->prstatus,
  887.                                     sizeof (gdb_prstatus_t))
  888.                               == sizeof (gdb_prstatus_t));
  889.         }
  890.     }
  891. #else        /* ioctl method */
  892. #ifdef PIOCTSTATUS        /* osf */
  893.   if (pi->tid == 0)        /* main process */
  894.     {
  895.       /* Just read the danged status.  Now isn't that simple?  */
  896.       pi->status_valid =
  897.         (ioctl (pi->status_fd, PIOCSTATUS, &pi->prstatus) >= 0);
  898.     }
  899.   else
  900.     {
  901.       int win;
  902.       struct {
  903.         long pr_count;
  904.         tid_t pr_error_thread;
  905.         struct prstatus status;
  906.       } thread_status;

  907.       thread_status.pr_count = 1;
  908.       thread_status.status.pr_tid = pi->tid;
  909.       win = (ioctl (pi->status_fd, PIOCTSTATUS, &thread_status) >= 0);
  910.       if (win)
  911.         {
  912.           memcpy (&pi->prstatus, &thread_status.status,
  913.                   sizeof (pi->prstatus));
  914.           pi->status_valid = 1;
  915.         }
  916.     }
  917. #else
  918.   /* Just read the danged status.  Now isn't that simple?  */
  919.   pi->status_valid = (ioctl (pi->status_fd, PIOCSTATUS, &pi->prstatus) >= 0);
  920. #endif
  921. #endif

  922.   if (pi->status_valid)
  923.     {
  924.       PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
  925.                                 proc_why (pi),
  926.                                 proc_what (pi),
  927.                                 proc_get_current_thread (pi));
  928.     }

  929.   /* The status struct includes general regs, so mark them valid too.  */
  930.   pi->gregs_valid  = pi->status_valid;
  931. #ifdef NEW_PROC_API
  932.   /* In the read/write multiple-fd model, the status struct includes
  933.      the fp regs too, so mark them valid too.  */
  934.   pi->fpregs_valid = pi->status_valid;
  935. #endif
  936.   return pi->status_valid;        /* True if success, false if failure.  */
  937. }

  938. /* Returns the process flags (pr_flags field).  */

  939. static long
  940. proc_flags (procinfo *pi)
  941. {
  942.   if (!pi->status_valid)
  943.     if (!proc_get_status (pi))
  944.       return 0;        /* FIXME: not a good failure value (but what is?)  */

  945. #ifdef NEW_PROC_API
  946.   return pi->prstatus.pr_lwp.pr_flags;
  947. #else
  948.   return pi->prstatus.pr_flags;
  949. #endif
  950. }

  951. /* Returns the pr_why field (why the process stopped).  */

  952. static int
  953. proc_why (procinfo *pi)
  954. {
  955.   if (!pi->status_valid)
  956.     if (!proc_get_status (pi))
  957.       return 0;        /* FIXME: not a good failure value (but what is?)  */

  958. #ifdef NEW_PROC_API
  959.   return pi->prstatus.pr_lwp.pr_why;
  960. #else
  961.   return pi->prstatus.pr_why;
  962. #endif
  963. }

  964. /* Returns the pr_what field (details of why the process stopped).  */

  965. static int
  966. proc_what (procinfo *pi)
  967. {
  968.   if (!pi->status_valid)
  969.     if (!proc_get_status (pi))
  970.       return 0;        /* FIXME: not a good failure value (but what is?)  */

  971. #ifdef NEW_PROC_API
  972.   return pi->prstatus.pr_lwp.pr_what;
  973. #else
  974.   return pi->prstatus.pr_what;
  975. #endif
  976. }

  977. /* This function is only called when PI is stopped by a watchpoint.
  978.    Assuming the OS supports it, write to *ADDR the data address which
  979.    triggered it and return 1.  Return 0 if it is not possible to know
  980.    the address.  */

  981. static int
  982. proc_watchpoint_address (procinfo *pi, CORE_ADDR *addr)
  983. {
  984.   if (!pi->status_valid)
  985.     if (!proc_get_status (pi))
  986.       return 0;

  987. #ifdef NEW_PROC_API
  988.   *addr = (CORE_ADDR) gdbarch_pointer_to_address (target_gdbarch (),
  989.             builtin_type (target_gdbarch ())->builtin_data_ptr,
  990.             (gdb_byte *) &pi->prstatus.pr_lwp.pr_info.si_addr);
  991. #else
  992.   *addr = (CORE_ADDR) gdbarch_pointer_to_address (target_gdbarch (),
  993.             builtin_type (target_gdbarch ())->builtin_data_ptr,
  994.             (gdb_byte *) &pi->prstatus.pr_info.si_addr);
  995. #endif
  996.   return 1;
  997. }

  998. #ifndef PIOCSSPCACT        /* The following is not supported on OSF.  */

  999. /* Returns the pr_nsysarg field (number of args to the current
  1000.    syscall).  */

  1001. static int
  1002. proc_nsysarg (procinfo *pi)
  1003. {
  1004.   if (!pi->status_valid)
  1005.     if (!proc_get_status (pi))
  1006.       return 0;

  1007. #ifdef NEW_PROC_API
  1008.   return pi->prstatus.pr_lwp.pr_nsysarg;
  1009. #else
  1010.   return pi->prstatus.pr_nsysarg;
  1011. #endif
  1012. }

  1013. /* Returns the pr_sysarg field (pointer to the arguments of current
  1014.    syscall).  */

  1015. static long *
  1016. proc_sysargs (procinfo *pi)
  1017. {
  1018.   if (!pi->status_valid)
  1019.     if (!proc_get_status (pi))
  1020.       return NULL;

  1021. #ifdef NEW_PROC_API
  1022.   return (long *) &pi->prstatus.pr_lwp.pr_sysarg;
  1023. #else
  1024.   return (long *) &pi->prstatus.pr_sysarg;
  1025. #endif
  1026. }
  1027. #endif /* PIOCSSPCACT */

  1028. #ifdef PROCFS_DONT_PIOCSSIG_CURSIG
  1029. /* Returns the pr_cursig field (current signal).  */

  1030. static long
  1031. proc_cursig (struct procinfo *pi)
  1032. {
  1033.   if (!pi->status_valid)
  1034.     if (!proc_get_status (pi))
  1035.       return 0;        /* FIXME: not a good failure value (but what is?)  */

  1036. #ifdef NEW_PROC_API
  1037.   return pi->prstatus.pr_lwp.pr_cursig;
  1038. #else
  1039.   return pi->prstatus.pr_cursig;
  1040. #endif
  1041. }
  1042. #endif /* PROCFS_DONT_PIOCSSIG_CURSIG */

  1043. /* === I appologize for the messiness of this function.
  1044.    === This is an area where the different versions of
  1045.    === /proc are more inconsistent than usual.

  1046.    Set or reset any of the following process flags:
  1047.       PR_FORK        -- forked child will inherit trace flags
  1048.       PR_RLC        -- traced process runs when last /proc file closed.
  1049.       PR_KLC    -- traced process is killed when last /proc file closed.
  1050.       PR_ASYNC        -- LWP's get to run/stop independently.

  1051.    There are three methods for doing this function:
  1052.    1) Newest: read/write [PCSET/PCRESET/PCUNSET]
  1053.       [Sol6, Sol7, UW]
  1054.    2) Middle: PIOCSET/PIOCRESET
  1055.       [Irix, Sol5]
  1056.    3) Oldest: PIOCSFORK/PIOCRFORK/PIOCSRLC/PIOCRRLC
  1057.       [OSF, Sol5]

  1058.    Note: Irix does not define PR_ASYNC.
  1059.    Note: OSF  does not define PR_KLC.
  1060.    Note: OSF  is the only one that can ONLY use the oldest method.

  1061.    Arguments:
  1062.       pi   -- the procinfo
  1063.       flag -- one of PR_FORK, PR_RLC, or PR_ASYNC
  1064.       mode -- 1 for set, 0 for reset.

  1065.    Returns non-zero for success, zero for failure.  */

  1066. enum { FLAG_RESET, FLAG_SET };

  1067. static int
  1068. proc_modify_flag (procinfo *pi, long flag, long mode)
  1069. {
  1070.   long win = 0;                /* default to fail */

  1071.   /* These operations affect the process as a whole, and applying them
  1072.      to an individual LWP has the same meaning as applying them to the
  1073.      main process.  Therefore, if we're ever called with a pointer to
  1074.      an LWP's procinfo, let's substitute the process's procinfo and
  1075.      avoid opening the LWP's file descriptor unnecessarily.  */

  1076.   if (pi->pid != 0)
  1077.     pi = find_procinfo_or_die (pi->pid, 0);

  1078. #ifdef NEW_PROC_API        /* Newest method: Newer Solarii.  */
  1079.   /* First normalize the PCUNSET/PCRESET command opcode
  1080.      (which for no obvious reason has a different definition
  1081.      from one operating system to the next...)  */
  1082. #ifdef  PCUNSET
  1083. #define GDBRESET PCUNSET
  1084. #else
  1085. #ifdef  PCRESET
  1086. #define GDBRESET PCRESET
  1087. #endif
  1088. #endif
  1089.   {
  1090.     procfs_ctl_t arg[2];

  1091.     if (mode == FLAG_SET)        /* Set the flag (RLC, FORK, or ASYNC).  */
  1092.       arg[0] = PCSET;
  1093.     else                        /* Reset the flag.  */
  1094.       arg[0] = GDBRESET;

  1095.     arg[1] = flag;
  1096.     win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
  1097.   }
  1098. #else
  1099. #ifdef PIOCSET                /* Irix/Sol5 method */
  1100.   if (mode == FLAG_SET)        /* Set the flag (hopefully RLC, FORK, or ASYNC).  */
  1101.     {
  1102.       win = (ioctl (pi->ctl_fd, PIOCSET, &flag)   >= 0);
  1103.     }
  1104.   else                        /* Reset the flag.  */
  1105.     {
  1106.       win = (ioctl (pi->ctl_fd, PIOCRESET, &flag) >= 0);
  1107.     }

  1108. #else
  1109. #ifdef PIOCSRLC                /* Oldest method: OSF */
  1110.   switch (flag) {
  1111.   case PR_RLC:
  1112.     if (mode == FLAG_SET)        /* Set run-on-last-close */
  1113.       {
  1114.         win = (ioctl (pi->ctl_fd, PIOCSRLC, NULL) >= 0);
  1115.       }
  1116.     else                        /* Clear run-on-last-close */
  1117.       {
  1118.         win = (ioctl (pi->ctl_fd, PIOCRRLC, NULL) >= 0);
  1119.       }
  1120.     break;
  1121.   case PR_FORK:
  1122.     if (mode == FLAG_SET)        /* Set inherit-on-fork */
  1123.       {
  1124.         win = (ioctl (pi->ctl_fd, PIOCSFORK, NULL) >= 0);
  1125.       }
  1126.     else                        /* Clear inherit-on-fork */
  1127.       {
  1128.         win = (ioctl (pi->ctl_fd, PIOCRFORK, NULL) >= 0);
  1129.       }
  1130.     break;
  1131.   default:
  1132.     win = 0;                /* Fail -- unknown flag (can't do PR_ASYNC).  */
  1133.     break;
  1134.   }
  1135. #endif
  1136. #endif
  1137. #endif
  1138. #undef GDBRESET
  1139.   /* The above operation renders the procinfo's cached pstatus
  1140.      obsolete.  */
  1141.   pi->status_valid = 0;

  1142.   if (!win)
  1143.     warning (_("procfs: modify_flag failed to turn %s %s"),
  1144.              flag == PR_FORK  ? "PR_FORK"  :
  1145.              flag == PR_RLC   ? "PR_RLC"   :
  1146. #ifdef PR_ASYNC
  1147.              flag == PR_ASYNC ? "PR_ASYNC" :
  1148. #endif
  1149. #ifdef PR_KLC
  1150.              flag == PR_KLC   ? "PR_KLC"   :
  1151. #endif
  1152.              "<unknown flag>",
  1153.              mode == FLAG_RESET ? "off" : "on");

  1154.   return win;
  1155. }

  1156. /* Set the run_on_last_close flag.  Process with all threads will
  1157.    become runnable when debugger closes all /proc fds.  Returns
  1158.    non-zero for success, zero for failure.  */

  1159. static int
  1160. proc_set_run_on_last_close (procinfo *pi)
  1161. {
  1162.   return proc_modify_flag (pi, PR_RLC, FLAG_SET);
  1163. }

  1164. /* Reset the run_on_last_close flag.  The process will NOT become
  1165.    runnable when debugger closes its file handles.  Returns non-zero
  1166.    for success, zero for failure.  */

  1167. static int
  1168. proc_unset_run_on_last_close (procinfo *pi)
  1169. {
  1170.   return proc_modify_flag (pi, PR_RLC, FLAG_RESET);
  1171. }

  1172. /* Reset inherit_on_fork flag.  If the process forks a child while we
  1173.    are registered for events in the parent, then we will NOT recieve
  1174.    events from the child.  Returns non-zero for success, zero for
  1175.    failure.  */

  1176. static int
  1177. proc_unset_inherit_on_fork (procinfo *pi)
  1178. {
  1179.   return proc_modify_flag (pi, PR_FORK, FLAG_RESET);
  1180. }

  1181. #ifdef PR_ASYNC
  1182. /* Set PR_ASYNC flag.  If one LWP stops because of a debug event
  1183.    (signal etc.), the remaining LWPs will continue to run.  Returns
  1184.    non-zero for success, zero for failure.  */

  1185. static int
  1186. proc_set_async (procinfo *pi)
  1187. {
  1188.   return proc_modify_flag (pi, PR_ASYNC, FLAG_SET);
  1189. }

  1190. /* Reset PR_ASYNC flag.  If one LWP stops because of a debug event
  1191.    (signal etc.), then all other LWPs will stop as well.  Returns
  1192.    non-zero for success, zero for failure.  */

  1193. static int
  1194. proc_unset_async (procinfo *pi)
  1195. {
  1196.   return proc_modify_flag (pi, PR_ASYNC, FLAG_RESET);
  1197. }
  1198. #endif /* PR_ASYNC */

  1199. /* Request the process/LWP to stop.  Does not wait.  Returns non-zero
  1200.    for success, zero for failure.  */

  1201. static int
  1202. proc_stop_process (procinfo *pi)
  1203. {
  1204.   int win;

  1205.   /* We might conceivably apply this operation to an LWP, and the
  1206.      LWP's ctl file descriptor might not be open.  */

  1207.   if (pi->ctl_fd == 0 &&
  1208.       open_procinfo_files (pi, FD_CTL) == 0)
  1209.     return 0;
  1210.   else
  1211.     {
  1212. #ifdef NEW_PROC_API
  1213.       procfs_ctl_t cmd = PCSTOP;

  1214.       win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
  1215. #else        /* ioctl method */
  1216.       win = (ioctl (pi->ctl_fd, PIOCSTOP, &pi->prstatus) >= 0);
  1217.       /* Note: the call also reads the prstatus.  */
  1218.       if (win)
  1219.         {
  1220.           pi->status_valid = 1;
  1221.           PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
  1222.                                     proc_why (pi),
  1223.                                     proc_what (pi),
  1224.                                     proc_get_current_thread (pi));
  1225.         }
  1226. #endif
  1227.     }

  1228.   return win;
  1229. }

  1230. /* Wait for the process or LWP to stop (block until it does).  Returns
  1231.    non-zero for success, zero for failure.  */

  1232. static int
  1233. proc_wait_for_stop (procinfo *pi)
  1234. {
  1235.   int win;

  1236.   /* We should never have to apply this operation to any procinfo
  1237.      except the one for the main process.  If that ever changes for
  1238.      any reason, then take out the following clause and replace it
  1239.      with one that makes sure the ctl_fd is open.  */

  1240.   if (pi->tid != 0)
  1241.     pi = find_procinfo_or_die (pi->pid, 0);

  1242. #ifdef NEW_PROC_API
  1243.   {
  1244.     procfs_ctl_t cmd = PCWSTOP;

  1245.     win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
  1246.     /* We been runnin' and we stopped -- need to update status.  */
  1247.     pi->status_valid = 0;
  1248.   }
  1249. #else        /* ioctl method */
  1250.   win = (ioctl (pi->ctl_fd, PIOCWSTOP, &pi->prstatus) >= 0);
  1251.   /* Above call also refreshes the prstatus.  */
  1252.   if (win)
  1253.     {
  1254.       pi->status_valid = 1;
  1255.       PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
  1256.                                 proc_why (pi),
  1257.                                 proc_what (pi),
  1258.                                 proc_get_current_thread (pi));
  1259.     }
  1260. #endif

  1261.   return win;
  1262. }

  1263. /* Make the process or LWP runnable.

  1264.    Options (not all are implemented):
  1265.      - single-step
  1266.      - clear current fault
  1267.      - clear current signal
  1268.      - abort the current system call
  1269.      - stop as soon as finished with system call
  1270.      - (ioctl): set traced signal set
  1271.      - (ioctl): set held   signal set
  1272.      - (ioctl): set traced fault  set
  1273.      - (ioctl): set start pc (vaddr)

  1274.    Always clears the current fault.  PI is the process or LWP to
  1275.    operate on.  If STEP is true, set the process or LWP to trap after
  1276.    one instruction.  If SIGNO is zero, clear the current signal if
  1277.    any; if non-zero, set the current signal to this one.  Returns
  1278.    non-zero for success, zero for failure.  */

  1279. static int
  1280. proc_run_process (procinfo *pi, int step, int signo)
  1281. {
  1282.   int win;
  1283.   int runflags;

  1284.   /* We will probably have to apply this operation to individual
  1285.      threads, so make sure the control file descriptor is open.  */

  1286.   if (pi->ctl_fd == 0 &&
  1287.       open_procinfo_files (pi, FD_CTL) == 0)
  1288.     {
  1289.       return 0;
  1290.     }

  1291.   runflags    = PRCFAULT;        /* Always clear current fault.  */
  1292.   if (step)
  1293.     runflags |= PRSTEP;
  1294.   if (signo == 0)
  1295.     runflags |= PRCSIG;
  1296.   else if (signo != -1)                /* -1 means do nothing W.R.T. signals.  */
  1297.     proc_set_current_signal (pi, signo);

  1298. #ifdef NEW_PROC_API
  1299.   {
  1300.     procfs_ctl_t cmd[2];

  1301.     cmd[0]  = PCRUN;
  1302.     cmd[1]  = runflags;
  1303.     win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
  1304.   }
  1305. #else        /* ioctl method */
  1306.   {
  1307.     prrun_t prrun;

  1308.     memset (&prrun, 0, sizeof (prrun));
  1309.     prrun.pr_flags  = runflags;
  1310.     win = (ioctl (pi->ctl_fd, PIOCRUN, &prrun) >= 0);
  1311.   }
  1312. #endif

  1313.   return win;
  1314. }

  1315. /* Register to trace signals in the process or LWP.  Returns non-zero
  1316.    for success, zero for failure.  */

  1317. static int
  1318. proc_set_traced_signals (procinfo *pi, gdb_sigset_t *sigset)
  1319. {
  1320.   int win;

  1321.   /* We should never have to apply this operation to any procinfo
  1322.      except the one for the main process.  If that ever changes for
  1323.      any reason, then take out the following clause and replace it
  1324.      with one that makes sure the ctl_fd is open.  */

  1325.   if (pi->tid != 0)
  1326.     pi = find_procinfo_or_die (pi->pid, 0);

  1327. #ifdef NEW_PROC_API
  1328.   {
  1329.     struct {
  1330.       procfs_ctl_t cmd;
  1331.       /* Use char array to avoid alignment issues.  */
  1332.       char sigset[sizeof (gdb_sigset_t)];
  1333.     } arg;

  1334.     arg.cmd = PCSTRACE;
  1335.     memcpy (&arg.sigset, sigset, sizeof (gdb_sigset_t));

  1336.     win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
  1337.   }
  1338. #else        /* ioctl method */
  1339.   win = (ioctl (pi->ctl_fd, PIOCSTRACE, sigset) >= 0);
  1340. #endif
  1341.   /* The above operation renders the procinfo's cached pstatus obsolete.  */
  1342.   pi->status_valid = 0;

  1343.   if (!win)
  1344.     warning (_("procfs: set_traced_signals failed"));
  1345.   return win;
  1346. }

  1347. /* Register to trace hardware faults in the process or LWP.  Returns
  1348.    non-zero for success, zero for failure.  */

  1349. static int
  1350. proc_set_traced_faults (procinfo *pi, fltset_t *fltset)
  1351. {
  1352.   int win;

  1353.   /* We should never have to apply this operation to any procinfo
  1354.      except the one for the main process.  If that ever changes for
  1355.      any reason, then take out the following clause and replace it
  1356.      with one that makes sure the ctl_fd is open.  */

  1357.   if (pi->tid != 0)
  1358.     pi = find_procinfo_or_die (pi->pid, 0);

  1359. #ifdef NEW_PROC_API
  1360.   {
  1361.     struct {
  1362.       procfs_ctl_t cmd;
  1363.       /* Use char array to avoid alignment issues.  */
  1364.       char fltset[sizeof (fltset_t)];
  1365.     } arg;

  1366.     arg.cmd = PCSFAULT;
  1367.     memcpy (&arg.fltset, fltset, sizeof (fltset_t));

  1368.     win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
  1369.   }
  1370. #else        /* ioctl method */
  1371.   win = (ioctl (pi->ctl_fd, PIOCSFAULT, fltset) >= 0);
  1372. #endif
  1373.   /* The above operation renders the procinfo's cached pstatus obsolete.  */
  1374.   pi->status_valid = 0;

  1375.   return win;
  1376. }

  1377. /* Register to trace entry to system calls in the process or LWP.
  1378.    Returns non-zero for success, zero for failure.  */

  1379. static int
  1380. proc_set_traced_sysentry (procinfo *pi, sysset_t *sysset)
  1381. {
  1382.   int win;

  1383.   /* We should never have to apply this operation to any procinfo
  1384.      except the one for the main process.  If that ever changes for
  1385.      any reason, then take out the following clause and replace it
  1386.      with one that makes sure the ctl_fd is open.  */

  1387.   if (pi->tid != 0)
  1388.     pi = find_procinfo_or_die (pi->pid, 0);

  1389. #ifdef NEW_PROC_API
  1390.   {
  1391.     struct gdb_proc_ctl_pcsentry {
  1392.       procfs_ctl_t cmd;
  1393.       /* Use char array to avoid alignment issues.  */
  1394.       char sysset[sizeof (sysset_t)];
  1395.     } *argp;
  1396.     int argp_size = sizeof (struct gdb_proc_ctl_pcsentry)
  1397.                   - sizeof (sysset_t)
  1398.                   + sysset_t_size (pi);

  1399.     argp = xmalloc (argp_size);

  1400.     argp->cmd = PCSENTRY;
  1401.     memcpy (&argp->sysset, sysset, sysset_t_size (pi));

  1402.     win = (write (pi->ctl_fd, (char *) argp, argp_size) == argp_size);
  1403.     xfree (argp);
  1404.   }
  1405. #else        /* ioctl method */
  1406.   win = (ioctl (pi->ctl_fd, PIOCSENTRY, sysset) >= 0);
  1407. #endif
  1408.   /* The above operation renders the procinfo's cached pstatus
  1409.      obsolete.  */
  1410.   pi->status_valid = 0;

  1411.   return win;
  1412. }

  1413. /* Register to trace exit from system calls in the process or LWP.
  1414.    Returns non-zero for success, zero for failure.  */

  1415. static int
  1416. proc_set_traced_sysexit (procinfo *pi, sysset_t *sysset)
  1417. {
  1418.   int win;

  1419.   /* We should never have to apply this operation to any procinfo
  1420.      except the one for the main process.  If that ever changes for
  1421.      any reason, then take out the following clause and replace it
  1422.      with one that makes sure the ctl_fd is open.  */

  1423.   if (pi->tid != 0)
  1424.     pi = find_procinfo_or_die (pi->pid, 0);

  1425. #ifdef NEW_PROC_API
  1426.   {
  1427.     struct gdb_proc_ctl_pcsexit {
  1428.       procfs_ctl_t cmd;
  1429.       /* Use char array to avoid alignment issues.  */
  1430.       char sysset[sizeof (sysset_t)];
  1431.     } *argp;
  1432.     int argp_size = sizeof (struct gdb_proc_ctl_pcsexit)
  1433.                   - sizeof (sysset_t)
  1434.                   + sysset_t_size (pi);

  1435.     argp = xmalloc (argp_size);

  1436.     argp->cmd = PCSEXIT;
  1437.     memcpy (&argp->sysset, sysset, sysset_t_size (pi));

  1438.     win = (write (pi->ctl_fd, (char *) argp, argp_size) == argp_size);
  1439.     xfree (argp);
  1440.   }
  1441. #else        /* ioctl method */
  1442.   win = (ioctl (pi->ctl_fd, PIOCSEXIT, sysset) >= 0);
  1443. #endif
  1444.   /* The above operation renders the procinfo's cached pstatus
  1445.      obsolete.  */
  1446.   pi->status_valid = 0;

  1447.   return win;
  1448. }

  1449. /* Specify the set of blocked / held signals in the process or LWP.
  1450.    Returns non-zero for success, zero for failure.  */

  1451. static int
  1452. proc_set_held_signals (procinfo *pi, gdb_sigset_t *sighold)
  1453. {
  1454.   int win;

  1455.   /* We should never have to apply this operation to any procinfo
  1456.      except the one for the main process.  If that ever changes for
  1457.      any reason, then take out the following clause and replace it
  1458.      with one that makes sure the ctl_fd is open.  */

  1459.   if (pi->tid != 0)
  1460.     pi = find_procinfo_or_die (pi->pid, 0);

  1461. #ifdef NEW_PROC_API
  1462.   {
  1463.     struct {
  1464.       procfs_ctl_t cmd;
  1465.       /* Use char array to avoid alignment issues.  */
  1466.       char hold[sizeof (gdb_sigset_t)];
  1467.     } arg;

  1468.     arg.cmd  = PCSHOLD;
  1469.     memcpy (&arg.hold, sighold, sizeof (gdb_sigset_t));
  1470.     win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
  1471.   }
  1472. #else
  1473.   win = (ioctl (pi->ctl_fd, PIOCSHOLD, sighold) >= 0);
  1474. #endif
  1475.   /* The above operation renders the procinfo's cached pstatus
  1476.      obsolete.  */
  1477.   pi->status_valid = 0;

  1478.   return win;
  1479. }

  1480. /* Returns the set of signals that are held / blocked.  Will also copy
  1481.    the sigset if SAVE is non-zero.  */

  1482. static gdb_sigset_t *
  1483. proc_get_held_signals (procinfo *pi, gdb_sigset_t *save)
  1484. {
  1485.   gdb_sigset_t *ret = NULL;

  1486.   /* We should never have to apply this operation to any procinfo
  1487.      except the one for the main process.  If that ever changes for
  1488.      any reason, then take out the following clause and replace it
  1489.      with one that makes sure the ctl_fd is open.  */

  1490.   if (pi->tid != 0)
  1491.     pi = find_procinfo_or_die (pi->pid, 0);

  1492. #ifdef NEW_PROC_API
  1493.   if (!pi->status_valid)
  1494.     if (!proc_get_status (pi))
  1495.       return NULL;

  1496.   ret = &pi->prstatus.pr_lwp.pr_lwphold;
  1497. #else  /* not NEW_PROC_API */
  1498.   {
  1499.     static gdb_sigset_t sigheld;

  1500.     if (ioctl (pi->ctl_fd, PIOCGHOLD, &sigheld) >= 0)
  1501.       ret = &sigheld;
  1502.   }
  1503. #endif /* NEW_PROC_API */
  1504.   if (save && ret)
  1505.     memcpy (save, ret, sizeof (gdb_sigset_t));

  1506.   return ret;
  1507. }

  1508. /* Returns the set of signals that are traced / debugged.  Will also
  1509.    copy the sigset if SAVE is non-zero.  */

  1510. static gdb_sigset_t *
  1511. proc_get_traced_signals (procinfo *pi, gdb_sigset_t *save)
  1512. {
  1513.   gdb_sigset_t *ret = NULL;

  1514.   /* We should never have to apply this operation to any procinfo
  1515.      except the one for the main process.  If that ever changes for
  1516.      any reason, then take out the following clause and replace it
  1517.      with one that makes sure the ctl_fd is open.  */

  1518.   if (pi->tid != 0)
  1519.     pi = find_procinfo_or_die (pi->pid, 0);

  1520. #ifdef NEW_PROC_API
  1521.   if (!pi->status_valid)
  1522.     if (!proc_get_status (pi))
  1523.       return NULL;

  1524.   ret = &pi->prstatus.pr_sigtrace;
  1525. #else
  1526.   {
  1527.     static gdb_sigset_t sigtrace;

  1528.     if (ioctl (pi->ctl_fd, PIOCGTRACE, &sigtrace) >= 0)
  1529.       ret = &sigtrace;
  1530.   }
  1531. #endif
  1532.   if (save && ret)
  1533.     memcpy (save, ret, sizeof (gdb_sigset_t));

  1534.   return ret;
  1535. }

  1536. /* Returns the set of hardware faults that are traced /debugged.  Will
  1537.    also copy the faultset if SAVE is non-zero.  */

  1538. static fltset_t *
  1539. proc_get_traced_faults (procinfo *pi, fltset_t *save)
  1540. {
  1541.   fltset_t *ret = NULL;

  1542.   /* We should never have to apply this operation to any procinfo
  1543.      except the one for the main process.  If that ever changes for
  1544.      any reason, then take out the following clause and replace it
  1545.      with one that makes sure the ctl_fd is open.  */

  1546.   if (pi->tid != 0)
  1547.     pi = find_procinfo_or_die (pi->pid, 0);

  1548. #ifdef NEW_PROC_API
  1549.   if (!pi->status_valid)
  1550.     if (!proc_get_status (pi))
  1551.       return NULL;

  1552.   ret = &pi->prstatus.pr_flttrace;
  1553. #else
  1554.   {
  1555.     static fltset_t flttrace;

  1556.     if (ioctl (pi->ctl_fd, PIOCGFAULT, &flttrace) >= 0)
  1557.       ret = &flttrace;
  1558.   }
  1559. #endif
  1560.   if (save && ret)
  1561.     memcpy (save, ret, sizeof (fltset_t));

  1562.   return ret;
  1563. }

  1564. /* Returns the set of syscalls that are traced /debugged on entry.
  1565.    Will also copy the syscall set if SAVE is non-zero.  */

  1566. static sysset_t *
  1567. proc_get_traced_sysentry (procinfo *pi, sysset_t *save)
  1568. {
  1569.   sysset_t *ret = NULL;

  1570.   /* We should never have to apply this operation to any procinfo
  1571.      except the one for the main process.  If that ever changes for
  1572.      any reason, then take out the following clause and replace it
  1573.      with one that makes sure the ctl_fd is open.  */

  1574.   if (pi->tid != 0)
  1575.     pi = find_procinfo_or_die (pi->pid, 0);

  1576. #ifdef NEW_PROC_API
  1577.   if (!pi->status_valid)
  1578.     if (!proc_get_status (pi))
  1579.       return NULL;

  1580. #ifndef DYNAMIC_SYSCALLS
  1581.   ret = &pi->prstatus.pr_sysentry;
  1582. #else /* DYNAMIC_SYSCALLS */
  1583.   {
  1584.     static sysset_t *sysentry;
  1585.     size_t size;

  1586.     if (!sysentry)
  1587.       sysentry = sysset_t_alloc (pi);
  1588.     ret = sysentry;
  1589.     if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
  1590.       return NULL;
  1591.     if (pi->prstatus.pr_sysentry_offset == 0)
  1592.       {
  1593.         gdb_premptysysset (sysentry);
  1594.       }
  1595.     else
  1596.       {
  1597.         int rsize;

  1598.         if (lseek (pi->status_fd, (off_t) pi->prstatus.pr_sysentry_offset,
  1599.                    SEEK_SET)
  1600.             != (off_t) pi->prstatus.pr_sysentry_offset)
  1601.           return NULL;
  1602.         size = sysset_t_size (pi);
  1603.         gdb_premptysysset (sysentry);
  1604.         rsize = read (pi->status_fd, sysentry, size);
  1605.         if (rsize < 0)
  1606.           return NULL;
  1607.       }
  1608.   }
  1609. #endif /* DYNAMIC_SYSCALLS */
  1610. #else /* !NEW_PROC_API */
  1611.   {
  1612.     static sysset_t sysentry;

  1613.     if (ioctl (pi->ctl_fd, PIOCGENTRY, &sysentry) >= 0)
  1614.       ret = &sysentry;
  1615.   }
  1616. #endif /* NEW_PROC_API */
  1617.   if (save && ret)
  1618.     memcpy (save, ret, sysset_t_size (pi));

  1619.   return ret;
  1620. }

  1621. /* Returns the set of syscalls that are traced /debugged on exit.
  1622.    Will also copy the syscall set if SAVE is non-zero.  */

  1623. static sysset_t *
  1624. proc_get_traced_sysexit (procinfo *pi, sysset_t *save)
  1625. {
  1626.   sysset_t * ret = NULL;

  1627.   /* We should never have to apply this operation to any procinfo
  1628.      except the one for the main process.  If that ever changes for
  1629.      any reason, then take out the following clause and replace it
  1630.      with one that makes sure the ctl_fd is open.  */

  1631.   if (pi->tid != 0)
  1632.     pi = find_procinfo_or_die (pi->pid, 0);

  1633. #ifdef NEW_PROC_API
  1634.   if (!pi->status_valid)
  1635.     if (!proc_get_status (pi))
  1636.       return NULL;

  1637. #ifndef DYNAMIC_SYSCALLS
  1638.   ret = &pi->prstatus.pr_sysexit;
  1639. #else /* DYNAMIC_SYSCALLS */
  1640.   {
  1641.     static sysset_t *sysexit;
  1642.     size_t size;

  1643.     if (!sysexit)
  1644.       sysexit = sysset_t_alloc (pi);
  1645.     ret = sysexit;
  1646.     if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
  1647.       return NULL;
  1648.     if (pi->prstatus.pr_sysexit_offset == 0)
  1649.       {
  1650.         gdb_premptysysset (sysexit);
  1651.       }
  1652.     else
  1653.       {
  1654.         int rsize;

  1655.         if (lseek (pi->status_fd, (off_t) pi->prstatus.pr_sysexit_offset,
  1656.                    SEEK_SET)
  1657.             != (off_t) pi->prstatus.pr_sysexit_offset)
  1658.           return NULL;
  1659.         size = sysset_t_size (pi);
  1660.         gdb_premptysysset (sysexit);
  1661.         rsize = read (pi->status_fd, sysexit, size);
  1662.         if (rsize < 0)
  1663.           return NULL;
  1664.       }
  1665.   }
  1666. #endif /* DYNAMIC_SYSCALLS */
  1667. #else
  1668.   {
  1669.     static sysset_t sysexit;

  1670.     if (ioctl (pi->ctl_fd, PIOCGEXIT, &sysexit) >= 0)
  1671.       ret = &sysexit;
  1672.   }
  1673. #endif
  1674.   if (save && ret)
  1675.     memcpy (save, ret, sysset_t_size (pi));

  1676.   return ret;
  1677. }

  1678. /* The current fault (if any) is cleared; the associated signal will
  1679.    not be sent to the process or LWP when it resumes.  Returns
  1680.    non-zero for success, zero for failure.  */

  1681. static int
  1682. proc_clear_current_fault (procinfo *pi)
  1683. {
  1684.   int win;

  1685.   /* We should never have to apply this operation to any procinfo
  1686.      except the one for the main process.  If that ever changes for
  1687.      any reason, then take out the following clause and replace it
  1688.      with one that makes sure the ctl_fd is open.  */

  1689.   if (pi->tid != 0)
  1690.     pi = find_procinfo_or_die (pi->pid, 0);

  1691. #ifdef NEW_PROC_API
  1692.   {
  1693.     procfs_ctl_t cmd = PCCFAULT;

  1694.     win = (write (pi->ctl_fd, (void *) &cmd, sizeof (cmd)) == sizeof (cmd));
  1695.   }
  1696. #else
  1697.   win = (ioctl (pi->ctl_fd, PIOCCFAULT, 0) >= 0);
  1698. #endif

  1699.   return win;
  1700. }

  1701. /* Set the "current signal" that will be delivered next to the
  1702.    process.  NOTE: semantics are different from those of KILL.  This
  1703.    signal will be delivered to the process or LWP immediately when it
  1704.    is resumed (even if the signal is held/blocked); it will NOT
  1705.    immediately cause another event of interest, and will NOT first
  1706.    trap back to the debugger.  Returns non-zero for success, zero for
  1707.    failure.  */

  1708. static int
  1709. proc_set_current_signal (procinfo *pi, int signo)
  1710. {
  1711.   int win;
  1712.   struct {
  1713.     procfs_ctl_t cmd;
  1714.     /* Use char array to avoid alignment issues.  */
  1715.     char sinfo[sizeof (gdb_siginfo_t)];
  1716.   } arg;
  1717.   gdb_siginfo_t mysinfo;
  1718.   ptid_t wait_ptid;
  1719.   struct target_waitstatus wait_status;

  1720.   /* We should never have to apply this operation to any procinfo
  1721.      except the one for the main process.  If that ever changes for
  1722.      any reason, then take out the following clause and replace it
  1723.      with one that makes sure the ctl_fd is open.  */

  1724.   if (pi->tid != 0)
  1725.     pi = find_procinfo_or_die (pi->pid, 0);

  1726. #ifdef PROCFS_DONT_PIOCSSIG_CURSIG
  1727.   /* With Alpha OSF/1 procfs, the kernel gets really confused if it
  1728.      receives a PIOCSSIG with a signal identical to the current
  1729.      signal, it messes up the current signal.  Work around the kernel
  1730.      bug.  */
  1731.   if (signo > 0 &&
  1732.       signo == proc_cursig (pi))
  1733.     return 1;           /* I assume this is a success?  */
  1734. #endif

  1735.   /* The pointer is just a type alias.  */
  1736.   get_last_target_status (&wait_ptid, &wait_status);
  1737.   if (ptid_equal (wait_ptid, inferior_ptid)
  1738.       && wait_status.kind == TARGET_WAITKIND_STOPPED
  1739.       && wait_status.value.sig == gdb_signal_from_host (signo)
  1740.       && proc_get_status (pi)
  1741. #ifdef NEW_PROC_API
  1742.       && pi->prstatus.pr_lwp.pr_info.si_signo == signo
  1743. #else
  1744.       && pi->prstatus.pr_info.si_signo == signo
  1745. #endif
  1746.       )
  1747.     /* Use the siginfo associated with the signal being
  1748.        redelivered.  */
  1749. #ifdef NEW_PROC_API
  1750.     memcpy (arg.sinfo, &pi->prstatus.pr_lwp.pr_info, sizeof (gdb_siginfo_t));
  1751. #else
  1752.     memcpy (arg.sinfo, &pi->prstatus.pr_info, sizeof (gdb_siginfo_t));
  1753. #endif
  1754.   else
  1755.     {
  1756.       mysinfo.si_signo = signo;
  1757.       mysinfo.si_code  = 0;
  1758.       mysinfo.si_pid   = getpid ();       /* ?why? */
  1759.       mysinfo.si_uid   = getuid ();       /* ?why? */
  1760.       memcpy (arg.sinfo, &mysinfo, sizeof (gdb_siginfo_t));
  1761.     }

  1762. #ifdef NEW_PROC_API
  1763.   arg.cmd = PCSSIG;
  1764.   win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg))  == sizeof (arg));
  1765. #else
  1766.   win = (ioctl (pi->ctl_fd, PIOCSSIG, (void *) &arg.sinfo) >= 0);
  1767. #endif

  1768.   return win;
  1769. }

  1770. /* The current signal (if any) is cleared, and is not sent to the
  1771.    process or LWP when it resumes.  Returns non-zero for success, zero
  1772.    for failure.  */

  1773. static int
  1774. proc_clear_current_signal (procinfo *pi)
  1775. {
  1776.   int win;

  1777.   /* We should never have to apply this operation to any procinfo
  1778.      except the one for the main process.  If that ever changes for
  1779.      any reason, then take out the following clause and replace it
  1780.      with one that makes sure the ctl_fd is open.  */

  1781.   if (pi->tid != 0)
  1782.     pi = find_procinfo_or_die (pi->pid, 0);

  1783. #ifdef NEW_PROC_API
  1784.   {
  1785.     struct {
  1786.       procfs_ctl_t cmd;
  1787.       /* Use char array to avoid alignment issues.  */
  1788.       char sinfo[sizeof (gdb_siginfo_t)];
  1789.     } arg;
  1790.     gdb_siginfo_t mysinfo;

  1791.     arg.cmd = PCSSIG;
  1792.     /* The pointer is just a type alias.  */
  1793.     mysinfo.si_signo = 0;
  1794.     mysinfo.si_code  = 0;
  1795.     mysinfo.si_errno = 0;
  1796.     mysinfo.si_pid   = getpid ();       /* ?why? */
  1797.     mysinfo.si_uid   = getuid ();       /* ?why? */
  1798.     memcpy (arg.sinfo, &mysinfo, sizeof (gdb_siginfo_t));

  1799.     win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
  1800.   }
  1801. #else
  1802.   win = (ioctl (pi->ctl_fd, PIOCSSIG, 0) >= 0);
  1803. #endif

  1804.   return win;
  1805. }

  1806. /* Return the general-purpose registers for the process or LWP
  1807.    corresponding to PI.  Upon failure, return NULL.  */

  1808. static gdb_gregset_t *
  1809. proc_get_gregs (procinfo *pi)
  1810. {
  1811.   if (!pi->status_valid || !pi->gregs_valid)
  1812.     if (!proc_get_status (pi))
  1813.       return NULL;

  1814. #ifdef NEW_PROC_API
  1815.   return &pi->prstatus.pr_lwp.pr_reg;
  1816. #else
  1817.   return &pi->prstatus.pr_reg;
  1818. #endif
  1819. }

  1820. /* Return the general-purpose registers for the process or LWP
  1821.    corresponding to PI.  Upon failure, return NULL.  */

  1822. static gdb_fpregset_t *
  1823. proc_get_fpregs (procinfo *pi)
  1824. {
  1825. #ifdef NEW_PROC_API
  1826.   if (!pi->status_valid || !pi->fpregs_valid)
  1827.     if (!proc_get_status (pi))
  1828.       return NULL;

  1829.   return &pi->prstatus.pr_lwp.pr_fpreg;

  1830. #else  /* not NEW_PROC_API */
  1831.   if (pi->fpregs_valid)
  1832.     return &pi->fpregset;        /* Already got 'em.  */
  1833.   else
  1834.     {
  1835.       if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
  1836.         {
  1837.           return NULL;
  1838.         }
  1839.       else
  1840.         {
  1841. # ifdef PIOCTGFPREG
  1842.           struct {
  1843.             long pr_count;
  1844.             tid_t pr_error_thread;
  1845.             tfpregset_t thread_1;
  1846.           } thread_fpregs;

  1847.           thread_fpregs.pr_count = 1;
  1848.           thread_fpregs.thread_1.tid = pi->tid;

  1849.           if (pi->tid == 0
  1850.               && ioctl (pi->ctl_fd, PIOCGFPREG, &pi->fpregset) >= 0)
  1851.             {
  1852.               pi->fpregs_valid = 1;
  1853.               return &pi->fpregset; /* Got 'em now!  */
  1854.             }
  1855.           else if (pi->tid != 0
  1856.                    && ioctl (pi->ctl_fd, PIOCTGFPREG, &thread_fpregs) >= 0)
  1857.             {
  1858.               memcpy (&pi->fpregset, &thread_fpregs.thread_1.pr_fpregs,
  1859.                       sizeof (pi->fpregset));
  1860.               pi->fpregs_valid = 1;
  1861.               return &pi->fpregset; /* Got 'em now!  */
  1862.             }
  1863.           else
  1864.             {
  1865.               return NULL;
  1866.             }
  1867. # else
  1868.           if (ioctl (pi->ctl_fd, PIOCGFPREG, &pi->fpregset) >= 0)
  1869.             {
  1870.               pi->fpregs_valid = 1;
  1871.               return &pi->fpregset; /* Got 'em now!  */
  1872.             }
  1873.           else
  1874.             {
  1875.               return NULL;
  1876.             }
  1877. # endif
  1878.         }
  1879.     }
  1880. #endif /* NEW_PROC_API */
  1881. }

  1882. /* Write the general-purpose registers back to the process or LWP
  1883.    corresponding to PI.  Return non-zero for success, zero for
  1884.    failure.  */

  1885. static int
  1886. proc_set_gregs (procinfo *pi)
  1887. {
  1888.   gdb_gregset_t *gregs;
  1889.   int win;

  1890.   gregs = proc_get_gregs (pi);
  1891.   if (gregs == NULL)
  1892.     return 0;                        /* proc_get_regs has already warned.  */

  1893.   if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
  1894.     {
  1895.       return 0;
  1896.     }
  1897.   else
  1898.     {
  1899. #ifdef NEW_PROC_API
  1900.       struct {
  1901.         procfs_ctl_t cmd;
  1902.         /* Use char array to avoid alignment issues.  */
  1903.         char gregs[sizeof (gdb_gregset_t)];
  1904.       } arg;

  1905.       arg.cmd = PCSREG;
  1906.       memcpy (&arg.gregs, gregs, sizeof (arg.gregs));
  1907.       win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
  1908. #else
  1909.       win = (ioctl (pi->ctl_fd, PIOCSREG, gregs) >= 0);
  1910. #endif
  1911.     }

  1912.   /* Policy: writing the registers invalidates our cache.  */
  1913.   pi->gregs_valid = 0;
  1914.   return win;
  1915. }

  1916. /* Write the floating-pointer registers back to the process or LWP
  1917.    corresponding to PI.  Return non-zero for success, zero for
  1918.    failure.  */

  1919. static int
  1920. proc_set_fpregs (procinfo *pi)
  1921. {
  1922.   gdb_fpregset_t *fpregs;
  1923.   int win;

  1924.   fpregs = proc_get_fpregs (pi);
  1925.   if (fpregs == NULL)
  1926.     return 0;                        /* proc_get_fpregs has already warned.  */

  1927.   if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
  1928.     {
  1929.       return 0;
  1930.     }
  1931.   else
  1932.     {
  1933. #ifdef NEW_PROC_API
  1934.       struct {
  1935.         procfs_ctl_t cmd;
  1936.         /* Use char array to avoid alignment issues.  */
  1937.         char fpregs[sizeof (gdb_fpregset_t)];
  1938.       } arg;

  1939.       arg.cmd = PCSFPREG;
  1940.       memcpy (&arg.fpregs, fpregs, sizeof (arg.fpregs));
  1941.       win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
  1942. #else
  1943. # ifdef PIOCTSFPREG
  1944.       if (pi->tid == 0)
  1945.         win = (ioctl (pi->ctl_fd, PIOCSFPREG, fpregs) >= 0);
  1946.       else
  1947.         {
  1948.           struct {
  1949.             long pr_count;
  1950.             tid_t pr_error_thread;
  1951.             tfpregset_t thread_1;
  1952.           } thread_fpregs;

  1953.           thread_fpregs.pr_count = 1;
  1954.           thread_fpregs.thread_1.tid = pi->tid;
  1955.           memcpy (&thread_fpregs.thread_1.pr_fpregs, fpregs,
  1956.                   sizeof (*fpregs));
  1957.           win = (ioctl (pi->ctl_fd, PIOCTSFPREG, &thread_fpregs) >= 0);
  1958.         }
  1959. # else
  1960.       win = (ioctl (pi->ctl_fd, PIOCSFPREG, fpregs) >= 0);
  1961. # endif
  1962. #endif /* NEW_PROC_API */
  1963.     }

  1964.   /* Policy: writing the registers invalidates our cache.  */
  1965.   pi->fpregs_valid = 0;
  1966.   return win;
  1967. }

  1968. /* Send a signal to the proc or lwp with the semantics of "kill()".
  1969.    Returns non-zero for success, zero for failure.  */

  1970. static int
  1971. proc_kill (procinfo *pi, int signo)
  1972. {
  1973.   int win;

  1974.   /* We might conceivably apply this operation to an LWP, and the
  1975.      LWP's ctl file descriptor might not be open.  */

  1976.   if (pi->ctl_fd == 0 &&
  1977.       open_procinfo_files (pi, FD_CTL) == 0)
  1978.     {
  1979.       return 0;
  1980.     }
  1981.   else
  1982.     {
  1983. #ifdef NEW_PROC_API
  1984.       procfs_ctl_t cmd[2];

  1985.       cmd[0] = PCKILL;
  1986.       cmd[1] = signo;
  1987.       win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
  1988. #else   /* ioctl method */
  1989.       /* FIXME: do I need the Alpha OSF fixups present in
  1990.          procfs.c/unconditionally_kill_inferior?  Perhaps only for SIGKILL?  */
  1991.       win = (ioctl (pi->ctl_fd, PIOCKILL, &signo) >= 0);
  1992. #endif
  1993.   }

  1994.   return win;
  1995. }

  1996. /* Find the pid of the process that started this one.  Returns the
  1997.    parent process pid, or zero.  */

  1998. static int
  1999. proc_parent_pid (procinfo *pi)
  2000. {
  2001.   /* We should never have to apply this operation to any procinfo
  2002.      except the one for the main process.  If that ever changes for
  2003.      any reason, then take out the following clause and replace it
  2004.      with one that makes sure the ctl_fd is open.  */

  2005.   if (pi->tid != 0)
  2006.     pi = find_procinfo_or_die (pi->pid, 0);

  2007.   if (!pi->status_valid)
  2008.     if (!proc_get_status (pi))
  2009.       return 0;

  2010.   return pi->prstatus.pr_ppid;
  2011. }

  2012. /* Convert a target address (a.k.a. CORE_ADDR) into a host address
  2013.    (a.k.a void pointer)!  */

  2014. #if (defined (PCWATCH) || defined (PIOCSWATCH)) \
  2015.     && !(defined (PIOCOPENLWP))
  2016. static void *
  2017. procfs_address_to_host_pointer (CORE_ADDR addr)
  2018. {
  2019.   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
  2020.   void *ptr;

  2021.   gdb_assert (sizeof (ptr) == TYPE_LENGTH (ptr_type));
  2022.   gdbarch_address_to_pointer (target_gdbarch (), ptr_type,
  2023.                               (gdb_byte *) &ptr, addr);
  2024.   return ptr;
  2025. }
  2026. #endif

  2027. static int
  2028. proc_set_watchpoint (procinfo *pi, CORE_ADDR addr, int len, int wflags)
  2029. {
  2030. #if !defined (PCWATCH) && !defined (PIOCSWATCH)
  2031.   /* If neither or these is defined, we can't support watchpoints.
  2032.      This just avoids possibly failing to compile the below on such
  2033.      systems.  */
  2034.   return 0;
  2035. #else
  2036. /* Horrible hack!  Detect Solaris 2.5, because this doesn't work on 2.5.  */
  2037. #if defined (PIOCOPENLWP)        /* Solaris 2.5: bail out.  */
  2038.   return 0;
  2039. #else
  2040.   struct {
  2041.     procfs_ctl_t cmd;
  2042.     char watch[sizeof (prwatch_t)];
  2043.   } arg;
  2044.   prwatch_t pwatch;

  2045.   /* NOTE: cagney/2003-02-01: Even more horrible hack.  Need to
  2046.      convert a target address into something that can be stored in a
  2047.      native data structure.  */
  2048. #ifdef PCAGENT        /* Horrible hack: only defined on Solaris 2.6+ */
  2049.   pwatch.pr_vaddr  = (uintptr_t) procfs_address_to_host_pointer (addr);
  2050. #else
  2051.   pwatch.pr_vaddr  = (caddr_t) procfs_address_to_host_pointer (addr);
  2052. #endif
  2053.   pwatch.pr_size   = len;
  2054.   pwatch.pr_wflags = wflags;
  2055. #if defined(NEW_PROC_API) && defined (PCWATCH)
  2056.   arg.cmd = PCWATCH;
  2057.   memcpy (arg.watch, &pwatch, sizeof (prwatch_t));
  2058.   return (write (pi->ctl_fd, &arg, sizeof (arg)) == sizeof (arg));
  2059. #else
  2060. #if defined (PIOCSWATCH)
  2061.   return (ioctl (pi->ctl_fd, PIOCSWATCH, &pwatch) >= 0);
  2062. #else
  2063.   return 0;        /* Fail */
  2064. #endif
  2065. #endif
  2066. #endif
  2067. #endif
  2068. }

  2069. #if (defined(__i386__) || defined(__x86_64__)) && defined (sun)

  2070. #include <sys/sysi86.h>

  2071. /* The KEY is actually the value of the lower 16 bits of the GS
  2072.    register for the LWP that we're interested in.  Returns the
  2073.    matching ssh struct (LDT entry).  */

  2074. static struct ssd *
  2075. proc_get_LDT_entry (procinfo *pi, int key)
  2076. {
  2077.   static struct ssd *ldt_entry = NULL;
  2078. #ifdef NEW_PROC_API
  2079.   char pathname[MAX_PROC_NAME_SIZE];
  2080.   struct cleanup *old_chain = NULL;
  2081.   int  fd;

  2082.   /* Allocate space for one LDT entry.
  2083.      This alloc must persist, because we return a pointer to it.  */
  2084.   if (ldt_entry == NULL)
  2085.     ldt_entry = (struct ssd *) xmalloc (sizeof (struct ssd));

  2086.   /* Open the file descriptor for the LDT table.  */
  2087.   sprintf (pathname, "/proc/%d/ldt", pi->pid);
  2088.   if ((fd = open_with_retry (pathname, O_RDONLY)) < 0)
  2089.     {
  2090.       proc_warn (pi, "proc_get_LDT_entry (open)", __LINE__);
  2091.       return NULL;
  2092.     }
  2093.   /* Make sure it gets closed again!  */
  2094.   old_chain = make_cleanup_close (fd);

  2095.   /* Now 'read' thru the table, find a match and return it.  */
  2096.   while (read (fd, ldt_entry, sizeof (struct ssd)) == sizeof (struct ssd))
  2097.     {
  2098.       if (ldt_entry->sel == 0 &&
  2099.           ldt_entry->bo  == 0 &&
  2100.           ldt_entry->acc1 == 0 &&
  2101.           ldt_entry->acc2 == 0)
  2102.         break;        /* end of table */
  2103.       /* If key matches, return this entry.  */
  2104.       if (ldt_entry->sel == key)
  2105.         return ldt_entry;
  2106.     }
  2107.   /* Loop ended, match not found.  */
  2108.   return NULL;
  2109. #else
  2110.   int nldt, i;
  2111.   static int nalloc = 0;

  2112.   /* Get the number of LDT entries.  */
  2113.   if (ioctl (pi->ctl_fd, PIOCNLDT, &nldt) < 0)
  2114.     {
  2115.       proc_warn (pi, "proc_get_LDT_entry (PIOCNLDT)", __LINE__);
  2116.       return NULL;
  2117.     }

  2118.   /* Allocate space for the number of LDT entries.  */
  2119.   /* This alloc has to persist, 'cause we return a pointer to it.  */
  2120.   if (nldt > nalloc)
  2121.     {
  2122.       ldt_entry = (struct ssd *)
  2123.         xrealloc (ldt_entry, (nldt + 1) * sizeof (struct ssd));
  2124.       nalloc = nldt;
  2125.     }

  2126.   /* Read the whole table in one gulp.  */
  2127.   if (ioctl (pi->ctl_fd, PIOCLDT, ldt_entry) < 0)
  2128.     {
  2129.       proc_warn (pi, "proc_get_LDT_entry (PIOCLDT)", __LINE__);
  2130.       return NULL;
  2131.     }

  2132.   /* Search the table and return the (first) entry matching 'key'.  */
  2133.   for (i = 0; i < nldt; i++)
  2134.     if (ldt_entry[i].sel == key)
  2135.       return &ldt_entry[i];

  2136.   /* Loop ended, match not found.  */
  2137.   return NULL;
  2138. #endif
  2139. }

  2140. /* Returns the pointer to the LDT entry of PTID.  */

  2141. struct ssd *
  2142. procfs_find_LDT_entry (ptid_t ptid)
  2143. {
  2144.   gdb_gregset_t *gregs;
  2145.   int            key;
  2146.   procinfo      *pi;

  2147.   /* Find procinfo for the lwp.  */
  2148.   if ((pi = find_procinfo (ptid_get_pid (ptid), ptid_get_lwp (ptid))) == NULL)
  2149.     {
  2150.       warning (_("procfs_find_LDT_entry: could not find procinfo for %d:%ld."),
  2151.                ptid_get_pid (ptid), ptid_get_lwp (ptid));
  2152.       return NULL;
  2153.     }
  2154.   /* get its general registers.  */
  2155.   if ((gregs = proc_get_gregs (pi)) == NULL)
  2156.     {
  2157.       warning (_("procfs_find_LDT_entry: could not read gregs for %d:%ld."),
  2158.                ptid_get_pid (ptid), ptid_get_lwp (ptid));
  2159.       return NULL;
  2160.     }
  2161.   /* Now extract the GS register's lower 16 bits.  */
  2162.   key = (*gregs)[GS] & 0xffff;

  2163.   /* Find the matching entry and return it.  */
  2164.   return proc_get_LDT_entry (pi, key);
  2165. }

  2166. #endif

  2167. /* =============== END, non-thread part of /proc  "MODULE" =============== */

  2168. /* =================== Thread "MODULE" =================== */

  2169. /* NOTE: you'll see more ifdefs and duplication of functions here,
  2170.    since there is a different way to do threads on every OS.  */

  2171. /* Returns the number of threads for the process.  */

  2172. #if defined (PIOCNTHR) && defined (PIOCTLIST)
  2173. /* OSF version */
  2174. static int
  2175. proc_get_nthreads (procinfo *pi)
  2176. {
  2177.   int nthreads = 0;

  2178.   if (ioctl (pi->ctl_fd, PIOCNTHR, &nthreads) < 0)
  2179.     proc_warn (pi, "procfs: PIOCNTHR failed", __LINE__);

  2180.   return nthreads;
  2181. }

  2182. #else
  2183. #if defined (SYS_lwpcreate) || defined (SYS_lwp_create) /* FIXME: multiple */
  2184. /* Solaris version */
  2185. static int
  2186. proc_get_nthreads (procinfo *pi)
  2187. {
  2188.   if (!pi->status_valid)
  2189.     if (!proc_get_status (pi))
  2190.       return 0;

  2191.   /* NEW_PROC_API: only works for the process procinfo, because the
  2192.      LWP procinfos do not get prstatus filled in.  */
  2193. #ifdef NEW_PROC_API
  2194.   if (pi->tid != 0)        /* Find the parent process procinfo.  */
  2195.     pi = find_procinfo_or_die (pi->pid, 0);
  2196. #endif
  2197.   return pi->prstatus.pr_nlwp;
  2198. }

  2199. #else
  2200. /* Default version */
  2201. static int
  2202. proc_get_nthreads (procinfo *pi)
  2203. {
  2204.   return 0;
  2205. }
  2206. #endif
  2207. #endif

  2208. /* LWP version.

  2209.    Return the ID of the thread that had an event of interest.
  2210.    (ie. the one that hit a breakpoint or other traced event).  All
  2211.    other things being equal, this should be the ID of a thread that is
  2212.    currently executing.  */

  2213. #if defined (SYS_lwpcreate) || defined (SYS_lwp_create) /* FIXME: multiple */
  2214. /* Solaris version */
  2215. static int
  2216. proc_get_current_thread (procinfo *pi)
  2217. {
  2218.   /* Note: this should be applied to the root procinfo for the
  2219.      process, not to the procinfo for an LWP.  If applied to the
  2220.      procinfo for an LWP, it will simply return that LWP's ID.  In
  2221.      that case, find the parent process procinfo.  */

  2222.   if (pi->tid != 0)
  2223.     pi = find_procinfo_or_die (pi->pid, 0);

  2224.   if (!pi->status_valid)
  2225.     if (!proc_get_status (pi))
  2226.       return 0;

  2227. #ifdef NEW_PROC_API
  2228.   return pi->prstatus.pr_lwp.pr_lwpid;
  2229. #else
  2230.   return pi->prstatus.pr_who;
  2231. #endif
  2232. }

  2233. #else
  2234. #if defined (PIOCNTHR) && defined (PIOCTLIST)
  2235. /* OSF version */
  2236. static int
  2237. proc_get_current_thread (procinfo *pi)
  2238. {
  2239. #if 0        /* FIXME: not ready for prime time?  */
  2240.   return pi->prstatus.pr_tid;
  2241. #else
  2242.   return 0;
  2243. #endif
  2244. }

  2245. #else
  2246. /* Default version */
  2247. static int
  2248. proc_get_current_thread (procinfo *pi)
  2249. {
  2250.   return 0;
  2251. }

  2252. #endif
  2253. #endif

  2254. /* Discover the IDs of all the threads within the process, and create
  2255.    a procinfo for each of them (chained to the parent).  This
  2256.    unfortunately requires a different method on every OS.  Returns
  2257.    non-zero for success, zero for failure.  */

  2258. static int
  2259. proc_delete_dead_threads (procinfo *parent, procinfo *thread, void *ignore)
  2260. {
  2261.   if (thread && parent)        /* sanity */
  2262.     {
  2263.       thread->status_valid = 0;
  2264.       if (!proc_get_status (thread))
  2265.         destroy_one_procinfo (&parent->thread_list, thread);
  2266.     }
  2267.   return 0;        /* keep iterating */
  2268. }

  2269. #if defined (PIOCLSTATUS)
  2270. /* Solaris 2.5 (ioctl) version */
  2271. static int
  2272. proc_update_threads (procinfo *pi)
  2273. {
  2274.   gdb_prstatus_t *prstatus;
  2275.   struct cleanup *old_chain = NULL;
  2276.   procinfo *thread;
  2277.   int nlwp, i;

  2278.   /* We should never have to apply this operation to any procinfo
  2279.      except the one for the main process.  If that ever changes for
  2280.      any reason, then take out the following clause and replace it
  2281.      with one that makes sure the ctl_fd is open.  */

  2282.   if (pi->tid != 0)
  2283.     pi = find_procinfo_or_die (pi->pid, 0);

  2284.   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);

  2285.   if ((nlwp = proc_get_nthreads (pi)) <= 1)
  2286.     return 1;        /* Process is not multi-threaded; nothing to do.  */

  2287.   prstatus = xmalloc (sizeof (gdb_prstatus_t) * (nlwp + 1));

  2288.   old_chain = make_cleanup (xfree, prstatus);
  2289.   if (ioctl (pi->ctl_fd, PIOCLSTATUS, prstatus) < 0)
  2290.     proc_error (pi, "update_threads (PIOCLSTATUS)", __LINE__);

  2291.   /* Skip element zero, which represents the process as a whole.  */
  2292.   for (i = 1; i < nlwp + 1; i++)
  2293.     {
  2294.       if ((thread = create_procinfo (pi->pid, prstatus[i].pr_who)) == NULL)
  2295.         proc_error (pi, "update_threads, create_procinfo", __LINE__);

  2296.       memcpy (&thread->prstatus, &prstatus[i], sizeof (*prstatus));
  2297.       thread->status_valid = 1;
  2298.     }
  2299.   pi->threads_valid = 1;
  2300.   do_cleanups (old_chain);
  2301.   return 1;
  2302. }
  2303. #else
  2304. #ifdef NEW_PROC_API
  2305. /* Solaris 6 (and later) version.  */
  2306. static void
  2307. do_closedir_cleanup (void *dir)
  2308. {
  2309.   closedir (dir);
  2310. }

  2311. static int
  2312. proc_update_threads (procinfo *pi)
  2313. {
  2314.   char pathname[MAX_PROC_NAME_SIZE + 16];
  2315.   struct dirent *direntry;
  2316.   struct cleanup *old_chain = NULL;
  2317.   procinfo *thread;
  2318.   DIR *dirp;
  2319.   int lwpid;

  2320.   /* We should never have to apply this operation to any procinfo
  2321.      except the one for the main process.  If that ever changes for
  2322.      any reason, then take out the following clause and replace it
  2323.      with one that makes sure the ctl_fd is open.  */

  2324.   if (pi->tid != 0)
  2325.     pi = find_procinfo_or_die (pi->pid, 0);

  2326.   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);

  2327.   /* Note: this brute-force method was originally devised for Unixware
  2328.      (support removed since), and will also work on Solaris 2.6 and
  2329.      2.7.  The original comment mentioned the existence of a much
  2330.      simpler and more elegant way to do this on Solaris, but didn't
  2331.      point out what that was.  */

  2332.   strcpy (pathname, pi->pathname);
  2333.   strcat (pathname, "/lwp");
  2334.   if ((dirp = opendir (pathname)) == NULL)
  2335.     proc_error (pi, "update_threads, opendir", __LINE__);

  2336.   old_chain = make_cleanup (do_closedir_cleanup, dirp);
  2337.   while ((direntry = readdir (dirp)) != NULL)
  2338.     if (direntry->d_name[0] != '.')                /* skip '.' and '..' */
  2339.       {
  2340.         lwpid = atoi (&direntry->d_name[0]);
  2341.         if ((thread = create_procinfo (pi->pid, lwpid)) == NULL)
  2342.           proc_error (pi, "update_threads, create_procinfo", __LINE__);
  2343.       }
  2344.   pi->threads_valid = 1;
  2345.   do_cleanups (old_chain);
  2346.   return 1;
  2347. }
  2348. #else
  2349. #ifdef PIOCTLIST
  2350. /* OSF version */
  2351. static int
  2352. proc_update_threads (procinfo *pi)
  2353. {
  2354.   int nthreads, i;
  2355.   tid_t *threads;

  2356.   /* We should never have to apply this operation to any procinfo
  2357.      except the one for the main process.  If that ever changes for
  2358.      any reason, then take out the following clause and replace it
  2359.      with one that makes sure the ctl_fd is open.  */

  2360.   if (pi->tid != 0)
  2361.     pi = find_procinfo_or_die (pi->pid, 0);

  2362.   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);

  2363.   nthreads = proc_get_nthreads (pi);
  2364.   if (nthreads < 2)
  2365.     return 0;                /* Nothing to do for 1 or fewer threads.  */

  2366.   threads = xmalloc (nthreads * sizeof (tid_t));

  2367.   if (ioctl (pi->ctl_fd, PIOCTLIST, threads) < 0)
  2368.     proc_error (pi, "procfs: update_threads (PIOCTLIST)", __LINE__);

  2369.   for (i = 0; i < nthreads; i++)
  2370.     {
  2371.       if (!find_procinfo (pi->pid, threads[i]))
  2372.         if (!create_procinfo  (pi->pid, threads[i]))
  2373.           proc_error (pi, "update_threads, create_procinfo", __LINE__);
  2374.     }
  2375.   pi->threads_valid = 1;
  2376.   return 1;
  2377. }
  2378. #else
  2379. /* Default version */
  2380. static int
  2381. proc_update_threads (procinfo *pi)
  2382. {
  2383.   return 0;
  2384. }
  2385. #endif        /* OSF PIOCTLIST */
  2386. #endif  /* NEW_PROC_API   */
  2387. #endif  /* SOL 2.5 PIOCLSTATUS */

  2388. /* Given a pointer to a function, call that function once for each lwp
  2389.    in the procinfo list, until the function returns non-zero, in which
  2390.    event return the value returned by the function.

  2391.    Note: this function does NOT call update_threads.  If you want to
  2392.    discover new threads first, you must call that function explicitly.
  2393.    This function just makes a quick pass over the currently-known
  2394.    procinfos.

  2395.    PI is the parent process procinfoFUNC is the per-thread
  2396.    functionPTR is an opaque parameter for function.  Returns the
  2397.    first non-zero return value from the callee, or zero.  */

  2398. static int
  2399. proc_iterate_over_threads (procinfo *pi,
  2400.                            int (*func) (procinfo *, procinfo *, void *),
  2401.                            void *ptr)
  2402. {
  2403.   procinfo *thread, *next;
  2404.   int retval = 0;

  2405.   /* We should never have to apply this operation to any procinfo
  2406.      except the one for the main process.  If that ever changes for
  2407.      any reason, then take out the following clause and replace it
  2408.      with one that makes sure the ctl_fd is open.  */

  2409.   if (pi->tid != 0)
  2410.     pi = find_procinfo_or_die (pi->pid, 0);

  2411.   for (thread = pi->thread_list; thread != NULL; thread = next)
  2412.     {
  2413.       next = thread->next;        /* In case thread is destroyed.  */
  2414.       if ((retval = (*func) (pi, thread, ptr)) != 0)
  2415.         break;
  2416.     }

  2417.   return retval;
  2418. }

  2419. /* =================== END, Thread "MODULE" =================== */

  2420. /* =================== END, /proc  "MODULE" =================== */

  2421. /* ===================  GDB  "MODULE" =================== */

  2422. /* Here are all of the gdb target vector functions and their
  2423.    friends.  */

  2424. static ptid_t do_attach (ptid_t ptid);
  2425. static void do_detach (int signo);
  2426. static void proc_trace_syscalls_1 (procinfo *pi, int syscallnum,
  2427.                                    int entry_or_exit, int mode, int from_tty);

  2428. /* Sets up the inferior to be debugged.  Registers to trace signals,
  2429.    hardware faults, and syscalls.  Note: does not set RLC flag: caller
  2430.    may want to customize that.  Returns zero for success (note!
  2431.    unlike most functions in this module); on failure, returns the LINE
  2432.    NUMBER where it failed!  */

  2433. static int
  2434. procfs_debug_inferior (procinfo *pi)
  2435. {
  2436.   fltset_t traced_faults;
  2437.   gdb_sigset_t traced_signals;
  2438.   sysset_t *traced_syscall_entries;
  2439.   sysset_t *traced_syscall_exits;
  2440.   int status;

  2441.   /* Register to trace hardware faults in the child.  */
  2442.   prfillset (&traced_faults);                /* trace all faults...  */
  2443.   gdb_prdelset  (&traced_faults, FLTPAGE);        /* except page fault.  */
  2444.   if (!proc_set_traced_faults  (pi, &traced_faults))
  2445.     return __LINE__;

  2446.   /* Initially, register to trace all signals in the child.  */
  2447.   prfillset (&traced_signals);
  2448.   if (!proc_set_traced_signals (pi, &traced_signals))
  2449.     return __LINE__;


  2450.   /* Register to trace the 'exit' system call (on entry).  */
  2451.   traced_syscall_entries = sysset_t_alloc (pi);
  2452.   gdb_premptysysset (traced_syscall_entries);
  2453. #ifdef SYS_exit
  2454.   gdb_praddsysset (traced_syscall_entries, SYS_exit);
  2455. #endif
  2456. #ifdef SYS_lwpexit
  2457.   gdb_praddsysset (traced_syscall_entries, SYS_lwpexit);/* And _lwp_exit...  */
  2458. #endif
  2459. #ifdef SYS_lwp_exit
  2460.   gdb_praddsysset (traced_syscall_entries, SYS_lwp_exit);
  2461. #endif
  2462. #ifdef DYNAMIC_SYSCALLS
  2463.   {
  2464.     int callnum = find_syscall (pi, "_exit");

  2465.     if (callnum >= 0)
  2466.       gdb_praddsysset (traced_syscall_entries, callnum);
  2467.   }
  2468. #endif

  2469.   status = proc_set_traced_sysentry (pi, traced_syscall_entries);
  2470.   xfree (traced_syscall_entries);
  2471.   if (!status)
  2472.     return __LINE__;

  2473. #ifdef PRFS_STOPEXEC        /* defined on OSF */
  2474.   /* OSF method for tracing exec syscalls.  Quoting:
  2475.      Under Alpha OSF/1 we have to use a PIOCSSPCACT ioctl to trace
  2476.      exits from exec system calls because of the user level loader.  */
  2477.   /* FIXME: make nice and maybe move into an access function.  */
  2478.   {
  2479.     int prfs_flags;

  2480.     if (ioctl (pi->ctl_fd, PIOCGSPCACT, &prfs_flags) < 0)
  2481.       return __LINE__;

  2482.     prfs_flags |= PRFS_STOPEXEC;

  2483.     if (ioctl (pi->ctl_fd, PIOCSSPCACT, &prfs_flags) < 0)
  2484.       return __LINE__;
  2485.   }
  2486. #else /* not PRFS_STOPEXEC */
  2487.   /* Everyone else's (except OSF) method for tracing exec syscalls.  */
  2488.   /* GW: Rationale...
  2489.      Not all systems with /proc have all the exec* syscalls with the same
  2490.      names.  On the SGI, for example, there is no SYS_exec, but there
  2491.      *is* a SYS_execv.  So, we try to account for that.  */

  2492.   traced_syscall_exits = sysset_t_alloc (pi);
  2493.   gdb_premptysysset (traced_syscall_exits);
  2494. #ifdef SYS_exec
  2495.   gdb_praddsysset (traced_syscall_exits, SYS_exec);
  2496. #endif
  2497. #ifdef SYS_execve
  2498.   gdb_praddsysset (traced_syscall_exits, SYS_execve);
  2499. #endif
  2500. #ifdef SYS_execv
  2501.   gdb_praddsysset (traced_syscall_exits, SYS_execv);
  2502. #endif

  2503. #ifdef SYS_lwpcreate
  2504.   gdb_praddsysset (traced_syscall_exits, SYS_lwpcreate);
  2505.   gdb_praddsysset (traced_syscall_exits, SYS_lwpexit);
  2506. #endif

  2507. #ifdef SYS_lwp_create        /* FIXME: once only, please.  */
  2508.   gdb_praddsysset (traced_syscall_exits, SYS_lwp_create);
  2509.   gdb_praddsysset (traced_syscall_exits, SYS_lwp_exit);
  2510. #endif

  2511. #ifdef DYNAMIC_SYSCALLS
  2512.   {
  2513.     int callnum = find_syscall (pi, "execve");

  2514.     if (callnum >= 0)
  2515.       gdb_praddsysset (traced_syscall_exits, callnum);
  2516.     callnum = find_syscall (pi, "ra_execve");
  2517.     if (callnum >= 0)
  2518.       gdb_praddsysset (traced_syscall_exits, callnum);
  2519.   }
  2520. #endif

  2521.   status = proc_set_traced_sysexit (pi, traced_syscall_exits);
  2522.   xfree (traced_syscall_exits);
  2523.   if (!status)
  2524.     return __LINE__;

  2525. #endif /* PRFS_STOPEXEC */
  2526.   return 0;
  2527. }

  2528. static void
  2529. procfs_attach (struct target_ops *ops, const char *args, int from_tty)
  2530. {
  2531.   char *exec_file;
  2532.   int   pid;

  2533.   pid = parse_pid_to_attach (args);

  2534.   if (pid == getpid ())
  2535.     error (_("Attaching GDB to itself is not a good idea..."));

  2536.   if (from_tty)
  2537.     {
  2538.       exec_file = get_exec_file (0);

  2539.       if (exec_file)
  2540.         printf_filtered (_("Attaching to program `%s', %s\n"),
  2541.                          exec_file, target_pid_to_str (pid_to_ptid (pid)));
  2542.       else
  2543.         printf_filtered (_("Attaching to %s\n"),
  2544.                          target_pid_to_str (pid_to_ptid (pid)));

  2545.       fflush (stdout);
  2546.     }
  2547.   inferior_ptid = do_attach (pid_to_ptid (pid));
  2548.   if (!target_is_pushed (ops))
  2549.     push_target (ops);
  2550. }

  2551. static void
  2552. procfs_detach (struct target_ops *ops, const char *args, int from_tty)
  2553. {
  2554.   int sig = 0;
  2555.   int pid = ptid_get_pid (inferior_ptid);

  2556.   if (args)
  2557.     sig = atoi (args);

  2558.   if (from_tty)
  2559.     {
  2560.       char *exec_file;

  2561.       exec_file = get_exec_file (0);
  2562.       if (exec_file == NULL)
  2563.         exec_file = "";

  2564.       printf_filtered (_("Detaching from program: %s, %s\n"), exec_file,
  2565.                        target_pid_to_str (pid_to_ptid (pid)));
  2566.       gdb_flush (gdb_stdout);
  2567.     }

  2568.   do_detach (sig);

  2569.   inferior_ptid = null_ptid;
  2570.   detach_inferior (pid);
  2571.   inf_child_maybe_unpush_target (ops);
  2572. }

  2573. static ptid_t
  2574. do_attach (ptid_t ptid)
  2575. {
  2576.   procinfo *pi;
  2577.   struct inferior *inf;
  2578.   int fail;
  2579.   int lwpid;

  2580.   if ((pi = create_procinfo (ptid_get_pid (ptid), 0)) == NULL)
  2581.     perror (_("procfs: out of memory in 'attach'"));

  2582.   if (!open_procinfo_files (pi, FD_CTL))
  2583.     {
  2584.       fprintf_filtered (gdb_stderr, "procfs:%d -- ", __LINE__);
  2585.       sprintf (errmsg, "do_attach: couldn't open /proc file for process %d",
  2586.                ptid_get_pid (ptid));
  2587.       dead_procinfo (pi, errmsg, NOKILL);
  2588.     }

  2589.   /* Stop the process (if it isn't already stopped).  */
  2590.   if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
  2591.     {
  2592.       pi->was_stopped = 1;
  2593.       proc_prettyprint_why (proc_why (pi), proc_what (pi), 1);
  2594.     }
  2595.   else
  2596.     {
  2597.       pi->was_stopped = 0;
  2598.       /* Set the process to run again when we close it.  */
  2599.       if (!proc_set_run_on_last_close (pi))
  2600.         dead_procinfo (pi, "do_attach: couldn't set RLC.", NOKILL);

  2601.       /* Now stop the process.  */
  2602.       if (!proc_stop_process (pi))
  2603.         dead_procinfo (pi, "do_attach: couldn't stop the process.", NOKILL);
  2604.       pi->ignore_next_sigstop = 1;
  2605.     }
  2606.   /* Save some of the /proc state to be restored if we detach.  */
  2607.   if (!proc_get_traced_faults   (pi, &pi->saved_fltset))
  2608.     dead_procinfo (pi, "do_attach: couldn't save traced faults.", NOKILL);
  2609.   if (!proc_get_traced_signals  (pi, &pi->saved_sigset))
  2610.     dead_procinfo (pi, "do_attach: couldn't save traced signals.", NOKILL);
  2611.   if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
  2612.     dead_procinfo (pi, "do_attach: couldn't save traced syscall entries.",
  2613.                    NOKILL);
  2614.   if (!proc_get_traced_sysexit  (pi, pi->saved_exitset))
  2615.     dead_procinfo (pi, "do_attach: couldn't save traced syscall exits.",
  2616.                    NOKILL);
  2617.   if (!proc_get_held_signals    (pi, &pi->saved_sighold))
  2618.     dead_procinfo (pi, "do_attach: couldn't save held signals.", NOKILL);

  2619.   if ((fail = procfs_debug_inferior (pi)) != 0)
  2620.     dead_procinfo (pi, "do_attach: failed in procfs_debug_inferior", NOKILL);

  2621.   inf = current_inferior ();
  2622.   inferior_appeared (inf, pi->pid);
  2623.   /* Let GDB know that the inferior was attached.  */
  2624.   inf->attach_flag = 1;

  2625.   /* Create a procinfo for the current lwp.  */
  2626.   lwpid = proc_get_current_thread (pi);
  2627.   create_procinfo (pi->pid, lwpid);

  2628.   /* Add it to gdb's thread list.  */
  2629.   ptid = ptid_build (pi->pid, lwpid, 0);
  2630.   add_thread (ptid);

  2631.   return ptid;
  2632. }

  2633. static void
  2634. do_detach (int signo)
  2635. {
  2636.   procinfo *pi;

  2637.   /* Find procinfo for the main process.  */
  2638.   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid),
  2639.                              0); /* FIXME: threads */
  2640.   if (signo)
  2641.     if (!proc_set_current_signal (pi, signo))
  2642.       proc_warn (pi, "do_detach, set_current_signal", __LINE__);

  2643.   if (!proc_set_traced_signals (pi, &pi->saved_sigset))
  2644.     proc_warn (pi, "do_detach, set_traced_signal", __LINE__);

  2645.   if (!proc_set_traced_faults (pi, &pi->saved_fltset))
  2646.     proc_warn (pi, "do_detach, set_traced_faults", __LINE__);

  2647.   if (!proc_set_traced_sysentry (pi, pi->saved_entryset))
  2648.     proc_warn (pi, "do_detach, set_traced_sysentry", __LINE__);

  2649.   if (!proc_set_traced_sysexit (pi, pi->saved_exitset))
  2650.     proc_warn (pi, "do_detach, set_traced_sysexit", __LINE__);

  2651.   if (!proc_set_held_signals (pi, &pi->saved_sighold))
  2652.     proc_warn (pi, "do_detach, set_held_signals", __LINE__);

  2653.   if (signo || (proc_flags (pi) & (PR_STOPPED | PR_ISTOP)))
  2654.     if (signo || !(pi->was_stopped) ||
  2655.         query (_("Was stopped when attached, make it runnable again? ")))
  2656.       {
  2657.         /* Clear any pending signal.  */
  2658.         if (!proc_clear_current_fault (pi))
  2659.           proc_warn (pi, "do_detach, clear_current_fault", __LINE__);

  2660.         if (signo == 0 && !proc_clear_current_signal (pi))
  2661.           proc_warn (pi, "do_detach, clear_current_signal", __LINE__);

  2662.         if (!proc_set_run_on_last_close (pi))
  2663.           proc_warn (pi, "do_detach, set_rlc", __LINE__);
  2664.       }

  2665.   destroy_procinfo (pi);
  2666. }

  2667. /* Fetch register REGNUM from the inferior.  If REGNUM is -1, do this
  2668.    for all registers.

  2669.    ??? Is the following note still relevant?  We can't get individual
  2670.    registers with the PT_GETREGS ptrace(2) request either, yet we
  2671.    don't bother with caching at all in that case.

  2672.    NOTE: Since the /proc interface cannot give us individual
  2673.    registers, we pay no attention to REGNUM, and just fetch them all.
  2674.    This results in the possibility that we will do unnecessarily many
  2675.    fetches, since we may be called repeatedly for individual
  2676.    registers.  So we cache the results, and mark the cache invalid
  2677.    when the process is resumed.  */

  2678. static void
  2679. procfs_fetch_registers (struct target_ops *ops,
  2680.                         struct regcache *regcache, int regnum)
  2681. {
  2682.   gdb_gregset_t *gregs;
  2683.   procinfo *pi;
  2684.   int pid = ptid_get_pid (inferior_ptid);
  2685.   int tid = ptid_get_lwp (inferior_ptid);
  2686.   struct gdbarch *gdbarch = get_regcache_arch (regcache);

  2687.   pi = find_procinfo_or_die (pid, tid);

  2688.   if (pi == NULL)
  2689.     error (_("procfs: fetch_registers failed to find procinfo for %s"),
  2690.            target_pid_to_str (inferior_ptid));

  2691.   gregs = proc_get_gregs (pi);
  2692.   if (gregs == NULL)
  2693.     proc_error (pi, "fetch_registers, get_gregs", __LINE__);

  2694.   supply_gregset (regcache, (const gdb_gregset_t *) gregs);

  2695.   if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU?  */
  2696.     {
  2697.       gdb_fpregset_t *fpregs;

  2698.       if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
  2699.           || regnum == gdbarch_pc_regnum (gdbarch)
  2700.           || regnum == gdbarch_sp_regnum (gdbarch))
  2701.         return;                        /* Not a floating point register.  */

  2702.       fpregs = proc_get_fpregs (pi);
  2703.       if (fpregs == NULL)
  2704.         proc_error (pi, "fetch_registers, get_fpregs", __LINE__);

  2705.       supply_fpregset (regcache, (const gdb_fpregset_t *) fpregs);
  2706.     }
  2707. }

  2708. /* Store register REGNUM back into the inferior.  If REGNUM is -1, do
  2709.    this for all registers.

  2710.    NOTE: Since the /proc interface will not read individual registers,
  2711.    we will cache these requests until the process is resumed, and only
  2712.    then write them back to the inferior process.

  2713.    FIXME: is that a really bad idea?  Have to think about cases where
  2714.    writing one register might affect the value of others, etc.  */

  2715. static void
  2716. procfs_store_registers (struct target_ops *ops,
  2717.                         struct regcache *regcache, int regnum)
  2718. {
  2719.   gdb_gregset_t *gregs;
  2720.   procinfo *pi;
  2721.   int pid = ptid_get_pid (inferior_ptid);
  2722.   int tid = ptid_get_lwp (inferior_ptid);
  2723.   struct gdbarch *gdbarch = get_regcache_arch (regcache);

  2724.   pi = find_procinfo_or_die (pid, tid);

  2725.   if (pi == NULL)
  2726.     error (_("procfs: store_registers: failed to find procinfo for %s"),
  2727.            target_pid_to_str (inferior_ptid));

  2728.   gregs = proc_get_gregs (pi);
  2729.   if (gregs == NULL)
  2730.     proc_error (pi, "store_registers, get_gregs", __LINE__);

  2731.   fill_gregset (regcache, gregs, regnum);
  2732.   if (!proc_set_gregs (pi))
  2733.     proc_error (pi, "store_registers, set_gregs", __LINE__);

  2734.   if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU?  */
  2735.     {
  2736.       gdb_fpregset_t *fpregs;

  2737.       if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
  2738.           || regnum == gdbarch_pc_regnum (gdbarch)
  2739.           || regnum == gdbarch_sp_regnum (gdbarch))
  2740.         return;                        /* Not a floating point register.  */

  2741.       fpregs = proc_get_fpregs (pi);
  2742.       if (fpregs == NULL)
  2743.         proc_error (pi, "store_registers, get_fpregs", __LINE__);

  2744.       fill_fpregset (regcache, fpregs, regnum);
  2745.       if (!proc_set_fpregs (pi))
  2746.         proc_error (pi, "store_registers, set_fpregs", __LINE__);
  2747.     }
  2748. }

  2749. static int
  2750. syscall_is_lwp_exit (procinfo *pi, int scall)
  2751. {
  2752. #ifdef SYS_lwp_exit
  2753.   if (scall == SYS_lwp_exit)
  2754.     return 1;
  2755. #endif
  2756. #ifdef SYS_lwpexit
  2757.   if (scall == SYS_lwpexit)
  2758.     return 1;
  2759. #endif
  2760.   return 0;
  2761. }

  2762. static int
  2763. syscall_is_exit (procinfo *pi, int scall)
  2764. {
  2765. #ifdef SYS_exit
  2766.   if (scall == SYS_exit)
  2767.     return 1;
  2768. #endif
  2769. #ifdef DYNAMIC_SYSCALLS
  2770.   if (find_syscall (pi, "_exit") == scall)
  2771.     return 1;
  2772. #endif
  2773.   return 0;
  2774. }

  2775. static int
  2776. syscall_is_exec (procinfo *pi, int scall)
  2777. {
  2778. #ifdef SYS_exec
  2779.   if (scall == SYS_exec)
  2780.     return 1;
  2781. #endif
  2782. #ifdef SYS_execv
  2783.   if (scall == SYS_execv)
  2784.     return 1;
  2785. #endif
  2786. #ifdef SYS_execve
  2787.   if (scall == SYS_execve)
  2788.     return 1;
  2789. #endif
  2790. #ifdef DYNAMIC_SYSCALLS
  2791.   if (find_syscall (pi, "_execve"))
  2792.     return 1;
  2793.   if (find_syscall (pi, "ra_execve"))
  2794.     return 1;
  2795. #endif
  2796.   return 0;
  2797. }

  2798. static int
  2799. syscall_is_lwp_create (procinfo *pi, int scall)
  2800. {
  2801. #ifdef SYS_lwp_create
  2802.   if (scall == SYS_lwp_create)
  2803.     return 1;
  2804. #endif
  2805. #ifdef SYS_lwpcreate
  2806.   if (scall == SYS_lwpcreate)
  2807.     return 1;
  2808. #endif
  2809.   return 0;
  2810. }

  2811. #ifdef SYS_syssgi
  2812. /* Return the address of the __dbx_link() function in the file
  2813.    refernced by ABFD by scanning its symbol table.  Return 0 if
  2814.    the symbol was not found.  */

  2815. static CORE_ADDR
  2816. dbx_link_addr (bfd *abfd)
  2817. {
  2818.   long storage_needed;
  2819.   asymbol **symbol_table;
  2820.   long number_of_symbols;
  2821.   long i;

  2822.   storage_needed = bfd_get_symtab_upper_bound (abfd);
  2823.   if (storage_needed <= 0)
  2824.     return 0;

  2825.   symbol_table = (asymbol **) xmalloc (storage_needed);
  2826.   make_cleanup (xfree, symbol_table);

  2827.   number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);

  2828.   for (i = 0; i < number_of_symbols; i++)
  2829.     {
  2830.       asymbol *sym = symbol_table[i];

  2831.       if ((sym->flags & BSF_GLOBAL)
  2832.           && sym->name != NULL && strcmp (sym->name, "__dbx_link") == 0)
  2833.         return (sym->value + sym->section->vma);
  2834.     }

  2835.   /* Symbol not found, return NULL.  */
  2836.   return 0;
  2837. }

  2838. /* Search the symbol table of the file referenced by FD for a symbol
  2839.    named __dbx_link().  If found, then insert a breakpoint at this location,
  2840.    and return nonzero.  Return zero otherwise.  */

  2841. static int
  2842. insert_dbx_link_bpt_in_file (int fd, CORE_ADDR ignored)
  2843. {
  2844.   bfd *abfd;
  2845.   long storage_needed;
  2846.   CORE_ADDR sym_addr;

  2847.   abfd = gdb_bfd_fdopenr ("unamed", 0, fd);
  2848.   if (abfd == NULL)
  2849.     {
  2850.       warning (_("Failed to create a bfd: %s."), bfd_errmsg (bfd_get_error ()));
  2851.       return 0;
  2852.     }

  2853.   if (!bfd_check_format (abfd, bfd_object))
  2854.     {
  2855.       /* Not the correct format, so we can not possibly find the dbx_link
  2856.          symbol in it.        */
  2857.       gdb_bfd_unref (abfd);
  2858.       return 0;
  2859.     }

  2860.   sym_addr = dbx_link_addr (abfd);
  2861.   if (sym_addr != 0)
  2862.     {
  2863.       struct breakpoint *dbx_link_bpt;

  2864.       /* Insert the breakpoint.  */
  2865.       dbx_link_bpt
  2866.         = create_and_insert_solib_event_breakpoint (target_gdbarch (),
  2867.                                                     sym_addr);
  2868.       if (dbx_link_bpt == NULL)
  2869.         {
  2870.           warning (_("Failed to insert dbx_link breakpoint."));
  2871.           gdb_bfd_unref (abfd);
  2872.           return 0;
  2873.         }
  2874.       gdb_bfd_unref (abfd);
  2875.       return 1;
  2876.     }

  2877.   gdb_bfd_unref (abfd);
  2878.   return 0;
  2879. }

  2880. /* Calls the supplied callback function once for each mapped address
  2881.    space in the process.  The callback function receives an open file
  2882.    descriptor for the file corresponding to that mapped address space
  2883.    (if there is one), and the base address of the mapped space.  Quit
  2884.    when the callback function returns a nonzero value, or at teh end
  2885.    of the mappings.  Returns the first non-zero return value of the
  2886.    callback function, or zero.  */

  2887. static int
  2888. solib_mappings_callback (struct prmap *map, int (*func) (int, CORE_ADDR),
  2889.                          void *data)
  2890. {
  2891.   procinfo *pi = data;
  2892.   int fd;

  2893. #ifdef NEW_PROC_API
  2894.   char name[MAX_PROC_NAME_SIZE + sizeof (map->pr_mapname)];

  2895.   if (map->pr_vaddr == 0 && map->pr_size == 0)
  2896.     return -1;                /* sanity */

  2897.   if (map->pr_mapname[0] == 0)
  2898.     {
  2899.       fd = -1;        /* no map file */
  2900.     }
  2901.   else
  2902.     {
  2903.       sprintf (name, "/proc/%d/object/%s", pi->pid, map->pr_mapname);
  2904.       /* Note: caller's responsibility to close this fd!  */
  2905.       fd = open_with_retry (name, O_RDONLY);
  2906.       /* Note: we don't test the above call for failure;
  2907.          we just pass the FD on as given.  Sometimes there is
  2908.          no file, so the open may return failure, but that's
  2909.          not a problem.  */
  2910.     }
  2911. #else
  2912.   fd = ioctl (pi->ctl_fd, PIOCOPENM, &map->pr_vaddr);
  2913.   /* Note: we don't test the above call for failure;
  2914.      we just pass the FD on as given.  Sometimes there is
  2915.      no file, so the ioctl may return failure, but that's
  2916.      not a problem.  */
  2917. #endif
  2918.   return (*func) (fd, (CORE_ADDR) map->pr_vaddr);
  2919. }

  2920. /* If the given memory region MAP contains a symbol named __dbx_link,
  2921.    insert a breakpoint at this location and return nonzero.  Return
  2922.    zero otherwise.  */

  2923. static int
  2924. insert_dbx_link_bpt_in_region (struct prmap *map,
  2925.                                find_memory_region_ftype child_func,
  2926.                                void *data)
  2927. {
  2928.   procinfo *pi = (procinfo *) data;

  2929.   /* We know the symbol we're looking for is in a text region, so
  2930.      only look for it if the region is a text one.  */
  2931.   if (map->pr_mflags & MA_EXEC)
  2932.     return solib_mappings_callback (map, insert_dbx_link_bpt_in_file, pi);

  2933.   return 0;
  2934. }

  2935. /* Search all memory regions for a symbol named __dbx_link.  If found,
  2936.    insert a breakpoint at its location, and return nonzero.  Return zero
  2937.    otherwise.  */

  2938. static int
  2939. insert_dbx_link_breakpoint (procinfo *pi)
  2940. {
  2941.   return iterate_over_mappings (pi, NULL, pi, insert_dbx_link_bpt_in_region);
  2942. }
  2943. #endif

  2944. /* Retrieve the next stop event from the child process.  If child has
  2945.    not stopped yet, wait for it to stop.  Translate /proc eventcodes
  2946.    (or possibly wait eventcodes) into gdb internal event codes.
  2947.    Returns the id of process (and possibly thread) that incurred the
  2948.    event.  Event codes are returned through a pointer parameter.  */

  2949. static ptid_t
  2950. procfs_wait (struct target_ops *ops,
  2951.              ptid_t ptid, struct target_waitstatus *status, int options)
  2952. {
  2953.   /* First cut: loosely based on original version 2.1.  */
  2954.   procinfo *pi;
  2955.   int       wstat;
  2956.   int       temp_tid;
  2957.   ptid_t    retval, temp_ptid;
  2958.   int       why, what, flags;
  2959.   int       retry = 0;

  2960. wait_again:

  2961.   retry++;
  2962.   wstat    = 0;
  2963.   retval   = pid_to_ptid (-1);

  2964.   /* Find procinfo for main process.  */
  2965.   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
  2966.   if (pi)
  2967.     {
  2968.       /* We must assume that the status is stale now...  */
  2969.       pi->status_valid = 0;
  2970.       pi->gregs_valid  = 0;
  2971.       pi->fpregs_valid = 0;

  2972. #if 0        /* just try this out...  */
  2973.       flags = proc_flags (pi);
  2974.       why   = proc_why (pi);
  2975.       if ((flags & PR_STOPPED) && (why == PR_REQUESTED))
  2976.         pi->status_valid = 0;        /* re-read again, IMMEDIATELY...  */
  2977. #endif
  2978.       /* If child is not stopped, wait for it to stop.  */
  2979.       if (!(proc_flags (pi) & (PR_STOPPED | PR_ISTOP)) &&
  2980.           !proc_wait_for_stop (pi))
  2981.         {
  2982.           /* wait_for_stop failed: has the child terminated?  */
  2983.           if (errno == ENOENT)
  2984.             {
  2985.               int wait_retval;

  2986.               /* /proc file not found; presumably child has terminated.  */
  2987.               wait_retval = wait (&wstat); /* "wait" for the child's exit.  */

  2988.               /* Wrong child?  */
  2989.               if (wait_retval != ptid_get_pid (inferior_ptid))
  2990.                 error (_("procfs: couldn't stop "
  2991.                          "process %d: wait returned %d."),
  2992.                        ptid_get_pid (inferior_ptid), wait_retval);
  2993.               /* FIXME: might I not just use waitpid?
  2994.                  Or try find_procinfo to see if I know about this child?  */
  2995.               retval = pid_to_ptid (wait_retval);
  2996.             }
  2997.           else if (errno == EINTR)
  2998.             goto wait_again;
  2999.           else
  3000.             {
  3001.               /* Unknown error from wait_for_stop.  */
  3002.               proc_error (pi, "target_wait (wait_for_stop)", __LINE__);
  3003.             }
  3004.         }
  3005.       else
  3006.         {
  3007.           /* This long block is reached if either:
  3008.              a) the child was already stopped, or
  3009.              b) we successfully waited for the child with wait_for_stop.
  3010.              This block will analyze the /proc status, and translate it
  3011.              into a waitstatus for GDB.

  3012.              If we actually had to call wait because the /proc file
  3013.              is gone (child terminated), then we skip this block,
  3014.              because we already have a waitstatus.  */

  3015.           flags = proc_flags (pi);
  3016.           why   = proc_why (pi);
  3017.           what  = proc_what (pi);

  3018.           if (flags & (PR_STOPPED | PR_ISTOP))
  3019.             {
  3020. #ifdef PR_ASYNC
  3021.               /* If it's running async (for single_thread control),
  3022.                  set it back to normal again.  */
  3023.               if (flags & PR_ASYNC)
  3024.                 if (!proc_unset_async (pi))
  3025.                   proc_error (pi, "target_wait, unset_async", __LINE__);
  3026. #endif

  3027.               if (info_verbose)
  3028.                 proc_prettyprint_why (why, what, 1);

  3029.               /* The 'pid' we will return to GDB is composed of
  3030.                  the process ID plus the lwp ID.  */
  3031.               retval = ptid_build (pi->pid, proc_get_current_thread (pi), 0);

  3032.               switch (why) {
  3033.               case PR_SIGNALLED:
  3034.                 wstat = (what << 8) | 0177;
  3035.                 break;
  3036.               case PR_SYSENTRY:
  3037.                 if (syscall_is_lwp_exit (pi, what))
  3038.                   {
  3039.                     if (print_thread_events)
  3040.                       printf_unfiltered (_("[%s exited]\n"),
  3041.                                          target_pid_to_str (retval));
  3042.                     delete_thread (retval);
  3043.                     status->kind = TARGET_WAITKIND_SPURIOUS;
  3044.                     return retval;
  3045.                   }
  3046.                 else if (syscall_is_exit (pi, what))
  3047.                   {
  3048.                     struct inferior *inf;

  3049.                     /* Handle SYS_exit call only.  */
  3050.                     /* Stopped at entry to SYS_exit.
  3051.                        Make it runnable, resume it, then use
  3052.                        the wait system call to get its exit code.
  3053.                        Proc_run_process always clears the current
  3054.                        fault and signal.
  3055.                        Then return its exit status.  */
  3056.                     pi->status_valid = 0;
  3057.                     wstat = 0;
  3058.                     /* FIXME: what we should do is return
  3059.                        TARGET_WAITKIND_SPURIOUS.  */
  3060.                     if (!proc_run_process (pi, 0, 0))
  3061.                       proc_error (pi, "target_wait, run_process", __LINE__);

  3062.                     inf = find_inferior_pid (pi->pid);
  3063.                     if (inf->attach_flag)
  3064.                       {
  3065.                         /* Don't call wait: simulate waiting for exit,
  3066.                            return a "success" exit code.  Bogus: what if
  3067.                            it returns something else?  */
  3068.                         wstat = 0;
  3069.                         retval = inferior_ptid/* ? ? ? */
  3070.                       }
  3071.                     else
  3072.                       {
  3073.                         int temp = wait (&wstat);

  3074.                         /* FIXME: shouldn't I make sure I get the right
  3075.                            event from the right process?  If (for
  3076.                            instance) I have killed an earlier inferior
  3077.                            process but failed to clean up after it
  3078.                            somehow, I could get its termination event
  3079.                            here.  */

  3080.                         /* If wait returns -1, that's what we return
  3081.                            to GDB.  */
  3082.                         if (temp < 0)
  3083.                           retval = pid_to_ptid (temp);
  3084.                       }
  3085.                   }
  3086.                 else
  3087.                   {
  3088.                     printf_filtered (_("procfs: trapped on entry to "));
  3089.                     proc_prettyprint_syscall (proc_what (pi), 0);
  3090.                     printf_filtered ("\n");
  3091. #ifndef PIOCSSPCACT
  3092.                     {
  3093.                       long i, nsysargs, *sysargs;

  3094.                       if ((nsysargs = proc_nsysarg (pi)) > 0 &&
  3095.                           (sysargs  = proc_sysargs (pi)) != NULL)
  3096.                         {
  3097.                           printf_filtered (_("%ld syscall arguments:\n"),
  3098.                                            nsysargs);
  3099.                           for (i = 0; i < nsysargs; i++)
  3100.                             printf_filtered ("#%ld: 0x%08lx\n",
  3101.                                              i, sysargs[i]);
  3102.                         }

  3103.                     }
  3104. #endif
  3105.                     if (status)
  3106.                       {
  3107.                         /* How to exit gracefully, returning "unknown
  3108.                            event".  */
  3109.                         status->kind = TARGET_WAITKIND_SPURIOUS;
  3110.                         return inferior_ptid;
  3111.                       }
  3112.                     else
  3113.                       {
  3114.                         /* How to keep going without returning to wfi: */
  3115.                         target_resume (ptid, 0, GDB_SIGNAL_0);
  3116.                         goto wait_again;
  3117.                       }
  3118.                   }
  3119.                 break;
  3120.               case PR_SYSEXIT:
  3121.                 if (syscall_is_exec (pi, what))
  3122.                   {
  3123.                     /* Hopefully this is our own "fork-child" execing
  3124.                        the real child.  Hoax this event into a trap, and
  3125.                        GDB will see the child about to execute its start
  3126.                        address.  */
  3127.                     wstat = (SIGTRAP << 8) | 0177;
  3128.                   }
  3129. #ifdef SYS_syssgi
  3130.                 else if (what == SYS_syssgi)
  3131.                   {
  3132.                     /* see if we can break on dbx_link().  If yes, then
  3133.                        we no longer need the SYS_syssgi notifications.        */
  3134.                     if (insert_dbx_link_breakpoint (pi))
  3135.                       proc_trace_syscalls_1 (pi, SYS_syssgi, PR_SYSEXIT,
  3136.                                              FLAG_RESET, 0);

  3137.                     /* This is an internal event and should be transparent
  3138.                        to wfi, so resume the execution and wait again.        See
  3139.                        comment in procfs_init_inferior() for more details.  */
  3140.                     target_resume (ptid, 0, GDB_SIGNAL_0);
  3141.                     goto wait_again;
  3142.                   }
  3143. #endif
  3144.                 else if (syscall_is_lwp_create (pi, what))
  3145.                   {
  3146.                     /* This syscall is somewhat like fork/exec.  We
  3147.                        will get the event twice: once for the parent
  3148.                        LWP, and once for the child.  We should already
  3149.                        know about the parent LWP, but the child will
  3150.                        be new to us.  So, whenever we get this event,
  3151.                        if it represents a new thread, simply add the
  3152.                        thread to the list.  */

  3153.                     /* If not in procinfo list, add it.  */
  3154.                     temp_tid = proc_get_current_thread (pi);
  3155.                     if (!find_procinfo (pi->pid, temp_tid))
  3156.                       create_procinfo  (pi->pid, temp_tid);

  3157.                     temp_ptid = ptid_build (pi->pid, temp_tid, 0);
  3158.                     /* If not in GDB's thread list, add it.  */
  3159.                     if (!in_thread_list (temp_ptid))
  3160.                       add_thread (temp_ptid);

  3161.                     /* Return to WFI, but tell it to immediately resume.  */
  3162.                     status->kind = TARGET_WAITKIND_SPURIOUS;
  3163.                     return inferior_ptid;
  3164.                   }
  3165.                 else if (syscall_is_lwp_exit (pi, what))
  3166.                   {
  3167.                     if (print_thread_events)
  3168.                       printf_unfiltered (_("[%s exited]\n"),
  3169.                                          target_pid_to_str (retval));
  3170.                     delete_thread (retval);
  3171.                     status->kind = TARGET_WAITKIND_SPURIOUS;
  3172.                     return retval;
  3173.                   }
  3174.                 else if (0)
  3175.                   {
  3176.                     /* FIXME:  Do we need to handle SYS_sproc,
  3177.                        SYS_fork, or SYS_vfork here?  The old procfs
  3178.                        seemed to use this event to handle threads on
  3179.                        older (non-LWP) systems, where I'm assuming
  3180.                        that threads were actually separate processes.
  3181.                        Irix, maybe?  Anyway, low priority for now.  */
  3182.                   }
  3183.                 else
  3184.                   {
  3185.                     printf_filtered (_("procfs: trapped on exit from "));
  3186.                     proc_prettyprint_syscall (proc_what (pi), 0);
  3187.                     printf_filtered ("\n");
  3188. #ifndef PIOCSSPCACT
  3189.                     {
  3190.                       long i, nsysargs, *sysargs;

  3191.                       if ((nsysargs = proc_nsysarg (pi)) > 0 &&
  3192.                           (sysargs  = proc_sysargs (pi)) != NULL)
  3193.                         {
  3194.                           printf_filtered (_("%ld syscall arguments:\n"),
  3195.                                            nsysargs);
  3196.                           for (i = 0; i < nsysargs; i++)
  3197.                             printf_filtered ("#%ld: 0x%08lx\n",
  3198.                                              i, sysargs[i]);
  3199.                         }
  3200.                     }
  3201. #endif
  3202.                     status->kind = TARGET_WAITKIND_SPURIOUS;
  3203.                     return inferior_ptid;
  3204.                   }
  3205.                 break;
  3206.               case PR_REQUESTED:
  3207. #if 0        /* FIXME */
  3208.                 wstat = (SIGSTOP << 8) | 0177;
  3209.                 break;
  3210. #else
  3211.                 if (retry < 5)
  3212.                   {
  3213.                     printf_filtered (_("Retry #%d:\n"), retry);
  3214.                     pi->status_valid = 0;
  3215.                     goto wait_again;
  3216.                   }
  3217.                 else
  3218.                   {
  3219.                     /* If not in procinfo list, add it.  */
  3220.                     temp_tid = proc_get_current_thread (pi);
  3221.                     if (!find_procinfo (pi->pid, temp_tid))
  3222.                       create_procinfo  (pi->pid, temp_tid);

  3223.                     /* If not in GDB's thread list, add it.  */
  3224.                     temp_ptid = ptid_build (pi->pid, temp_tid, 0);
  3225.                     if (!in_thread_list (temp_ptid))
  3226.                       add_thread (temp_ptid);

  3227.                     status->kind = TARGET_WAITKIND_STOPPED;
  3228.                     status->value.sig = 0;
  3229.                     return retval;
  3230.                   }
  3231. #endif
  3232.               case PR_JOBCONTROL:
  3233.                 wstat = (what << 8) | 0177;
  3234.                 break;
  3235.               case PR_FAULTED:
  3236.                 switch (what) {
  3237. #ifdef FLTWATCH
  3238.                 case FLTWATCH:
  3239.                   wstat = (SIGTRAP << 8) | 0177;
  3240.                   break;
  3241. #endif
  3242. #ifdef FLTKWATCH
  3243.                 case FLTKWATCH:
  3244.                   wstat = (SIGTRAP << 8) | 0177;
  3245.                   break;
  3246. #endif
  3247.                   /* FIXME: use si_signo where possible.  */
  3248.                 case FLTPRIV:
  3249. #if (FLTILL != FLTPRIV)                /* Avoid "duplicate case" error.  */
  3250.                 case FLTILL:
  3251. #endif
  3252.                   wstat = (SIGILL << 8) | 0177;
  3253.                   break;
  3254.                 case FLTBPT:
  3255. #if (FLTTRACE != FLTBPT)        /* Avoid "duplicate case" error.  */
  3256.                 case FLTTRACE:
  3257. #endif
  3258.                   wstat = (SIGTRAP << 8) | 0177;
  3259.                   break;
  3260.                 case FLTSTACK:
  3261.                 case FLTACCESS:
  3262. #if (FLTBOUNDS != FLTSTACK)        /* Avoid "duplicate case" error.  */
  3263.                 case FLTBOUNDS:
  3264. #endif
  3265.                   wstat = (SIGSEGV << 8) | 0177;
  3266.                   break;
  3267.                 case FLTIOVF:
  3268.                 case FLTIZDIV:
  3269. #if (FLTFPE != FLTIOVF)                /* Avoid "duplicate case" error.  */
  3270.                 case FLTFPE:
  3271. #endif
  3272.                   wstat = (SIGFPE << 8) | 0177;
  3273.                   break;
  3274.                 case FLTPAGE:        /* Recoverable page fault */
  3275.                 default:        /* FIXME: use si_signo if possible for
  3276.                                    fault.  */
  3277.                   retval = pid_to_ptid (-1);
  3278.                   printf_filtered ("procfs:%d -- ", __LINE__);
  3279.                   printf_filtered (_("child stopped for unknown reason:\n"));
  3280.                   proc_prettyprint_why (why, what, 1);
  3281.                   error (_("... giving up..."));
  3282.                   break;
  3283.                 }
  3284.                 break;        /* case PR_FAULTED: */
  3285.               default:        /* switch (why) unmatched */
  3286.                 printf_filtered ("procfs:%d -- ", __LINE__);
  3287.                 printf_filtered (_("child stopped for unknown reason:\n"));
  3288.                 proc_prettyprint_why (why, what, 1);
  3289.                 error (_("... giving up..."));
  3290.                 break;
  3291.               }
  3292.               /* Got this far without error: If retval isn't in the
  3293.                  threads database, add it.  */
  3294.               if (ptid_get_pid (retval) > 0 &&
  3295.                   !ptid_equal (retval, inferior_ptid) &&
  3296.                   !in_thread_list (retval))
  3297.                 {
  3298.                   /* We have a new thread.  We need to add it both to
  3299.                      GDB's list and to our own.  If we don't create a
  3300.                      procinfo, resume may be unhappy later.  */
  3301.                   add_thread (retval);
  3302.                   if (find_procinfo (ptid_get_pid (retval),
  3303.                                      ptid_get_lwp (retval)) == NULL)
  3304.                     create_procinfo (ptid_get_pid (retval),
  3305.                                      ptid_get_lwp (retval));
  3306.                 }
  3307.             }
  3308.           else        /* Flags do not indicate STOPPED.  */
  3309.             {
  3310.               /* surely this can't happen...  */
  3311.               printf_filtered ("procfs:%d -- process not stopped.\n",
  3312.                                __LINE__);
  3313.               proc_prettyprint_flags (flags, 1);
  3314.               error (_("procfs: ...giving up..."));
  3315.             }
  3316.         }

  3317.       if (status)
  3318.         store_waitstatus (status, wstat);
  3319.     }

  3320.   return retval;
  3321. }

  3322. /* Perform a partial transfer to/from the specified object.  For
  3323.    memory transfers, fall back to the old memory xfer functions.  */

  3324. static enum target_xfer_status
  3325. procfs_xfer_partial (struct target_ops *ops, enum target_object object,
  3326.                      const char *annex, gdb_byte *readbuf,
  3327.                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  3328.                      ULONGEST *xfered_len)
  3329. {
  3330.   switch (object)
  3331.     {
  3332.     case TARGET_OBJECT_MEMORY:
  3333.       return procfs_xfer_memory (readbuf, writebuf, offset, len, xfered_len);

  3334. #ifdef NEW_PROC_API
  3335.     case TARGET_OBJECT_AUXV:
  3336.       return memory_xfer_auxv (ops, object, annex, readbuf, writebuf,
  3337.                                offset, len, xfered_len);
  3338. #endif

  3339.     default:
  3340.       return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
  3341.                                             readbuf, writebuf, offset, len,
  3342.                                             xfered_len);
  3343.     }
  3344. }

  3345. /* Helper for procfs_xfer_partial that handles memory transfers.
  3346.    Arguments are like target_xfer_partial.  */

  3347. static enum target_xfer_status
  3348. procfs_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
  3349.                     ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
  3350. {
  3351.   procinfo *pi;
  3352.   int nbytes;

  3353.   /* Find procinfo for main process.  */
  3354.   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
  3355.   if (pi->as_fd == 0 &&
  3356.       open_procinfo_files (pi, FD_AS) == 0)
  3357.     {
  3358.       proc_warn (pi, "xfer_memory, open_proc_files", __LINE__);
  3359.       return TARGET_XFER_E_IO;
  3360.     }

  3361.   if (lseek (pi->as_fd, (off_t) memaddr, SEEK_SET) != (off_t) memaddr)
  3362.     return TARGET_XFER_E_IO;

  3363.   if (writebuf != NULL)
  3364.     {
  3365.       PROCFS_NOTE ("write memory:\n");
  3366.       nbytes = write (pi->as_fd, writebuf, len);
  3367.     }
  3368.   else
  3369.     {
  3370.       PROCFS_NOTE ("read  memory:\n");
  3371.       nbytes = read (pi->as_fd, readbuf, len);
  3372.     }
  3373.   if (nbytes <= 0)
  3374.     return TARGET_XFER_E_IO;
  3375.   *xfered_len = nbytes;
  3376.   return TARGET_XFER_OK;
  3377. }

  3378. /* Called by target_resume before making child runnable.  Mark cached
  3379.    registers and status's invalid.  If there are "dirty" caches that
  3380.    need to be written back to the child process, do that.

  3381.    File descriptors are also cached.  As they are a limited resource,
  3382.    we cannot hold onto them indefinitely.  However, as they are
  3383.    expensive to open, we don't want to throw them away
  3384.    indescriminately either.  As a compromise, we will keep the file
  3385.    descriptors for the parent process, but discard any file
  3386.    descriptors we may have accumulated for the threads.

  3387.    As this function is called by iterate_over_threads, it always
  3388.    returns zero (so that iterate_over_threads will keep
  3389.    iterating).  */

  3390. static int
  3391. invalidate_cache (procinfo *parent, procinfo *pi, void *ptr)
  3392. {
  3393.   /* About to run the child; invalidate caches and do any other
  3394.      cleanup.  */

  3395. #if 0
  3396.   if (pi->gregs_dirty)
  3397.     if (parent == NULL ||
  3398.         proc_get_current_thread (parent) != pi->tid)
  3399.       if (!proc_set_gregs (pi))        /* flush gregs cache */
  3400.         proc_warn (pi, "target_resume, set_gregs",
  3401.                    __LINE__);
  3402.   if (gdbarch_fp0_regnum (target_gdbarch ()) >= 0)
  3403.     if (pi->fpregs_dirty)
  3404.       if (parent == NULL ||
  3405.           proc_get_current_thread (parent) != pi->tid)
  3406.         if (!proc_set_fpregs (pi))        /* flush fpregs cache */
  3407.           proc_warn (pi, "target_resume, set_fpregs",
  3408.                      __LINE__);
  3409. #endif

  3410.   if (parent != NULL)
  3411.     {
  3412.       /* The presence of a parent indicates that this is an LWP.
  3413.          Close any file descriptors that it might have open.
  3414.          We don't do this to the master (parent) procinfo.  */

  3415.       close_procinfo_files (pi);
  3416.     }
  3417.   pi->gregs_valid   = 0;
  3418.   pi->fpregs_valid  = 0;
  3419. #if 0
  3420.   pi->gregs_dirty   = 0;
  3421.   pi->fpregs_dirty  = 0;
  3422. #endif
  3423.   pi->status_valid  = 0;
  3424.   pi->threads_valid = 0;

  3425.   return 0;
  3426. }

  3427. #if 0
  3428. /* A callback function for iterate_over_threads.  Find the
  3429.    asynchronous signal thread, and make it runnable.  See if that
  3430.    helps matters any.  */

  3431. static int
  3432. make_signal_thread_runnable (procinfo *process, procinfo *pi, void *ptr)
  3433. {
  3434. #ifdef PR_ASLWP
  3435.   if (proc_flags (pi) & PR_ASLWP)
  3436.     {
  3437.       if (!proc_run_process (pi, 0, -1))
  3438.         proc_error (pi, "make_signal_thread_runnable", __LINE__);
  3439.       return 1;
  3440.     }
  3441. #endif
  3442.   return 0;
  3443. }
  3444. #endif

  3445. /* Make the child process runnable.  Normally we will then call
  3446.    procfs_wait and wait for it to stop again (unless gdb is async).

  3447.    If STEP is true, then arrange for the child to stop again after
  3448.    executing a single instruction.  If SIGNO is zero, then cancel any
  3449.    pending signal; if non-zero, then arrange for the indicated signal
  3450.    to be delivered to the child when it runs.  If PID is -1, then
  3451.    allow any child thread to run; if non-zero, then allow only the
  3452.    indicated thread to run.  (not implemented yet).  */

  3453. static void
  3454. procfs_resume (struct target_ops *ops,
  3455.                ptid_t ptid, int step, enum gdb_signal signo)
  3456. {
  3457.   procinfo *pi, *thread;
  3458.   int native_signo;

  3459.   /* 2.1:
  3460.      prrun.prflags |= PRSVADDR;
  3461.      prrun.pr_vaddr = $PC;           set resume address
  3462.      prrun.prflags |= PRSTRACE;    trace signals in pr_trace (all)
  3463.      prrun.prflags |= PRSFAULT;    trace faults in pr_fault (all but PAGE)
  3464.      prrun.prflags |= PRCFAULT;    clear current fault.

  3465.      PRSTRACE and PRSFAULT can be done by other means
  3466.         (proc_trace_signals, proc_trace_faults)
  3467.      PRSVADDR is unnecessary.
  3468.      PRCFAULT may be replaced by a PIOCCFAULT call (proc_clear_current_fault)
  3469.      This basically leaves PRSTEP and PRCSIG.
  3470.      PRCSIG is like PIOCSSIG (proc_clear_current_signal).
  3471.      So basically PR_STEP is the sole argument that must be passed
  3472.      to proc_run_process (for use in the prrun struct by ioctl).  */

  3473.   /* Find procinfo for main process.  */
  3474.   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);

  3475.   /* First cut: ignore pid argument.  */
  3476.   errno = 0;

  3477.   /* Convert signal to host numbering.  */
  3478.   if (signo == 0 ||
  3479.       (signo == GDB_SIGNAL_STOP && pi->ignore_next_sigstop))
  3480.     native_signo = 0;
  3481.   else
  3482.     native_signo = gdb_signal_to_host (signo);

  3483.   pi->ignore_next_sigstop = 0;

  3484.   /* Running the process voids all cached registers and status.  */
  3485.   /* Void the threads' caches first.  */
  3486.   proc_iterate_over_threads (pi, invalidate_cache, NULL);
  3487.   /* Void the process procinfo's caches.  */
  3488.   invalidate_cache (NULL, pi, NULL);

  3489.   if (ptid_get_pid (ptid) != -1)
  3490.     {
  3491.       /* Resume a specific thread, presumably suppressing the
  3492.          others.  */
  3493.       thread = find_procinfo (ptid_get_pid (ptid), ptid_get_lwp (ptid));
  3494.       if (thread != NULL)
  3495.         {
  3496.           if (thread->tid != 0)
  3497.             {
  3498.               /* We're to resume a specific thread, and not the
  3499.                  others.  Set the child process's PR_ASYNC flag.  */
  3500. #ifdef PR_ASYNC
  3501.               if (!proc_set_async (pi))
  3502.                 proc_error (pi, "target_resume, set_async", __LINE__);
  3503. #endif
  3504. #if 0
  3505.               proc_iterate_over_threads (pi,
  3506.                                          make_signal_thread_runnable,
  3507.                                          NULL);
  3508. #endif
  3509.               pi = thread;        /* Substitute the thread's procinfo
  3510.                                    for run.  */
  3511.             }
  3512.         }
  3513.     }

  3514.   if (!proc_run_process (pi, step, native_signo))
  3515.     {
  3516.       if (errno == EBUSY)
  3517.         warning (_("resume: target already running.  "
  3518.                    "Pretend to resume, and hope for the best!"));
  3519.       else
  3520.         proc_error (pi, "target_resume", __LINE__);
  3521.     }
  3522. }

  3523. /* Set up to trace signals in the child process.  */

  3524. static void
  3525. procfs_pass_signals (struct target_ops *self,
  3526.                      int numsigs, unsigned char *pass_signals)
  3527. {
  3528.   gdb_sigset_t signals;
  3529.   procinfo *pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
  3530.   int signo;

  3531.   prfillset (&signals);

  3532.   for (signo = 0; signo < NSIG; signo++)
  3533.     {
  3534.       int target_signo = gdb_signal_from_host (signo);
  3535.       if (target_signo < numsigs && pass_signals[target_signo])
  3536.         gdb_prdelset (&signals, signo);
  3537.     }

  3538.   if (!proc_set_traced_signals (pi, &signals))
  3539.     proc_error (pi, "pass_signals", __LINE__);
  3540. }

  3541. /* Print status information about the child process.  */

  3542. static void
  3543. procfs_files_info (struct target_ops *ignore)
  3544. {
  3545.   struct inferior *inf = current_inferior ();

  3546.   printf_filtered (_("\tUsing the running image of %s %s via /proc.\n"),
  3547.                    inf->attach_flag? "attached": "child",
  3548.                    target_pid_to_str (inferior_ptid));
  3549. }

  3550. /* Stop the child process asynchronously, as when the gdb user types
  3551.    control-c or presses a "stop" button.  Works by sending
  3552.    kill(SIGINT) to the child's process group.  */

  3553. static void
  3554. procfs_stop (struct target_ops *self, ptid_t ptid)
  3555. {
  3556.   kill (-inferior_process_group (), SIGINT);
  3557. }

  3558. /* Make it die.  Wait for it to die.  Clean up after it.  Note: this
  3559.    should only be applied to the real process, not to an LWP, because
  3560.    of the check for parent-process.  If we need this to work for an
  3561.    LWP, it needs some more logic.  */

  3562. static void
  3563. unconditionally_kill_inferior (procinfo *pi)
  3564. {
  3565.   int parent_pid;

  3566.   parent_pid = proc_parent_pid (pi);
  3567. #ifdef PROCFS_NEED_PIOCSSIG_FOR_KILL
  3568.   /* Alpha OSF/1-2.x procfs needs a PIOCSSIG call with a SIGKILL signal
  3569.      to kill the inferior, otherwise it might remain stopped with a
  3570.      pending SIGKILL.
  3571.      We do not check the result of the PIOCSSIG, the inferior might have
  3572.      died already.  */
  3573.   {
  3574.     gdb_siginfo_t newsiginfo;

  3575.     memset ((char *) &newsiginfo, 0, sizeof (newsiginfo));
  3576.     newsiginfo.si_signo = SIGKILL;
  3577.     newsiginfo.si_code = 0;
  3578.     newsiginfo.si_errno = 0;
  3579.     newsiginfo.si_pid = getpid ();
  3580.     newsiginfo.si_uid = getuid ();
  3581.     /* FIXME: use proc_set_current_signal.  */
  3582.     ioctl (pi->ctl_fd, PIOCSSIG, &newsiginfo);
  3583.   }
  3584. #else /* PROCFS_NEED_PIOCSSIG_FOR_KILL */
  3585.   if (!proc_kill (pi, SIGKILL))
  3586.     proc_error (pi, "unconditionally_kill, proc_kill", __LINE__);
  3587. #endif /* PROCFS_NEED_PIOCSSIG_FOR_KILL */
  3588.   destroy_procinfo (pi);

  3589.   /* If pi is GDB's child, wait for it to die.  */
  3590.   if (parent_pid == getpid ())
  3591.     /* FIXME: should we use waitpid to make sure we get the right event?
  3592.        Should we check the returned event?  */
  3593.     {
  3594. #if 0
  3595.       int status, ret;

  3596.       ret = waitpid (pi->pid, &status, 0);
  3597. #else
  3598.       wait (NULL);
  3599. #endif
  3600.     }
  3601. }

  3602. /* We're done debugging it, and we want it to go away.  Then we want
  3603.    GDB to forget all about it.  */

  3604. static void
  3605. procfs_kill_inferior (struct target_ops *ops)
  3606. {
  3607.   if (!ptid_equal (inferior_ptid, null_ptid)) /* ? */
  3608.     {
  3609.       /* Find procinfo for main process.  */
  3610.       procinfo *pi = find_procinfo (ptid_get_pid (inferior_ptid), 0);

  3611.       if (pi)
  3612.         unconditionally_kill_inferior (pi);
  3613.       target_mourn_inferior ();
  3614.     }
  3615. }

  3616. /* Forget we ever debugged this thing!  */

  3617. static void
  3618. procfs_mourn_inferior (struct target_ops *ops)
  3619. {
  3620.   procinfo *pi;

  3621.   if (!ptid_equal (inferior_ptid, null_ptid))
  3622.     {
  3623.       /* Find procinfo for main process.  */
  3624.       pi = find_procinfo (ptid_get_pid (inferior_ptid), 0);
  3625.       if (pi)
  3626.         destroy_procinfo (pi);
  3627.     }

  3628.   generic_mourn_inferior ();

  3629.   inf_child_maybe_unpush_target (ops);
  3630. }

  3631. /* When GDB forks to create a runnable inferior process, this function
  3632.    is called on the parent side of the fork.  It's job is to do
  3633.    whatever is necessary to make the child ready to be debugged, and
  3634.    then wait for the child to synchronize.  */

  3635. static void
  3636. procfs_init_inferior (struct target_ops *ops, int pid)
  3637. {
  3638.   procinfo *pi;
  3639.   gdb_sigset_t signals;
  3640.   int fail;
  3641.   int lwpid;

  3642.   /* This routine called on the parent side (GDB side)
  3643.      after GDB forks the inferior.  */
  3644.   if (!target_is_pushed (ops))
  3645.     push_target (ops);

  3646.   if ((pi = create_procinfo (pid, 0)) == NULL)
  3647.     perror (_("procfs: out of memory in 'init_inferior'"));

  3648.   if (!open_procinfo_files (pi, FD_CTL))
  3649.     proc_error (pi, "init_inferior, open_proc_files", __LINE__);

  3650.   /*
  3651.     xmalloc                        // done
  3652.     open_procinfo_files                // done
  3653.     link list                        // done
  3654.     prfillset (trace)
  3655.     procfs_notice_signals
  3656.     prfillset (fault)
  3657.     prdelset (FLTPAGE)
  3658.     PIOCWSTOP
  3659.     PIOCSFAULT
  3660.     */

  3661.   /* If not stopped yet, wait for it to stop.  */
  3662.   if (!(proc_flags (pi) & PR_STOPPED) &&
  3663.       !(proc_wait_for_stop (pi)))
  3664.     dead_procinfo (pi, "init_inferior: wait_for_stop failed", KILL);

  3665.   /* Save some of the /proc state to be restored if we detach.  */
  3666.   /* FIXME: Why?  In case another debugger was debugging it?
  3667.      We're it's parent, for Ghu's sake!  */
  3668.   if (!proc_get_traced_signals  (pi, &pi->saved_sigset))
  3669.     proc_error (pi, "init_inferior, get_traced_signals", __LINE__);
  3670.   if (!proc_get_held_signals    (pi, &pi->saved_sighold))
  3671.     proc_error (pi, "init_inferior, get_held_signals", __LINE__);
  3672.   if (!proc_get_traced_faults   (pi, &pi->saved_fltset))
  3673.     proc_error (pi, "init_inferior, get_traced_faults", __LINE__);
  3674.   if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
  3675.     proc_error (pi, "init_inferior, get_traced_sysentry", __LINE__);
  3676.   if (!proc_get_traced_sysexit  (pi, pi->saved_exitset))
  3677.     proc_error (pi, "init_inferior, get_traced_sysexit", __LINE__);

  3678.   if ((fail = procfs_debug_inferior (pi)) != 0)
  3679.     proc_error (pi, "init_inferior (procfs_debug_inferior)", fail);

  3680.   /* FIXME: logically, we should really be turning OFF run-on-last-close,
  3681.      and possibly even turning ON kill-on-last-close at this point.  But
  3682.      I can't make that change without careful testing which I don't have
  3683.      time to do right now...  */
  3684.   /* Turn on run-on-last-close flag so that the child
  3685.      will die if GDB goes away for some reason.  */
  3686.   if (!proc_set_run_on_last_close (pi))
  3687.     proc_error (pi, "init_inferior, set_RLC", __LINE__);

  3688.   /* We now have have access to the lwpid of the main thread/lwp.  */
  3689.   lwpid = proc_get_current_thread (pi);

  3690.   /* Create a procinfo for the main lwp.  */
  3691.   create_procinfo (pid, lwpid);

  3692.   /* We already have a main thread registered in the thread table at
  3693.      this point, but it didn't have any lwp info yet.  Notify the core
  3694.      about it.  This changes inferior_ptid as well.  */
  3695.   thread_change_ptid (pid_to_ptid (pid),
  3696.                       ptid_build (pid, lwpid, 0));

  3697.   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);

  3698. #ifdef SYS_syssgi
  3699.   /* On mips-irix, we need to stop the inferior early enough during
  3700.      the startup phase in order to be able to load the shared library
  3701.      symbols and insert the breakpoints that are located in these shared
  3702.      libraries.  Stopping at the program entry point is not good enough
  3703.      because the -init code is executed before the execution reaches
  3704.      that point.

  3705.      So what we need to do is to insert a breakpoint in the runtime
  3706.      loader (rld), more precisely in __dbx_link().  This procedure is
  3707.      called by rld once all shared libraries have been mapped, but before
  3708.      the -init code is executed.  Unfortuantely, this is not straightforward,
  3709.      as rld is not part of the executable we are running, and thus we need
  3710.      the inferior to run until rld itself has been mapped in memory.

  3711.      For this, we trace all syssgi() syscall exit events.  Each time
  3712.      we detect such an event, we iterate over each text memory maps,
  3713.      get its associated fd, and scan the symbol table for __dbx_link().
  3714.      When found, we know that rld has been mapped, and that we can insert
  3715.      the breakpoint at the symbol address.  Once the dbx_link() breakpoint
  3716.      has been inserted, the syssgi() notifications are no longer necessary,
  3717.      so they should be canceled.  */
  3718.   proc_trace_syscalls_1 (pi, SYS_syssgi, PR_SYSEXIT, FLAG_SET, 0);
  3719. #endif
  3720. }

  3721. /* When GDB forks to create a new process, this function is called on
  3722.    the child side of the fork before GDB exec's the user program.  Its
  3723.    job is to make the child minimally debuggable, so that the parent
  3724.    GDB process can connect to the child and take over.  This function
  3725.    should do only the minimum to make that possible, and to
  3726.    synchronize with the parent process.  The parent process should
  3727.    take care of the details.  */

  3728. static void
  3729. procfs_set_exec_trap (void)
  3730. {
  3731.   /* This routine called on the child side (inferior side)
  3732.      after GDB forks the inferior.  It must use only local variables,
  3733.      because it may be sharing data space with its parent.  */

  3734.   procinfo *pi;
  3735.   sysset_t *exitset;

  3736.   if ((pi = create_procinfo (getpid (), 0)) == NULL)
  3737.     perror_with_name (_("procfs: create_procinfo failed in child."));

  3738.   if (open_procinfo_files (pi, FD_CTL) == 0)
  3739.     {
  3740.       proc_warn (pi, "set_exec_trap, open_proc_files", __LINE__);
  3741.       gdb_flush (gdb_stderr);
  3742.       /* No need to call "dead_procinfo", because we're going to
  3743.          exit.  */
  3744.       _exit (127);
  3745.     }

  3746. #ifdef PRFS_STOPEXEC        /* defined on OSF */
  3747.   /* OSF method for tracing exec syscalls.  Quoting:
  3748.      Under Alpha OSF/1 we have to use a PIOCSSPCACT ioctl to trace
  3749.      exits from exec system calls because of the user level loader.  */
  3750.   /* FIXME: make nice and maybe move into an access function.  */
  3751.   {
  3752.     int prfs_flags;

  3753.     if (ioctl (pi->ctl_fd, PIOCGSPCACT, &prfs_flags) < 0)
  3754.       {
  3755.         proc_warn (pi, "set_exec_trap (PIOCGSPCACT)", __LINE__);
  3756.         gdb_flush (gdb_stderr);
  3757.         _exit (127);
  3758.       }
  3759.     prfs_flags |= PRFS_STOPEXEC;

  3760.     if (ioctl (pi->ctl_fd, PIOCSSPCACT, &prfs_flags) < 0)
  3761.       {
  3762.         proc_warn (pi, "set_exec_trap (PIOCSSPCACT)", __LINE__);
  3763.         gdb_flush (gdb_stderr);
  3764.         _exit (127);
  3765.       }
  3766.   }
  3767. #else /* not PRFS_STOPEXEC */
  3768.   /* Everyone else's (except OSF) method for tracing exec syscalls.  */
  3769.   /* GW: Rationale...
  3770.      Not all systems with /proc have all the exec* syscalls with the same
  3771.      names.  On the SGI, for example, there is no SYS_exec, but there
  3772.      *is* a SYS_execv.  So, we try to account for that.  */

  3773.   exitset = sysset_t_alloc (pi);
  3774.   gdb_premptysysset (exitset);
  3775. #ifdef SYS_exec
  3776.   gdb_praddsysset (exitset, SYS_exec);
  3777. #endif
  3778. #ifdef SYS_execve
  3779.   gdb_praddsysset (exitset, SYS_execve);
  3780. #endif
  3781. #ifdef SYS_execv
  3782.   gdb_praddsysset (exitset, SYS_execv);
  3783. #endif
  3784. #ifdef DYNAMIC_SYSCALLS
  3785.   {
  3786.     int callnum = find_syscall (pi, "execve");

  3787.     if (callnum >= 0)
  3788.       gdb_praddsysset (exitset, callnum);

  3789.     callnum = find_syscall (pi, "ra_execve");
  3790.     if (callnum >= 0)
  3791.       gdb_praddsysset (exitset, callnum);
  3792.   }
  3793. #endif /* DYNAMIC_SYSCALLS */

  3794.   if (!proc_set_traced_sysexit (pi, exitset))
  3795.     {
  3796.       proc_warn (pi, "set_exec_trap, set_traced_sysexit", __LINE__);
  3797.       gdb_flush (gdb_stderr);
  3798.       _exit (127);
  3799.     }
  3800. #endif /* PRFS_STOPEXEC */

  3801.   /* FIXME: should this be done in the parent instead?  */
  3802.   /* Turn off inherit on fork flag so that all grand-children
  3803.      of gdb start with tracing flags cleared.  */
  3804.   if (!proc_unset_inherit_on_fork (pi))
  3805.     proc_warn (pi, "set_exec_trap, unset_inherit", __LINE__);

  3806.   /* Turn off run on last close flag, so that the child process
  3807.      cannot run away just because we close our handle on it.
  3808.      We want it to wait for the parent to attach.  */
  3809.   if (!proc_unset_run_on_last_close (pi))
  3810.     proc_warn (pi, "set_exec_trap, unset_RLC", __LINE__);

  3811.   /* FIXME: No need to destroy the procinfo --
  3812.      we have our own address space, and we're about to do an exec!  */
  3813.   /*destroy_procinfo (pi);*/
  3814. }

  3815. /* This function is called BEFORE gdb forks the inferior process.  Its
  3816.    only real responsibility is to set things up for the fork, and tell
  3817.    GDB which two functions to call after the fork (one for the parent,
  3818.    and one for the child).

  3819.    This function does a complicated search for a unix shell program,
  3820.    which it then uses to parse arguments and environment variables to
  3821.    be sent to the child.  I wonder whether this code could not be
  3822.    abstracted out and shared with other unix targets such as
  3823.    inf-ptrace?  */

  3824. static void
  3825. procfs_create_inferior (struct target_ops *ops, char *exec_file,
  3826.                         char *allargs, char **env, int from_tty)
  3827. {
  3828.   char *shell_file = getenv ("SHELL");
  3829.   char *tryname;
  3830.   int pid;

  3831.   if (shell_file != NULL && strchr (shell_file, '/') == NULL)
  3832.     {

  3833.       /* We will be looking down the PATH to find shell_file.  If we
  3834.          just do this the normal way (via execlp, which operates by
  3835.          attempting an exec for each element of the PATH until it
  3836.          finds one which succeeds), then there will be an exec for
  3837.          each failed attempt, each of which will cause a PR_SYSEXIT
  3838.          stop, and we won't know how to distinguish the PR_SYSEXIT's
  3839.          for these failed execs with the ones for successful execs
  3840.          (whether the exec has succeeded is stored at that time in the
  3841.          carry bit or some such architecture-specific and
  3842.          non-ABI-specified place).

  3843.          So I can't think of anything better than to search the PATH
  3844.          now.  This has several disadvantages: (1) There is a race
  3845.          condition; if we find a file now and it is deleted before we
  3846.          exec it, we lose, even if the deletion leaves a valid file
  3847.          further down in the PATH, (2) there is no way to know exactly
  3848.          what an executable (in the sense of "capable of being
  3849.          exec'd") file is.  Using access() loses because it may lose
  3850.          if the caller is the superuser; failing to use it loses if
  3851.          there are ACLs or some such.  */

  3852.       char *p;
  3853.       char *p1;
  3854.       /* FIXME-maybe: might want "set path" command so user can change what
  3855.          path is used from within GDB.  */
  3856.       char *path = getenv ("PATH");
  3857.       int len;
  3858.       struct stat statbuf;

  3859.       if (path == NULL)
  3860.         path = "/bin:/usr/bin";

  3861.       tryname = alloca (strlen (path) + strlen (shell_file) + 2);
  3862.       for (p = path; p != NULL; p = p1 ? p1 + 1: NULL)
  3863.         {
  3864.           p1 = strchr (p, ':');
  3865.           if (p1 != NULL)
  3866.             len = p1 - p;
  3867.           else
  3868.             len = strlen (p);
  3869.           strncpy (tryname, p, len);
  3870.           tryname[len] = '\0';
  3871.           strcat (tryname, "/");
  3872.           strcat (tryname, shell_file);
  3873.           if (access (tryname, X_OK) < 0)
  3874.             continue;
  3875.           if (stat (tryname, &statbuf) < 0)
  3876.             continue;
  3877.           if (!S_ISREG (statbuf.st_mode))
  3878.             /* We certainly need to reject directories.  I'm not quite
  3879.                as sure about FIFOs, sockets, etc., but I kind of doubt
  3880.                that people want to exec() these things.  */
  3881.             continue;
  3882.           break;
  3883.         }
  3884.       if (p == NULL)
  3885.         /* Not found.  This must be an error rather than merely passing
  3886.            the file to execlp(), because execlp() would try all the
  3887.            exec()s, causing GDB to get confused.  */
  3888.         error (_("procfs:%d -- Can't find shell %s in PATH"),
  3889.                __LINE__, shell_file);

  3890.       shell_file = tryname;
  3891.     }

  3892.   pid = fork_inferior (exec_file, allargs, env, procfs_set_exec_trap,
  3893.                        NULL, NULL, shell_file, NULL);

  3894.   procfs_init_inferior (ops, pid);
  3895. }

  3896. /* An observer for the "inferior_created" event.  */

  3897. static void
  3898. procfs_inferior_created (struct target_ops *ops, int from_tty)
  3899. {
  3900. #ifdef SYS_syssgi
  3901.   /* Make sure to cancel the syssgi() syscall-exit notifications.
  3902.      They should normally have been removed by now, but they may still
  3903.      be activated if the inferior doesn't use shared libraries, or if
  3904.      we didn't locate __dbx_link, or if we never stopped in __dbx_link.
  3905.      See procfs_init_inferior() for more details.

  3906.      Since these notifications are only ever enabled when we spawned
  3907.      the inferior ourselves, there is nothing to do when the inferior
  3908.      was created by attaching to an already running process, or when
  3909.      debugging a core file.  */
  3910.   if (current_inferior ()->attach_flag || !target_can_run (&current_target))
  3911.     return;

  3912.   proc_trace_syscalls_1 (find_procinfo_or_die (ptid_get_pid (inferior_ptid),
  3913.                          0), SYS_syssgi, PR_SYSEXIT, FLAG_RESET, 0);
  3914. #endif
  3915. }

  3916. /* Callback for update_thread_list.  Calls "add_thread".  */

  3917. static int
  3918. procfs_notice_thread (procinfo *pi, procinfo *thread, void *ptr)
  3919. {
  3920.   ptid_t gdb_threadid = ptid_build (pi->pid, thread->tid, 0);

  3921.   if (!in_thread_list (gdb_threadid) || is_exited (gdb_threadid))
  3922.     add_thread (gdb_threadid);

  3923.   return 0;
  3924. }

  3925. /* Query all the threads that the target knows about, and give them
  3926.    back to GDB to add to its list.  */

  3927. static void
  3928. procfs_update_thread_list (struct target_ops *ops)
  3929. {
  3930.   procinfo *pi;

  3931.   prune_threads ();

  3932.   /* Find procinfo for main process.  */
  3933.   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
  3934.   proc_update_threads (pi);
  3935.   proc_iterate_over_threads (pi, procfs_notice_thread, NULL);
  3936. }

  3937. /* Return true if the thread is still 'alive'.  This guy doesn't
  3938.    really seem to be doing his job.  Got to investigate how to tell
  3939.    when a thread is really gone.  */

  3940. static int
  3941. procfs_thread_alive (struct target_ops *ops, ptid_t ptid)
  3942. {
  3943.   int proc, thread;
  3944.   procinfo *pi;

  3945.   proc    = ptid_get_pid (ptid);
  3946.   thread  = ptid_get_lwp (ptid);
  3947.   /* If I don't know it, it ain't alive!  */
  3948.   if ((pi = find_procinfo (proc, thread)) == NULL)
  3949.     return 0;

  3950.   /* If I can't get its status, it ain't alive!
  3951.      What's more, I need to forget about it!  */
  3952.   if (!proc_get_status (pi))
  3953.     {
  3954.       destroy_procinfo (pi);
  3955.       return 0;
  3956.     }
  3957.   /* I couldn't have got its status if it weren't alive, so it's
  3958.      alive.  */
  3959.   return 1;
  3960. }

  3961. /* Convert PTID to a string.  Returns the string in a static
  3962.    buffer.  */

  3963. static char *
  3964. procfs_pid_to_str (struct target_ops *ops, ptid_t ptid)
  3965. {
  3966.   static char buf[80];

  3967.   if (ptid_get_lwp (ptid) == 0)
  3968.     sprintf (buf, "process %d", ptid_get_pid (ptid));
  3969.   else
  3970.     sprintf (buf, "LWP %ld", ptid_get_lwp (ptid));

  3971.   return buf;
  3972. }

  3973. /* Insert a watchpoint.  */

  3974. static int
  3975. procfs_set_watchpoint (ptid_t ptid, CORE_ADDR addr, int len, int rwflag,
  3976.                        int after)
  3977. {
  3978. #ifndef AIX5
  3979.   int       pflags = 0;
  3980.   procinfo *pi;

  3981.   pi = find_procinfo_or_die (ptid_get_pid (ptid) == -1 ?
  3982.                              ptid_get_pid (inferior_ptid) : ptid_get_pid (ptid),
  3983.                              0);

  3984.   /* Translate from GDB's flags to /proc's.  */
  3985.   if (len > 0)        /* len == 0 means delete watchpoint.  */
  3986.     {
  3987.       switch (rwflag) {                /* FIXME: need an enum!  */
  3988.       case hw_write:                /* default watchpoint (write) */
  3989.         pflags = WRITE_WATCHFLAG;
  3990.         break;
  3991.       case hw_read:                /* read watchpoint */
  3992.         pflags = READ_WATCHFLAG;
  3993.         break;
  3994.       case hw_access:                /* access watchpoint */
  3995.         pflags = READ_WATCHFLAG | WRITE_WATCHFLAG;
  3996.         break;
  3997.       case hw_execute:                /* execution HW breakpoint */
  3998.         pflags = EXEC_WATCHFLAG;
  3999.         break;
  4000.       default:                        /* Something weird.  Return error.  */
  4001.         return -1;
  4002.       }
  4003.       if (after)                /* Stop after r/w access is completed.  */
  4004.         pflags |= AFTER_WATCHFLAG;
  4005.     }

  4006.   if (!proc_set_watchpoint (pi, addr, len, pflags))
  4007.     {
  4008.       if (errno == E2BIG)        /* Typical error for no resources.  */
  4009.         return -1;                /* fail */
  4010.       /* GDB may try to remove the same watchpoint twice.
  4011.          If a remove request returns no match, don't error.  */
  4012.       if (errno == ESRCH && len == 0)
  4013.         return 0;                /* ignore */
  4014.       proc_error (pi, "set_watchpoint", __LINE__);
  4015.     }
  4016. #endif /* AIX5 */
  4017.   return 0;
  4018. }

  4019. /* Return non-zero if we can set a hardware watchpoint of type TYPETYPE
  4020.    is one of bp_hardware_watchpoint, bp_read_watchpoint, bp_write_watchpoint,
  4021.    or bp_hardware_watchpoint.  CNT is the number of watchpoints used so
  4022.    far.

  4023.    Note:  procfs_can_use_hw_breakpoint() is not yet used by all
  4024.    procfs.c targets due to the fact that some of them still define
  4025.    target_can_use_hardware_watchpoint.  */

  4026. static int
  4027. procfs_can_use_hw_breakpoint (struct target_ops *self,
  4028.                               int type, int cnt, int othertype)
  4029. {
  4030.   /* Due to the way that proc_set_watchpoint() is implemented, host
  4031.      and target pointers must be of the same size.  If they are not,
  4032.      we can't use hardware watchpoints.  This limitation is due to the
  4033.      fact that proc_set_watchpoint() calls
  4034.      procfs_address_to_host_pointer(); a close inspection of
  4035.      procfs_address_to_host_pointer will reveal that an internal error
  4036.      will be generated when the host and target pointer sizes are
  4037.      different.  */
  4038.   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;

  4039.   if (sizeof (void *) != TYPE_LENGTH (ptr_type))
  4040.     return 0;

  4041.   /* Other tests here???  */

  4042.   return 1;
  4043. }

  4044. /* Returns non-zero if process is stopped on a hardware watchpoint
  4045.    fault, else returns zero.  */

  4046. static int
  4047. procfs_stopped_by_watchpoint (struct target_ops *ops)
  4048. {
  4049.   procinfo *pi;

  4050.   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);

  4051.   if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
  4052.     {
  4053.       if (proc_why (pi) == PR_FAULTED)
  4054.         {
  4055. #ifdef FLTWATCH
  4056.           if (proc_what (pi) == FLTWATCH)
  4057.             return 1;
  4058. #endif
  4059. #ifdef FLTKWATCH
  4060.           if (proc_what (pi) == FLTKWATCH)
  4061.             return 1;
  4062. #endif
  4063.         }
  4064.     }
  4065.   return 0;
  4066. }

  4067. /* Returns 1 if the OS knows the position of the triggered watchpoint,
  4068.    and sets *ADDR to that address.  Returns 0 if OS cannot report that
  4069.    address.  This function is only called if
  4070.    procfs_stopped_by_watchpoint returned 1, thus no further checks are
  4071.    done.  The function also assumes that ADDR is not NULL.  */

  4072. static int
  4073. procfs_stopped_data_address (struct target_ops *targ, CORE_ADDR *addr)
  4074. {
  4075.   procinfo *pi;

  4076.   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
  4077.   return proc_watchpoint_address (pi, addr);
  4078. }

  4079. static int
  4080. procfs_insert_watchpoint (struct target_ops *self,
  4081.                           CORE_ADDR addr, int len, int type,
  4082.                           struct expression *cond)
  4083. {
  4084.   if (!target_have_steppable_watchpoint
  4085.       && !gdbarch_have_nonsteppable_watchpoint (target_gdbarch ()))
  4086.     {
  4087.       /* When a hardware watchpoint fires off the PC will be left at
  4088.          the instruction following the one which caused the
  4089.          watchpoint.  It will *NOT* be necessary for GDB to step over
  4090.          the watchpoint.  */
  4091.       return procfs_set_watchpoint (inferior_ptid, addr, len, type, 1);
  4092.     }
  4093.   else
  4094.     {
  4095.       /* When a hardware watchpoint fires off the PC will be left at
  4096.          the instruction which caused the watchpoint.  It will be
  4097.          necessary for GDB to step over the watchpoint.  */
  4098.       return procfs_set_watchpoint (inferior_ptid, addr, len, type, 0);
  4099.     }
  4100. }

  4101. static int
  4102. procfs_remove_watchpoint (struct target_ops *self,
  4103.                           CORE_ADDR addr, int len, int type,
  4104.                           struct expression *cond)
  4105. {
  4106.   return procfs_set_watchpoint (inferior_ptid, addr, 0, 0, 0);
  4107. }

  4108. static int
  4109. procfs_region_ok_for_hw_watchpoint (struct target_ops *self,
  4110.                                     CORE_ADDR addr, int len)
  4111. {
  4112.   /* The man page for proc(4) on Solaris 2.6 and up says that the
  4113.      system can support "thousands" of hardware watchpoints, but gives
  4114.      no method for finding out how many; It doesn't say anything about
  4115.      the allowed size for the watched area either.  So we just tell
  4116.      GDB 'yes'.  */
  4117.   return 1;
  4118. }

  4119. void
  4120. procfs_use_watchpoints (struct target_ops *t)
  4121. {
  4122.   t->to_stopped_by_watchpoint = procfs_stopped_by_watchpoint;
  4123.   t->to_insert_watchpoint = procfs_insert_watchpoint;
  4124.   t->to_remove_watchpoint = procfs_remove_watchpoint;
  4125.   t->to_region_ok_for_hw_watchpoint = procfs_region_ok_for_hw_watchpoint;
  4126.   t->to_can_use_hw_breakpoint = procfs_can_use_hw_breakpoint;
  4127.   t->to_stopped_data_address = procfs_stopped_data_address;
  4128. }

  4129. /* Memory Mappings Functions: */

  4130. /* Call a callback function once for each mapping, passing it the
  4131.    mapping, an optional secondary callback function, and some optional
  4132.    opaque data.  Quit and return the first non-zero value returned
  4133.    from the callback.

  4134.    PI is the procinfo struct for the process to be mapped.  FUNC is
  4135.    the callback function to be called by this iterator.  DATA is the
  4136.    optional opaque data to be passed to the callback function.
  4137.    CHILD_FUNC is the optional secondary function pointer to be passed
  4138.    to the child function.  Returns the first non-zero return value
  4139.    from the callback function, or zero.  */

  4140. static int
  4141. iterate_over_mappings (procinfo *pi, find_memory_region_ftype child_func,
  4142.                        void *data,
  4143.                        int (*func) (struct prmap *map,
  4144.                                     find_memory_region_ftype child_func,
  4145.                                     void *data))
  4146. {
  4147.   char pathname[MAX_PROC_NAME_SIZE];
  4148.   struct prmap *prmaps;
  4149.   struct prmap *prmap;
  4150.   int funcstat;
  4151.   int map_fd;
  4152.   int nmap;
  4153.   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
  4154. #ifdef NEW_PROC_API
  4155.   struct stat sbuf;
  4156. #endif

  4157.   /* Get the number of mappings, allocate space,
  4158.      and read the mappings into prmaps.  */
  4159. #ifdef NEW_PROC_API
  4160.   /* Open map fd.  */
  4161.   sprintf (pathname, "/proc/%d/map", pi->pid);
  4162.   if ((map_fd = open (pathname, O_RDONLY)) < 0)
  4163.     proc_error (pi, "iterate_over_mappings (open)", __LINE__);

  4164.   /* Make sure it gets closed again.  */
  4165.   make_cleanup_close (map_fd);

  4166.   /* Use stat to determine the file size, and compute
  4167.      the number of prmap_t objects it contains.  */
  4168.   if (fstat (map_fd, &sbuf) != 0)
  4169.     proc_error (pi, "iterate_over_mappings (fstat)", __LINE__);

  4170.   nmap = sbuf.st_size / sizeof (prmap_t);
  4171.   prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
  4172.   if (read (map_fd, (char *) prmaps, nmap * sizeof (*prmaps))
  4173.       != (nmap * sizeof (*prmaps)))
  4174.     proc_error (pi, "iterate_over_mappings (read)", __LINE__);
  4175. #else
  4176.   /* Use ioctl command PIOCNMAP to get number of mappings.  */
  4177.   if (ioctl (pi->ctl_fd, PIOCNMAP, &nmap) != 0)
  4178.     proc_error (pi, "iterate_over_mappings (PIOCNMAP)", __LINE__);

  4179.   prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
  4180.   if (ioctl (pi->ctl_fd, PIOCMAP, prmaps) != 0)
  4181.     proc_error (pi, "iterate_over_mappings (PIOCMAP)", __LINE__);
  4182. #endif

  4183.   for (prmap = prmaps; nmap > 0; prmap++, nmap--)
  4184.     if ((funcstat = (*func) (prmap, child_func, data)) != 0)
  4185.       {
  4186.         do_cleanups (cleanups);
  4187.         return funcstat;
  4188.       }

  4189.   do_cleanups (cleanups);
  4190.   return 0;
  4191. }

  4192. /* Implements the to_find_memory_regions method.  Calls an external
  4193.    function for each memory region.
  4194.    Returns the integer value returned by the callback.  */

  4195. static int
  4196. find_memory_regions_callback (struct prmap *map,
  4197.                               find_memory_region_ftype func, void *data)
  4198. {
  4199.   return (*func) ((CORE_ADDR) map->pr_vaddr,
  4200.                   map->pr_size,
  4201.                   (map->pr_mflags & MA_READ) != 0,
  4202.                   (map->pr_mflags & MA_WRITE) != 0,
  4203.                   (map->pr_mflags & MA_EXEC) != 0,
  4204.                   1, /* MODIFIED is unknown, pass it as true.  */
  4205.                   data);
  4206. }

  4207. /* External interface.  Calls a callback function once for each
  4208.    mapped memory region in the child process, passing as arguments:

  4209.         CORE_ADDR virtual_address,
  4210.         unsigned long size,
  4211.         int read,        TRUE if region is readable by the child
  4212.         int write,        TRUE if region is writable by the child
  4213.         int execute        TRUE if region is executable by the child.

  4214.    Stops iterating and returns the first non-zero value returned by
  4215.    the callback.  */

  4216. static int
  4217. proc_find_memory_regions (struct target_ops *self,
  4218.                           find_memory_region_ftype func, void *data)
  4219. {
  4220.   procinfo *pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);

  4221.   return iterate_over_mappings (pi, func, data,
  4222.                                 find_memory_regions_callback);
  4223. }

  4224. /* Returns an ascii representation of a memory mapping's flags.  */

  4225. static char *
  4226. mappingflags (long flags)
  4227. {
  4228.   static char asciiflags[8];

  4229.   strcpy (asciiflags, "-------");
  4230. #if defined (MA_PHYS)
  4231.   if (flags & MA_PHYS)
  4232.     asciiflags[0] = 'd';
  4233. #endif
  4234.   if (flags & MA_STACK)
  4235.     asciiflags[1] = 's';
  4236.   if (flags & MA_BREAK)
  4237.     asciiflags[2] = 'b';
  4238.   if (flags & MA_SHARED)
  4239.     asciiflags[3] = 's';
  4240.   if (flags & MA_READ)
  4241.     asciiflags[4] = 'r';
  4242.   if (flags & MA_WRITE)
  4243.     asciiflags[5] = 'w';
  4244.   if (flags & MA_EXEC)
  4245.     asciiflags[6] = 'x';
  4246.   return (asciiflags);
  4247. }

  4248. /* Callback function, does the actual work for 'info proc
  4249.    mappings'.  */

  4250. static int
  4251. info_mappings_callback (struct prmap *map, find_memory_region_ftype ignore,
  4252.                         void *unused)
  4253. {
  4254.   unsigned int pr_off;

  4255. #ifdef PCAGENT        /* Horrible hack: only defined on Solaris 2.6+ */
  4256.   pr_off = (unsigned int) map->pr_offset;
  4257. #else
  4258.   pr_off = map->pr_off;
  4259. #endif

  4260.   if (gdbarch_addr_bit (target_gdbarch ()) == 32)
  4261.     printf_filtered ("\t%#10lx %#10lx %#10lx %#10x %7s\n",
  4262.                      (unsigned long) map->pr_vaddr,
  4263.                      (unsigned long) map->pr_vaddr + map->pr_size - 1,
  4264.                      (unsigned long) map->pr_size,
  4265.                      pr_off,
  4266.                      mappingflags (map->pr_mflags));
  4267.   else
  4268.     printf_filtered (%#18lx %#18lx %#10lx %#10x %7s\n",
  4269.                      (unsigned long) map->pr_vaddr,
  4270.                      (unsigned long) map->pr_vaddr + map->pr_size - 1,
  4271.                      (unsigned long) map->pr_size,
  4272.                      pr_off,
  4273.                      mappingflags (map->pr_mflags));

  4274.   return 0;
  4275. }

  4276. /* Implement the "info proc mappings" subcommand.  */

  4277. static void
  4278. info_proc_mappings (procinfo *pi, int summary)
  4279. {
  4280.   if (summary)
  4281.     return;        /* No output for summary mode.  */

  4282.   printf_filtered (_("Mapped address spaces:\n\n"));
  4283.   if (gdbarch_ptr_bit (target_gdbarch ()) == 32)
  4284.     printf_filtered ("\t%10s %10s %10s %10s %7s\n",
  4285.                      "Start Addr",
  4286.                      "  End Addr",
  4287.                      "      Size",
  4288.                      "    Offset",
  4289.                      "Flags");
  4290.   else
  4291.     printf_filtered (%18s %18s %10s %10s %7s\n",
  4292.                      "Start Addr",
  4293.                      "  End Addr",
  4294.                      "      Size",
  4295.                      "    Offset",
  4296.                      "Flags");

  4297.   iterate_over_mappings (pi, NULL, NULL, info_mappings_callback);
  4298.   printf_filtered ("\n");
  4299. }

  4300. /* Implement the "info proc" command.  */

  4301. static void
  4302. procfs_info_proc (struct target_ops *ops, const char *args,
  4303.                   enum info_proc_what what)
  4304. {
  4305.   struct cleanup *old_chain;
  4306.   procinfo *process  = NULL;
  4307.   procinfo *thread   = NULL;
  4308.   char    **argv     = NULL;
  4309.   char     *tmp      = NULL;
  4310.   int       pid      = 0;
  4311.   int       tid      = 0;
  4312.   int       mappings = 0;

  4313.   switch (what)
  4314.     {
  4315.     case IP_MINIMAL:
  4316.       break;

  4317.     case IP_MAPPINGS:
  4318.     case IP_ALL:
  4319.       mappings = 1;
  4320.       break;

  4321.     default:
  4322.       error (_("Not supported on this target."));
  4323.     }

  4324.   old_chain = make_cleanup (null_cleanup, 0);
  4325.   if (args)
  4326.     {
  4327.       argv = gdb_buildargv (args);
  4328.       make_cleanup_freeargv (argv);
  4329.     }
  4330.   while (argv != NULL && *argv != NULL)
  4331.     {
  4332.       if (isdigit (argv[0][0]))
  4333.         {
  4334.           pid = strtoul (argv[0], &tmp, 10);
  4335.           if (*tmp == '/')
  4336.             tid = strtoul (++tmp, NULL, 10);
  4337.         }
  4338.       else if (argv[0][0] == '/')
  4339.         {
  4340.           tid = strtoul (argv[0] + 1, NULL, 10);
  4341.         }
  4342.       argv++;
  4343.     }
  4344.   if (pid == 0)
  4345.     pid = ptid_get_pid (inferior_ptid);
  4346.   if (pid == 0)
  4347.     error (_("No current process: you must name one."));
  4348.   else
  4349.     {
  4350.       /* Have pid, will travel.
  4351.          First see if it's a process we're already debugging.  */
  4352.       process = find_procinfo (pid, 0);
  4353.        if (process == NULL)
  4354.          {
  4355.            /* No.  So open a procinfo for it, but
  4356.               remember to close it again when finished.  */
  4357.            process = create_procinfo (pid, 0);
  4358.            make_cleanup (do_destroy_procinfo_cleanup, process);
  4359.            if (!open_procinfo_files (process, FD_CTL))
  4360.              proc_error (process, "info proc, open_procinfo_files", __LINE__);
  4361.          }
  4362.     }
  4363.   if (tid != 0)
  4364.     thread = create_procinfo (pid, tid);

  4365.   if (process)
  4366.     {
  4367.       printf_filtered (_("process %d flags:\n"), process->pid);
  4368.       proc_prettyprint_flags (proc_flags (process), 1);
  4369.       if (proc_flags (process) & (PR_STOPPED | PR_ISTOP))
  4370.         proc_prettyprint_why (proc_why (process), proc_what (process), 1);
  4371.       if (proc_get_nthreads (process) > 1)
  4372.         printf_filtered ("Process has %d threads.\n",
  4373.                          proc_get_nthreads (process));
  4374.     }
  4375.   if (thread)
  4376.     {
  4377.       printf_filtered (_("thread %d flags:\n"), thread->tid);
  4378.       proc_prettyprint_flags (proc_flags (thread), 1);
  4379.       if (proc_flags (thread) & (PR_STOPPED | PR_ISTOP))
  4380.         proc_prettyprint_why (proc_why (thread), proc_what (thread), 1);
  4381.     }

  4382.   if (mappings)
  4383.     {
  4384.       info_proc_mappings (process, 0);
  4385.     }

  4386.   do_cleanups (old_chain);
  4387. }

  4388. /* Modify the status of the system call identified by SYSCALLNUM in
  4389.    the set of syscalls that are currently traced/debugged.

  4390.    If ENTRY_OR_EXIT is set to PR_SYSENTRY, then the entry syscalls set
  4391.    will be updated.  Otherwise, the exit syscalls set will be updated.

  4392.    If MODE is FLAG_SET, then traces will be enabled.  Otherwise, they
  4393.    will be disabled.  */

  4394. static void
  4395. proc_trace_syscalls_1 (procinfo *pi, int syscallnum, int entry_or_exit,
  4396.                        int mode, int from_tty)
  4397. {
  4398.   sysset_t *sysset;

  4399.   if (entry_or_exit == PR_SYSENTRY)
  4400.     sysset = proc_get_traced_sysentry (pi, NULL);
  4401.   else
  4402.     sysset = proc_get_traced_sysexit (pi, NULL);

  4403.   if (sysset == NULL)
  4404.     proc_error (pi, "proc-trace, get_traced_sysset", __LINE__);

  4405.   if (mode == FLAG_SET)
  4406.     gdb_praddsysset (sysset, syscallnum);
  4407.   else
  4408.     gdb_prdelsysset (sysset, syscallnum);

  4409.   if (entry_or_exit == PR_SYSENTRY)
  4410.     {
  4411.       if (!proc_set_traced_sysentry (pi, sysset))
  4412.         proc_error (pi, "proc-trace, set_traced_sysentry", __LINE__);
  4413.     }
  4414.   else
  4415.     {
  4416.       if (!proc_set_traced_sysexit (pi, sysset))
  4417.         proc_error (pi, "proc-trace, set_traced_sysexit", __LINE__);
  4418.     }
  4419. }

  4420. static void
  4421. proc_trace_syscalls (char *args, int from_tty, int entry_or_exit, int mode)
  4422. {
  4423.   procinfo *pi;

  4424.   if (ptid_get_pid (inferior_ptid) <= 0)
  4425.     error (_("you must be debugging a process to use this command."));

  4426.   if (args == NULL || args[0] == 0)
  4427.     error_no_arg (_("system call to trace"));

  4428.   pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
  4429.   if (isdigit (args[0]))
  4430.     {
  4431.       const int syscallnum = atoi (args);

  4432.       proc_trace_syscalls_1 (pi, syscallnum, entry_or_exit, mode, from_tty);
  4433.     }
  4434. }

  4435. static void
  4436. proc_trace_sysentry_cmd (char *args, int from_tty)
  4437. {
  4438.   proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_SET);
  4439. }

  4440. static void
  4441. proc_trace_sysexit_cmd (char *args, int from_tty)
  4442. {
  4443.   proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_SET);
  4444. }

  4445. static void
  4446. proc_untrace_sysentry_cmd (char *args, int from_tty)
  4447. {
  4448.   proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_RESET);
  4449. }

  4450. static void
  4451. proc_untrace_sysexit_cmd (char *args, int from_tty)
  4452. {
  4453.   proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_RESET);
  4454. }


  4455. /* Provide a prototype to silence -Wmissing-prototypes.  */
  4456. extern void _initialize_procfs (void);

  4457. void
  4458. _initialize_procfs (void)
  4459. {
  4460.   observer_attach_inferior_created (procfs_inferior_created);

  4461.   add_com ("proc-trace-entry", no_class, proc_trace_sysentry_cmd,
  4462.            _("Give a trace of entries into the syscall."));
  4463.   add_com ("proc-trace-exit", no_class, proc_trace_sysexit_cmd,
  4464.            _("Give a trace of exits from the syscall."));
  4465.   add_com ("proc-untrace-entry", no_class, proc_untrace_sysentry_cmd,
  4466.            _("Cancel a trace of entries into the syscall."));
  4467.   add_com ("proc-untrace-exit", no_class, proc_untrace_sysexit_cmd,
  4468.            _("Cancel a trace of exits from the syscall."));
  4469. }

  4470. /* =================== END, GDB  "MODULE" =================== */



  4471. /* miscellaneous stubs: */

  4472. /* The following satisfy a few random symbols mostly created by the
  4473.    solaris threads implementation, which I will chase down later.  */

  4474. /* Return a pid for which we guarantee we will be able to find a
  4475.    'live' procinfo.  */

  4476. ptid_t
  4477. procfs_first_available (void)
  4478. {
  4479.   return pid_to_ptid (procinfo_list ? procinfo_list->pid : -1);
  4480. }

  4481. /* ===================  GCORE .NOTE "MODULE" =================== */
  4482. #if defined (PIOCOPENLWP) || defined (PCAGENT)
  4483. /* gcore only implemented on solaris (so far) */

  4484. static char *
  4485. procfs_do_thread_registers (bfd *obfd, ptid_t ptid,
  4486.                             char *note_data, int *note_size,
  4487.                             enum gdb_signal stop_signal)
  4488. {
  4489.   struct regcache *regcache = get_thread_regcache (ptid);
  4490.   gdb_gregset_t gregs;
  4491.   gdb_fpregset_t fpregs;
  4492.   unsigned long merged_pid;
  4493.   struct cleanup *old_chain;

  4494.   merged_pid = ptid_get_lwp (ptid) << 16 | ptid_get_pid (ptid);

  4495.   /* This part is the old method for fetching registers.
  4496.      It should be replaced by the newer one using regsets
  4497.      once it is implemented in this platform:
  4498.      gdbarch_iterate_over_regset_sections().  */

  4499.   old_chain = save_inferior_ptid ();
  4500.   inferior_ptid = ptid;
  4501.   target_fetch_registers (regcache, -1);

  4502.   fill_gregset (regcache, &gregs, -1);
  4503. #if defined (NEW_PROC_API)
  4504.   note_data = (char *) elfcore_write_lwpstatus (obfd,
  4505.                                                 note_data,
  4506.                                                 note_size,
  4507.                                                 merged_pid,
  4508.                                                 stop_signal,
  4509.                                                 &gregs);
  4510. #else
  4511.   note_data = (char *) elfcore_write_prstatus (obfd,
  4512.                                                note_data,
  4513.                                                note_size,
  4514.                                                merged_pid,
  4515.                                                stop_signal,
  4516.                                                &gregs);
  4517. #endif
  4518.   fill_fpregset (regcache, &fpregs, -1);
  4519.   note_data = (char *) elfcore_write_prfpreg (obfd,
  4520.                                               note_data,
  4521.                                               note_size,
  4522.                                               &fpregs,
  4523.                                               sizeof (fpregs));

  4524.   do_cleanups (old_chain);

  4525.   return note_data;
  4526. }

  4527. struct procfs_corefile_thread_data {
  4528.   bfd *obfd;
  4529.   char *note_data;
  4530.   int *note_size;
  4531.   enum gdb_signal stop_signal;
  4532. };

  4533. static int
  4534. procfs_corefile_thread_callback (procinfo *pi, procinfo *thread, void *data)
  4535. {
  4536.   struct procfs_corefile_thread_data *args = data;

  4537.   if (pi != NULL)
  4538.     {
  4539.       ptid_t ptid = ptid_build (pi->pid, thread->tid, 0);

  4540.       args->note_data = procfs_do_thread_registers (args->obfd, ptid,
  4541.                                                     args->note_data,
  4542.                                                     args->note_size,
  4543.                                                     args->stop_signal);
  4544.     }
  4545.   return 0;
  4546. }

  4547. static int
  4548. find_signalled_thread (struct thread_info *info, void *data)
  4549. {
  4550.   if (info->suspend.stop_signal != GDB_SIGNAL_0
  4551.       && ptid_get_pid (info->ptid) == ptid_get_pid (inferior_ptid))
  4552.     return 1;

  4553.   return 0;
  4554. }

  4555. static enum gdb_signal
  4556. find_stop_signal (void)
  4557. {
  4558.   struct thread_info *info =
  4559.     iterate_over_threads (find_signalled_thread, NULL);

  4560.   if (info)
  4561.     return info->suspend.stop_signal;
  4562.   else
  4563.     return GDB_SIGNAL_0;
  4564. }

  4565. static char *
  4566. procfs_make_note_section (struct target_ops *self, bfd *obfd, int *note_size)
  4567. {
  4568.   struct cleanup *old_chain;
  4569.   gdb_gregset_t gregs;
  4570.   gdb_fpregset_t fpregs;
  4571.   char fname[16] = {'\0'};
  4572.   char psargs[80] = {'\0'};
  4573.   procinfo *pi = find_procinfo_or_die (ptid_get_pid (inferior_ptid), 0);
  4574.   char *note_data = NULL;
  4575.   char *inf_args;
  4576.   struct procfs_corefile_thread_data thread_args;
  4577.   gdb_byte *auxv;
  4578.   int auxv_len;
  4579.   enum gdb_signal stop_signal;

  4580.   if (get_exec_file (0))
  4581.     {
  4582.       strncpy (fname, lbasename (get_exec_file (0)), sizeof (fname));
  4583.       fname[sizeof (fname) - 1] = 0;
  4584.       strncpy (psargs, get_exec_file (0), sizeof (psargs));
  4585.       psargs[sizeof (psargs) - 1] = 0;

  4586.       inf_args = get_inferior_args ();
  4587.       if (inf_args && *inf_args &&
  4588.           strlen (inf_args) < ((int) sizeof (psargs) - (int) strlen (psargs)))
  4589.         {
  4590.           strncat (psargs, " ",
  4591.                    sizeof (psargs) - strlen (psargs));
  4592.           strncat (psargs, inf_args,
  4593.                    sizeof (psargs) - strlen (psargs));
  4594.         }
  4595.     }

  4596.   note_data = (char *) elfcore_write_prpsinfo (obfd,
  4597.                                                note_data,
  4598.                                                note_size,
  4599.                                                fname,
  4600.                                                psargs);

  4601.   stop_signal = find_stop_signal ();

  4602. #ifdef NEW_PROC_API
  4603.   fill_gregset (get_current_regcache (), &gregs, -1);
  4604.   note_data = elfcore_write_pstatus (obfd, note_data, note_size,
  4605.                                      ptid_get_pid (inferior_ptid),
  4606.                                      stop_signal, &gregs);
  4607. #endif

  4608.   thread_args.obfd = obfd;
  4609.   thread_args.note_data = note_data;
  4610.   thread_args.note_size = note_size;
  4611.   thread_args.stop_signal = stop_signal;
  4612.   proc_iterate_over_threads (pi, procfs_corefile_thread_callback,
  4613.                              &thread_args);
  4614.   note_data = thread_args.note_data;

  4615.   auxv_len = target_read_alloc (&current_target, TARGET_OBJECT_AUXV,
  4616.                                 NULL, &auxv);
  4617.   if (auxv_len > 0)
  4618.     {
  4619.       note_data = elfcore_write_note (obfd, note_data, note_size,
  4620.                                       "CORE", NT_AUXV, auxv, auxv_len);
  4621.       xfree (auxv);
  4622.     }

  4623.   return note_data;
  4624. }
  4625. #else /* !Solaris */
  4626. static char *
  4627. procfs_make_note_section (struct target_ops *self, bfd *obfd, int *note_size)
  4628. {
  4629.   error (_("gcore not implemented for this host."));
  4630.   return NULL;        /* lint */
  4631. }
  4632. #endif /* Solaris */
  4633. /* ===================  END GCORE .NOTE "MODULE" =================== */