Automatic date update in version.in
[binutils-gdb.git] / gdb / procfs.c
blob2c009c3e32047512c4053a197da0b6778cc640a4
1 /* Machine independent support for Solaris /proc (process file system) for GDB.
3 Copyright (C) 1999-2023 Free Software Foundation, Inc.
5 Written by Michael Snyder at Cygnus Solutions.
6 Based on work by Fred Fish, Stu Grossman, Geoff Noer, and others.
8 This file is part of GDB.
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.
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.
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/>. */
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"
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"
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.
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.
59 The most important thing to know about /proc and this module is
60 that there are two very different interfaces to /proc:
62 One that uses the ioctl system call, and another that uses read
63 and write system calls.
65 This module supports only the Solaris version of the read/write
66 interface. */
68 #include <sys/types.h>
69 #include <dirent.h> /* opendir/readdir, for listing the LWP's */
71 #include <fcntl.h> /* for O_RDONLY */
72 #include <unistd.h> /* for "X_OK" */
73 #include <sys/stat.h> /* for struct stat */
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. */
79 #include "proc-utils.h"
81 /* Prototypes for supply_gregset etc. */
82 #include "gregset.h"
84 /* =================== TARGET_OPS "MODULE" =================== */
86 /* This module defines the GDB target vector and its methods. */
89 static enum target_xfer_status procfs_xfer_memory (gdb_byte *,
90 const gdb_byte *,
91 ULONGEST, ULONGEST,
92 ULONGEST *);
94 class procfs_target final : public inf_child_target
96 public:
97 void create_inferior (const char *, const std::string &,
98 char **, int) override;
100 void kill () override;
102 void mourn_inferior () override;
104 void attach (const char *, int) override;
105 void detach (inferior *inf, int) override;
107 void resume (ptid_t, int, enum gdb_signal) override;
108 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
110 void fetch_registers (struct regcache *, int) override;
111 void store_registers (struct regcache *, int) override;
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;
120 void pass_signals (gdb::array_view<const unsigned char>) override;
122 void files_info () override;
124 void update_thread_list () override;
126 bool thread_alive (ptid_t ptid) override;
128 std::string pid_to_str (ptid_t) override;
130 const char *pid_to_exec_file (int pid) override;
132 thread_control_capabilities get_thread_control_capabilities () override
133 { return tc_schedlock; }
135 /* find_memory_regions support method for gcore */
136 int find_memory_regions (find_memory_region_ftype func, void *data)
137 override;
139 gdb::unique_xmalloc_ptr<char> make_corefile_notes (bfd *, int *) override;
141 bool info_proc (const char *, enum info_proc_what) override;
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
149 bool stopped_by_watchpoint () override;
151 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
152 struct expression *) override;
154 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
155 struct expression *) override;
157 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
159 int can_use_hw_breakpoint (enum bptype, int, int) override;
160 bool stopped_data_address (CORE_ADDR *) override;
162 void procfs_init_inferior (int pid);
165 static procfs_target the_procfs_target;
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. */
172 procfs_target::auxv_parse (const gdb_byte **readptr,
173 const gdb_byte *endptr, CORE_ADDR *typep,
174 CORE_ADDR *valp)
176 enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
177 const gdb_byte *ptr = *readptr;
179 if (endptr == ptr)
180 return 0;
182 if (endptr - ptr < 8 * 2)
183 return -1;
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;
192 *readptr = ptr;
193 return 1;
195 #endif
197 /* =================== END, TARGET_OPS "MODULE" =================== */
199 /* =================== STRUCT PROCINFO "MODULE" =================== */
201 /* FIXME: this comment will soon be out of date W.R.T. threads. */
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.
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.
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. */
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")
227 typedef struct procinfo {
228 struct procinfo *next;
229 int pid; /* Process ID */
230 int tid; /* Thread/LWP id */
232 /* process state */
233 int was_stopped;
234 int ignore_next_sigstop;
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 */
240 char pathname[MAX_PROC_NAME_SIZE]; /* Pathname to /proc entry */
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 */
248 pstatus_t prstatus; /* Current process status info */
250 struct procinfo *thread_list;
252 int status_valid : 1;
253 int gregs_valid : 1;
254 int fpregs_valid : 1;
255 int threads_valid: 1;
256 } procinfo;
258 static char errmsg[128]; /* shared error msg buffer */
260 /* Function prototypes for procinfo module: */
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);
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));
275 /* The head of the procinfo list: */
276 static procinfo *procinfo_list;
278 /* Search the procinfo list. Return a pointer to procinfo, or NULL if
279 not found. */
281 static procinfo *
282 find_procinfo (int pid, int tid)
284 procinfo *pi;
286 for (pi = procinfo_list; pi; pi = pi->next)
287 if (pi->pid == pid)
288 break;
290 if (pi)
291 if (tid)
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. */
300 for (pi = pi->thread_list; pi; pi = pi->next)
301 if (pi->tid == tid)
302 break;
305 return pi;
308 /* Calls find_procinfo, but errors on failure. */
310 static procinfo *
311 find_procinfo_or_die (int pid, int tid)
313 procinfo *pi = find_procinfo (pid, tid);
315 if (pi == NULL)
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);
324 return pi;
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.
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. */
337 static int
338 open_with_retry (const char *pathname, int flags)
340 int retries_remaining, status;
342 retries_remaining = 2;
344 while (1)
346 status = open (pathname, flags);
348 if (status >= 0 || retries_remaining == 0)
349 break;
350 else if (errno != EINTR && errno != EAGAIN)
352 retries_remaining--;
353 sleep (1);
357 return status;
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. */
364 enum { FD_CTL, FD_STATUS, FD_AS };
366 static int
367 open_procinfo_files (procinfo *pi, int which)
369 char tmp[MAX_PROC_NAME_SIZE];
370 int fd;
372 /* This function is getting ALMOST long enough to break up into
373 several. Here is some rationale:
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. */
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. */
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 */
435 return 1; /* success */
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. */
442 static procinfo *
443 create_procinfo (int pid, int tid)
445 procinfo *pi, *parent = NULL;
447 pi = find_procinfo (pid, tid);
448 if (pi != NULL)
449 return pi; /* Already exists, nothing to do. */
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? */
457 pi = XNEW (procinfo);
458 memset (pi, 0, sizeof (procinfo));
459 pi->pid = pid;
460 pi->tid = tid;
462 pi->saved_entryset = XNEW (sysset_t);
463 pi->saved_exitset = XNEW (sysset_t);
465 /* Chain into list. */
466 if (tid == 0)
468 xsnprintf (pi->pathname, sizeof (pi->pathname), "/proc/%d", pid);
469 pi->next = procinfo_list;
470 procinfo_list = pi;
472 else
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;
479 return pi;
482 /* Close all file descriptors associated with the procinfo. */
484 static void
485 close_procinfo_files (procinfo *pi)
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;
496 /* Destructor function. Close, unlink and deallocate the object. */
498 static void
499 destroy_one_procinfo (procinfo **list, procinfo *pi)
501 procinfo *ptr;
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)
510 ptr->next = pi->next;
511 break;
514 /* Step two: close any open file descriptors. */
515 close_procinfo_files (pi);
517 /* Step three: free the memory. */
518 xfree (pi->saved_entryset);
519 xfree (pi->saved_exitset);
520 xfree (pi);
523 static void
524 destroy_procinfo (procinfo *pi)
526 procinfo *tmp;
528 if (pi->tid != 0) /* Destroy a thread procinfo. */
530 tmp = find_procinfo (pi->pid, 0); /* Find the parent process. */
531 destroy_one_procinfo (&tmp->thread_list, pi);
533 else /* Destroy a process procinfo and all its threads. */
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);
543 /* A deleter that calls destroy_procinfo. */
544 struct procinfo_deleter
546 void operator() (procinfo *pi) const
548 destroy_procinfo (pi);
552 typedef std::unique_ptr<procinfo, procinfo_deleter> procinfo_up;
554 enum { NOKILL, KILL };
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. */
560 static void
561 dead_procinfo (procinfo *pi, const char *msg, int kill_p)
563 print_sys_errmsg (pi->pathname, errno);
564 if (kill_p == KILL)
565 kill (pi->pid, SIGKILL);
567 destroy_procinfo (pi);
568 error ("%s", msg);
571 /* =================== END, STRUCT PROCINFO "MODULE" =================== */
573 /* =================== /proc "MODULE" =================== */
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.
580 The main motivation for this layer is to hide the fact that there
581 were two very different implementations of the /proc API. */
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);
593 static void
594 proc_warn (procinfo *pi, const char *func, int line)
596 xsnprintf (errmsg, sizeof (errmsg), "procfs: %s line %d, %s",
597 func, line, pi->pathname);
598 print_sys_errmsg (errmsg, errno);
601 static void
602 proc_error (procinfo *pi, const char *func, int line)
604 xsnprintf (errmsg, sizeof (errmsg), "procfs: %s line %d, %s",
605 func, line, pi->pathname);
606 perror_with_name (errmsg);
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. */
615 static int
616 proc_get_status (procinfo *pi)
618 /* Status file descriptor is opened "lazily". */
619 if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
621 pi->status_valid = 0;
622 return 0;
625 if (lseek (pi->status_fd, 0, SEEK_SET) < 0)
626 pi->status_valid = 0; /* fail */
627 else
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
638 pi->status_valid = (read (pi->status_fd,
639 (char *) &pi->prstatus,
640 sizeof (pstatus_t))
641 == sizeof (pstatus_t));
645 if (pi->status_valid)
647 PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
648 proc_why (pi),
649 proc_what (pi),
650 proc_get_current_thread (pi));
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. */
661 /* Returns the process flags (pr_flags field). */
663 static long
664 proc_flags (procinfo *pi)
666 if (!pi->status_valid)
667 if (!proc_get_status (pi))
668 return 0; /* FIXME: not a good failure value (but what is?) */
670 return pi->prstatus.pr_lwp.pr_flags;
673 /* Returns the pr_why field (why the process stopped). */
675 static int
676 proc_why (procinfo *pi)
678 if (!pi->status_valid)
679 if (!proc_get_status (pi))
680 return 0; /* FIXME: not a good failure value (but what is?) */
682 return pi->prstatus.pr_lwp.pr_why;
685 /* Returns the pr_what field (details of why the process stopped). */
687 static int
688 proc_what (procinfo *pi)
690 if (!pi->status_valid)
691 if (!proc_get_status (pi))
692 return 0; /* FIXME: not a good failure value (but what is?) */
694 return pi->prstatus.pr_lwp.pr_what;
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. */
702 static int
703 proc_watchpoint_address (procinfo *pi, CORE_ADDR *addr)
705 if (!pi->status_valid)
706 if (!proc_get_status (pi))
707 return 0;
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;
715 /* Returns the pr_nsysarg field (number of args to the current
716 syscall). */
718 static int
719 proc_nsysarg (procinfo *pi)
721 if (!pi->status_valid)
722 if (!proc_get_status (pi))
723 return 0;
725 return pi->prstatus.pr_lwp.pr_nsysarg;
728 /* Returns the pr_sysarg field (pointer to the arguments of current
729 syscall). */
731 static long *
732 proc_sysargs (procinfo *pi)
734 if (!pi->status_valid)
735 if (!proc_get_status (pi))
736 return NULL;
738 return (long *) &pi->prstatus.pr_lwp.pr_sysarg;
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.
747 This function is done using read/write [PCSET/PCRESET/PCUNSET].
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.
754 Returns non-zero for success, zero for failure. */
756 enum { FLAG_RESET, FLAG_SET };
758 static int
759 proc_modify_flag (procinfo *pi, long flag, long mode)
761 long win = 0; /* default to fail */
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. */
769 if (pi->pid != 0)
770 pi = find_procinfo_or_die (pi->pid, 0);
772 procfs_ctl_t arg[2];
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;
779 arg[1] = flag;
780 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
782 /* The above operation renders the procinfo's cached pstatus
783 obsolete. */
784 pi->status_valid = 0;
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");
795 return win;
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. */
802 static int
803 proc_set_run_on_last_close (procinfo *pi)
805 return proc_modify_flag (pi, PR_RLC, FLAG_SET);
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. */
812 static int
813 proc_unset_run_on_last_close (procinfo *pi)
815 return proc_modify_flag (pi, PR_RLC, FLAG_RESET);
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. */
823 static int
824 proc_unset_inherit_on_fork (procinfo *pi)
826 return proc_modify_flag (pi, PR_FORK, FLAG_RESET);
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. */
833 static int
834 proc_set_async (procinfo *pi)
836 return proc_modify_flag (pi, PR_ASYNC, FLAG_SET);
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. */
843 static int
844 proc_unset_async (procinfo *pi)
846 return proc_modify_flag (pi, PR_ASYNC, FLAG_RESET);
849 /* Request the process/LWP to stop. Does not wait. Returns non-zero
850 for success, zero for failure. */
852 static int
853 proc_stop_process (procinfo *pi)
855 int win;
857 /* We might conceivably apply this operation to an LWP, and the
858 LWP's ctl file descriptor might not be open. */
860 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
861 return 0;
862 else
864 procfs_ctl_t cmd = PCSTOP;
866 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
869 return win;
872 /* Wait for the process or LWP to stop (block until it does). Returns
873 non-zero for success, zero for failure. */
875 static int
876 proc_wait_for_stop (procinfo *pi)
878 int win;
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. */
885 if (pi->tid != 0)
886 pi = find_procinfo_or_die (pi->pid, 0);
888 procfs_ctl_t cmd = PCWSTOP;
890 set_sigint_trap ();
892 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
894 clear_sigint_trap ();
896 /* We been runnin' and we stopped -- need to update status. */
897 pi->status_valid = 0;
899 return win;
902 /* Make the process or LWP runnable.
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
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. */
917 static int
918 proc_run_process (procinfo *pi, int step, int signo)
920 int win;
921 int runflags;
923 /* We will probably have to apply this operation to individual
924 threads, so make sure the control file descriptor is open. */
926 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
927 return 0;
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);
937 procfs_ctl_t cmd[2];
939 cmd[0] = PCRUN;
940 cmd[1] = runflags;
941 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
943 return win;
946 /* Register to trace signals in the process or LWP. Returns non-zero
947 for success, zero for failure. */
949 static int
950 proc_set_traced_signals (procinfo *pi, sigset_t *sigset)
952 int win;
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. */
959 if (pi->tid != 0)
960 pi = find_procinfo_or_die (pi->pid, 0);
962 struct {
963 procfs_ctl_t cmd;
964 /* Use char array to avoid alignment issues. */
965 char sigset[sizeof (sigset_t)];
966 } arg;
968 arg.cmd = PCSTRACE;
969 memcpy (&arg.sigset, sigset, sizeof (sigset_t));
971 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
973 /* The above operation renders the procinfo's cached pstatus obsolete. */
974 pi->status_valid = 0;
976 if (!win)
977 warning (_("procfs: set_traced_signals failed"));
978 return win;
981 /* Register to trace hardware faults in the process or LWP. Returns
982 non-zero for success, zero for failure. */
984 static int
985 proc_set_traced_faults (procinfo *pi, fltset_t *fltset)
987 int win;
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. */
994 if (pi->tid != 0)
995 pi = find_procinfo_or_die (pi->pid, 0);
997 struct {
998 procfs_ctl_t cmd;
999 /* Use char array to avoid alignment issues. */
1000 char fltset[sizeof (fltset_t)];
1001 } arg;
1003 arg.cmd = PCSFAULT;
1004 memcpy (&arg.fltset, fltset, sizeof (fltset_t));
1006 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1008 /* The above operation renders the procinfo's cached pstatus obsolete. */
1009 pi->status_valid = 0;
1011 return win;
1014 /* Register to trace entry to system calls in the process or LWP.
1015 Returns non-zero for success, zero for failure. */
1017 static int
1018 proc_set_traced_sysentry (procinfo *pi, sysset_t *sysset)
1020 int win;
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. */
1027 if (pi->tid != 0)
1028 pi = find_procinfo_or_die (pi->pid, 0);
1030 struct {
1031 procfs_ctl_t cmd;
1032 /* Use char array to avoid alignment issues. */
1033 char sysset[sizeof (sysset_t)];
1034 } arg;
1036 arg.cmd = PCSENTRY;
1037 memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1039 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1041 /* The above operation renders the procinfo's cached pstatus
1042 obsolete. */
1043 pi->status_valid = 0;
1045 return win;
1048 /* Register to trace exit from system calls in the process or LWP.
1049 Returns non-zero for success, zero for failure. */
1051 static int
1052 proc_set_traced_sysexit (procinfo *pi, sysset_t *sysset)
1054 int win;
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. */
1061 if (pi->tid != 0)
1062 pi = find_procinfo_or_die (pi->pid, 0);
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;
1070 arg.cmd = PCSEXIT;
1071 memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1073 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1075 /* The above operation renders the procinfo's cached pstatus
1076 obsolete. */
1077 pi->status_valid = 0;
1079 return win;
1082 /* Specify the set of blocked / held signals in the process or LWP.
1083 Returns non-zero for success, zero for failure. */
1085 static int
1086 proc_set_held_signals (procinfo *pi, sigset_t *sighold)
1088 int win;
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. */
1095 if (pi->tid != 0)
1096 pi = find_procinfo_or_die (pi->pid, 0);
1098 struct {
1099 procfs_ctl_t cmd;
1100 /* Use char array to avoid alignment issues. */
1101 char hold[sizeof (sigset_t)];
1102 } arg;
1104 arg.cmd = PCSHOLD;
1105 memcpy (&arg.hold, sighold, sizeof (sigset_t));
1106 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1108 /* The above operation renders the procinfo's cached pstatus
1109 obsolete. */
1110 pi->status_valid = 0;
1112 return win;
1115 /* Returns the set of signals that are held / blocked. Will also copy
1116 the sigset if SAVE is non-zero. */
1118 static sigset_t *
1119 proc_get_held_signals (procinfo *pi, sigset_t *save)
1121 sigset_t *ret = NULL;
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. */
1128 if (pi->tid != 0)
1129 pi = find_procinfo_or_die (pi->pid, 0);
1131 if (!pi->status_valid)
1132 if (!proc_get_status (pi))
1133 return NULL;
1135 ret = &pi->prstatus.pr_lwp.pr_lwphold;
1136 if (save && ret)
1137 memcpy (save, ret, sizeof (sigset_t));
1139 return ret;
1142 /* Returns the set of signals that are traced / debugged. Will also
1143 copy the sigset if SAVE is non-zero. */
1145 static sigset_t *
1146 proc_get_traced_signals (procinfo *pi, sigset_t *save)
1148 sigset_t *ret = NULL;
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. */
1155 if (pi->tid != 0)
1156 pi = find_procinfo_or_die (pi->pid, 0);
1158 if (!pi->status_valid)
1159 if (!proc_get_status (pi))
1160 return NULL;
1162 ret = &pi->prstatus.pr_sigtrace;
1163 if (save && ret)
1164 memcpy (save, ret, sizeof (sigset_t));
1166 return ret;
1169 /* Returns the set of hardware faults that are traced /debugged. Will
1170 also copy the faultset if SAVE is non-zero. */
1172 static fltset_t *
1173 proc_get_traced_faults (procinfo *pi, fltset_t *save)
1175 fltset_t *ret = NULL;
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. */
1182 if (pi->tid != 0)
1183 pi = find_procinfo_or_die (pi->pid, 0);
1185 if (!pi->status_valid)
1186 if (!proc_get_status (pi))
1187 return NULL;
1189 ret = &pi->prstatus.pr_flttrace;
1190 if (save && ret)
1191 memcpy (save, ret, sizeof (fltset_t));
1193 return ret;
1196 /* Returns the set of syscalls that are traced /debugged on entry.
1197 Will also copy the syscall set if SAVE is non-zero. */
1199 static sysset_t *
1200 proc_get_traced_sysentry (procinfo *pi, sysset_t *save)
1202 sysset_t *ret = NULL;
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. */
1209 if (pi->tid != 0)
1210 pi = find_procinfo_or_die (pi->pid, 0);
1212 if (!pi->status_valid)
1213 if (!proc_get_status (pi))
1214 return NULL;
1216 ret = &pi->prstatus.pr_sysentry;
1217 if (save && ret)
1218 memcpy (save, ret, sizeof (sysset_t));
1220 return ret;
1223 /* Returns the set of syscalls that are traced /debugged on exit.
1224 Will also copy the syscall set if SAVE is non-zero. */
1226 static sysset_t *
1227 proc_get_traced_sysexit (procinfo *pi, sysset_t *save)
1229 sysset_t *ret = NULL;
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. */
1236 if (pi->tid != 0)
1237 pi = find_procinfo_or_die (pi->pid, 0);
1239 if (!pi->status_valid)
1240 if (!proc_get_status (pi))
1241 return NULL;
1243 ret = &pi->prstatus.pr_sysexit;
1244 if (save && ret)
1245 memcpy (save, ret, sizeof (sysset_t));
1247 return ret;
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. */
1254 static int
1255 proc_clear_current_fault (procinfo *pi)
1257 int win;
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. */
1264 if (pi->tid != 0)
1265 pi = find_procinfo_or_die (pi->pid, 0);
1267 procfs_ctl_t cmd = PCCFAULT;
1269 win = (write (pi->ctl_fd, (void *) &cmd, sizeof (cmd)) == sizeof (cmd));
1271 return win;
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. */
1282 static int
1283 proc_set_current_signal (procinfo *pi, int signo)
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;
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. */
1301 if (pi->tid != 0)
1302 pi = find_procinfo_or_die (pi->pid, 0);
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
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
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));
1325 arg.cmd = PCSSIG;
1326 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1328 return win;
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. */
1335 static int
1336 proc_clear_current_signal (procinfo *pi)
1338 int win;
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. */
1345 if (pi->tid != 0)
1346 pi = find_procinfo_or_die (pi->pid, 0);
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;
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));
1364 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1366 return win;
1369 /* Return the general-purpose registers for the process or LWP
1370 corresponding to PI. Upon failure, return NULL. */
1372 static gdb_gregset_t *
1373 proc_get_gregs (procinfo *pi)
1375 if (!pi->status_valid || !pi->gregs_valid)
1376 if (!proc_get_status (pi))
1377 return NULL;
1379 return &pi->prstatus.pr_lwp.pr_reg;
1382 /* Return the general-purpose registers for the process or LWP
1383 corresponding to PI. Upon failure, return NULL. */
1385 static gdb_fpregset_t *
1386 proc_get_fpregs (procinfo *pi)
1388 if (!pi->status_valid || !pi->fpregs_valid)
1389 if (!proc_get_status (pi))
1390 return NULL;
1392 return &pi->prstatus.pr_lwp.pr_fpreg;
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. */
1399 static int
1400 proc_set_gregs (procinfo *pi)
1402 gdb_gregset_t *gregs;
1403 int win;
1405 gregs = proc_get_gregs (pi);
1406 if (gregs == NULL)
1407 return 0; /* proc_get_regs has already warned. */
1409 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1410 return 0;
1411 else
1413 struct {
1414 procfs_ctl_t cmd;
1415 /* Use char array to avoid alignment issues. */
1416 char gregs[sizeof (gdb_gregset_t)];
1417 } arg;
1419 arg.cmd = PCSREG;
1420 memcpy (&arg.gregs, gregs, sizeof (arg.gregs));
1421 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1424 /* Policy: writing the registers invalidates our cache. */
1425 pi->gregs_valid = 0;
1426 return win;
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. */
1433 static int
1434 proc_set_fpregs (procinfo *pi)
1436 gdb_fpregset_t *fpregs;
1437 int win;
1439 fpregs = proc_get_fpregs (pi);
1440 if (fpregs == NULL)
1441 return 0; /* proc_get_fpregs has already warned. */
1443 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1444 return 0;
1445 else
1447 struct {
1448 procfs_ctl_t cmd;
1449 /* Use char array to avoid alignment issues. */
1450 char fpregs[sizeof (gdb_fpregset_t)];
1451 } arg;
1453 arg.cmd = PCSFPREG;
1454 memcpy (&arg.fpregs, fpregs, sizeof (arg.fpregs));
1455 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1458 /* Policy: writing the registers invalidates our cache. */
1459 pi->fpregs_valid = 0;
1460 return win;
1463 /* Send a signal to the proc or lwp with the semantics of "kill()".
1464 Returns non-zero for success, zero for failure. */
1466 static int
1467 proc_kill (procinfo *pi, int signo)
1469 int win;
1471 /* We might conceivably apply this operation to an LWP, and the
1472 LWP's ctl file descriptor might not be open. */
1474 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1475 return 0;
1476 else
1478 procfs_ctl_t cmd[2];
1480 cmd[0] = PCKILL;
1481 cmd[1] = signo;
1482 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
1485 return win;
1488 /* Find the pid of the process that started this one. Returns the
1489 parent process pid, or zero. */
1491 static int
1492 proc_parent_pid (procinfo *pi)
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. */
1499 if (pi->tid != 0)
1500 pi = find_procinfo_or_die (pi->pid, 0);
1502 if (!pi->status_valid)
1503 if (!proc_get_status (pi))
1504 return 0;
1506 return pi->prstatus.pr_ppid;
1509 /* Convert a target address (a.k.a. CORE_ADDR) into a host address
1510 (a.k.a void pointer)! */
1512 static void *
1513 procfs_address_to_host_pointer (CORE_ADDR addr)
1515 struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
1516 void *ptr;
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;
1524 static int
1525 proc_set_watchpoint (procinfo *pi, CORE_ADDR addr, int len, int wflags)
1527 struct {
1528 procfs_ctl_t cmd;
1529 char watch[sizeof (prwatch_t)];
1530 } arg;
1531 prwatch_t pwatch;
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));
1544 /* =============== END, non-thread part of /proc "MODULE" =============== */
1546 /* =================== Thread "MODULE" =================== */
1548 /* Returns the number of threads for the process. */
1550 static int
1551 proc_get_nthreads (procinfo *pi)
1553 if (!pi->status_valid)
1554 if (!proc_get_status (pi))
1555 return 0;
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;
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. */
1569 static int
1570 proc_get_current_thread (procinfo *pi)
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. */
1577 if (pi->tid != 0)
1578 pi = find_procinfo_or_die (pi->pid, 0);
1580 if (!pi->status_valid)
1581 if (!proc_get_status (pi))
1582 return 0;
1584 return pi->prstatus.pr_lwp.pr_lwpid;
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. */
1591 static int
1592 proc_delete_dead_threads (procinfo *parent, procinfo *thread, void *ignore)
1594 if (thread && parent) /* sanity */
1596 thread->status_valid = 0;
1597 if (!proc_get_status (thread))
1598 destroy_one_procinfo (&parent->thread_list, thread);
1600 return 0; /* keep iterating */
1603 static int
1604 proc_update_threads (procinfo *pi)
1606 char pathname[MAX_PROC_NAME_SIZE + 16];
1607 struct dirent *direntry;
1608 procinfo *thread;
1609 gdb_dir_up dirp;
1610 int lwpid;
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. */
1617 if (pi->tid != 0)
1618 pi = find_procinfo_or_die (pi->pid, 0);
1620 proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
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. */
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__);
1634 while ((direntry = readdir (dirp.get ())) != NULL)
1635 if (direntry->d_name[0] != '.') /* skip '.' and '..' */
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__);
1642 pi->threads_valid = 1;
1643 return 1;
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.
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.
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. */
1659 static int
1660 proc_iterate_over_threads (procinfo *pi,
1661 int (*func) (procinfo *, procinfo *, void *),
1662 void *ptr)
1664 procinfo *thread, *next;
1665 int retval = 0;
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. */
1672 if (pi->tid != 0)
1673 pi = find_procinfo_or_die (pi->pid, 0);
1675 for (thread = pi->thread_list; thread != NULL; thread = next)
1677 next = thread->next; /* In case thread is destroyed. */
1678 retval = (*func) (pi, thread, ptr);
1679 if (retval != 0)
1680 break;
1683 return retval;
1686 /* =================== END, Thread "MODULE" =================== */
1688 /* =================== END, /proc "MODULE" =================== */
1690 /* =================== GDB "MODULE" =================== */
1692 /* Here are all of the gdb target vector functions and their
1693 friends. */
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);
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! */
1706 static int
1707 procfs_debug_inferior (procinfo *pi)
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;
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__;
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__;
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);
1733 status = proc_set_traced_sysentry (pi, traced_syscall_entries);
1734 xfree (traced_syscall_entries);
1735 if (!status)
1736 return __LINE__;
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);
1745 status = proc_set_traced_sysexit (pi, traced_syscall_exits);
1746 xfree (traced_syscall_exits);
1747 if (!status)
1748 return __LINE__;
1750 return 0;
1753 void
1754 procfs_target::attach (const char *args, int from_tty)
1756 int pid;
1758 pid = parse_pid_to_attach (args);
1760 if (pid == getpid ())
1761 error (_("Attaching GDB to itself is not a good idea..."));
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))
1768 inf->push_target (this);
1769 unpusher.reset (this);
1772 target_announce_attach (from_tty, pid);
1774 do_attach (ptid_t (pid));
1776 /* Everything went fine, keep the target pushed. */
1777 unpusher.release ();
1780 void
1781 procfs_target::detach (inferior *inf, int from_tty)
1783 target_announce_detach (from_tty);
1785 do_detach ();
1787 switch_to_no_thread ();
1788 detach_inferior (inf);
1789 maybe_unpush_target ();
1792 static void
1793 do_attach (ptid_t ptid)
1795 procinfo *pi;
1796 struct inferior *inf;
1797 int fail;
1798 int lwpid;
1800 pi = create_procinfo (ptid.pid (), 0);
1801 if (pi == NULL)
1802 perror (_("procfs: out of memory in 'attach'"));
1804 if (!open_procinfo_files (pi, FD_CTL))
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);
1813 /* Stop the process (if it isn't already stopped). */
1814 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1816 pi->was_stopped = 1;
1817 proc_prettyprint_why (proc_why (pi), proc_what (pi), 1);
1819 else
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);
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;
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);
1845 fail = procfs_debug_inferior (pi);
1846 if (fail != 0)
1847 dead_procinfo (pi, "do_attach: failed in procfs_debug_inferior", NOKILL);
1849 inf = current_inferior ();
1850 inferior_appeared (inf, pi->pid);
1851 /* Let GDB know that the inferior was attached. */
1852 inf->attach_flag = true;
1854 /* Create a procinfo for the current lwp. */
1855 lwpid = proc_get_current_thread (pi);
1856 create_procinfo (pi->pid, lwpid);
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);
1864 static void
1865 do_detach ()
1867 procinfo *pi;
1869 /* Find procinfo for the main process. */
1870 pi = find_procinfo_or_die (inferior_ptid.pid (),
1871 0); /* FIXME: threads */
1873 if (!proc_set_traced_signals (pi, &pi->saved_sigset))
1874 proc_warn (pi, "do_detach, set_traced_signal", __LINE__);
1876 if (!proc_set_traced_faults (pi, &pi->saved_fltset))
1877 proc_warn (pi, "do_detach, set_traced_faults", __LINE__);
1879 if (!proc_set_traced_sysentry (pi, pi->saved_entryset))
1880 proc_warn (pi, "do_detach, set_traced_sysentry", __LINE__);
1882 if (!proc_set_traced_sysexit (pi, pi->saved_exitset))
1883 proc_warn (pi, "do_detach, set_traced_sysexit", __LINE__);
1885 if (!proc_set_held_signals (pi, &pi->saved_sighold))
1886 proc_warn (pi, "do_detach, set_held_signals", __LINE__);
1888 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1889 if (!(pi->was_stopped)
1890 || query (_("Was stopped when attached, make it runnable again? ")))
1892 /* Clear any pending signal. */
1893 if (!proc_clear_current_fault (pi))
1894 proc_warn (pi, "do_detach, clear_current_fault", __LINE__);
1896 if (!proc_clear_current_signal (pi))
1897 proc_warn (pi, "do_detach, clear_current_signal", __LINE__);
1899 if (!proc_set_run_on_last_close (pi))
1900 proc_warn (pi, "do_detach, set_rlc", __LINE__);
1903 destroy_procinfo (pi);
1906 /* Fetch register REGNUM from the inferior. If REGNUM is -1, do this
1907 for all registers.
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. */
1916 void
1917 procfs_target::fetch_registers (struct regcache *regcache, int regnum)
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 ();
1926 pi = find_procinfo_or_die (pid, tid);
1928 if (pi == NULL)
1929 error (_("procfs: fetch_registers failed to find procinfo for %s"),
1930 target_pid_to_str (ptid).c_str ());
1932 gregs = proc_get_gregs (pi);
1933 if (gregs == NULL)
1934 proc_error (pi, "fetch_registers, get_gregs", __LINE__);
1936 supply_gregset (regcache, (const gdb_gregset_t *) gregs);
1938 if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU? */
1940 gdb_fpregset_t *fpregs;
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. */
1947 fpregs = proc_get_fpregs (pi);
1948 if (fpregs == NULL)
1949 proc_error (pi, "fetch_registers, get_fpregs", __LINE__);
1951 supply_fpregset (regcache, (const gdb_fpregset_t *) fpregs);
1955 /* Store register REGNUM back into the inferior. If REGNUM is -1, do
1956 this for all registers.
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.
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. */
1965 void
1966 procfs_target::store_registers (struct regcache *regcache, int regnum)
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 ();
1975 pi = find_procinfo_or_die (pid, tid);
1977 if (pi == NULL)
1978 error (_("procfs: store_registers: failed to find procinfo for %s"),
1979 target_pid_to_str (ptid).c_str ());
1981 gregs = proc_get_gregs (pi);
1982 if (gregs == NULL)
1983 proc_error (pi, "store_registers, get_gregs", __LINE__);
1985 fill_gregset (regcache, gregs, regnum);
1986 if (!proc_set_gregs (pi))
1987 proc_error (pi, "store_registers, set_gregs", __LINE__);
1989 if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU? */
1991 gdb_fpregset_t *fpregs;
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. */
1998 fpregs = proc_get_fpregs (pi);
1999 if (fpregs == NULL)
2000 proc_error (pi, "store_registers, get_fpregs", __LINE__);
2002 fill_fpregset (regcache, fpregs, regnum);
2003 if (!proc_set_fpregs (pi))
2004 proc_error (pi, "store_registers, set_fpregs", __LINE__);
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. */
2014 ptid_t
2015 procfs_target::wait (ptid_t ptid, struct target_waitstatus *status,
2016 target_wait_flags options)
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;
2026 wait_again:
2028 retry++;
2029 wstat = 0;
2030 retval = ptid_t (-1);
2032 /* Find procinfo for main process. */
2034 /* procfs_target currently only supports one inferior. */
2035 inferior *inf = current_inferior ();
2037 pi = find_procinfo_or_die (inf->pid, 0);
2038 if (pi)
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;
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))
2055 /* wait_for_stop failed: has the child terminated? */
2056 if (errno == ENOENT)
2058 int wait_retval;
2060 /* /proc file not found; presumably child has terminated. */
2061 wait_retval = ::wait (&wstat); /* "wait" for the child's exit. */
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);
2072 else if (errno == EINTR)
2073 goto wait_again;
2074 else
2076 /* Unknown error from wait_for_stop. */
2077 proc_error (pi, "target_wait (wait_for_stop)", __LINE__);
2080 else
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.
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. */
2092 flags = proc_flags (pi);
2093 why = proc_why (pi);
2094 what = proc_what (pi);
2096 if (flags & (PR_STOPPED | PR_ISTOP))
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__);
2104 if (info_verbose)
2105 proc_prettyprint_why (why, what, 1);
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);
2111 switch (why) {
2112 case PR_SIGNALLED:
2113 wstat = (what << 8) | 0177;
2114 break;
2115 case PR_SYSENTRY:
2116 if (what == SYS_lwp_exit)
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;
2125 else if (what == SYS_exit)
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__);
2141 if (inf->attach_flag)
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); /* ? ? ? */
2149 else
2151 int temp = ::wait (&wstat);
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. */
2160 /* If wait returns -1, that's what we return
2161 to GDB. */
2162 if (temp < 0)
2163 retval = ptid_t (temp);
2166 else
2168 gdb_printf (_("procfs: trapped on entry to "));
2169 proc_prettyprint_syscall (proc_what (pi), 0);
2170 gdb_printf ("\n");
2172 long i, nsysargs, *sysargs;
2174 nsysargs = proc_nsysarg (pi);
2175 sysargs = proc_sysargs (pi);
2177 if (nsysargs > 0 && sysargs != NULL)
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]);
2186 /* How to keep going without returning to wfi: */
2187 target_continue_no_signal (ptid);
2188 goto wait_again;
2190 break;
2191 case PR_SYSEXIT:
2192 if (what == SYS_execve)
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;
2200 else if (what == SYS_lwp_create)
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. */
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);
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);
2220 target_continue_no_signal (ptid);
2221 goto wait_again;
2223 else if (what == SYS_lwp_exit)
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;
2232 else
2234 gdb_printf (_("procfs: trapped on exit from "));
2235 proc_prettyprint_syscall (proc_what (pi), 0);
2236 gdb_printf ("\n");
2238 long i, nsysargs, *sysargs;
2240 nsysargs = proc_nsysarg (pi);
2241 sysargs = proc_sysargs (pi);
2243 if (nsysargs > 0 && sysargs != NULL)
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]);
2252 target_continue_no_signal (ptid);
2253 goto wait_again;
2255 break;
2256 case PR_REQUESTED:
2257 #if 0 /* FIXME */
2258 wstat = (SIGSTOP << 8) | 0177;
2259 break;
2260 #else
2261 if (retry < 5)
2263 gdb_printf (_("Retry #%d:\n"), retry);
2264 pi->status_valid = 0;
2265 goto wait_again;
2267 else
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);
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);
2279 status->set_stopped (GDB_SIGNAL_0);
2280 return retval;
2282 #endif
2283 case PR_JOBCONTROL:
2284 wstat = (what << 8) | 0177;
2285 break;
2286 case PR_FAULTED:
2288 int signo = pi->prstatus.pr_lwp.pr_info.si_signo;
2289 if (signo != 0)
2290 wstat = (signo << 8) | 0177;
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;
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))
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 ());
2315 else /* Flags do not indicate STOPPED. */
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..."));
2325 if (status)
2326 *status = host_status_to_waitstatus (wstat);
2329 return retval;
2332 /* Perform a partial transfer to/from the specified object. For
2333 memory transfers, fall back to the old memory xfer functions. */
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)
2341 switch (object)
2343 case TARGET_OBJECT_MEMORY:
2344 return procfs_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2346 case TARGET_OBJECT_AUXV:
2347 return memory_xfer_auxv (this, object, annex, readbuf, writebuf,
2348 offset, len, xfered_len);
2350 default:
2351 return this->beneath ()->xfer_partial (object, annex,
2352 readbuf, writebuf, offset, len,
2353 xfered_len);
2357 /* Helper for procfs_xfer_partial that handles memory transfers.
2358 Arguments are like target_xfer_partial. */
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)
2364 procinfo *pi;
2365 int nbytes;
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)
2371 proc_warn (pi, "xfer_memory, open_proc_files", __LINE__);
2372 return TARGET_XFER_E_IO;
2375 if (lseek (pi->as_fd, (off_t) memaddr, SEEK_SET) != (off_t) memaddr)
2376 return TARGET_XFER_E_IO;
2378 if (writebuf != NULL)
2380 PROCFS_NOTE ("write memory:\n");
2381 nbytes = write (pi->as_fd, writebuf, len);
2383 else
2385 PROCFS_NOTE ("read memory:\n");
2386 nbytes = read (pi->as_fd, readbuf, len);
2388 if (nbytes <= 0)
2389 return TARGET_XFER_E_IO;
2390 *xfered_len = nbytes;
2391 return TARGET_XFER_OK;
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.
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.
2405 As this function is called by iterate_over_threads, it always
2406 returns zero (so that iterate_over_threads will keep
2407 iterating). */
2409 static int
2410 invalidate_cache (procinfo *parent, procinfo *pi, void *ptr)
2412 /* About to run the child; invalidate caches and do any other
2413 cleanup. */
2415 if (parent != NULL)
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. */
2421 close_procinfo_files (pi);
2423 pi->gregs_valid = 0;
2424 pi->fpregs_valid = 0;
2425 pi->status_valid = 0;
2426 pi->threads_valid = 0;
2428 return 0;
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).
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). */
2441 void
2442 procfs_target::resume (ptid_t ptid, int step, enum gdb_signal signo)
2444 procinfo *pi, *thread;
2445 int native_signo;
2447 /* FIXME: Check/reword. */
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. */
2456 /* Find procinfo for main process. */
2457 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2459 /* First cut: ignore pid argument. */
2460 errno = 0;
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);
2468 pi->ignore_next_sigstop = 0;
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);
2476 if (ptid.pid () != -1)
2478 /* Resume a specific thread, presumably suppressing the
2479 others. */
2480 thread = find_procinfo (ptid.pid (), ptid.lwp ());
2481 if (thread != NULL)
2483 if (thread->tid != 0)
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. */
2495 if (!proc_run_process (pi, step, native_signo))
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__);
2505 /* Set up to trace signals in the child process. */
2507 void
2508 procfs_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2510 sigset_t signals;
2511 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2512 int signo;
2514 prfillset (&signals);
2516 for (signo = 0; signo < NSIG; signo++)
2518 int target_signo = gdb_signal_from_host (signo);
2519 if (target_signo < pass_signals.size () && pass_signals[target_signo])
2520 prdelset (&signals, signo);
2523 if (!proc_set_traced_signals (pi, &signals))
2524 proc_error (pi, "pass_signals", __LINE__);
2527 /* Print status information about the child process. */
2529 void
2530 procfs_target::files_info ()
2532 struct inferior *inf = current_inferior ();
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 ());
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. */
2544 static void
2545 unconditionally_kill_inferior (procinfo *pi)
2547 int parent_pid;
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);
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? */
2559 #if 0
2560 int status, ret;
2562 ret = waitpid (pi->pid, &status, 0);
2563 #else
2564 wait (NULL);
2565 #endif
2569 /* We're done debugging it, and we want it to go away. Then we want
2570 GDB to forget all about it. */
2572 void
2573 procfs_target::kill ()
2575 if (inferior_ptid != null_ptid) /* ? */
2577 /* Find procinfo for main process. */
2578 procinfo *pi = find_procinfo (inferior_ptid.pid (), 0);
2580 if (pi)
2581 unconditionally_kill_inferior (pi);
2582 target_mourn_inferior (inferior_ptid);
2586 /* Forget we ever debugged this thing! */
2588 void
2589 procfs_target::mourn_inferior ()
2591 procinfo *pi;
2593 if (inferior_ptid != null_ptid)
2595 /* Find procinfo for main process. */
2596 pi = find_procinfo (inferior_ptid.pid (), 0);
2597 if (pi)
2598 destroy_procinfo (pi);
2601 generic_mourn_inferior ();
2603 maybe_unpush_target ();
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. */
2611 void
2612 procfs_target::procfs_init_inferior (int pid)
2614 procinfo *pi;
2615 int fail;
2616 int lwpid;
2618 pi = create_procinfo (pid, 0);
2619 if (pi == NULL)
2620 perror (_("procfs: out of memory in 'init_inferior'"));
2622 if (!open_procinfo_files (pi, FD_CTL))
2623 proc_error (pi, "init_inferior, open_proc_files", __LINE__);
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)
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);
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__);
2653 fail = procfs_debug_inferior (pi);
2654 if (fail != 0)
2655 proc_error (pi, "init_inferior (procfs_debug_inferior)", fail);
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__);
2666 /* We now have have access to the lwpid of the main thread/lwp. */
2667 lwpid = proc_get_current_thread (pi);
2669 /* Create a procinfo for the main lwp. */
2670 create_procinfo (pid, lwpid);
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));
2677 gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
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. */
2688 static void
2689 procfs_set_exec_trap (void)
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. */
2695 procinfo *pi;
2696 sysset_t *exitset;
2698 pi = create_procinfo (getpid (), 0);
2699 if (pi == NULL)
2700 perror_with_name (_("procfs: create_procinfo failed in child"));
2702 if (open_procinfo_files (pi, FD_CTL) == 0)
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);
2711 exitset = XNEW (sysset_t);
2712 premptyset (exitset);
2713 praddset (exitset, SYS_execve);
2715 if (!proc_set_traced_sysexit (pi, exitset))
2717 proc_warn (pi, "set_exec_trap, set_traced_sysexit", __LINE__);
2718 gdb_flush (gdb_stderr);
2719 _exit (127);
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__);
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__);
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);*/
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)
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).
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? */
2757 void
2758 procfs_target::create_inferior (const char *exec_file,
2759 const std::string &allargs,
2760 char **env, int from_tty)
2762 const char *shell_file = get_shell ();
2763 char *tryname;
2764 int pid;
2766 if (strchr (shell_file, '/') == NULL)
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).
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. */
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;
2798 if (path == NULL)
2799 path = "/bin:/usr/bin";
2801 tryname = (char *) alloca (strlen (path) + strlen (shell_file) + 2);
2802 for (p = path; p != NULL; p = p1 ? p1 + 1: NULL)
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;
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);
2831 shell_file = tryname;
2834 inferior *inf = current_inferior ();
2835 if (!inf->target_is_pushed (this))
2836 inf->push_target (this);
2838 pid = fork_inferior (exec_file, allargs, env, procfs_set_exec_trap,
2839 NULL, procfs_pre_trace, shell_file, NULL);
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);
2847 procfs_init_inferior (pid);
2850 /* Callback for update_thread_list. Calls "add_thread". */
2852 static int
2853 procfs_notice_thread (procinfo *pi, procinfo *thread, void *ptr)
2855 ptid_t gdb_threadid = ptid_t (pi->pid, thread->tid, 0);
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);
2861 return 0;
2864 /* Query all the threads that the target knows about, and give them
2865 back to GDB to add to its list. */
2867 void
2868 procfs_target::update_thread_list ()
2870 procinfo *pi;
2872 prune_threads ();
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);
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. */
2884 bool
2885 procfs_target::thread_alive (ptid_t ptid)
2887 int proc, thread;
2888 procinfo *pi;
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;
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))
2901 destroy_procinfo (pi);
2902 return false;
2904 /* I couldn't have got its status if it weren't alive, so it's
2905 alive. */
2906 return true;
2909 /* Convert PTID to a string. */
2911 std::string
2912 procfs_target::pid_to_str (ptid_t ptid)
2914 if (ptid.lwp () == 0)
2915 return string_printf ("process %d", ptid.pid ());
2916 else
2917 return string_printf ("LWP %ld", ptid.lwp ());
2920 /* Accepts an integer PID; Returns a string representing a file that
2921 can be opened to get the symbols for the child process. */
2923 const char *
2924 procfs_target::pid_to_exec_file (int pid)
2926 static char buf[PATH_MAX];
2927 char name[PATH_MAX];
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)
2934 /* If that fails, fall back to /proc/<proc-id>/path/a.out introduced in
2935 Solaris 10. */
2936 ssize_t len;
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';
2946 return buf;
2949 /* Insert a watchpoint. */
2951 static int
2952 procfs_set_watchpoint (ptid_t ptid, CORE_ADDR addr, int len, int rwflag,
2953 int after)
2955 int pflags = 0;
2956 procinfo *pi;
2958 pi = find_procinfo_or_die (ptid.pid () == -1 ?
2959 inferior_ptid.pid () : ptid.pid (),
2962 /* Translate from GDB's flags to /proc's. */
2963 if (len > 0) /* len == 0 means delete watchpoint. */
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;
2981 if (after) /* Stop after r/w access is completed. */
2982 pflags |= WA_TRAPAFTER;
2985 if (!proc_set_watchpoint (pi, addr, len, pflags))
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__);
2995 return 0;
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. */
3004 procfs_target::can_use_hw_breakpoint (enum bptype type, int cnt, int othertype)
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;
3016 if (sizeof (void *) != ptr_type->length ())
3017 return 0;
3019 /* Other tests here??? */
3021 return 1;
3024 /* Returns non-zero if process is stopped on a hardware watchpoint
3025 fault, else returns zero. */
3027 bool
3028 procfs_target::stopped_by_watchpoint ()
3030 procinfo *pi;
3032 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
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;
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. */
3047 bool
3048 procfs_target::stopped_data_address (CORE_ADDR *addr)
3050 procinfo *pi;
3052 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3053 return proc_watchpoint_address (pi, addr);
3057 procfs_target::insert_watchpoint (CORE_ADDR addr, int len,
3058 enum target_hw_bp_type type,
3059 struct expression *cond)
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);
3076 procfs_target::remove_watchpoint (CORE_ADDR addr, int len,
3077 enum target_hw_bp_type type,
3078 struct expression *cond)
3080 return procfs_set_watchpoint (inferior_ptid, addr, 0, 0, 0);
3084 procfs_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
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;
3094 /* Memory Mappings Functions: */
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.
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. */
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))
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;
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);
3127 scoped_fd map_fd (open (pathname, O_RDONLY));
3128 if (map_fd.get () < 0)
3129 proc_error (pi, "iterate_over_mappings (open)", __LINE__);
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__);
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__);
3142 for (prmap = prmaps; nmap > 0; prmap++, nmap--)
3144 funcstat = (*func) (prmap, child_func, data);
3145 if (funcstat != 0)
3146 return funcstat;
3149 return 0;
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. */
3156 static int
3157 find_memory_regions_callback (struct prmap *map,
3158 find_memory_region_ftype func, void *data)
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);
3170 /* External interface. Calls a callback function once for each
3171 mapped memory region in the child process, passing as arguments:
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.
3179 Stops iterating and returns the first non-zero value returned by
3180 the callback. */
3183 procfs_target::find_memory_regions (find_memory_region_ftype func, void *data)
3185 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3187 return iterate_over_mappings (pi, func, data,
3188 find_memory_regions_callback);
3191 /* Returns an ascii representation of a memory mapping's flags. */
3193 static char *
3194 mappingflags (long flags)
3196 static char asciiflags[8];
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);
3214 /* Callback function, does the actual work for 'info proc
3215 mappings'. */
3217 static int
3218 info_mappings_callback (struct prmap *map, find_memory_region_ftype ignore,
3219 void *unused)
3221 unsigned int pr_off;
3223 pr_off = (unsigned int) map->pr_offset;
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));
3240 return 0;
3243 /* Implement the "info proc mappings" subcommand. */
3245 static void
3246 info_proc_mappings (procinfo *pi, int summary)
3248 if (summary)
3249 return; /* No output for summary mode. */
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");
3267 iterate_over_mappings (pi, NULL, NULL, info_mappings_callback);
3268 gdb_printf ("\n");
3271 /* Implement the "info proc" command. */
3273 bool
3274 procfs_target::info_proc (const char *args, enum info_proc_what what)
3276 procinfo *process = NULL;
3277 procinfo *thread = NULL;
3278 char *tmp = NULL;
3279 int pid = 0;
3280 int tid = 0;
3281 int mappings = 0;
3283 switch (what)
3285 case IP_MINIMAL:
3286 break;
3288 case IP_MAPPINGS:
3289 case IP_ALL:
3290 mappings = 1;
3291 break;
3293 default:
3294 error (_("Not supported on this target."));
3297 gdb_argv built_argv (args);
3298 for (char *arg : built_argv)
3300 if (isdigit (arg[0]))
3302 pid = strtoul (arg, &tmp, 10);
3303 if (*tmp == '/')
3304 tid = strtoul (++tmp, NULL, 10);
3306 else if (arg[0] == '/')
3308 tid = strtoul (arg + 1, NULL, 10);
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
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)
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__);
3332 if (tid != 0)
3333 thread = create_procinfo (pid, tid);
3335 if (process)
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));
3345 if (thread)
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);
3353 if (mappings)
3354 info_proc_mappings (process, 0);
3356 return true;
3359 /* Modify the status of the system call identified by SYSCALLNUM in
3360 the set of syscalls that are currently traced/debugged.
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.
3365 If MODE is FLAG_SET, then traces will be enabled. Otherwise, they
3366 will be disabled. */
3368 static void
3369 proc_trace_syscalls_1 (procinfo *pi, int syscallnum, int entry_or_exit,
3370 int mode, int from_tty)
3372 sysset_t *sysset;
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);
3379 if (sysset == NULL)
3380 proc_error (pi, "proc-trace, get_traced_sysset", __LINE__);
3382 if (mode == FLAG_SET)
3383 praddset (sysset, syscallnum);
3384 else
3385 prdelset (sysset, syscallnum);
3387 if (entry_or_exit == PR_SYSENTRY)
3389 if (!proc_set_traced_sysentry (pi, sysset))
3390 proc_error (pi, "proc-trace, set_traced_sysentry", __LINE__);
3392 else
3394 if (!proc_set_traced_sysexit (pi, sysset))
3395 proc_error (pi, "proc-trace, set_traced_sysexit", __LINE__);
3399 static void
3400 proc_trace_syscalls (const char *args, int from_tty, int entry_or_exit, int mode)
3402 procinfo *pi;
3404 if (inferior_ptid.pid () <= 0)
3405 error (_("you must be debugging a process to use this command."));
3407 if (args == NULL || args[0] == 0)
3408 error_no_arg (_("system call to trace"));
3410 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3411 if (isdigit (args[0]))
3413 const int syscallnum = atoi (args);
3415 proc_trace_syscalls_1 (pi, syscallnum, entry_or_exit, mode, from_tty);
3419 static void
3420 proc_trace_sysentry_cmd (const char *args, int from_tty)
3422 proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_SET);
3425 static void
3426 proc_trace_sysexit_cmd (const char *args, int from_tty)
3428 proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_SET);
3431 static void
3432 proc_untrace_sysentry_cmd (const char *args, int from_tty)
3434 proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_RESET);
3437 static void
3438 proc_untrace_sysexit_cmd (const char *args, int from_tty)
3440 proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_RESET);
3443 void _initialize_procfs ();
3444 void
3445 _initialize_procfs ()
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."));
3456 add_inf_child_target (&the_procfs_target);
3459 /* =================== END, GDB "MODULE" =================== */
3463 /* miscellaneous stubs: */
3465 /* The following satisfy a few random symbols mostly created by the
3466 solaris threads implementation, which I will chase down later. */
3468 /* Return a pid for which we guarantee we will be able to find a
3469 'live' procinfo. */
3471 ptid_t
3472 procfs_first_available (void)
3474 return ptid_t (procinfo_list ? procinfo_list->pid : -1);
3477 /* =================== GCORE .NOTE "MODULE" =================== */
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)
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;
3489 merged_pid = ptid.lwp () << 16 | ptid.pid ();
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(). */
3496 target_fetch_registers (regcache, -1);
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)));
3513 struct procfs_corefile_thread_data
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)
3522 bfd *obfd;
3523 gdb::unique_xmalloc_ptr<char> &note_data;
3524 int *note_size;
3525 enum gdb_signal stop_signal;
3528 static int
3529 procfs_corefile_thread_callback (procinfo *pi, procinfo *thread, void *data)
3531 struct procfs_corefile_thread_data *args
3532 = (struct procfs_corefile_thread_data *) data;
3534 if (pi != NULL)
3536 ptid_t ptid = ptid_t (pi->pid, thread->tid, 0);
3538 procfs_do_thread_registers (args->obfd, ptid,
3539 args->note_data,
3540 args->note_size,
3541 args->stop_signal);
3543 return 0;
3546 static int
3547 find_signalled_thread (struct thread_info *info, void *data)
3549 if (info->stop_signal () != GDB_SIGNAL_0
3550 && info->ptid.pid () == inferior_ptid.pid ())
3551 return 1;
3553 return 0;
3556 static enum gdb_signal
3557 find_stop_signal (void)
3559 struct thread_info *info =
3560 iterate_over_threads (find_signalled_thread, NULL);
3562 if (info)
3563 return info->stop_signal ();
3564 else
3565 return GDB_SIGNAL_0;
3568 gdb::unique_xmalloc_ptr<char>
3569 procfs_target::make_corefile_notes (bfd *obfd, int *note_size)
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;
3578 if (get_exec_file (0))
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;
3585 const std::string &inf_args = current_inferior ()->args ();
3586 if (!inf_args.empty () &&
3587 inf_args.length () < ((int) sizeof (psargs) - (int) strlen (psargs)))
3589 strncat (psargs, " ",
3590 sizeof (psargs) - strlen (psargs));
3591 strncat (psargs, inf_args.c_str (),
3592 sizeof (psargs) - strlen (psargs));
3596 note_data.reset (elfcore_write_prpsinfo (obfd,
3597 note_data.release (),
3598 note_size,
3599 fname,
3600 psargs));
3602 stop_signal = find_stop_signal ();
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));
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);
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 ()));
3622 return note_data;
3624 /* =================== END GCORE .NOTE "MODULE" =================== */