xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/procfs.c (revision 8b657b0747480f8989760d71343d6dd33f8d4cf9)
1 /* Machine independent support for Solaris /proc (process file system) for GDB.
2 
3    Copyright (C) 1999-2023 Free Software Foundation, Inc.
4 
5    Written by Michael Snyder at Cygnus Solutions.
6    Based on work by Fred Fish, Stu Grossman, Geoff Noer, and others.
7 
8    This file is part of GDB.
9 
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14 
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22 
23 #include "defs.h"
24 #include "inferior.h"
25 #include "infrun.h"
26 #include "target.h"
27 #include "gdbcore.h"
28 #include "elf-bfd.h"		/* for elfcore_write_* */
29 #include "gdbcmd.h"
30 #include "gdbthread.h"
31 #include "regcache.h"
32 #include "inf-child.h"
33 #include "nat/fork-inferior.h"
34 #include "gdbarch.h"
35 
36 #include <sys/procfs.h>
37 #include <sys/fault.h>
38 #include <sys/syscall.h>
39 #include "gdbsupport/gdb_wait.h"
40 #include <signal.h>
41 #include <ctype.h>
42 #include "gdb_bfd.h"
43 #include "auxv.h"
44 #include "procfs.h"
45 #include "observable.h"
46 #include "gdbsupport/scoped_fd.h"
47 #include "gdbsupport/pathstuff.h"
48 #include "gdbsupport/buildargv.h"
49 
50 /* This module provides the interface between GDB and the
51    /proc file system, which is used on many versions of Unix
52    as a means for debuggers to control other processes.
53 
54    /proc works by imitating a file system: you open a simulated file
55    that represents the process you wish to interact with, and perform
56    operations on that "file" in order to examine or change the state
57    of the other process.
58 
59    The most important thing to know about /proc and this module is
60    that there are two very different interfaces to /proc:
61 
62      One that uses the ioctl system call, and another that uses read
63      and write system calls.
64 
65    This module supports only the Solaris version of the read/write
66    interface.  */
67 
68 #include <sys/types.h>
69 #include <dirent.h>	/* opendir/readdir, for listing the LWP's */
70 
71 #include <fcntl.h>	/* for O_RDONLY */
72 #include <unistd.h>	/* for "X_OK" */
73 #include <sys/stat.h>	/* for struct stat */
74 
75 /* Note: procfs-utils.h must be included after the above system header
76    files, because it redefines various system calls using macros.
77    This may be incompatible with the prototype declarations.  */
78 
79 #include "proc-utils.h"
80 
81 /* Prototypes for supply_gregset etc.  */
82 #include "gregset.h"
83 
84 /* =================== TARGET_OPS "MODULE" =================== */
85 
86 /* This module defines the GDB target vector and its methods.  */
87 
88 
89 static enum target_xfer_status procfs_xfer_memory (gdb_byte *,
90 						   const gdb_byte *,
91 						   ULONGEST, ULONGEST,
92 						   ULONGEST *);
93 
94 class procfs_target final : public inf_child_target
95 {
96 public:
97   void create_inferior (const char *, const std::string &,
98 			char **, int) override;
99 
100   void kill () override;
101 
102   void mourn_inferior () override;
103 
104   void attach (const char *, int) override;
105   void detach (inferior *inf, int) override;
106 
107   void resume (ptid_t, int, enum gdb_signal) override;
108   ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
109 
110   void fetch_registers (struct regcache *, int) override;
111   void store_registers (struct regcache *, int) override;
112 
113   enum target_xfer_status xfer_partial (enum target_object object,
114 					const char *annex,
115 					gdb_byte *readbuf,
116 					const gdb_byte *writebuf,
117 					ULONGEST offset, ULONGEST len,
118 					ULONGEST *xfered_len) override;
119 
120   void pass_signals (gdb::array_view<const unsigned char>) override;
121 
122   void files_info () override;
123 
124   void update_thread_list () override;
125 
126   bool thread_alive (ptid_t ptid) override;
127 
128   std::string pid_to_str (ptid_t) override;
129 
130   const char *pid_to_exec_file (int pid) override;
131 
132   thread_control_capabilities get_thread_control_capabilities () override
133   { return tc_schedlock; }
134 
135   /* find_memory_regions support method for gcore */
136   int find_memory_regions (find_memory_region_ftype func, void *data)
137     override;
138 
139   gdb::unique_xmalloc_ptr<char> make_corefile_notes (bfd *, int *) override;
140 
141   bool info_proc (const char *, enum info_proc_what) override;
142 
143 #if PR_MODEL_NATIVE == PR_MODEL_LP64
144   int auxv_parse (const gdb_byte **readptr,
145 		  const gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
146     override;
147 #endif
148 
149   bool stopped_by_watchpoint () override;
150 
151   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
152 			 struct expression *) override;
153 
154   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
155 			 struct expression *) override;
156 
157   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
158 
159   int can_use_hw_breakpoint (enum bptype, int, int) override;
160   bool stopped_data_address (CORE_ADDR *) override;
161 
162   void procfs_init_inferior (int pid);
163 };
164 
165 static procfs_target the_procfs_target;
166 
167 #if PR_MODEL_NATIVE == PR_MODEL_LP64
168 /* When GDB is built as 64-bit application on Solaris, the auxv data
169    is presented in 64-bit format.  We need to provide a custom parser
170    to handle that.  */
171 int
172 procfs_target::auxv_parse (const gdb_byte **readptr,
173 			   const gdb_byte *endptr, CORE_ADDR *typep,
174 			   CORE_ADDR *valp)
175 {
176   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
177   const gdb_byte *ptr = *readptr;
178 
179   if (endptr == ptr)
180     return 0;
181 
182   if (endptr - ptr < 8 * 2)
183     return -1;
184 
185   *typep = extract_unsigned_integer (ptr, 4, byte_order);
186   ptr += 8;
187   /* The size of data is always 64-bit.  If the application is 32-bit,
188      it will be zero extended, as expected.  */
189   *valp = extract_unsigned_integer (ptr, 8, byte_order);
190   ptr += 8;
191 
192   *readptr = ptr;
193   return 1;
194 }
195 #endif
196 
197 /* =================== END, TARGET_OPS "MODULE" =================== */
198 
199 /* =================== STRUCT PROCINFO "MODULE" =================== */
200 
201      /* FIXME: this comment will soon be out of date W.R.T. threads.  */
202 
203 /* The procinfo struct is a wrapper to hold all the state information
204    concerning a /proc process.  There should be exactly one procinfo
205    for each process, and since GDB currently can debug only one
206    process at a time, that means there should be only one procinfo.
207    All of the LWP's of a process can be accessed indirectly thru the
208    single process procinfo.
209 
210    However, against the day when GDB may debug more than one process,
211    this data structure is kept in a list (which for now will hold no
212    more than one member), and many functions will have a pointer to a
213    procinfo as an argument.
214 
215    There will be a separate procinfo structure for use by the (not yet
216    implemented) "info proc" command, so that we can print useful
217    information about any random process without interfering with the
218    inferior's procinfo information.  */
219 
220 /* format strings for /proc paths */
221 #define CTL_PROC_NAME_FMT    "/proc/%d/ctl"
222 #define AS_PROC_NAME_FMT     "/proc/%d/as"
223 #define MAP_PROC_NAME_FMT    "/proc/%d/map"
224 #define STATUS_PROC_NAME_FMT "/proc/%d/status"
225 #define MAX_PROC_NAME_SIZE sizeof("/proc/999999/lwp/0123456789/lwpstatus")
226 
227 typedef struct procinfo {
228   struct procinfo *next;
229   int pid;			/* Process ID    */
230   int tid;			/* Thread/LWP id */
231 
232   /* process state */
233   int was_stopped;
234   int ignore_next_sigstop;
235 
236   int ctl_fd;			/* File descriptor for /proc control file */
237   int status_fd;		/* File descriptor for /proc status file */
238   int as_fd;			/* File descriptor for /proc as file */
239 
240   char pathname[MAX_PROC_NAME_SIZE];	/* Pathname to /proc entry */
241 
242   fltset_t saved_fltset;	/* Saved traced hardware fault set */
243   sigset_t saved_sigset;	/* Saved traced signal set */
244   sigset_t saved_sighold;	/* Saved held signal set */
245   sysset_t *saved_exitset;	/* Saved traced system call exit set */
246   sysset_t *saved_entryset;	/* Saved traced system call entry set */
247 
248   pstatus_t prstatus;		/* Current process status info */
249 
250   struct procinfo *thread_list;
251 
252   int status_valid : 1;
253   int gregs_valid  : 1;
254   int fpregs_valid : 1;
255   int threads_valid: 1;
256 } procinfo;
257 
258 static char errmsg[128];	/* shared error msg buffer */
259 
260 /* Function prototypes for procinfo module: */
261 
262 static procinfo *find_procinfo_or_die (int pid, int tid);
263 static procinfo *find_procinfo (int pid, int tid);
264 static procinfo *create_procinfo (int pid, int tid);
265 static void destroy_procinfo (procinfo *p);
266 static void dead_procinfo (procinfo *p, const char *msg, int killp);
267 static int open_procinfo_files (procinfo *p, int which);
268 static void close_procinfo_files (procinfo *p);
269 
270 static int iterate_over_mappings
271   (procinfo *pi, find_memory_region_ftype child_func, void *data,
272    int (*func) (struct prmap *map, find_memory_region_ftype child_func,
273 		void *data));
274 
275 /* The head of the procinfo list: */
276 static procinfo *procinfo_list;
277 
278 /* Search the procinfo list.  Return a pointer to procinfo, or NULL if
279    not found.  */
280 
281 static procinfo *
282 find_procinfo (int pid, int tid)
283 {
284   procinfo *pi;
285 
286   for (pi = procinfo_list; pi; pi = pi->next)
287     if (pi->pid == pid)
288       break;
289 
290   if (pi)
291     if (tid)
292       {
293 	/* Don't check threads_valid.  If we're updating the
294 	   thread_list, we want to find whatever threads are already
295 	   here.  This means that in general it is the caller's
296 	   responsibility to check threads_valid and update before
297 	   calling find_procinfo, if the caller wants to find a new
298 	   thread.  */
299 
300 	for (pi = pi->thread_list; pi; pi = pi->next)
301 	  if (pi->tid == tid)
302 	    break;
303       }
304 
305   return pi;
306 }
307 
308 /* Calls find_procinfo, but errors on failure.  */
309 
310 static procinfo *
311 find_procinfo_or_die (int pid, int tid)
312 {
313   procinfo *pi = find_procinfo (pid, tid);
314 
315   if (pi == NULL)
316     {
317       if (tid)
318 	error (_("procfs: couldn't find pid %d "
319 		 "(kernel thread %d) in procinfo list."),
320 	       pid, tid);
321       else
322 	error (_("procfs: couldn't find pid %d in procinfo list."), pid);
323     }
324   return pi;
325 }
326 
327 /* Wrapper for `open'.  The appropriate open call is attempted; if
328    unsuccessful, it will be retried as many times as needed for the
329    EAGAIN and EINTR conditions.
330 
331    For other conditions, retry the open a limited number of times.  In
332    addition, a short sleep is imposed prior to retrying the open.  The
333    reason for this sleep is to give the kernel a chance to catch up
334    and create the file in question in the event that GDB "wins" the
335    race to open a file before the kernel has created it.  */
336 
337 static int
338 open_with_retry (const char *pathname, int flags)
339 {
340   int retries_remaining, status;
341 
342   retries_remaining = 2;
343 
344   while (1)
345     {
346       status = open (pathname, flags);
347 
348       if (status >= 0 || retries_remaining == 0)
349 	break;
350       else if (errno != EINTR && errno != EAGAIN)
351 	{
352 	  retries_remaining--;
353 	  sleep (1);
354 	}
355     }
356 
357   return status;
358 }
359 
360 /* Open the file descriptor for the process or LWP.  We only open the
361    control file descriptor; the others are opened lazily as needed.
362    Returns the file descriptor, or zero for failure.  */
363 
364 enum { FD_CTL, FD_STATUS, FD_AS };
365 
366 static int
367 open_procinfo_files (procinfo *pi, int which)
368 {
369   char tmp[MAX_PROC_NAME_SIZE];
370   int  fd;
371 
372   /* This function is getting ALMOST long enough to break up into
373      several.  Here is some rationale:
374 
375      There are several file descriptors that may need to be open
376      for any given process or LWP.  The ones we're interested in are:
377 	 - control	 (ctl)	  write-only	change the state
378 	 - status	 (status) read-only	query the state
379 	 - address space (as)	  read/write	access memory
380 	 - map		 (map)	  read-only	virtual addr map
381      Most of these are opened lazily as they are needed.
382      The pathnames for the 'files' for an LWP look slightly
383      different from those of a first-class process:
384 	 Pathnames for a process (<proc-id>):
385 	   /proc/<proc-id>/ctl
386 	   /proc/<proc-id>/status
387 	   /proc/<proc-id>/as
388 	   /proc/<proc-id>/map
389 	 Pathnames for an LWP (lwp-id):
390 	   /proc/<proc-id>/lwp/<lwp-id>/lwpctl
391 	   /proc/<proc-id>/lwp/<lwp-id>/lwpstatus
392      An LWP has no map or address space file descriptor, since
393      the memory map and address space are shared by all LWPs.  */
394 
395   /* In this case, there are several different file descriptors that
396      we might be asked to open.  The control file descriptor will be
397      opened early, but the others will be opened lazily as they are
398      needed.  */
399 
400   strcpy (tmp, pi->pathname);
401   switch (which) {	/* Which file descriptor to open?  */
402   case FD_CTL:
403     if (pi->tid)
404       strcat (tmp, "/lwpctl");
405     else
406       strcat (tmp, "/ctl");
407     fd = open_with_retry (tmp, O_WRONLY);
408     if (fd < 0)
409       return 0;		/* fail */
410     pi->ctl_fd = fd;
411     break;
412   case FD_AS:
413     if (pi->tid)
414       return 0;		/* There is no 'as' file descriptor for an lwp.  */
415     strcat (tmp, "/as");
416     fd = open_with_retry (tmp, O_RDWR);
417     if (fd < 0)
418       return 0;		/* fail */
419     pi->as_fd = fd;
420     break;
421   case FD_STATUS:
422     if (pi->tid)
423       strcat (tmp, "/lwpstatus");
424     else
425       strcat (tmp, "/status");
426     fd = open_with_retry (tmp, O_RDONLY);
427     if (fd < 0)
428       return 0;		/* fail */
429     pi->status_fd = fd;
430     break;
431   default:
432     return 0;		/* unknown file descriptor */
433   }
434 
435   return 1;		/* success */
436 }
437 
438 /* Allocate a data structure and link it into the procinfo list.
439    First tries to find a pre-existing one (FIXME: why?).  Returns the
440    pointer to new procinfo struct.  */
441 
442 static procinfo *
443 create_procinfo (int pid, int tid)
444 {
445   procinfo *pi, *parent = NULL;
446 
447   pi = find_procinfo (pid, tid);
448   if (pi != NULL)
449     return pi;			/* Already exists, nothing to do.  */
450 
451   /* Find parent before doing malloc, to save having to cleanup.  */
452   if (tid != 0)
453     parent = find_procinfo_or_die (pid, 0);	/* FIXME: should I
454 						   create it if it
455 						   doesn't exist yet?  */
456 
457   pi = XNEW (procinfo);
458   memset (pi, 0, sizeof (procinfo));
459   pi->pid = pid;
460   pi->tid = tid;
461 
462   pi->saved_entryset = XNEW (sysset_t);
463   pi->saved_exitset = XNEW (sysset_t);
464 
465   /* Chain into list.  */
466   if (tid == 0)
467     {
468       xsnprintf (pi->pathname, sizeof (pi->pathname), "/proc/%d", pid);
469       pi->next = procinfo_list;
470       procinfo_list = pi;
471     }
472   else
473     {
474       xsnprintf (pi->pathname, sizeof (pi->pathname), "/proc/%d/lwp/%d",
475 		 pid, tid);
476       pi->next = parent->thread_list;
477       parent->thread_list = pi;
478     }
479   return pi;
480 }
481 
482 /* Close all file descriptors associated with the procinfo.  */
483 
484 static void
485 close_procinfo_files (procinfo *pi)
486 {
487   if (pi->ctl_fd > 0)
488     close (pi->ctl_fd);
489   if (pi->as_fd > 0)
490     close (pi->as_fd);
491   if (pi->status_fd > 0)
492     close (pi->status_fd);
493   pi->ctl_fd = pi->as_fd = pi->status_fd = 0;
494 }
495 
496 /* Destructor function.  Close, unlink and deallocate the object.  */
497 
498 static void
499 destroy_one_procinfo (procinfo **list, procinfo *pi)
500 {
501   procinfo *ptr;
502 
503   /* Step one: unlink the procinfo from its list.  */
504   if (pi == *list)
505     *list = pi->next;
506   else
507     for (ptr = *list; ptr; ptr = ptr->next)
508       if (ptr->next == pi)
509 	{
510 	  ptr->next =  pi->next;
511 	  break;
512 	}
513 
514   /* Step two: close any open file descriptors.  */
515   close_procinfo_files (pi);
516 
517   /* Step three: free the memory.  */
518   xfree (pi->saved_entryset);
519   xfree (pi->saved_exitset);
520   xfree (pi);
521 }
522 
523 static void
524 destroy_procinfo (procinfo *pi)
525 {
526   procinfo *tmp;
527 
528   if (pi->tid != 0)	/* Destroy a thread procinfo.  */
529     {
530       tmp = find_procinfo (pi->pid, 0);	/* Find the parent process.  */
531       destroy_one_procinfo (&tmp->thread_list, pi);
532     }
533   else			/* Destroy a process procinfo and all its threads.  */
534     {
535       /* First destroy the children, if any; */
536       while (pi->thread_list != NULL)
537 	destroy_one_procinfo (&pi->thread_list, pi->thread_list);
538       /* Then destroy the parent.  Genocide!!!  */
539       destroy_one_procinfo (&procinfo_list, pi);
540     }
541 }
542 
543 /* A deleter that calls destroy_procinfo.  */
544 struct procinfo_deleter
545 {
546   void operator() (procinfo *pi) const
547   {
548     destroy_procinfo (pi);
549   }
550 };
551 
552 typedef std::unique_ptr<procinfo, procinfo_deleter> procinfo_up;
553 
554 enum { NOKILL, KILL };
555 
556 /* To be called on a non_recoverable error for a procinfo.  Prints
557    error messages, optionally sends a SIGKILL to the process, then
558    destroys the data structure.  */
559 
560 static void
561 dead_procinfo (procinfo *pi, const char *msg, int kill_p)
562 {
563   print_sys_errmsg (pi->pathname, errno);
564   if (kill_p == KILL)
565     kill (pi->pid, SIGKILL);
566 
567   destroy_procinfo (pi);
568   error ("%s", msg);
569 }
570 
571 /* =================== END, STRUCT PROCINFO "MODULE" =================== */
572 
573 /* ===================  /proc "MODULE" =================== */
574 
575 /* This "module" is the interface layer between the /proc system API
576    and the gdb target vector functions.  This layer consists of access
577    functions that encapsulate each of the basic operations that we
578    need to use from the /proc API.
579 
580    The main motivation for this layer is to hide the fact that there
581    were two very different implementations of the /proc API.  */
582 
583 static long proc_flags (procinfo *pi);
584 static int proc_why (procinfo *pi);
585 static int proc_what (procinfo *pi);
586 static int proc_set_current_signal (procinfo *pi, int signo);
587 static int proc_get_current_thread (procinfo *pi);
588 static int proc_iterate_over_threads
589   (procinfo *pi,
590    int (*func) (procinfo *, procinfo *, void *),
591    void *ptr);
592 
593 static void
594 proc_warn (procinfo *pi, const char *func, int line)
595 {
596   xsnprintf (errmsg, sizeof (errmsg), "procfs: %s line %d, %s",
597 	     func, line, pi->pathname);
598   print_sys_errmsg (errmsg, errno);
599 }
600 
601 static void
602 proc_error (procinfo *pi, const char *func, int line)
603 {
604   xsnprintf (errmsg, sizeof (errmsg), "procfs: %s line %d, %s",
605 	     func, line, pi->pathname);
606   perror_with_name (errmsg);
607 }
608 
609 /* Updates the status struct in the procinfo.  There is a 'valid'
610    flag, to let other functions know when this function needs to be
611    called (so the status is only read when it is needed).  The status
612    file descriptor is also only opened when it is needed.  Returns
613    non-zero for success, zero for failure.  */
614 
615 static int
616 proc_get_status (procinfo *pi)
617 {
618   /* Status file descriptor is opened "lazily".  */
619   if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
620     {
621       pi->status_valid = 0;
622       return 0;
623     }
624 
625   if (lseek (pi->status_fd, 0, SEEK_SET) < 0)
626     pi->status_valid = 0;			/* fail */
627   else
628     {
629       /* Sigh... I have to read a different data structure,
630 	 depending on whether this is a main process or an LWP.  */
631       if (pi->tid)
632 	pi->status_valid = (read (pi->status_fd,
633 				  (char *) &pi->prstatus.pr_lwp,
634 				  sizeof (lwpstatus_t))
635 			    == sizeof (lwpstatus_t));
636       else
637 	{
638 	  pi->status_valid = (read (pi->status_fd,
639 				    (char *) &pi->prstatus,
640 				    sizeof (pstatus_t))
641 			      == sizeof (pstatus_t));
642 	}
643     }
644 
645   if (pi->status_valid)
646     {
647       PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
648 				proc_why (pi),
649 				proc_what (pi),
650 				proc_get_current_thread (pi));
651     }
652 
653   /* The status struct includes general regs, so mark them valid too.  */
654   pi->gregs_valid  = pi->status_valid;
655   /* In the read/write multiple-fd model, the status struct includes
656      the fp regs too, so mark them valid too.  */
657   pi->fpregs_valid = pi->status_valid;
658   return pi->status_valid;	/* True if success, false if failure.  */
659 }
660 
661 /* Returns the process flags (pr_flags field).  */
662 
663 static long
664 proc_flags (procinfo *pi)
665 {
666   if (!pi->status_valid)
667     if (!proc_get_status (pi))
668       return 0;	/* FIXME: not a good failure value (but what is?)  */
669 
670   return pi->prstatus.pr_lwp.pr_flags;
671 }
672 
673 /* Returns the pr_why field (why the process stopped).  */
674 
675 static int
676 proc_why (procinfo *pi)
677 {
678   if (!pi->status_valid)
679     if (!proc_get_status (pi))
680       return 0;	/* FIXME: not a good failure value (but what is?)  */
681 
682   return pi->prstatus.pr_lwp.pr_why;
683 }
684 
685 /* Returns the pr_what field (details of why the process stopped).  */
686 
687 static int
688 proc_what (procinfo *pi)
689 {
690   if (!pi->status_valid)
691     if (!proc_get_status (pi))
692       return 0;	/* FIXME: not a good failure value (but what is?)  */
693 
694   return pi->prstatus.pr_lwp.pr_what;
695 }
696 
697 /* This function is only called when PI is stopped by a watchpoint.
698    Assuming the OS supports it, write to *ADDR the data address which
699    triggered it and return 1.  Return 0 if it is not possible to know
700    the address.  */
701 
702 static int
703 proc_watchpoint_address (procinfo *pi, CORE_ADDR *addr)
704 {
705   if (!pi->status_valid)
706     if (!proc_get_status (pi))
707       return 0;
708 
709   *addr = (CORE_ADDR) gdbarch_pointer_to_address (target_gdbarch (),
710 	    builtin_type (target_gdbarch ())->builtin_data_ptr,
711 	    (gdb_byte *) &pi->prstatus.pr_lwp.pr_info.si_addr);
712   return 1;
713 }
714 
715 /* Returns the pr_nsysarg field (number of args to the current
716    syscall).  */
717 
718 static int
719 proc_nsysarg (procinfo *pi)
720 {
721   if (!pi->status_valid)
722     if (!proc_get_status (pi))
723       return 0;
724 
725   return pi->prstatus.pr_lwp.pr_nsysarg;
726 }
727 
728 /* Returns the pr_sysarg field (pointer to the arguments of current
729    syscall).  */
730 
731 static long *
732 proc_sysargs (procinfo *pi)
733 {
734   if (!pi->status_valid)
735     if (!proc_get_status (pi))
736       return NULL;
737 
738   return (long *) &pi->prstatus.pr_lwp.pr_sysarg;
739 }
740 
741 /* Set or reset any of the following process flags:
742       PR_FORK	-- forked child will inherit trace flags
743       PR_RLC	-- traced process runs when last /proc file closed.
744       PR_KLC    -- traced process is killed when last /proc file closed.
745       PR_ASYNC	-- LWP's get to run/stop independently.
746 
747    This function is done using read/write [PCSET/PCRESET/PCUNSET].
748 
749    Arguments:
750       pi   -- the procinfo
751       flag -- one of PR_FORK, PR_RLC, or PR_ASYNC
752       mode -- 1 for set, 0 for reset.
753 
754    Returns non-zero for success, zero for failure.  */
755 
756 enum { FLAG_RESET, FLAG_SET };
757 
758 static int
759 proc_modify_flag (procinfo *pi, long flag, long mode)
760 {
761   long win = 0;		/* default to fail */
762 
763   /* These operations affect the process as a whole, and applying them
764      to an individual LWP has the same meaning as applying them to the
765      main process.  Therefore, if we're ever called with a pointer to
766      an LWP's procinfo, let's substitute the process's procinfo and
767      avoid opening the LWP's file descriptor unnecessarily.  */
768 
769   if (pi->pid != 0)
770     pi = find_procinfo_or_die (pi->pid, 0);
771 
772   procfs_ctl_t arg[2];
773 
774   if (mode == FLAG_SET)	/* Set the flag (RLC, FORK, or ASYNC).  */
775     arg[0] = PCSET;
776   else			/* Reset the flag.  */
777     arg[0] = PCUNSET;
778 
779   arg[1] = flag;
780   win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
781 
782   /* The above operation renders the procinfo's cached pstatus
783      obsolete.  */
784   pi->status_valid = 0;
785 
786   if (!win)
787     warning (_("procfs: modify_flag failed to turn %s %s"),
788 	     flag == PR_FORK  ? "PR_FORK"  :
789 	     flag == PR_RLC   ? "PR_RLC"   :
790 	     flag == PR_ASYNC ? "PR_ASYNC" :
791 	     flag == PR_KLC   ? "PR_KLC"   :
792 	     "<unknown flag>",
793 	     mode == FLAG_RESET ? "off" : "on");
794 
795   return win;
796 }
797 
798 /* Set the run_on_last_close flag.  Process with all threads will
799    become runnable when debugger closes all /proc fds.  Returns
800    non-zero for success, zero for failure.  */
801 
802 static int
803 proc_set_run_on_last_close (procinfo *pi)
804 {
805   return proc_modify_flag (pi, PR_RLC, FLAG_SET);
806 }
807 
808 /* Reset the run_on_last_close flag.  The process will NOT become
809    runnable when debugger closes its file handles.  Returns non-zero
810    for success, zero for failure.  */
811 
812 static int
813 proc_unset_run_on_last_close (procinfo *pi)
814 {
815   return proc_modify_flag (pi, PR_RLC, FLAG_RESET);
816 }
817 
818 /* Reset inherit_on_fork flag.  If the process forks a child while we
819    are registered for events in the parent, then we will NOT receive
820    events from the child.  Returns non-zero for success, zero for
821    failure.  */
822 
823 static int
824 proc_unset_inherit_on_fork (procinfo *pi)
825 {
826   return proc_modify_flag (pi, PR_FORK, FLAG_RESET);
827 }
828 
829 /* Set PR_ASYNC flag.  If one LWP stops because of a debug event
830    (signal etc.), the remaining LWPs will continue to run.  Returns
831    non-zero for success, zero for failure.  */
832 
833 static int
834 proc_set_async (procinfo *pi)
835 {
836   return proc_modify_flag (pi, PR_ASYNC, FLAG_SET);
837 }
838 
839 /* Reset PR_ASYNC flag.  If one LWP stops because of a debug event
840    (signal etc.), then all other LWPs will stop as well.  Returns
841    non-zero for success, zero for failure.  */
842 
843 static int
844 proc_unset_async (procinfo *pi)
845 {
846   return proc_modify_flag (pi, PR_ASYNC, FLAG_RESET);
847 }
848 
849 /* Request the process/LWP to stop.  Does not wait.  Returns non-zero
850    for success, zero for failure.  */
851 
852 static int
853 proc_stop_process (procinfo *pi)
854 {
855   int win;
856 
857   /* We might conceivably apply this operation to an LWP, and the
858      LWP's ctl file descriptor might not be open.  */
859 
860   if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
861     return 0;
862   else
863     {
864       procfs_ctl_t cmd = PCSTOP;
865 
866       win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
867     }
868 
869   return win;
870 }
871 
872 /* Wait for the process or LWP to stop (block until it does).  Returns
873    non-zero for success, zero for failure.  */
874 
875 static int
876 proc_wait_for_stop (procinfo *pi)
877 {
878   int win;
879 
880   /* We should never have to apply this operation to any procinfo
881      except the one for the main process.  If that ever changes for
882      any reason, then take out the following clause and replace it
883      with one that makes sure the ctl_fd is open.  */
884 
885   if (pi->tid != 0)
886     pi = find_procinfo_or_die (pi->pid, 0);
887 
888   procfs_ctl_t cmd = PCWSTOP;
889 
890   set_sigint_trap ();
891 
892   win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
893 
894   clear_sigint_trap ();
895 
896   /* We been runnin' and we stopped -- need to update status.  */
897   pi->status_valid = 0;
898 
899   return win;
900 }
901 
902 /* Make the process or LWP runnable.
903 
904    Options (not all are implemented):
905      - single-step
906      - clear current fault
907      - clear current signal
908      - abort the current system call
909      - stop as soon as finished with system call
910 
911    Always clears the current fault.  PI is the process or LWP to
912    operate on.  If STEP is true, set the process or LWP to trap after
913    one instruction.  If SIGNO is zero, clear the current signal if
914    any; if non-zero, set the current signal to this one.  Returns
915    non-zero for success, zero for failure.  */
916 
917 static int
918 proc_run_process (procinfo *pi, int step, int signo)
919 {
920   int win;
921   int runflags;
922 
923   /* We will probably have to apply this operation to individual
924      threads, so make sure the control file descriptor is open.  */
925 
926   if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
927     return 0;
928 
929   runflags    = PRCFAULT;	/* Always clear current fault.  */
930   if (step)
931     runflags |= PRSTEP;
932   if (signo == 0)
933     runflags |= PRCSIG;
934   else if (signo != -1)		/* -1 means do nothing W.R.T. signals.  */
935     proc_set_current_signal (pi, signo);
936 
937   procfs_ctl_t cmd[2];
938 
939   cmd[0]  = PCRUN;
940   cmd[1]  = runflags;
941   win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
942 
943   return win;
944 }
945 
946 /* Register to trace signals in the process or LWP.  Returns non-zero
947    for success, zero for failure.  */
948 
949 static int
950 proc_set_traced_signals (procinfo *pi, sigset_t *sigset)
951 {
952   int win;
953 
954   /* We should never have to apply this operation to any procinfo
955      except the one for the main process.  If that ever changes for
956      any reason, then take out the following clause and replace it
957      with one that makes sure the ctl_fd is open.  */
958 
959   if (pi->tid != 0)
960     pi = find_procinfo_or_die (pi->pid, 0);
961 
962   struct {
963     procfs_ctl_t cmd;
964     /* Use char array to avoid alignment issues.  */
965     char sigset[sizeof (sigset_t)];
966   } arg;
967 
968   arg.cmd = PCSTRACE;
969   memcpy (&arg.sigset, sigset, sizeof (sigset_t));
970 
971   win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
972 
973   /* The above operation renders the procinfo's cached pstatus obsolete.  */
974   pi->status_valid = 0;
975 
976   if (!win)
977     warning (_("procfs: set_traced_signals failed"));
978   return win;
979 }
980 
981 /* Register to trace hardware faults in the process or LWP.  Returns
982    non-zero for success, zero for failure.  */
983 
984 static int
985 proc_set_traced_faults (procinfo *pi, fltset_t *fltset)
986 {
987   int win;
988 
989   /* We should never have to apply this operation to any procinfo
990      except the one for the main process.  If that ever changes for
991      any reason, then take out the following clause and replace it
992      with one that makes sure the ctl_fd is open.  */
993 
994   if (pi->tid != 0)
995     pi = find_procinfo_or_die (pi->pid, 0);
996 
997   struct {
998     procfs_ctl_t cmd;
999     /* Use char array to avoid alignment issues.  */
1000     char fltset[sizeof (fltset_t)];
1001   } arg;
1002 
1003   arg.cmd = PCSFAULT;
1004   memcpy (&arg.fltset, fltset, sizeof (fltset_t));
1005 
1006   win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1007 
1008   /* The above operation renders the procinfo's cached pstatus obsolete.  */
1009   pi->status_valid = 0;
1010 
1011   return win;
1012 }
1013 
1014 /* Register to trace entry to system calls in the process or LWP.
1015    Returns non-zero for success, zero for failure.  */
1016 
1017 static int
1018 proc_set_traced_sysentry (procinfo *pi, sysset_t *sysset)
1019 {
1020   int win;
1021 
1022   /* We should never have to apply this operation to any procinfo
1023      except the one for the main process.  If that ever changes for
1024      any reason, then take out the following clause and replace it
1025      with one that makes sure the ctl_fd is open.  */
1026 
1027   if (pi->tid != 0)
1028     pi = find_procinfo_or_die (pi->pid, 0);
1029 
1030   struct {
1031     procfs_ctl_t cmd;
1032     /* Use char array to avoid alignment issues.  */
1033     char sysset[sizeof (sysset_t)];
1034   } arg;
1035 
1036   arg.cmd = PCSENTRY;
1037   memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1038 
1039   win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1040 
1041   /* The above operation renders the procinfo's cached pstatus
1042      obsolete.  */
1043   pi->status_valid = 0;
1044 
1045   return win;
1046 }
1047 
1048 /* Register to trace exit from system calls in the process or LWP.
1049    Returns non-zero for success, zero for failure.  */
1050 
1051 static int
1052 proc_set_traced_sysexit (procinfo *pi, sysset_t *sysset)
1053 {
1054   int win;
1055 
1056   /* We should never have to apply this operation to any procinfo
1057      except the one for the main process.  If that ever changes for
1058      any reason, then take out the following clause and replace it
1059      with one that makes sure the ctl_fd is open.  */
1060 
1061   if (pi->tid != 0)
1062     pi = find_procinfo_or_die (pi->pid, 0);
1063 
1064   struct gdb_proc_ctl_pcsexit {
1065     procfs_ctl_t cmd;
1066     /* Use char array to avoid alignment issues.  */
1067     char sysset[sizeof (sysset_t)];
1068   } arg;
1069 
1070   arg.cmd = PCSEXIT;
1071   memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1072 
1073   win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1074 
1075   /* The above operation renders the procinfo's cached pstatus
1076      obsolete.  */
1077   pi->status_valid = 0;
1078 
1079   return win;
1080 }
1081 
1082 /* Specify the set of blocked / held signals in the process or LWP.
1083    Returns non-zero for success, zero for failure.  */
1084 
1085 static int
1086 proc_set_held_signals (procinfo *pi, sigset_t *sighold)
1087 {
1088   int win;
1089 
1090   /* We should never have to apply this operation to any procinfo
1091      except the one for the main process.  If that ever changes for
1092      any reason, then take out the following clause and replace it
1093      with one that makes sure the ctl_fd is open.  */
1094 
1095   if (pi->tid != 0)
1096     pi = find_procinfo_or_die (pi->pid, 0);
1097 
1098   struct {
1099     procfs_ctl_t cmd;
1100     /* Use char array to avoid alignment issues.  */
1101     char hold[sizeof (sigset_t)];
1102   } arg;
1103 
1104   arg.cmd  = PCSHOLD;
1105   memcpy (&arg.hold, sighold, sizeof (sigset_t));
1106   win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1107 
1108   /* The above operation renders the procinfo's cached pstatus
1109      obsolete.  */
1110   pi->status_valid = 0;
1111 
1112   return win;
1113 }
1114 
1115 /* Returns the set of signals that are held / blocked.  Will also copy
1116    the sigset if SAVE is non-zero.  */
1117 
1118 static sigset_t *
1119 proc_get_held_signals (procinfo *pi, sigset_t *save)
1120 {
1121   sigset_t *ret = NULL;
1122 
1123   /* We should never have to apply this operation to any procinfo
1124      except the one for the main process.  If that ever changes for
1125      any reason, then take out the following clause and replace it
1126      with one that makes sure the ctl_fd is open.  */
1127 
1128   if (pi->tid != 0)
1129     pi = find_procinfo_or_die (pi->pid, 0);
1130 
1131   if (!pi->status_valid)
1132     if (!proc_get_status (pi))
1133       return NULL;
1134 
1135   ret = &pi->prstatus.pr_lwp.pr_lwphold;
1136   if (save && ret)
1137     memcpy (save, ret, sizeof (sigset_t));
1138 
1139   return ret;
1140 }
1141 
1142 /* Returns the set of signals that are traced / debugged.  Will also
1143    copy the sigset if SAVE is non-zero.  */
1144 
1145 static sigset_t *
1146 proc_get_traced_signals (procinfo *pi, sigset_t *save)
1147 {
1148   sigset_t *ret = NULL;
1149 
1150   /* We should never have to apply this operation to any procinfo
1151      except the one for the main process.  If that ever changes for
1152      any reason, then take out the following clause and replace it
1153      with one that makes sure the ctl_fd is open.  */
1154 
1155   if (pi->tid != 0)
1156     pi = find_procinfo_or_die (pi->pid, 0);
1157 
1158   if (!pi->status_valid)
1159     if (!proc_get_status (pi))
1160       return NULL;
1161 
1162   ret = &pi->prstatus.pr_sigtrace;
1163   if (save && ret)
1164     memcpy (save, ret, sizeof (sigset_t));
1165 
1166   return ret;
1167 }
1168 
1169 /* Returns the set of hardware faults that are traced /debugged.  Will
1170    also copy the faultset if SAVE is non-zero.  */
1171 
1172 static fltset_t *
1173 proc_get_traced_faults (procinfo *pi, fltset_t *save)
1174 {
1175   fltset_t *ret = NULL;
1176 
1177   /* We should never have to apply this operation to any procinfo
1178      except the one for the main process.  If that ever changes for
1179      any reason, then take out the following clause and replace it
1180      with one that makes sure the ctl_fd is open.  */
1181 
1182   if (pi->tid != 0)
1183     pi = find_procinfo_or_die (pi->pid, 0);
1184 
1185   if (!pi->status_valid)
1186     if (!proc_get_status (pi))
1187       return NULL;
1188 
1189   ret = &pi->prstatus.pr_flttrace;
1190   if (save && ret)
1191     memcpy (save, ret, sizeof (fltset_t));
1192 
1193   return ret;
1194 }
1195 
1196 /* Returns the set of syscalls that are traced /debugged on entry.
1197    Will also copy the syscall set if SAVE is non-zero.  */
1198 
1199 static sysset_t *
1200 proc_get_traced_sysentry (procinfo *pi, sysset_t *save)
1201 {
1202   sysset_t *ret = NULL;
1203 
1204   /* We should never have to apply this operation to any procinfo
1205      except the one for the main process.  If that ever changes for
1206      any reason, then take out the following clause and replace it
1207      with one that makes sure the ctl_fd is open.  */
1208 
1209   if (pi->tid != 0)
1210     pi = find_procinfo_or_die (pi->pid, 0);
1211 
1212   if (!pi->status_valid)
1213     if (!proc_get_status (pi))
1214       return NULL;
1215 
1216   ret = &pi->prstatus.pr_sysentry;
1217   if (save && ret)
1218     memcpy (save, ret, sizeof (sysset_t));
1219 
1220   return ret;
1221 }
1222 
1223 /* Returns the set of syscalls that are traced /debugged on exit.
1224    Will also copy the syscall set if SAVE is non-zero.  */
1225 
1226 static sysset_t *
1227 proc_get_traced_sysexit (procinfo *pi, sysset_t *save)
1228 {
1229   sysset_t *ret = NULL;
1230 
1231   /* We should never have to apply this operation to any procinfo
1232      except the one for the main process.  If that ever changes for
1233      any reason, then take out the following clause and replace it
1234      with one that makes sure the ctl_fd is open.  */
1235 
1236   if (pi->tid != 0)
1237     pi = find_procinfo_or_die (pi->pid, 0);
1238 
1239   if (!pi->status_valid)
1240     if (!proc_get_status (pi))
1241       return NULL;
1242 
1243   ret = &pi->prstatus.pr_sysexit;
1244   if (save && ret)
1245     memcpy (save, ret, sizeof (sysset_t));
1246 
1247   return ret;
1248 }
1249 
1250 /* The current fault (if any) is cleared; the associated signal will
1251    not be sent to the process or LWP when it resumes.  Returns
1252    non-zero for success, zero for failure.  */
1253 
1254 static int
1255 proc_clear_current_fault (procinfo *pi)
1256 {
1257   int win;
1258 
1259   /* We should never have to apply this operation to any procinfo
1260      except the one for the main process.  If that ever changes for
1261      any reason, then take out the following clause and replace it
1262      with one that makes sure the ctl_fd is open.  */
1263 
1264   if (pi->tid != 0)
1265     pi = find_procinfo_or_die (pi->pid, 0);
1266 
1267   procfs_ctl_t cmd = PCCFAULT;
1268 
1269   win = (write (pi->ctl_fd, (void *) &cmd, sizeof (cmd)) == sizeof (cmd));
1270 
1271   return win;
1272 }
1273 
1274 /* Set the "current signal" that will be delivered next to the
1275    process.  NOTE: semantics are different from those of KILL.  This
1276    signal will be delivered to the process or LWP immediately when it
1277    is resumed (even if the signal is held/blocked); it will NOT
1278    immediately cause another event of interest, and will NOT first
1279    trap back to the debugger.  Returns non-zero for success, zero for
1280    failure.  */
1281 
1282 static int
1283 proc_set_current_signal (procinfo *pi, int signo)
1284 {
1285   int win;
1286   struct {
1287     procfs_ctl_t cmd;
1288     /* Use char array to avoid alignment issues.  */
1289     char sinfo[sizeof (siginfo_t)];
1290   } arg;
1291   siginfo_t mysinfo;
1292   process_stratum_target *wait_target;
1293   ptid_t wait_ptid;
1294   struct target_waitstatus wait_status;
1295 
1296   /* We should never have to apply this operation to any procinfo
1297      except the one for the main process.  If that ever changes for
1298      any reason, then take out the following clause and replace it
1299      with one that makes sure the ctl_fd is open.  */
1300 
1301   if (pi->tid != 0)
1302     pi = find_procinfo_or_die (pi->pid, 0);
1303 
1304   /* The pointer is just a type alias.  */
1305   get_last_target_status (&wait_target, &wait_ptid, &wait_status);
1306   if (wait_target == &the_procfs_target
1307       && wait_ptid == inferior_ptid
1308       && wait_status.kind () == TARGET_WAITKIND_STOPPED
1309       && wait_status.sig () == gdb_signal_from_host (signo)
1310       && proc_get_status (pi)
1311       && pi->prstatus.pr_lwp.pr_info.si_signo == signo
1312       )
1313     /* Use the siginfo associated with the signal being
1314        redelivered.  */
1315     memcpy (arg.sinfo, &pi->prstatus.pr_lwp.pr_info, sizeof (siginfo_t));
1316   else
1317     {
1318       mysinfo.si_signo = signo;
1319       mysinfo.si_code  = 0;
1320       mysinfo.si_pid   = getpid ();       /* ?why? */
1321       mysinfo.si_uid   = getuid ();       /* ?why? */
1322       memcpy (arg.sinfo, &mysinfo, sizeof (siginfo_t));
1323     }
1324 
1325   arg.cmd = PCSSIG;
1326   win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg))  == sizeof (arg));
1327 
1328   return win;
1329 }
1330 
1331 /* The current signal (if any) is cleared, and is not sent to the
1332    process or LWP when it resumes.  Returns non-zero for success, zero
1333    for failure.  */
1334 
1335 static int
1336 proc_clear_current_signal (procinfo *pi)
1337 {
1338   int win;
1339 
1340   /* We should never have to apply this operation to any procinfo
1341      except the one for the main process.  If that ever changes for
1342      any reason, then take out the following clause and replace it
1343      with one that makes sure the ctl_fd is open.  */
1344 
1345   if (pi->tid != 0)
1346     pi = find_procinfo_or_die (pi->pid, 0);
1347 
1348   struct {
1349     procfs_ctl_t cmd;
1350     /* Use char array to avoid alignment issues.  */
1351     char sinfo[sizeof (siginfo_t)];
1352   } arg;
1353   siginfo_t mysinfo;
1354 
1355   arg.cmd = PCSSIG;
1356   /* The pointer is just a type alias.  */
1357   mysinfo.si_signo = 0;
1358   mysinfo.si_code  = 0;
1359   mysinfo.si_errno = 0;
1360   mysinfo.si_pid   = getpid ();       /* ?why? */
1361   mysinfo.si_uid   = getuid ();       /* ?why? */
1362   memcpy (arg.sinfo, &mysinfo, sizeof (siginfo_t));
1363 
1364   win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1365 
1366   return win;
1367 }
1368 
1369 /* Return the general-purpose registers for the process or LWP
1370    corresponding to PI.  Upon failure, return NULL.  */
1371 
1372 static gdb_gregset_t *
1373 proc_get_gregs (procinfo *pi)
1374 {
1375   if (!pi->status_valid || !pi->gregs_valid)
1376     if (!proc_get_status (pi))
1377       return NULL;
1378 
1379   return &pi->prstatus.pr_lwp.pr_reg;
1380 }
1381 
1382 /* Return the general-purpose registers for the process or LWP
1383    corresponding to PI.  Upon failure, return NULL.  */
1384 
1385 static gdb_fpregset_t *
1386 proc_get_fpregs (procinfo *pi)
1387 {
1388   if (!pi->status_valid || !pi->fpregs_valid)
1389     if (!proc_get_status (pi))
1390       return NULL;
1391 
1392   return &pi->prstatus.pr_lwp.pr_fpreg;
1393 }
1394 
1395 /* Write the general-purpose registers back to the process or LWP
1396    corresponding to PI.  Return non-zero for success, zero for
1397    failure.  */
1398 
1399 static int
1400 proc_set_gregs (procinfo *pi)
1401 {
1402   gdb_gregset_t *gregs;
1403   int win;
1404 
1405   gregs = proc_get_gregs (pi);
1406   if (gregs == NULL)
1407     return 0;			/* proc_get_regs has already warned.  */
1408 
1409   if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1410     return 0;
1411   else
1412     {
1413       struct {
1414 	procfs_ctl_t cmd;
1415 	/* Use char array to avoid alignment issues.  */
1416 	char gregs[sizeof (gdb_gregset_t)];
1417       } arg;
1418 
1419       arg.cmd = PCSREG;
1420       memcpy (&arg.gregs, gregs, sizeof (arg.gregs));
1421       win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1422     }
1423 
1424   /* Policy: writing the registers invalidates our cache.  */
1425   pi->gregs_valid = 0;
1426   return win;
1427 }
1428 
1429 /* Write the floating-pointer registers back to the process or LWP
1430    corresponding to PI.  Return non-zero for success, zero for
1431    failure.  */
1432 
1433 static int
1434 proc_set_fpregs (procinfo *pi)
1435 {
1436   gdb_fpregset_t *fpregs;
1437   int win;
1438 
1439   fpregs = proc_get_fpregs (pi);
1440   if (fpregs == NULL)
1441     return 0;			/* proc_get_fpregs has already warned.  */
1442 
1443   if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1444     return 0;
1445   else
1446     {
1447       struct {
1448 	procfs_ctl_t cmd;
1449 	/* Use char array to avoid alignment issues.  */
1450 	char fpregs[sizeof (gdb_fpregset_t)];
1451       } arg;
1452 
1453       arg.cmd = PCSFPREG;
1454       memcpy (&arg.fpregs, fpregs, sizeof (arg.fpregs));
1455       win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1456     }
1457 
1458   /* Policy: writing the registers invalidates our cache.  */
1459   pi->fpregs_valid = 0;
1460   return win;
1461 }
1462 
1463 /* Send a signal to the proc or lwp with the semantics of "kill()".
1464    Returns non-zero for success, zero for failure.  */
1465 
1466 static int
1467 proc_kill (procinfo *pi, int signo)
1468 {
1469   int win;
1470 
1471   /* We might conceivably apply this operation to an LWP, and the
1472      LWP's ctl file descriptor might not be open.  */
1473 
1474   if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1475     return 0;
1476   else
1477     {
1478       procfs_ctl_t cmd[2];
1479 
1480       cmd[0] = PCKILL;
1481       cmd[1] = signo;
1482       win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
1483   }
1484 
1485   return win;
1486 }
1487 
1488 /* Find the pid of the process that started this one.  Returns the
1489    parent process pid, or zero.  */
1490 
1491 static int
1492 proc_parent_pid (procinfo *pi)
1493 {
1494   /* We should never have to apply this operation to any procinfo
1495      except the one for the main process.  If that ever changes for
1496      any reason, then take out the following clause and replace it
1497      with one that makes sure the ctl_fd is open.  */
1498 
1499   if (pi->tid != 0)
1500     pi = find_procinfo_or_die (pi->pid, 0);
1501 
1502   if (!pi->status_valid)
1503     if (!proc_get_status (pi))
1504       return 0;
1505 
1506   return pi->prstatus.pr_ppid;
1507 }
1508 
1509 /* Convert a target address (a.k.a. CORE_ADDR) into a host address
1510    (a.k.a void pointer)!  */
1511 
1512 static void *
1513 procfs_address_to_host_pointer (CORE_ADDR addr)
1514 {
1515   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
1516   void *ptr;
1517 
1518   gdb_assert (sizeof (ptr) == ptr_type->length ());
1519   gdbarch_address_to_pointer (target_gdbarch (), ptr_type,
1520 			      (gdb_byte *) &ptr, addr);
1521   return ptr;
1522 }
1523 
1524 static int
1525 proc_set_watchpoint (procinfo *pi, CORE_ADDR addr, int len, int wflags)
1526 {
1527   struct {
1528     procfs_ctl_t cmd;
1529     char watch[sizeof (prwatch_t)];
1530   } arg;
1531   prwatch_t pwatch;
1532 
1533   /* NOTE: cagney/2003-02-01: Even more horrible hack.  Need to
1534      convert a target address into something that can be stored in a
1535      native data structure.  */
1536   pwatch.pr_vaddr  = (uintptr_t) procfs_address_to_host_pointer (addr);
1537   pwatch.pr_size   = len;
1538   pwatch.pr_wflags = wflags;
1539   arg.cmd = PCWATCH;
1540   memcpy (arg.watch, &pwatch, sizeof (prwatch_t));
1541   return (write (pi->ctl_fd, &arg, sizeof (arg)) == sizeof (arg));
1542 }
1543 
1544 /* =============== END, non-thread part of /proc  "MODULE" =============== */
1545 
1546 /* =================== Thread "MODULE" =================== */
1547 
1548 /* Returns the number of threads for the process.  */
1549 
1550 static int
1551 proc_get_nthreads (procinfo *pi)
1552 {
1553   if (!pi->status_valid)
1554     if (!proc_get_status (pi))
1555       return 0;
1556 
1557   /* Only works for the process procinfo, because the LWP procinfos do not
1558      get prstatus filled in.  */
1559   if (pi->tid != 0)	/* Find the parent process procinfo.  */
1560     pi = find_procinfo_or_die (pi->pid, 0);
1561   return pi->prstatus.pr_nlwp;
1562 }
1563 
1564 /* Return the ID of the thread that had an event of interest.
1565    (ie. the one that hit a breakpoint or other traced event).  All
1566    other things being equal, this should be the ID of a thread that is
1567    currently executing.  */
1568 
1569 static int
1570 proc_get_current_thread (procinfo *pi)
1571 {
1572   /* Note: this should be applied to the root procinfo for the
1573      process, not to the procinfo for an LWP.  If applied to the
1574      procinfo for an LWP, it will simply return that LWP's ID.  In
1575      that case, find the parent process procinfo.  */
1576 
1577   if (pi->tid != 0)
1578     pi = find_procinfo_or_die (pi->pid, 0);
1579 
1580   if (!pi->status_valid)
1581     if (!proc_get_status (pi))
1582       return 0;
1583 
1584   return pi->prstatus.pr_lwp.pr_lwpid;
1585 }
1586 
1587 /* Discover the IDs of all the threads within the process, and create
1588    a procinfo for each of them (chained to the parent).  Returns
1589    non-zero for success, zero for failure.  */
1590 
1591 static int
1592 proc_delete_dead_threads (procinfo *parent, procinfo *thread, void *ignore)
1593 {
1594   if (thread && parent)	/* sanity */
1595     {
1596       thread->status_valid = 0;
1597       if (!proc_get_status (thread))
1598 	destroy_one_procinfo (&parent->thread_list, thread);
1599     }
1600   return 0;	/* keep iterating */
1601 }
1602 
1603 static int
1604 proc_update_threads (procinfo *pi)
1605 {
1606   char pathname[MAX_PROC_NAME_SIZE + 16];
1607   struct dirent *direntry;
1608   procinfo *thread;
1609   gdb_dir_up dirp;
1610   int lwpid;
1611 
1612   /* We should never have to apply this operation to any procinfo
1613      except the one for the main process.  If that ever changes for
1614      any reason, then take out the following clause and replace it
1615      with one that makes sure the ctl_fd is open.  */
1616 
1617   if (pi->tid != 0)
1618     pi = find_procinfo_or_die (pi->pid, 0);
1619 
1620   proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
1621 
1622   /* Note: this brute-force method was originally devised for Unixware
1623      (support removed since), and will also work on Solaris 2.6 and
1624      2.7.  The original comment mentioned the existence of a much
1625      simpler and more elegant way to do this on Solaris, but didn't
1626      point out what that was.  */
1627 
1628   strcpy (pathname, pi->pathname);
1629   strcat (pathname, "/lwp");
1630   dirp.reset (opendir (pathname));
1631   if (dirp == NULL)
1632     proc_error (pi, "update_threads, opendir", __LINE__);
1633 
1634   while ((direntry = readdir (dirp.get ())) != NULL)
1635     if (direntry->d_name[0] != '.')		/* skip '.' and '..' */
1636       {
1637 	lwpid = atoi (&direntry->d_name[0]);
1638 	thread = create_procinfo (pi->pid, lwpid);
1639 	if (thread == NULL)
1640 	  proc_error (pi, "update_threads, create_procinfo", __LINE__);
1641       }
1642   pi->threads_valid = 1;
1643   return 1;
1644 }
1645 
1646 /* Given a pointer to a function, call that function once for each lwp
1647    in the procinfo list, until the function returns non-zero, in which
1648    event return the value returned by the function.
1649 
1650    Note: this function does NOT call update_threads.  If you want to
1651    discover new threads first, you must call that function explicitly.
1652    This function just makes a quick pass over the currently-known
1653    procinfos.
1654 
1655    PI is the parent process procinfo.  FUNC is the per-thread
1656    function.  PTR is an opaque parameter for function.  Returns the
1657    first non-zero return value from the callee, or zero.  */
1658 
1659 static int
1660 proc_iterate_over_threads (procinfo *pi,
1661 			   int (*func) (procinfo *, procinfo *, void *),
1662 			   void *ptr)
1663 {
1664   procinfo *thread, *next;
1665   int retval = 0;
1666 
1667   /* We should never have to apply this operation to any procinfo
1668      except the one for the main process.  If that ever changes for
1669      any reason, then take out the following clause and replace it
1670      with one that makes sure the ctl_fd is open.  */
1671 
1672   if (pi->tid != 0)
1673     pi = find_procinfo_or_die (pi->pid, 0);
1674 
1675   for (thread = pi->thread_list; thread != NULL; thread = next)
1676     {
1677       next = thread->next;	/* In case thread is destroyed.  */
1678       retval = (*func) (pi, thread, ptr);
1679       if (retval != 0)
1680 	break;
1681     }
1682 
1683   return retval;
1684 }
1685 
1686 /* =================== END, Thread "MODULE" =================== */
1687 
1688 /* =================== END, /proc  "MODULE" =================== */
1689 
1690 /* ===================  GDB  "MODULE" =================== */
1691 
1692 /* Here are all of the gdb target vector functions and their
1693    friends.  */
1694 
1695 static void do_attach (ptid_t ptid);
1696 static void do_detach ();
1697 static void proc_trace_syscalls_1 (procinfo *pi, int syscallnum,
1698 				   int entry_or_exit, int mode, int from_tty);
1699 
1700 /* Sets up the inferior to be debugged.  Registers to trace signals,
1701    hardware faults, and syscalls.  Note: does not set RLC flag: caller
1702    may want to customize that.  Returns zero for success (note!
1703    unlike most functions in this module); on failure, returns the LINE
1704    NUMBER where it failed!  */
1705 
1706 static int
1707 procfs_debug_inferior (procinfo *pi)
1708 {
1709   fltset_t traced_faults;
1710   sigset_t traced_signals;
1711   sysset_t *traced_syscall_entries;
1712   sysset_t *traced_syscall_exits;
1713   int status;
1714 
1715   /* Register to trace hardware faults in the child.  */
1716   prfillset (&traced_faults);		/* trace all faults...  */
1717   prdelset  (&traced_faults, FLTPAGE);	/* except page fault.  */
1718   if (!proc_set_traced_faults  (pi, &traced_faults))
1719     return __LINE__;
1720 
1721   /* Initially, register to trace all signals in the child.  */
1722   prfillset (&traced_signals);
1723   if (!proc_set_traced_signals (pi, &traced_signals))
1724     return __LINE__;
1725 
1726 
1727   /* Register to trace the 'exit' system call (on entry).  */
1728   traced_syscall_entries = XNEW (sysset_t);
1729   premptyset (traced_syscall_entries);
1730   praddset (traced_syscall_entries, SYS_exit);
1731   praddset (traced_syscall_entries, SYS_lwp_exit);
1732 
1733   status = proc_set_traced_sysentry (pi, traced_syscall_entries);
1734   xfree (traced_syscall_entries);
1735   if (!status)
1736     return __LINE__;
1737 
1738   /* Method for tracing exec syscalls.  */
1739   traced_syscall_exits = XNEW (sysset_t);
1740   premptyset (traced_syscall_exits);
1741   praddset (traced_syscall_exits, SYS_execve);
1742   praddset (traced_syscall_exits, SYS_lwp_create);
1743   praddset (traced_syscall_exits, SYS_lwp_exit);
1744 
1745   status = proc_set_traced_sysexit (pi, traced_syscall_exits);
1746   xfree (traced_syscall_exits);
1747   if (!status)
1748     return __LINE__;
1749 
1750   return 0;
1751 }
1752 
1753 void
1754 procfs_target::attach (const char *args, int from_tty)
1755 {
1756   int   pid;
1757 
1758   pid = parse_pid_to_attach (args);
1759 
1760   if (pid == getpid ())
1761     error (_("Attaching GDB to itself is not a good idea..."));
1762 
1763   /* Push the target if needed, ensure it gets un-pushed it if attach fails.  */
1764   inferior *inf = current_inferior ();
1765   target_unpush_up unpusher;
1766   if (!inf->target_is_pushed (this))
1767     {
1768       inf->push_target (this);
1769       unpusher.reset (this);
1770     }
1771 
1772   target_announce_attach (from_tty, pid);
1773 
1774   do_attach (ptid_t (pid));
1775 
1776   /* Everything went fine, keep the target pushed.  */
1777   unpusher.release ();
1778 }
1779 
1780 void
1781 procfs_target::detach (inferior *inf, int from_tty)
1782 {
1783   target_announce_detach (from_tty);
1784 
1785   do_detach ();
1786 
1787   switch_to_no_thread ();
1788   detach_inferior (inf);
1789   maybe_unpush_target ();
1790 }
1791 
1792 static void
1793 do_attach (ptid_t ptid)
1794 {
1795   procinfo *pi;
1796   struct inferior *inf;
1797   int fail;
1798   int lwpid;
1799 
1800   pi = create_procinfo (ptid.pid (), 0);
1801   if (pi == NULL)
1802     perror (_("procfs: out of memory in 'attach'"));
1803 
1804   if (!open_procinfo_files (pi, FD_CTL))
1805     {
1806       gdb_printf (gdb_stderr, "procfs:%d -- ", __LINE__);
1807       xsnprintf (errmsg, sizeof (errmsg),
1808 		 "do_attach: couldn't open /proc file for process %d",
1809 		 ptid.pid ());
1810       dead_procinfo (pi, errmsg, NOKILL);
1811     }
1812 
1813   /* Stop the process (if it isn't already stopped).  */
1814   if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1815     {
1816       pi->was_stopped = 1;
1817       proc_prettyprint_why (proc_why (pi), proc_what (pi), 1);
1818     }
1819   else
1820     {
1821       pi->was_stopped = 0;
1822       /* Set the process to run again when we close it.  */
1823       if (!proc_set_run_on_last_close (pi))
1824 	dead_procinfo (pi, "do_attach: couldn't set RLC.", NOKILL);
1825 
1826       /* Now stop the process.  */
1827       if (!proc_stop_process (pi))
1828 	dead_procinfo (pi, "do_attach: couldn't stop the process.", NOKILL);
1829       pi->ignore_next_sigstop = 1;
1830     }
1831   /* Save some of the /proc state to be restored if we detach.  */
1832   if (!proc_get_traced_faults   (pi, &pi->saved_fltset))
1833     dead_procinfo (pi, "do_attach: couldn't save traced faults.", NOKILL);
1834   if (!proc_get_traced_signals  (pi, &pi->saved_sigset))
1835     dead_procinfo (pi, "do_attach: couldn't save traced signals.", NOKILL);
1836   if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
1837     dead_procinfo (pi, "do_attach: couldn't save traced syscall entries.",
1838 		   NOKILL);
1839   if (!proc_get_traced_sysexit  (pi, pi->saved_exitset))
1840     dead_procinfo (pi, "do_attach: couldn't save traced syscall exits.",
1841 		   NOKILL);
1842   if (!proc_get_held_signals    (pi, &pi->saved_sighold))
1843     dead_procinfo (pi, "do_attach: couldn't save held signals.", NOKILL);
1844 
1845   fail = procfs_debug_inferior (pi);
1846   if (fail != 0)
1847     dead_procinfo (pi, "do_attach: failed in procfs_debug_inferior", NOKILL);
1848 
1849   inf = current_inferior ();
1850   inferior_appeared (inf, pi->pid);
1851   /* Let GDB know that the inferior was attached.  */
1852   inf->attach_flag = true;
1853 
1854   /* Create a procinfo for the current lwp.  */
1855   lwpid = proc_get_current_thread (pi);
1856   create_procinfo (pi->pid, lwpid);
1857 
1858   /* Add it to gdb's thread list.  */
1859   ptid = ptid_t (pi->pid, lwpid, 0);
1860   thread_info *thr = add_thread (&the_procfs_target, ptid);
1861   switch_to_thread (thr);
1862 }
1863 
1864 static void
1865 do_detach ()
1866 {
1867   procinfo *pi;
1868 
1869   /* Find procinfo for the main process.  */
1870   pi = find_procinfo_or_die (inferior_ptid.pid (),
1871 			     0); /* FIXME: threads */
1872 
1873   if (!proc_set_traced_signals (pi, &pi->saved_sigset))
1874     proc_warn (pi, "do_detach, set_traced_signal", __LINE__);
1875 
1876   if (!proc_set_traced_faults (pi, &pi->saved_fltset))
1877     proc_warn (pi, "do_detach, set_traced_faults", __LINE__);
1878 
1879   if (!proc_set_traced_sysentry (pi, pi->saved_entryset))
1880     proc_warn (pi, "do_detach, set_traced_sysentry", __LINE__);
1881 
1882   if (!proc_set_traced_sysexit (pi, pi->saved_exitset))
1883     proc_warn (pi, "do_detach, set_traced_sysexit", __LINE__);
1884 
1885   if (!proc_set_held_signals (pi, &pi->saved_sighold))
1886     proc_warn (pi, "do_detach, set_held_signals", __LINE__);
1887 
1888   if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1889     if (!(pi->was_stopped)
1890 	|| query (_("Was stopped when attached, make it runnable again? ")))
1891       {
1892 	/* Clear any pending signal.  */
1893 	if (!proc_clear_current_fault (pi))
1894 	  proc_warn (pi, "do_detach, clear_current_fault", __LINE__);
1895 
1896 	if (!proc_clear_current_signal (pi))
1897 	  proc_warn (pi, "do_detach, clear_current_signal", __LINE__);
1898 
1899 	if (!proc_set_run_on_last_close (pi))
1900 	  proc_warn (pi, "do_detach, set_rlc", __LINE__);
1901       }
1902 
1903   destroy_procinfo (pi);
1904 }
1905 
1906 /* Fetch register REGNUM from the inferior.  If REGNUM is -1, do this
1907    for all registers.
1908 
1909    NOTE: Since the /proc interface cannot give us individual
1910    registers, we pay no attention to REGNUM, and just fetch them all.
1911    This results in the possibility that we will do unnecessarily many
1912    fetches, since we may be called repeatedly for individual
1913    registers.  So we cache the results, and mark the cache invalid
1914    when the process is resumed.  */
1915 
1916 void
1917 procfs_target::fetch_registers (struct regcache *regcache, int regnum)
1918 {
1919   gdb_gregset_t *gregs;
1920   procinfo *pi;
1921   ptid_t ptid = regcache->ptid ();
1922   int pid = ptid.pid ();
1923   int tid = ptid.lwp ();
1924   struct gdbarch *gdbarch = regcache->arch ();
1925 
1926   pi = find_procinfo_or_die (pid, tid);
1927 
1928   if (pi == NULL)
1929     error (_("procfs: fetch_registers failed to find procinfo for %s"),
1930 	   target_pid_to_str (ptid).c_str ());
1931 
1932   gregs = proc_get_gregs (pi);
1933   if (gregs == NULL)
1934     proc_error (pi, "fetch_registers, get_gregs", __LINE__);
1935 
1936   supply_gregset (regcache, (const gdb_gregset_t *) gregs);
1937 
1938   if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU?  */
1939     {
1940       gdb_fpregset_t *fpregs;
1941 
1942       if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
1943 	  || regnum == gdbarch_pc_regnum (gdbarch)
1944 	  || regnum == gdbarch_sp_regnum (gdbarch))
1945 	return;			/* Not a floating point register.  */
1946 
1947       fpregs = proc_get_fpregs (pi);
1948       if (fpregs == NULL)
1949 	proc_error (pi, "fetch_registers, get_fpregs", __LINE__);
1950 
1951       supply_fpregset (regcache, (const gdb_fpregset_t *) fpregs);
1952     }
1953 }
1954 
1955 /* Store register REGNUM back into the inferior.  If REGNUM is -1, do
1956    this for all registers.
1957 
1958    NOTE: Since the /proc interface will not read individual registers,
1959    we will cache these requests until the process is resumed, and only
1960    then write them back to the inferior process.
1961 
1962    FIXME: is that a really bad idea?  Have to think about cases where
1963    writing one register might affect the value of others, etc.  */
1964 
1965 void
1966 procfs_target::store_registers (struct regcache *regcache, int regnum)
1967 {
1968   gdb_gregset_t *gregs;
1969   procinfo *pi;
1970   ptid_t ptid = regcache->ptid ();
1971   int pid = ptid.pid ();
1972   int tid = ptid.lwp ();
1973   struct gdbarch *gdbarch = regcache->arch ();
1974 
1975   pi = find_procinfo_or_die (pid, tid);
1976 
1977   if (pi == NULL)
1978     error (_("procfs: store_registers: failed to find procinfo for %s"),
1979 	   target_pid_to_str (ptid).c_str ());
1980 
1981   gregs = proc_get_gregs (pi);
1982   if (gregs == NULL)
1983     proc_error (pi, "store_registers, get_gregs", __LINE__);
1984 
1985   fill_gregset (regcache, gregs, regnum);
1986   if (!proc_set_gregs (pi))
1987     proc_error (pi, "store_registers, set_gregs", __LINE__);
1988 
1989   if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU?  */
1990     {
1991       gdb_fpregset_t *fpregs;
1992 
1993       if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
1994 	  || regnum == gdbarch_pc_regnum (gdbarch)
1995 	  || regnum == gdbarch_sp_regnum (gdbarch))
1996 	return;			/* Not a floating point register.  */
1997 
1998       fpregs = proc_get_fpregs (pi);
1999       if (fpregs == NULL)
2000 	proc_error (pi, "store_registers, get_fpregs", __LINE__);
2001 
2002       fill_fpregset (regcache, fpregs, regnum);
2003       if (!proc_set_fpregs (pi))
2004 	proc_error (pi, "store_registers, set_fpregs", __LINE__);
2005     }
2006 }
2007 
2008 /* Retrieve the next stop event from the child process.  If child has
2009    not stopped yet, wait for it to stop.  Translate /proc eventcodes
2010    (or possibly wait eventcodes) into gdb internal event codes.
2011    Returns the id of process (and possibly thread) that incurred the
2012    event.  Event codes are returned through a pointer parameter.  */
2013 
2014 ptid_t
2015 procfs_target::wait (ptid_t ptid, struct target_waitstatus *status,
2016 		     target_wait_flags options)
2017 {
2018   /* First cut: loosely based on original version 2.1.  */
2019   procinfo *pi;
2020   int       wstat;
2021   int       temp_tid;
2022   ptid_t    retval, temp_ptid;
2023   int       why, what, flags;
2024   int       retry = 0;
2025 
2026 wait_again:
2027 
2028   retry++;
2029   wstat    = 0;
2030   retval   = ptid_t (-1);
2031 
2032   /* Find procinfo for main process.  */
2033 
2034   /* procfs_target currently only supports one inferior.  */
2035   inferior *inf = current_inferior ();
2036 
2037   pi = find_procinfo_or_die (inf->pid, 0);
2038   if (pi)
2039     {
2040       /* We must assume that the status is stale now...  */
2041       pi->status_valid = 0;
2042       pi->gregs_valid  = 0;
2043       pi->fpregs_valid = 0;
2044 
2045 #if 0	/* just try this out...  */
2046       flags = proc_flags (pi);
2047       why   = proc_why (pi);
2048       if ((flags & PR_STOPPED) && (why == PR_REQUESTED))
2049 	pi->status_valid = 0;	/* re-read again, IMMEDIATELY...  */
2050 #endif
2051       /* If child is not stopped, wait for it to stop.  */
2052       if (!(proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
2053 	  && !proc_wait_for_stop (pi))
2054 	{
2055 	  /* wait_for_stop failed: has the child terminated?  */
2056 	  if (errno == ENOENT)
2057 	    {
2058 	      int wait_retval;
2059 
2060 	      /* /proc file not found; presumably child has terminated.  */
2061 	      wait_retval = ::wait (&wstat); /* "wait" for the child's exit.  */
2062 
2063 	      /* Wrong child?  */
2064 	      if (wait_retval != inf->pid)
2065 		error (_("procfs: couldn't stop "
2066 			 "process %d: wait returned %d."),
2067 		       inf->pid, wait_retval);
2068 	      /* FIXME: might I not just use waitpid?
2069 		 Or try find_procinfo to see if I know about this child?  */
2070 	      retval = ptid_t (wait_retval);
2071 	    }
2072 	  else if (errno == EINTR)
2073 	    goto wait_again;
2074 	  else
2075 	    {
2076 	      /* Unknown error from wait_for_stop.  */
2077 	      proc_error (pi, "target_wait (wait_for_stop)", __LINE__);
2078 	    }
2079 	}
2080       else
2081 	{
2082 	  /* This long block is reached if either:
2083 	     a) the child was already stopped, or
2084 	     b) we successfully waited for the child with wait_for_stop.
2085 	     This block will analyze the /proc status, and translate it
2086 	     into a waitstatus for GDB.
2087 
2088 	     If we actually had to call wait because the /proc file
2089 	     is gone (child terminated), then we skip this block,
2090 	     because we already have a waitstatus.  */
2091 
2092 	  flags = proc_flags (pi);
2093 	  why   = proc_why (pi);
2094 	  what  = proc_what (pi);
2095 
2096 	  if (flags & (PR_STOPPED | PR_ISTOP))
2097 	    {
2098 	      /* If it's running async (for single_thread control),
2099 		 set it back to normal again.  */
2100 	      if (flags & PR_ASYNC)
2101 		if (!proc_unset_async (pi))
2102 		  proc_error (pi, "target_wait, unset_async", __LINE__);
2103 
2104 	      if (info_verbose)
2105 		proc_prettyprint_why (why, what, 1);
2106 
2107 	      /* The 'pid' we will return to GDB is composed of
2108 		 the process ID plus the lwp ID.  */
2109 	      retval = ptid_t (pi->pid, proc_get_current_thread (pi), 0);
2110 
2111 	      switch (why) {
2112 	      case PR_SIGNALLED:
2113 		wstat = (what << 8) | 0177;
2114 		break;
2115 	      case PR_SYSENTRY:
2116 		if (what == SYS_lwp_exit)
2117 		  {
2118 		    if (print_thread_events)
2119 		      gdb_printf (_("[%s exited]\n"),
2120 				  target_pid_to_str (retval).c_str ());
2121 		    delete_thread (find_thread_ptid (this, retval));
2122 		    target_continue_no_signal (ptid);
2123 		    goto wait_again;
2124 		  }
2125 		else if (what == SYS_exit)
2126 		  {
2127 		    /* Handle SYS_exit call only.  */
2128 		    /* Stopped at entry to SYS_exit.
2129 		       Make it runnable, resume it, then use
2130 		       the wait system call to get its exit code.
2131 		       Proc_run_process always clears the current
2132 		       fault and signal.
2133 		       Then return its exit status.  */
2134 		    pi->status_valid = 0;
2135 		    wstat = 0;
2136 		    /* FIXME: what we should do is return
2137 		       TARGET_WAITKIND_SPURIOUS.  */
2138 		    if (!proc_run_process (pi, 0, 0))
2139 		      proc_error (pi, "target_wait, run_process", __LINE__);
2140 
2141 		    if (inf->attach_flag)
2142 		      {
2143 			/* Don't call wait: simulate waiting for exit,
2144 			   return a "success" exit code.  Bogus: what if
2145 			   it returns something else?  */
2146 			wstat = 0;
2147 			retval = ptid_t (inf->pid);  /* ? ? ? */
2148 		      }
2149 		    else
2150 		      {
2151 			int temp = ::wait (&wstat);
2152 
2153 			/* FIXME: shouldn't I make sure I get the right
2154 			   event from the right process?  If (for
2155 			   instance) I have killed an earlier inferior
2156 			   process but failed to clean up after it
2157 			   somehow, I could get its termination event
2158 			   here.  */
2159 
2160 			/* If wait returns -1, that's what we return
2161 			   to GDB.  */
2162 			if (temp < 0)
2163 			  retval = ptid_t (temp);
2164 		      }
2165 		  }
2166 		else
2167 		  {
2168 		    gdb_printf (_("procfs: trapped on entry to "));
2169 		    proc_prettyprint_syscall (proc_what (pi), 0);
2170 		    gdb_printf ("\n");
2171 
2172 		    long i, nsysargs, *sysargs;
2173 
2174 		    nsysargs = proc_nsysarg (pi);
2175 		    sysargs  = proc_sysargs (pi);
2176 
2177 		    if (nsysargs > 0 && sysargs != NULL)
2178 		      {
2179 			gdb_printf (_("%ld syscall arguments:\n"),
2180 				    nsysargs);
2181 			for (i = 0; i < nsysargs; i++)
2182 			  gdb_printf ("#%ld: 0x%08lx\n",
2183 				      i, sysargs[i]);
2184 		      }
2185 
2186 		    /* How to keep going without returning to wfi: */
2187 		    target_continue_no_signal (ptid);
2188 		    goto wait_again;
2189 		  }
2190 		break;
2191 	      case PR_SYSEXIT:
2192 		if (what == SYS_execve)
2193 		  {
2194 		    /* Hopefully this is our own "fork-child" execing
2195 		       the real child.  Hoax this event into a trap, and
2196 		       GDB will see the child about to execute its start
2197 		       address.  */
2198 		    wstat = (SIGTRAP << 8) | 0177;
2199 		  }
2200 		else if (what == SYS_lwp_create)
2201 		  {
2202 		    /* This syscall is somewhat like fork/exec.  We
2203 		       will get the event twice: once for the parent
2204 		       LWP, and once for the child.  We should already
2205 		       know about the parent LWP, but the child will
2206 		       be new to us.  So, whenever we get this event,
2207 		       if it represents a new thread, simply add the
2208 		       thread to the list.  */
2209 
2210 		    /* If not in procinfo list, add it.  */
2211 		    temp_tid = proc_get_current_thread (pi);
2212 		    if (!find_procinfo (pi->pid, temp_tid))
2213 		      create_procinfo  (pi->pid, temp_tid);
2214 
2215 		    temp_ptid = ptid_t (pi->pid, temp_tid, 0);
2216 		    /* If not in GDB's thread list, add it.  */
2217 		    if (!in_thread_list (this, temp_ptid))
2218 		      add_thread (this, temp_ptid);
2219 
2220 		    target_continue_no_signal (ptid);
2221 		    goto wait_again;
2222 		  }
2223 		else if (what == SYS_lwp_exit)
2224 		  {
2225 		    if (print_thread_events)
2226 		      gdb_printf (_("[%s exited]\n"),
2227 				  target_pid_to_str (retval).c_str ());
2228 		    delete_thread (find_thread_ptid (this, retval));
2229 		    status->set_spurious ();
2230 		    return retval;
2231 		  }
2232 		else
2233 		  {
2234 		    gdb_printf (_("procfs: trapped on exit from "));
2235 		    proc_prettyprint_syscall (proc_what (pi), 0);
2236 		    gdb_printf ("\n");
2237 
2238 		    long i, nsysargs, *sysargs;
2239 
2240 		    nsysargs = proc_nsysarg (pi);
2241 		    sysargs = proc_sysargs (pi);
2242 
2243 		    if (nsysargs > 0 && sysargs != NULL)
2244 		      {
2245 			gdb_printf (_("%ld syscall arguments:\n"),
2246 				    nsysargs);
2247 			for (i = 0; i < nsysargs; i++)
2248 			  gdb_printf ("#%ld: 0x%08lx\n",
2249 				      i, sysargs[i]);
2250 		      }
2251 
2252 		    target_continue_no_signal (ptid);
2253 		    goto wait_again;
2254 		  }
2255 		break;
2256 	      case PR_REQUESTED:
2257 #if 0	/* FIXME */
2258 		wstat = (SIGSTOP << 8) | 0177;
2259 		break;
2260 #else
2261 		if (retry < 5)
2262 		  {
2263 		    gdb_printf (_("Retry #%d:\n"), retry);
2264 		    pi->status_valid = 0;
2265 		    goto wait_again;
2266 		  }
2267 		else
2268 		  {
2269 		    /* If not in procinfo list, add it.  */
2270 		    temp_tid = proc_get_current_thread (pi);
2271 		    if (!find_procinfo (pi->pid, temp_tid))
2272 		      create_procinfo  (pi->pid, temp_tid);
2273 
2274 		    /* If not in GDB's thread list, add it.  */
2275 		    temp_ptid = ptid_t (pi->pid, temp_tid, 0);
2276 		    if (!in_thread_list (this, temp_ptid))
2277 		      add_thread (this, temp_ptid);
2278 
2279 		    status->set_stopped (GDB_SIGNAL_0);
2280 		    return retval;
2281 		  }
2282 #endif
2283 	      case PR_JOBCONTROL:
2284 		wstat = (what << 8) | 0177;
2285 		break;
2286 	      case PR_FAULTED:
2287 		{
2288 		  int signo = pi->prstatus.pr_lwp.pr_info.si_signo;
2289 		  if (signo != 0)
2290 		    wstat = (signo << 8) | 0177;
2291 		}
2292 		break;
2293 	      default:	/* switch (why) unmatched */
2294 		gdb_printf ("procfs:%d -- ", __LINE__);
2295 		gdb_printf (_("child stopped for unknown reason:\n"));
2296 		proc_prettyprint_why (why, what, 1);
2297 		error (_("... giving up..."));
2298 		break;
2299 	      }
2300 	      /* Got this far without error: If retval isn't in the
2301 		 threads database, add it.  */
2302 	      if (retval.pid () > 0
2303 		  && !in_thread_list (this, retval))
2304 		{
2305 		  /* We have a new thread.  We need to add it both to
2306 		     GDB's list and to our own.  If we don't create a
2307 		     procinfo, resume may be unhappy later.  */
2308 		  add_thread (this, retval);
2309 		  if (find_procinfo (retval.pid (),
2310 				     retval.lwp ()) == NULL)
2311 		    create_procinfo (retval.pid (),
2312 				     retval.lwp ());
2313 		}
2314 	    }
2315 	  else	/* Flags do not indicate STOPPED.  */
2316 	    {
2317 	      /* surely this can't happen...  */
2318 	      gdb_printf ("procfs:%d -- process not stopped.\n",
2319 			  __LINE__);
2320 	      proc_prettyprint_flags (flags, 1);
2321 	      error (_("procfs: ...giving up..."));
2322 	    }
2323 	}
2324 
2325       if (status)
2326 	*status = host_status_to_waitstatus (wstat);
2327     }
2328 
2329   return retval;
2330 }
2331 
2332 /* Perform a partial transfer to/from the specified object.  For
2333    memory transfers, fall back to the old memory xfer functions.  */
2334 
2335 enum target_xfer_status
2336 procfs_target::xfer_partial (enum target_object object,
2337 			     const char *annex, gdb_byte *readbuf,
2338 			     const gdb_byte *writebuf, ULONGEST offset,
2339 			     ULONGEST len, ULONGEST *xfered_len)
2340 {
2341   switch (object)
2342     {
2343     case TARGET_OBJECT_MEMORY:
2344       return procfs_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2345 
2346     case TARGET_OBJECT_AUXV:
2347       return memory_xfer_auxv (this, object, annex, readbuf, writebuf,
2348 			       offset, len, xfered_len);
2349 
2350     default:
2351       return this->beneath ()->xfer_partial (object, annex,
2352 					     readbuf, writebuf, offset, len,
2353 					     xfered_len);
2354     }
2355 }
2356 
2357 /* Helper for procfs_xfer_partial that handles memory transfers.
2358    Arguments are like target_xfer_partial.  */
2359 
2360 static enum target_xfer_status
2361 procfs_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2362 		    ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2363 {
2364   procinfo *pi;
2365   int nbytes;
2366 
2367   /* Find procinfo for main process.  */
2368   pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2369   if (pi->as_fd == 0 && open_procinfo_files (pi, FD_AS) == 0)
2370     {
2371       proc_warn (pi, "xfer_memory, open_proc_files", __LINE__);
2372       return TARGET_XFER_E_IO;
2373     }
2374 
2375   if (lseek (pi->as_fd, (off_t) memaddr, SEEK_SET) != (off_t) memaddr)
2376     return TARGET_XFER_E_IO;
2377 
2378   if (writebuf != NULL)
2379     {
2380       PROCFS_NOTE ("write memory:\n");
2381       nbytes = write (pi->as_fd, writebuf, len);
2382     }
2383   else
2384     {
2385       PROCFS_NOTE ("read  memory:\n");
2386       nbytes = read (pi->as_fd, readbuf, len);
2387     }
2388   if (nbytes <= 0)
2389     return TARGET_XFER_E_IO;
2390   *xfered_len = nbytes;
2391   return TARGET_XFER_OK;
2392 }
2393 
2394 /* Called by target_resume before making child runnable.  Mark cached
2395    registers and status's invalid.  If there are "dirty" caches that
2396    need to be written back to the child process, do that.
2397 
2398    File descriptors are also cached.  As they are a limited resource,
2399    we cannot hold onto them indefinitely.  However, as they are
2400    expensive to open, we don't want to throw them away
2401    indiscriminately either.  As a compromise, we will keep the file
2402    descriptors for the parent process, but discard any file
2403    descriptors we may have accumulated for the threads.
2404 
2405    As this function is called by iterate_over_threads, it always
2406    returns zero (so that iterate_over_threads will keep
2407    iterating).  */
2408 
2409 static int
2410 invalidate_cache (procinfo *parent, procinfo *pi, void *ptr)
2411 {
2412   /* About to run the child; invalidate caches and do any other
2413      cleanup.  */
2414 
2415   if (parent != NULL)
2416     {
2417       /* The presence of a parent indicates that this is an LWP.
2418 	 Close any file descriptors that it might have open.
2419 	 We don't do this to the master (parent) procinfo.  */
2420 
2421       close_procinfo_files (pi);
2422     }
2423   pi->gregs_valid   = 0;
2424   pi->fpregs_valid  = 0;
2425   pi->status_valid  = 0;
2426   pi->threads_valid = 0;
2427 
2428   return 0;
2429 }
2430 
2431 /* Make the child process runnable.  Normally we will then call
2432    procfs_wait and wait for it to stop again (unless gdb is async).
2433 
2434    If STEP is true, then arrange for the child to stop again after
2435    executing a single instruction.  If SIGNO is zero, then cancel any
2436    pending signal; if non-zero, then arrange for the indicated signal
2437    to be delivered to the child when it runs.  If PID is -1, then
2438    allow any child thread to run; if non-zero, then allow only the
2439    indicated thread to run.  (not implemented yet).  */
2440 
2441 void
2442 procfs_target::resume (ptid_t ptid, int step, enum gdb_signal signo)
2443 {
2444   procinfo *pi, *thread;
2445   int native_signo;
2446 
2447   /* FIXME: Check/reword.  */
2448 
2449   /* prrun.prflags |= PRCFAULT;    clear current fault.
2450      PRCFAULT may be replaced by a PCCFAULT call (proc_clear_current_fault)
2451      This basically leaves PRSTEP and PRCSIG.
2452      PRCSIG is like PCSSIG (proc_clear_current_signal).
2453      So basically PR_STEP is the sole argument that must be passed
2454      to proc_run_process.  */
2455 
2456   /* Find procinfo for main process.  */
2457   pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2458 
2459   /* First cut: ignore pid argument.  */
2460   errno = 0;
2461 
2462   /* Convert signal to host numbering.  */
2463   if (signo == 0 || (signo == GDB_SIGNAL_STOP && pi->ignore_next_sigstop))
2464     native_signo = 0;
2465   else
2466     native_signo = gdb_signal_to_host (signo);
2467 
2468   pi->ignore_next_sigstop = 0;
2469 
2470   /* Running the process voids all cached registers and status.  */
2471   /* Void the threads' caches first.  */
2472   proc_iterate_over_threads (pi, invalidate_cache, NULL);
2473   /* Void the process procinfo's caches.  */
2474   invalidate_cache (NULL, pi, NULL);
2475 
2476   if (ptid.pid () != -1)
2477     {
2478       /* Resume a specific thread, presumably suppressing the
2479 	 others.  */
2480       thread = find_procinfo (ptid.pid (), ptid.lwp ());
2481       if (thread != NULL)
2482 	{
2483 	  if (thread->tid != 0)
2484 	    {
2485 	      /* We're to resume a specific thread, and not the
2486 		 others.  Set the child process's PR_ASYNC flag.  */
2487 	      if (!proc_set_async (pi))
2488 		proc_error (pi, "target_resume, set_async", __LINE__);
2489 	      pi = thread;	/* Substitute the thread's procinfo
2490 				   for run.  */
2491 	    }
2492 	}
2493     }
2494 
2495   if (!proc_run_process (pi, step, native_signo))
2496     {
2497       if (errno == EBUSY)
2498 	warning (_("resume: target already running.  "
2499 		   "Pretend to resume, and hope for the best!"));
2500       else
2501 	proc_error (pi, "target_resume", __LINE__);
2502     }
2503 }
2504 
2505 /* Set up to trace signals in the child process.  */
2506 
2507 void
2508 procfs_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2509 {
2510   sigset_t signals;
2511   procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2512   int signo;
2513 
2514   prfillset (&signals);
2515 
2516   for (signo = 0; signo < NSIG; signo++)
2517     {
2518       int target_signo = gdb_signal_from_host (signo);
2519       if (target_signo < pass_signals.size () && pass_signals[target_signo])
2520 	prdelset (&signals, signo);
2521     }
2522 
2523   if (!proc_set_traced_signals (pi, &signals))
2524     proc_error (pi, "pass_signals", __LINE__);
2525 }
2526 
2527 /* Print status information about the child process.  */
2528 
2529 void
2530 procfs_target::files_info ()
2531 {
2532   struct inferior *inf = current_inferior ();
2533 
2534   gdb_printf (_("\tUsing the running image of %s %s via /proc.\n"),
2535 	      inf->attach_flag? "attached": "child",
2536 	      target_pid_to_str (inferior_ptid).c_str ());
2537 }
2538 
2539 /* Make it die.  Wait for it to die.  Clean up after it.  Note: this
2540    should only be applied to the real process, not to an LWP, because
2541    of the check for parent-process.  If we need this to work for an
2542    LWP, it needs some more logic.  */
2543 
2544 static void
2545 unconditionally_kill_inferior (procinfo *pi)
2546 {
2547   int parent_pid;
2548 
2549   parent_pid = proc_parent_pid (pi);
2550   if (!proc_kill (pi, SIGKILL))
2551     proc_error (pi, "unconditionally_kill, proc_kill", __LINE__);
2552   destroy_procinfo (pi);
2553 
2554   /* If pi is GDB's child, wait for it to die.  */
2555   if (parent_pid == getpid ())
2556     /* FIXME: should we use waitpid to make sure we get the right event?
2557        Should we check the returned event?  */
2558     {
2559 #if 0
2560       int status, ret;
2561 
2562       ret = waitpid (pi->pid, &status, 0);
2563 #else
2564       wait (NULL);
2565 #endif
2566     }
2567 }
2568 
2569 /* We're done debugging it, and we want it to go away.  Then we want
2570    GDB to forget all about it.  */
2571 
2572 void
2573 procfs_target::kill ()
2574 {
2575   if (inferior_ptid != null_ptid) /* ? */
2576     {
2577       /* Find procinfo for main process.  */
2578       procinfo *pi = find_procinfo (inferior_ptid.pid (), 0);
2579 
2580       if (pi)
2581 	unconditionally_kill_inferior (pi);
2582       target_mourn_inferior (inferior_ptid);
2583     }
2584 }
2585 
2586 /* Forget we ever debugged this thing!  */
2587 
2588 void
2589 procfs_target::mourn_inferior ()
2590 {
2591   procinfo *pi;
2592 
2593   if (inferior_ptid != null_ptid)
2594     {
2595       /* Find procinfo for main process.  */
2596       pi = find_procinfo (inferior_ptid.pid (), 0);
2597       if (pi)
2598 	destroy_procinfo (pi);
2599     }
2600 
2601   generic_mourn_inferior ();
2602 
2603   maybe_unpush_target ();
2604 }
2605 
2606 /* When GDB forks to create a runnable inferior process, this function
2607    is called on the parent side of the fork.  It's job is to do
2608    whatever is necessary to make the child ready to be debugged, and
2609    then wait for the child to synchronize.  */
2610 
2611 void
2612 procfs_target::procfs_init_inferior (int pid)
2613 {
2614   procinfo *pi;
2615   int fail;
2616   int lwpid;
2617 
2618   pi = create_procinfo (pid, 0);
2619   if (pi == NULL)
2620     perror (_("procfs: out of memory in 'init_inferior'"));
2621 
2622   if (!open_procinfo_files (pi, FD_CTL))
2623     proc_error (pi, "init_inferior, open_proc_files", __LINE__);
2624 
2625   /*
2626     xmalloc			// done
2627     open_procinfo_files		// done
2628     link list			// done
2629     prfillset (trace)
2630     procfs_notice_signals
2631     prfillset (fault)
2632     prdelset (FLTPAGE)
2633     */
2634 
2635   /* If not stopped yet, wait for it to stop.  */
2636   if (!(proc_flags (pi) & PR_STOPPED) && !(proc_wait_for_stop (pi)))
2637     dead_procinfo (pi, "init_inferior: wait_for_stop failed", KILL);
2638 
2639   /* Save some of the /proc state to be restored if we detach.  */
2640   /* FIXME: Why?  In case another debugger was debugging it?
2641      We're it's parent, for Ghu's sake!  */
2642   if (!proc_get_traced_signals  (pi, &pi->saved_sigset))
2643     proc_error (pi, "init_inferior, get_traced_signals", __LINE__);
2644   if (!proc_get_held_signals    (pi, &pi->saved_sighold))
2645     proc_error (pi, "init_inferior, get_held_signals", __LINE__);
2646   if (!proc_get_traced_faults   (pi, &pi->saved_fltset))
2647     proc_error (pi, "init_inferior, get_traced_faults", __LINE__);
2648   if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
2649     proc_error (pi, "init_inferior, get_traced_sysentry", __LINE__);
2650   if (!proc_get_traced_sysexit  (pi, pi->saved_exitset))
2651     proc_error (pi, "init_inferior, get_traced_sysexit", __LINE__);
2652 
2653   fail = procfs_debug_inferior (pi);
2654   if (fail != 0)
2655     proc_error (pi, "init_inferior (procfs_debug_inferior)", fail);
2656 
2657   /* FIXME: logically, we should really be turning OFF run-on-last-close,
2658      and possibly even turning ON kill-on-last-close at this point.  But
2659      I can't make that change without careful testing which I don't have
2660      time to do right now...  */
2661   /* Turn on run-on-last-close flag so that the child
2662      will die if GDB goes away for some reason.  */
2663   if (!proc_set_run_on_last_close (pi))
2664     proc_error (pi, "init_inferior, set_RLC", __LINE__);
2665 
2666   /* We now have have access to the lwpid of the main thread/lwp.  */
2667   lwpid = proc_get_current_thread (pi);
2668 
2669   /* Create a procinfo for the main lwp.  */
2670   create_procinfo (pid, lwpid);
2671 
2672   /* We already have a main thread registered in the thread table at
2673      this point, but it didn't have any lwp info yet.  Notify the core
2674      about it.  This changes inferior_ptid as well.  */
2675   thread_change_ptid (this, ptid_t (pid), ptid_t (pid, lwpid, 0));
2676 
2677   gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
2678 }
2679 
2680 /* When GDB forks to create a new process, this function is called on
2681    the child side of the fork before GDB exec's the user program.  Its
2682    job is to make the child minimally debuggable, so that the parent
2683    GDB process can connect to the child and take over.  This function
2684    should do only the minimum to make that possible, and to
2685    synchronize with the parent process.  The parent process should
2686    take care of the details.  */
2687 
2688 static void
2689 procfs_set_exec_trap (void)
2690 {
2691   /* This routine called on the child side (inferior side)
2692      after GDB forks the inferior.  It must use only local variables,
2693      because it may be sharing data space with its parent.  */
2694 
2695   procinfo *pi;
2696   sysset_t *exitset;
2697 
2698   pi = create_procinfo (getpid (), 0);
2699   if (pi == NULL)
2700     perror_with_name (_("procfs: create_procinfo failed in child"));
2701 
2702   if (open_procinfo_files (pi, FD_CTL) == 0)
2703     {
2704       proc_warn (pi, "set_exec_trap, open_proc_files", __LINE__);
2705       gdb_flush (gdb_stderr);
2706       /* No need to call "dead_procinfo", because we're going to
2707 	 exit.  */
2708       _exit (127);
2709     }
2710 
2711   exitset = XNEW (sysset_t);
2712   premptyset (exitset);
2713   praddset (exitset, SYS_execve);
2714 
2715   if (!proc_set_traced_sysexit (pi, exitset))
2716     {
2717       proc_warn (pi, "set_exec_trap, set_traced_sysexit", __LINE__);
2718       gdb_flush (gdb_stderr);
2719       _exit (127);
2720     }
2721 
2722   /* FIXME: should this be done in the parent instead?  */
2723   /* Turn off inherit on fork flag so that all grand-children
2724      of gdb start with tracing flags cleared.  */
2725   if (!proc_unset_inherit_on_fork (pi))
2726     proc_warn (pi, "set_exec_trap, unset_inherit", __LINE__);
2727 
2728   /* Turn off run on last close flag, so that the child process
2729      cannot run away just because we close our handle on it.
2730      We want it to wait for the parent to attach.  */
2731   if (!proc_unset_run_on_last_close (pi))
2732     proc_warn (pi, "set_exec_trap, unset_RLC", __LINE__);
2733 
2734   /* FIXME: No need to destroy the procinfo --
2735      we have our own address space, and we're about to do an exec!  */
2736   /*destroy_procinfo (pi);*/
2737 }
2738 
2739 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2).
2740    This avoids a possible deadlock gdb and its vfork'ed child.  */
2741 static void
2742 procfs_pre_trace (void)
2743 {
2744 }
2745 
2746 /* This function is called BEFORE gdb forks the inferior process.  Its
2747    only real responsibility is to set things up for the fork, and tell
2748    GDB which two functions to call after the fork (one for the parent,
2749    and one for the child).
2750 
2751    This function does a complicated search for a unix shell program,
2752    which it then uses to parse arguments and environment variables to
2753    be sent to the child.  I wonder whether this code could not be
2754    abstracted out and shared with other unix targets such as
2755    inf-ptrace?  */
2756 
2757 void
2758 procfs_target::create_inferior (const char *exec_file,
2759 				const std::string &allargs,
2760 				char **env, int from_tty)
2761 {
2762   const char *shell_file = get_shell ();
2763   char *tryname;
2764   int pid;
2765 
2766   if (strchr (shell_file, '/') == NULL)
2767     {
2768 
2769       /* We will be looking down the PATH to find shell_file.  If we
2770 	 just do this the normal way (via execlp, which operates by
2771 	 attempting an exec for each element of the PATH until it
2772 	 finds one which succeeds), then there will be an exec for
2773 	 each failed attempt, each of which will cause a PR_SYSEXIT
2774 	 stop, and we won't know how to distinguish the PR_SYSEXIT's
2775 	 for these failed execs with the ones for successful execs
2776 	 (whether the exec has succeeded is stored at that time in the
2777 	 carry bit or some such architecture-specific and
2778 	 non-ABI-specified place).
2779 
2780 	 So I can't think of anything better than to search the PATH
2781 	 now.  This has several disadvantages: (1) There is a race
2782 	 condition; if we find a file now and it is deleted before we
2783 	 exec it, we lose, even if the deletion leaves a valid file
2784 	 further down in the PATH, (2) there is no way to know exactly
2785 	 what an executable (in the sense of "capable of being
2786 	 exec'd") file is.  Using access() loses because it may lose
2787 	 if the caller is the superuser; failing to use it loses if
2788 	 there are ACLs or some such.  */
2789 
2790       const char *p;
2791       const char *p1;
2792       /* FIXME-maybe: might want "set path" command so user can change what
2793 	 path is used from within GDB.  */
2794       const char *path = getenv ("PATH");
2795       int len;
2796       struct stat statbuf;
2797 
2798       if (path == NULL)
2799 	path = "/bin:/usr/bin";
2800 
2801       tryname = (char *) alloca (strlen (path) + strlen (shell_file) + 2);
2802       for (p = path; p != NULL; p = p1 ? p1 + 1: NULL)
2803 	{
2804 	  p1 = strchr (p, ':');
2805 	  if (p1 != NULL)
2806 	    len = p1 - p;
2807 	  else
2808 	    len = strlen (p);
2809 	  memcpy (tryname, p, len);
2810 	  tryname[len] = '\0';
2811 	  strcat (tryname, "/");
2812 	  strcat (tryname, shell_file);
2813 	  if (access (tryname, X_OK) < 0)
2814 	    continue;
2815 	  if (stat (tryname, &statbuf) < 0)
2816 	    continue;
2817 	  if (!S_ISREG (statbuf.st_mode))
2818 	    /* We certainly need to reject directories.  I'm not quite
2819 	       as sure about FIFOs, sockets, etc., but I kind of doubt
2820 	       that people want to exec() these things.  */
2821 	    continue;
2822 	  break;
2823 	}
2824       if (p == NULL)
2825 	/* Not found.  This must be an error rather than merely passing
2826 	   the file to execlp(), because execlp() would try all the
2827 	   exec()s, causing GDB to get confused.  */
2828 	error (_("procfs:%d -- Can't find shell %s in PATH"),
2829 	       __LINE__, shell_file);
2830 
2831       shell_file = tryname;
2832     }
2833 
2834   inferior *inf = current_inferior ();
2835   if (!inf->target_is_pushed (this))
2836     inf->push_target (this);
2837 
2838   pid = fork_inferior (exec_file, allargs, env, procfs_set_exec_trap,
2839 		       NULL, procfs_pre_trace, shell_file, NULL);
2840 
2841   /* We have something that executes now.  We'll be running through
2842      the shell at this point (if startup-with-shell is true), but the
2843      pid shouldn't change.  */
2844   thread_info *thr = add_thread_silent (this, ptid_t (pid));
2845   switch_to_thread (thr);
2846 
2847   procfs_init_inferior (pid);
2848 }
2849 
2850 /* Callback for update_thread_list.  Calls "add_thread".  */
2851 
2852 static int
2853 procfs_notice_thread (procinfo *pi, procinfo *thread, void *ptr)
2854 {
2855   ptid_t gdb_threadid = ptid_t (pi->pid, thread->tid, 0);
2856 
2857   thread_info *thr = find_thread_ptid (&the_procfs_target, gdb_threadid);
2858   if (thr == NULL || thr->state == THREAD_EXITED)
2859     add_thread (&the_procfs_target, gdb_threadid);
2860 
2861   return 0;
2862 }
2863 
2864 /* Query all the threads that the target knows about, and give them
2865    back to GDB to add to its list.  */
2866 
2867 void
2868 procfs_target::update_thread_list ()
2869 {
2870   procinfo *pi;
2871 
2872   prune_threads ();
2873 
2874   /* Find procinfo for main process.  */
2875   pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2876   proc_update_threads (pi);
2877   proc_iterate_over_threads (pi, procfs_notice_thread, NULL);
2878 }
2879 
2880 /* Return true if the thread is still 'alive'.  This guy doesn't
2881    really seem to be doing his job.  Got to investigate how to tell
2882    when a thread is really gone.  */
2883 
2884 bool
2885 procfs_target::thread_alive (ptid_t ptid)
2886 {
2887   int proc, thread;
2888   procinfo *pi;
2889 
2890   proc    = ptid.pid ();
2891   thread  = ptid.lwp ();
2892   /* If I don't know it, it ain't alive!  */
2893   pi = find_procinfo (proc, thread);
2894   if (pi == NULL)
2895     return false;
2896 
2897   /* If I can't get its status, it ain't alive!
2898      What's more, I need to forget about it!  */
2899   if (!proc_get_status (pi))
2900     {
2901       destroy_procinfo (pi);
2902       return false;
2903     }
2904   /* I couldn't have got its status if it weren't alive, so it's
2905      alive.  */
2906   return true;
2907 }
2908 
2909 /* Convert PTID to a string.  */
2910 
2911 std::string
2912 procfs_target::pid_to_str (ptid_t ptid)
2913 {
2914   if (ptid.lwp () == 0)
2915     return string_printf ("process %d", ptid.pid ());
2916   else
2917     return string_printf ("LWP %ld", ptid.lwp ());
2918 }
2919 
2920 /* Accepts an integer PID; Returns a string representing a file that
2921    can be opened to get the symbols for the child process.  */
2922 
2923 const char *
2924 procfs_target::pid_to_exec_file (int pid)
2925 {
2926   static char buf[PATH_MAX];
2927   char name[PATH_MAX];
2928 
2929   /* Solaris 11 introduced /proc/<proc-id>/execname.  */
2930   xsnprintf (name, sizeof (name), "/proc/%d/execname", pid);
2931   scoped_fd fd (gdb_open_cloexec (name, O_RDONLY, 0));
2932   if (fd.get () < 0 || read (fd.get (), buf, PATH_MAX - 1) < 0)
2933     {
2934       /* If that fails, fall back to /proc/<proc-id>/path/a.out introduced in
2935 	 Solaris 10.  */
2936       ssize_t len;
2937 
2938       xsnprintf (name, sizeof (name), "/proc/%d/path/a.out", pid);
2939       len = readlink (name, buf, PATH_MAX - 1);
2940       if (len <= 0)
2941 	strcpy (buf, name);
2942       else
2943 	buf[len] = '\0';
2944     }
2945 
2946   return buf;
2947 }
2948 
2949 /* Insert a watchpoint.  */
2950 
2951 static int
2952 procfs_set_watchpoint (ptid_t ptid, CORE_ADDR addr, int len, int rwflag,
2953 		       int after)
2954 {
2955   int       pflags = 0;
2956   procinfo *pi;
2957 
2958   pi = find_procinfo_or_die (ptid.pid () == -1 ?
2959 			     inferior_ptid.pid () : ptid.pid (),
2960 			     0);
2961 
2962   /* Translate from GDB's flags to /proc's.  */
2963   if (len > 0)	/* len == 0 means delete watchpoint.  */
2964     {
2965       switch (rwflag) {		/* FIXME: need an enum!  */
2966       case hw_write:		/* default watchpoint (write) */
2967 	pflags = WA_WRITE;
2968 	break;
2969       case hw_read:		/* read watchpoint */
2970 	pflags = WA_READ;
2971 	break;
2972       case hw_access:		/* access watchpoint */
2973 	pflags = WA_READ | WA_WRITE;
2974 	break;
2975       case hw_execute:		/* execution HW breakpoint */
2976 	pflags = WA_EXEC;
2977 	break;
2978       default:			/* Something weird.  Return error.  */
2979 	return -1;
2980       }
2981       if (after)		/* Stop after r/w access is completed.  */
2982 	pflags |= WA_TRAPAFTER;
2983     }
2984 
2985   if (!proc_set_watchpoint (pi, addr, len, pflags))
2986     {
2987       if (errno == E2BIG)	/* Typical error for no resources.  */
2988 	return -1;		/* fail */
2989       /* GDB may try to remove the same watchpoint twice.
2990 	 If a remove request returns no match, don't error.  */
2991       if (errno == ESRCH && len == 0)
2992 	return 0;		/* ignore */
2993       proc_error (pi, "set_watchpoint", __LINE__);
2994     }
2995   return 0;
2996 }
2997 
2998 /* Return non-zero if we can set a hardware watchpoint of type TYPE.  TYPE
2999    is one of bp_hardware_watchpoint, bp_read_watchpoint, bp_write_watchpoint,
3000    or bp_hardware_watchpoint.  CNT is the number of watchpoints used so
3001    far.  */
3002 
3003 int
3004 procfs_target::can_use_hw_breakpoint (enum bptype type, int cnt, int othertype)
3005 {
3006   /* Due to the way that proc_set_watchpoint() is implemented, host
3007      and target pointers must be of the same size.  If they are not,
3008      we can't use hardware watchpoints.  This limitation is due to the
3009      fact that proc_set_watchpoint() calls
3010      procfs_address_to_host_pointer(); a close inspection of
3011      procfs_address_to_host_pointer will reveal that an internal error
3012      will be generated when the host and target pointer sizes are
3013      different.  */
3014   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
3015 
3016   if (sizeof (void *) != ptr_type->length ())
3017     return 0;
3018 
3019   /* Other tests here???  */
3020 
3021   return 1;
3022 }
3023 
3024 /* Returns non-zero if process is stopped on a hardware watchpoint
3025    fault, else returns zero.  */
3026 
3027 bool
3028 procfs_target::stopped_by_watchpoint ()
3029 {
3030   procinfo *pi;
3031 
3032   pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3033 
3034   if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
3035     if (proc_why (pi) == PR_FAULTED)
3036       if (proc_what (pi) == FLTWATCH)
3037 	return true;
3038   return false;
3039 }
3040 
3041 /* Returns 1 if the OS knows the position of the triggered watchpoint,
3042    and sets *ADDR to that address.  Returns 0 if OS cannot report that
3043    address.  This function is only called if
3044    procfs_stopped_by_watchpoint returned 1, thus no further checks are
3045    done.  The function also assumes that ADDR is not NULL.  */
3046 
3047 bool
3048 procfs_target::stopped_data_address (CORE_ADDR *addr)
3049 {
3050   procinfo *pi;
3051 
3052   pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3053   return proc_watchpoint_address (pi, addr);
3054 }
3055 
3056 int
3057 procfs_target::insert_watchpoint (CORE_ADDR addr, int len,
3058 				  enum target_hw_bp_type type,
3059 				  struct expression *cond)
3060 {
3061   if (!target_have_steppable_watchpoint ()
3062       && !gdbarch_have_nonsteppable_watchpoint (target_gdbarch ()))
3063     /* When a hardware watchpoint fires off the PC will be left at
3064        the instruction following the one which caused the
3065        watchpoint.  It will *NOT* be necessary for GDB to step over
3066        the watchpoint.  */
3067     return procfs_set_watchpoint (inferior_ptid, addr, len, type, 1);
3068   else
3069     /* When a hardware watchpoint fires off the PC will be left at
3070        the instruction which caused the watchpoint.  It will be
3071        necessary for GDB to step over the watchpoint.  */
3072     return procfs_set_watchpoint (inferior_ptid, addr, len, type, 0);
3073 }
3074 
3075 int
3076 procfs_target::remove_watchpoint (CORE_ADDR addr, int len,
3077 				  enum target_hw_bp_type type,
3078 				  struct expression *cond)
3079 {
3080   return procfs_set_watchpoint (inferior_ptid, addr, 0, 0, 0);
3081 }
3082 
3083 int
3084 procfs_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
3085 {
3086   /* The man page for proc(4) on Solaris 2.6 and up says that the
3087      system can support "thousands" of hardware watchpoints, but gives
3088      no method for finding out how many; It doesn't say anything about
3089      the allowed size for the watched area either.  So we just tell
3090      GDB 'yes'.  */
3091   return 1;
3092 }
3093 
3094 /* Memory Mappings Functions: */
3095 
3096 /* Call a callback function once for each mapping, passing it the
3097    mapping, an optional secondary callback function, and some optional
3098    opaque data.  Quit and return the first non-zero value returned
3099    from the callback.
3100 
3101    PI is the procinfo struct for the process to be mapped.  FUNC is
3102    the callback function to be called by this iterator.  DATA is the
3103    optional opaque data to be passed to the callback function.
3104    CHILD_FUNC is the optional secondary function pointer to be passed
3105    to the child function.  Returns the first non-zero return value
3106    from the callback function, or zero.  */
3107 
3108 static int
3109 iterate_over_mappings (procinfo *pi, find_memory_region_ftype child_func,
3110 		       void *data,
3111 		       int (*func) (struct prmap *map,
3112 				    find_memory_region_ftype child_func,
3113 				    void *data))
3114 {
3115   char pathname[MAX_PROC_NAME_SIZE];
3116   struct prmap *prmaps;
3117   struct prmap *prmap;
3118   int funcstat;
3119   int nmap;
3120   struct stat sbuf;
3121 
3122   /* Get the number of mappings, allocate space,
3123      and read the mappings into prmaps.  */
3124   /* Open map fd.  */
3125   xsnprintf (pathname, sizeof (pathname), "/proc/%d/map", pi->pid);
3126 
3127   scoped_fd map_fd (open (pathname, O_RDONLY));
3128   if (map_fd.get () < 0)
3129     proc_error (pi, "iterate_over_mappings (open)", __LINE__);
3130 
3131   /* Use stat to determine the file size, and compute
3132      the number of prmap_t objects it contains.  */
3133   if (fstat (map_fd.get (), &sbuf) != 0)
3134     proc_error (pi, "iterate_over_mappings (fstat)", __LINE__);
3135 
3136   nmap = sbuf.st_size / sizeof (prmap_t);
3137   prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
3138   if (read (map_fd.get (), (char *) prmaps, nmap * sizeof (*prmaps))
3139       != (nmap * sizeof (*prmaps)))
3140     proc_error (pi, "iterate_over_mappings (read)", __LINE__);
3141 
3142   for (prmap = prmaps; nmap > 0; prmap++, nmap--)
3143     {
3144       funcstat = (*func) (prmap, child_func, data);
3145       if (funcstat != 0)
3146 	return funcstat;
3147     }
3148 
3149   return 0;
3150 }
3151 
3152 /* Implements the to_find_memory_regions method.  Calls an external
3153    function for each memory region.
3154    Returns the integer value returned by the callback.  */
3155 
3156 static int
3157 find_memory_regions_callback (struct prmap *map,
3158 			      find_memory_region_ftype func, void *data)
3159 {
3160   return (*func) ((CORE_ADDR) map->pr_vaddr,
3161 		  map->pr_size,
3162 		  (map->pr_mflags & MA_READ) != 0,
3163 		  (map->pr_mflags & MA_WRITE) != 0,
3164 		  (map->pr_mflags & MA_EXEC) != 0,
3165 		  1, /* MODIFIED is unknown, pass it as true.  */
3166 		  false,
3167 		  data);
3168 }
3169 
3170 /* External interface.  Calls a callback function once for each
3171    mapped memory region in the child process, passing as arguments:
3172 
3173 	CORE_ADDR virtual_address,
3174 	unsigned long size,
3175 	int read,	TRUE if region is readable by the child
3176 	int write,	TRUE if region is writable by the child
3177 	int execute	TRUE if region is executable by the child.
3178 
3179    Stops iterating and returns the first non-zero value returned by
3180    the callback.  */
3181 
3182 int
3183 procfs_target::find_memory_regions (find_memory_region_ftype func, void *data)
3184 {
3185   procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3186 
3187   return iterate_over_mappings (pi, func, data,
3188 				find_memory_regions_callback);
3189 }
3190 
3191 /* Returns an ascii representation of a memory mapping's flags.  */
3192 
3193 static char *
3194 mappingflags (long flags)
3195 {
3196   static char asciiflags[8];
3197 
3198   strcpy (asciiflags, "-------");
3199   if (flags & MA_STACK)
3200     asciiflags[1] = 's';
3201   if (flags & MA_BREAK)
3202     asciiflags[2] = 'b';
3203   if (flags & MA_SHARED)
3204     asciiflags[3] = 's';
3205   if (flags & MA_READ)
3206     asciiflags[4] = 'r';
3207   if (flags & MA_WRITE)
3208     asciiflags[5] = 'w';
3209   if (flags & MA_EXEC)
3210     asciiflags[6] = 'x';
3211   return (asciiflags);
3212 }
3213 
3214 /* Callback function, does the actual work for 'info proc
3215    mappings'.  */
3216 
3217 static int
3218 info_mappings_callback (struct prmap *map, find_memory_region_ftype ignore,
3219 			void *unused)
3220 {
3221   unsigned int pr_off;
3222 
3223   pr_off = (unsigned int) map->pr_offset;
3224 
3225   if (gdbarch_addr_bit (target_gdbarch ()) == 32)
3226     gdb_printf ("\t%#10lx %#10lx %#10lx %#10x %7s\n",
3227 		(unsigned long) map->pr_vaddr,
3228 		(unsigned long) map->pr_vaddr + map->pr_size - 1,
3229 		(unsigned long) map->pr_size,
3230 		pr_off,
3231 		mappingflags (map->pr_mflags));
3232   else
3233     gdb_printf ("  %#18lx %#18lx %#10lx %#10x %7s\n",
3234 		(unsigned long) map->pr_vaddr,
3235 		(unsigned long) map->pr_vaddr + map->pr_size - 1,
3236 		(unsigned long) map->pr_size,
3237 		pr_off,
3238 		mappingflags (map->pr_mflags));
3239 
3240   return 0;
3241 }
3242 
3243 /* Implement the "info proc mappings" subcommand.  */
3244 
3245 static void
3246 info_proc_mappings (procinfo *pi, int summary)
3247 {
3248   if (summary)
3249     return;	/* No output for summary mode.  */
3250 
3251   gdb_printf (_("Mapped address spaces:\n\n"));
3252   if (gdbarch_ptr_bit (target_gdbarch ()) == 32)
3253     gdb_printf ("\t%10s %10s %10s %10s %7s\n",
3254 		"Start Addr",
3255 		"  End Addr",
3256 		"      Size",
3257 		"    Offset",
3258 		"Flags");
3259   else
3260     gdb_printf ("  %18s %18s %10s %10s %7s\n",
3261 		"Start Addr",
3262 		"  End Addr",
3263 		"      Size",
3264 		"    Offset",
3265 		"Flags");
3266 
3267   iterate_over_mappings (pi, NULL, NULL, info_mappings_callback);
3268   gdb_printf ("\n");
3269 }
3270 
3271 /* Implement the "info proc" command.  */
3272 
3273 bool
3274 procfs_target::info_proc (const char *args, enum info_proc_what what)
3275 {
3276   procinfo *process  = NULL;
3277   procinfo *thread   = NULL;
3278   char     *tmp      = NULL;
3279   int       pid      = 0;
3280   int       tid      = 0;
3281   int       mappings = 0;
3282 
3283   switch (what)
3284     {
3285     case IP_MINIMAL:
3286       break;
3287 
3288     case IP_MAPPINGS:
3289     case IP_ALL:
3290       mappings = 1;
3291       break;
3292 
3293     default:
3294       error (_("Not supported on this target."));
3295     }
3296 
3297   gdb_argv built_argv (args);
3298   for (char *arg : built_argv)
3299     {
3300       if (isdigit (arg[0]))
3301 	{
3302 	  pid = strtoul (arg, &tmp, 10);
3303 	  if (*tmp == '/')
3304 	    tid = strtoul (++tmp, NULL, 10);
3305 	}
3306       else if (arg[0] == '/')
3307 	{
3308 	  tid = strtoul (arg + 1, NULL, 10);
3309 	}
3310     }
3311 
3312   procinfo_up temporary_procinfo;
3313   if (pid == 0)
3314     pid = inferior_ptid.pid ();
3315   if (pid == 0)
3316     error (_("No current process: you must name one."));
3317   else
3318     {
3319       /* Have pid, will travel.
3320 	 First see if it's a process we're already debugging.  */
3321       process = find_procinfo (pid, 0);
3322        if (process == NULL)
3323 	 {
3324 	   /* No.  So open a procinfo for it, but
3325 	      remember to close it again when finished.  */
3326 	   process = create_procinfo (pid, 0);
3327 	   temporary_procinfo.reset (process);
3328 	   if (!open_procinfo_files (process, FD_CTL))
3329 	     proc_error (process, "info proc, open_procinfo_files", __LINE__);
3330 	 }
3331     }
3332   if (tid != 0)
3333     thread = create_procinfo (pid, tid);
3334 
3335   if (process)
3336     {
3337       gdb_printf (_("process %d flags:\n"), process->pid);
3338       proc_prettyprint_flags (proc_flags (process), 1);
3339       if (proc_flags (process) & (PR_STOPPED | PR_ISTOP))
3340 	proc_prettyprint_why (proc_why (process), proc_what (process), 1);
3341       if (proc_get_nthreads (process) > 1)
3342 	gdb_printf ("Process has %d threads.\n",
3343 		    proc_get_nthreads (process));
3344     }
3345   if (thread)
3346     {
3347       gdb_printf (_("thread %d flags:\n"), thread->tid);
3348       proc_prettyprint_flags (proc_flags (thread), 1);
3349       if (proc_flags (thread) & (PR_STOPPED | PR_ISTOP))
3350 	proc_prettyprint_why (proc_why (thread), proc_what (thread), 1);
3351     }
3352 
3353   if (mappings)
3354     info_proc_mappings (process, 0);
3355 
3356   return true;
3357 }
3358 
3359 /* Modify the status of the system call identified by SYSCALLNUM in
3360    the set of syscalls that are currently traced/debugged.
3361 
3362    If ENTRY_OR_EXIT is set to PR_SYSENTRY, then the entry syscalls set
3363    will be updated.  Otherwise, the exit syscalls set will be updated.
3364 
3365    If MODE is FLAG_SET, then traces will be enabled.  Otherwise, they
3366    will be disabled.  */
3367 
3368 static void
3369 proc_trace_syscalls_1 (procinfo *pi, int syscallnum, int entry_or_exit,
3370 		       int mode, int from_tty)
3371 {
3372   sysset_t *sysset;
3373 
3374   if (entry_or_exit == PR_SYSENTRY)
3375     sysset = proc_get_traced_sysentry (pi, NULL);
3376   else
3377     sysset = proc_get_traced_sysexit (pi, NULL);
3378 
3379   if (sysset == NULL)
3380     proc_error (pi, "proc-trace, get_traced_sysset", __LINE__);
3381 
3382   if (mode == FLAG_SET)
3383     praddset (sysset, syscallnum);
3384   else
3385     prdelset (sysset, syscallnum);
3386 
3387   if (entry_or_exit == PR_SYSENTRY)
3388     {
3389       if (!proc_set_traced_sysentry (pi, sysset))
3390 	proc_error (pi, "proc-trace, set_traced_sysentry", __LINE__);
3391     }
3392   else
3393     {
3394       if (!proc_set_traced_sysexit (pi, sysset))
3395 	proc_error (pi, "proc-trace, set_traced_sysexit", __LINE__);
3396     }
3397 }
3398 
3399 static void
3400 proc_trace_syscalls (const char *args, int from_tty, int entry_or_exit, int mode)
3401 {
3402   procinfo *pi;
3403 
3404   if (inferior_ptid.pid () <= 0)
3405     error (_("you must be debugging a process to use this command."));
3406 
3407   if (args == NULL || args[0] == 0)
3408     error_no_arg (_("system call to trace"));
3409 
3410   pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3411   if (isdigit (args[0]))
3412     {
3413       const int syscallnum = atoi (args);
3414 
3415       proc_trace_syscalls_1 (pi, syscallnum, entry_or_exit, mode, from_tty);
3416     }
3417 }
3418 
3419 static void
3420 proc_trace_sysentry_cmd (const char *args, int from_tty)
3421 {
3422   proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_SET);
3423 }
3424 
3425 static void
3426 proc_trace_sysexit_cmd (const char *args, int from_tty)
3427 {
3428   proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_SET);
3429 }
3430 
3431 static void
3432 proc_untrace_sysentry_cmd (const char *args, int from_tty)
3433 {
3434   proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_RESET);
3435 }
3436 
3437 static void
3438 proc_untrace_sysexit_cmd (const char *args, int from_tty)
3439 {
3440   proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_RESET);
3441 }
3442 
3443 void _initialize_procfs ();
3444 void
3445 _initialize_procfs ()
3446 {
3447   add_com ("proc-trace-entry", no_class, proc_trace_sysentry_cmd,
3448 	   _("Give a trace of entries into the syscall."));
3449   add_com ("proc-trace-exit", no_class, proc_trace_sysexit_cmd,
3450 	   _("Give a trace of exits from the syscall."));
3451   add_com ("proc-untrace-entry", no_class, proc_untrace_sysentry_cmd,
3452 	   _("Cancel a trace of entries into the syscall."));
3453   add_com ("proc-untrace-exit", no_class, proc_untrace_sysexit_cmd,
3454 	   _("Cancel a trace of exits from the syscall."));
3455 
3456   add_inf_child_target (&the_procfs_target);
3457 }
3458 
3459 /* =================== END, GDB  "MODULE" =================== */
3460 
3461 
3462 
3463 /* miscellaneous stubs: */
3464 
3465 /* The following satisfy a few random symbols mostly created by the
3466    solaris threads implementation, which I will chase down later.  */
3467 
3468 /* Return a pid for which we guarantee we will be able to find a
3469    'live' procinfo.  */
3470 
3471 ptid_t
3472 procfs_first_available (void)
3473 {
3474   return ptid_t (procinfo_list ? procinfo_list->pid : -1);
3475 }
3476 
3477 /* ===================  GCORE .NOTE "MODULE" =================== */
3478 
3479 static void
3480 procfs_do_thread_registers (bfd *obfd, ptid_t ptid,
3481 			    gdb::unique_xmalloc_ptr<char> &note_data,
3482 			    int *note_size, enum gdb_signal stop_signal)
3483 {
3484   struct regcache *regcache = get_thread_regcache (&the_procfs_target, ptid);
3485   gdb_gregset_t gregs;
3486   gdb_fpregset_t fpregs;
3487   unsigned long merged_pid;
3488 
3489   merged_pid = ptid.lwp () << 16 | ptid.pid ();
3490 
3491   /* This part is the old method for fetching registers.
3492      It should be replaced by the newer one using regsets
3493      once it is implemented in this platform:
3494      gdbarch_iterate_over_regset_sections().  */
3495 
3496   target_fetch_registers (regcache, -1);
3497 
3498   fill_gregset (regcache, &gregs, -1);
3499   note_data.reset (elfcore_write_lwpstatus (obfd,
3500 					    note_data.release (),
3501 					    note_size,
3502 					    merged_pid,
3503 					    stop_signal,
3504 					    &gregs));
3505   fill_fpregset (regcache, &fpregs, -1);
3506   note_data.reset (elfcore_write_prfpreg (obfd,
3507 					  note_data.release (),
3508 					  note_size,
3509 					  &fpregs,
3510 					  sizeof (fpregs)));
3511 }
3512 
3513 struct procfs_corefile_thread_data
3514 {
3515   procfs_corefile_thread_data (bfd *obfd,
3516 			       gdb::unique_xmalloc_ptr<char> &note_data,
3517 			       int *note_size, gdb_signal stop_signal)
3518     : obfd (obfd), note_data (note_data), note_size (note_size),
3519       stop_signal (stop_signal)
3520   {}
3521 
3522   bfd *obfd;
3523   gdb::unique_xmalloc_ptr<char> &note_data;
3524   int *note_size;
3525   enum gdb_signal stop_signal;
3526 };
3527 
3528 static int
3529 procfs_corefile_thread_callback (procinfo *pi, procinfo *thread, void *data)
3530 {
3531   struct procfs_corefile_thread_data *args
3532     = (struct procfs_corefile_thread_data *) data;
3533 
3534   if (pi != NULL)
3535     {
3536       ptid_t ptid = ptid_t (pi->pid, thread->tid, 0);
3537 
3538       procfs_do_thread_registers (args->obfd, ptid,
3539 				  args->note_data,
3540 				  args->note_size,
3541 				  args->stop_signal);
3542     }
3543   return 0;
3544 }
3545 
3546 static int
3547 find_signalled_thread (struct thread_info *info, void *data)
3548 {
3549   if (info->stop_signal () != GDB_SIGNAL_0
3550       && info->ptid.pid () == inferior_ptid.pid ())
3551     return 1;
3552 
3553   return 0;
3554 }
3555 
3556 static enum gdb_signal
3557 find_stop_signal (void)
3558 {
3559   struct thread_info *info =
3560     iterate_over_threads (find_signalled_thread, NULL);
3561 
3562   if (info)
3563     return info->stop_signal ();
3564   else
3565     return GDB_SIGNAL_0;
3566 }
3567 
3568 gdb::unique_xmalloc_ptr<char>
3569 procfs_target::make_corefile_notes (bfd *obfd, int *note_size)
3570 {
3571   gdb_gregset_t gregs;
3572   char fname[16] = {'\0'};
3573   char psargs[80] = {'\0'};
3574   procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3575   gdb::unique_xmalloc_ptr<char> note_data;
3576   enum gdb_signal stop_signal;
3577 
3578   if (get_exec_file (0))
3579     {
3580       strncpy (fname, lbasename (get_exec_file (0)), sizeof (fname));
3581       fname[sizeof (fname) - 1] = 0;
3582       strncpy (psargs, get_exec_file (0), sizeof (psargs));
3583       psargs[sizeof (psargs) - 1] = 0;
3584 
3585       const std::string &inf_args = current_inferior ()->args ();
3586       if (!inf_args.empty () &&
3587 	  inf_args.length () < ((int) sizeof (psargs) - (int) strlen (psargs)))
3588 	{
3589 	  strncat (psargs, " ",
3590 		   sizeof (psargs) - strlen (psargs));
3591 	  strncat (psargs, inf_args.c_str (),
3592 		   sizeof (psargs) - strlen (psargs));
3593 	}
3594     }
3595 
3596   note_data.reset (elfcore_write_prpsinfo (obfd,
3597 					   note_data.release (),
3598 					   note_size,
3599 					   fname,
3600 					   psargs));
3601 
3602   stop_signal = find_stop_signal ();
3603 
3604   fill_gregset (get_current_regcache (), &gregs, -1);
3605   note_data.reset (elfcore_write_pstatus (obfd, note_data.release (), note_size,
3606 					  inferior_ptid.pid (),
3607 					  stop_signal, &gregs));
3608 
3609   procfs_corefile_thread_data thread_args (obfd, note_data, note_size,
3610 					   stop_signal);
3611   proc_iterate_over_threads (pi, procfs_corefile_thread_callback,
3612 			     &thread_args);
3613 
3614   gdb::optional<gdb::byte_vector> auxv =
3615     target_read_alloc (current_inferior ()->top_target (),
3616 		       TARGET_OBJECT_AUXV, NULL);
3617   if (auxv && !auxv->empty ())
3618     note_data.reset (elfcore_write_note (obfd, note_data.release (), note_size,
3619 					 "CORE", NT_AUXV, auxv->data (),
3620 					 auxv->size ()));
3621 
3622   return note_data;
3623 }
3624 /* ===================  END GCORE .NOTE "MODULE" =================== */
3625