gdb, testsuite: Fix return value in gdb.base/foll-fork.exp
[binutils-gdb.git] / gdb / procfs.c
blobb5bda4dfb858f7e07e9c91d117872cf4999d2755
1 /* Machine independent support for Solaris /proc (process file system) for GDB.
3 Copyright (C) 1999-2024 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 "extract-store-integer.h"
24 #include "inferior.h"
25 #include "infrun.h"
26 #include "target.h"
27 #include "gdbcore.h"
28 #include "elf-bfd.h"
29 #include "cli/cli-cmds.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"
49 #include "cli/cli-style.h"
51 /* This module provides the interface between GDB and the
52 /proc file system, which is used on many versions of Unix
53 as a means for debuggers to control other processes.
55 /proc works by imitating a file system: you open a simulated file
56 that represents the process you wish to interact with, and perform
57 operations on that "file" in order to examine or change the state
58 of the other process.
60 The most important thing to know about /proc and this module is
61 that there are two very different interfaces to /proc:
63 One that uses the ioctl system call, and another that uses read
64 and write system calls.
66 This module supports only the Solaris version of the read/write
67 interface. */
69 #include <sys/types.h>
70 #include <dirent.h>
72 #include <fcntl.h>
73 #include <unistd.h>
74 #include <sys/stat.h>
76 /* Note: procfs-utils.h must be included after the above system header
77 files, because it redefines various system calls using macros.
78 This may be incompatible with the prototype declarations. */
80 #include "proc-utils.h"
82 /* Prototypes for supply_gregset etc. */
83 #include "gregset.h"
85 /* =================== TARGET_OPS "MODULE" =================== */
87 /* This module defines the GDB target vector and its methods. */
90 static enum target_xfer_status procfs_xfer_memory (gdb_byte *,
91 const gdb_byte *,
92 ULONGEST, ULONGEST,
93 ULONGEST *);
95 class procfs_target final : public inf_child_target
97 public:
98 void create_inferior (const char *, const std::string &,
99 char **, int) override;
101 void kill () override;
103 void mourn_inferior () override;
105 void attach (const char *, int) override;
106 void detach (inferior *inf, int) override;
108 void resume (ptid_t, int, enum gdb_signal) override;
109 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
111 void fetch_registers (struct regcache *, int) override;
112 void store_registers (struct regcache *, int) override;
114 enum target_xfer_status xfer_partial (enum target_object object,
115 const char *annex,
116 gdb_byte *readbuf,
117 const gdb_byte *writebuf,
118 ULONGEST offset, ULONGEST len,
119 ULONGEST *xfered_len) override;
121 void pass_signals (gdb::array_view<const unsigned char>) override;
123 void files_info () override;
125 void update_thread_list () override;
127 bool thread_alive (ptid_t ptid) override;
129 std::string pid_to_str (ptid_t) override;
131 const char *pid_to_exec_file (int pid) override;
133 thread_control_capabilities get_thread_control_capabilities () override
134 { return tc_schedlock; }
136 /* find_memory_regions support method for gcore */
137 int find_memory_regions (find_memory_region_ftype func, void *data)
138 override;
140 gdb::unique_xmalloc_ptr<char> make_corefile_notes (bfd *, int *) override;
142 bool info_proc (const char *, enum info_proc_what) override;
144 #if PR_MODEL_NATIVE == PR_MODEL_LP64
145 int auxv_parse (const gdb_byte **readptr,
146 const gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
147 override;
148 #endif
150 bool stopped_by_watchpoint () override;
152 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
153 struct expression *) override;
155 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
156 struct expression *) override;
158 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
160 int can_use_hw_breakpoint (enum bptype, int, int) override;
161 bool stopped_data_address (CORE_ADDR *) override;
163 void procfs_init_inferior (int pid);
166 static procfs_target the_procfs_target;
168 #if PR_MODEL_NATIVE == PR_MODEL_LP64
169 /* When GDB is built as 64-bit application on Solaris, the auxv data
170 is presented in 64-bit format. We need to provide a custom parser
171 to handle that. */
173 procfs_target::auxv_parse (const gdb_byte **readptr,
174 const gdb_byte *endptr, CORE_ADDR *typep,
175 CORE_ADDR *valp)
177 bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
178 const gdb_byte *ptr = *readptr;
180 if (endptr == ptr)
181 return 0;
183 if (endptr - ptr < 8 * 2)
184 return -1;
186 *typep = extract_unsigned_integer (ptr, 4, byte_order);
187 ptr += 8;
188 /* The size of data is always 64-bit. If the application is 32-bit,
189 it will be zero extended, as expected. */
190 *valp = extract_unsigned_integer (ptr, 8, byte_order);
191 ptr += 8;
193 *readptr = ptr;
194 return 1;
196 #endif
198 /* =================== END, TARGET_OPS "MODULE" =================== */
200 /* =================== STRUCT PROCINFO "MODULE" =================== */
202 /* FIXME: this comment will soon be out of date W.R.T. threads. */
204 /* The procinfo struct is a wrapper to hold all the state information
205 concerning a /proc process. There should be exactly one procinfo
206 for each process, and since GDB currently can debug only one
207 process at a time, that means there should be only one procinfo.
208 All of the LWP's of a process can be accessed indirectly thru the
209 single process procinfo.
211 However, against the day when GDB may debug more than one process,
212 this data structure is kept in a list (which for now will hold no
213 more than one member), and many functions will have a pointer to a
214 procinfo as an argument.
216 There will be a separate procinfo structure for use by the (not yet
217 implemented) "info proc" command, so that we can print useful
218 information about any random process without interfering with the
219 inferior's procinfo information. */
221 /* format strings for /proc paths */
222 #define CTL_PROC_NAME_FMT "/proc/%d/ctl"
223 #define AS_PROC_NAME_FMT "/proc/%d/as"
224 #define MAP_PROC_NAME_FMT "/proc/%d/map"
225 #define STATUS_PROC_NAME_FMT "/proc/%d/status"
226 #define MAX_PROC_NAME_SIZE sizeof("/proc/999999/lwp/0123456789/lwpstatus")
228 typedef struct procinfo {
229 struct procinfo *next;
230 int pid; /* Process ID */
231 int tid; /* Thread/LWP id */
233 /* process state */
234 int was_stopped;
235 int ignore_next_sigstop;
237 int ctl_fd; /* File descriptor for /proc control file */
238 int status_fd; /* File descriptor for /proc status file */
239 int as_fd; /* File descriptor for /proc as file */
241 char pathname[MAX_PROC_NAME_SIZE]; /* Pathname to /proc entry */
243 fltset_t saved_fltset; /* Saved traced hardware fault set */
244 sigset_t saved_sigset; /* Saved traced signal set */
245 sigset_t saved_sighold; /* Saved held signal set */
246 sysset_t *saved_exitset; /* Saved traced system call exit set */
247 sysset_t *saved_entryset; /* Saved traced system call entry set */
249 pstatus_t prstatus; /* Current process status info */
251 struct procinfo *thread_list;
253 int status_valid : 1;
254 int gregs_valid : 1;
255 int fpregs_valid : 1;
256 int threads_valid: 1;
257 } procinfo;
259 /* Function prototypes for procinfo module: */
261 static procinfo *find_procinfo_or_die (int pid, int tid);
262 static procinfo *find_procinfo (int pid, int tid);
263 static procinfo *create_procinfo (int pid, int tid);
264 static void destroy_procinfo (procinfo *p);
265 static void dead_procinfo (procinfo *p, const char *msg, int killp);
266 static int open_procinfo_files (procinfo *p, int which);
267 static void close_procinfo_files (procinfo *p);
269 static int iterate_over_mappings
270 (procinfo *pi, find_memory_region_ftype child_func, void *data,
271 int (*func) (struct prmap *map, find_memory_region_ftype child_func,
272 void *data));
274 /* The head of the procinfo list: */
275 static procinfo *procinfo_list;
277 /* Search the procinfo list. Return a pointer to procinfo, or NULL if
278 not found. */
280 static procinfo *
281 find_procinfo (int pid, int tid)
283 procinfo *pi;
285 for (pi = procinfo_list; pi; pi = pi->next)
286 if (pi->pid == pid)
287 break;
289 if (pi)
290 if (tid)
292 /* Don't check threads_valid. If we're updating the
293 thread_list, we want to find whatever threads are already
294 here. This means that in general it is the caller's
295 responsibility to check threads_valid and update before
296 calling find_procinfo, if the caller wants to find a new
297 thread. */
299 for (pi = pi->thread_list; pi; pi = pi->next)
300 if (pi->tid == tid)
301 break;
304 return pi;
307 /* Calls find_procinfo, but errors on failure. */
309 static procinfo *
310 find_procinfo_or_die (int pid, int tid)
312 procinfo *pi = find_procinfo (pid, tid);
314 if (pi == NULL)
316 if (tid)
317 error (_("procfs: couldn't find pid %d "
318 "(kernel thread %d) in procinfo list."),
319 pid, tid);
320 else
321 error (_("procfs: couldn't find pid %d in procinfo list."), pid);
323 return pi;
326 /* Wrapper for `open'. The appropriate open call is attempted; if
327 unsuccessful, it will be retried as many times as needed for the
328 EAGAIN and EINTR conditions.
330 For other conditions, retry the open a limited number of times. In
331 addition, a short sleep is imposed prior to retrying the open. The
332 reason for this sleep is to give the kernel a chance to catch up
333 and create the file in question in the event that GDB "wins" the
334 race to open a file before the kernel has created it. */
336 static int
337 open_with_retry (const char *pathname, int flags)
339 int retries_remaining, status;
341 retries_remaining = 2;
343 while (1)
345 status = open (pathname, flags);
347 if (status >= 0 || retries_remaining == 0)
348 break;
349 else if (errno != EINTR && errno != EAGAIN)
351 retries_remaining--;
352 sleep (1);
356 return status;
359 /* Open the file descriptor for the process or LWP. We only open the
360 control file descriptor; the others are opened lazily as needed.
361 Returns the file descriptor, or zero for failure. */
363 enum { FD_CTL, FD_STATUS, FD_AS };
365 static int
366 open_procinfo_files (procinfo *pi, int which)
368 char tmp[MAX_PROC_NAME_SIZE];
369 int fd;
371 /* This function is getting ALMOST long enough to break up into
372 several. Here is some rationale:
374 There are several file descriptors that may need to be open
375 for any given process or LWP. The ones we're interested in are:
376 - control (ctl) write-only change the state
377 - status (status) read-only query the state
378 - address space (as) read/write access memory
379 - map (map) read-only virtual addr map
380 Most of these are opened lazily as they are needed.
381 The pathnames for the 'files' for an LWP look slightly
382 different from those of a first-class process:
383 Pathnames for a process (<proc-id>):
384 /proc/<proc-id>/ctl
385 /proc/<proc-id>/status
386 /proc/<proc-id>/as
387 /proc/<proc-id>/map
388 Pathnames for an LWP (lwp-id):
389 /proc/<proc-id>/lwp/<lwp-id>/lwpctl
390 /proc/<proc-id>/lwp/<lwp-id>/lwpstatus
391 An LWP has no map or address space file descriptor, since
392 the memory map and address space are shared by all LWPs. */
394 /* In this case, there are several different file descriptors that
395 we might be asked to open. The control file descriptor will be
396 opened early, but the others will be opened lazily as they are
397 needed. */
399 strcpy (tmp, pi->pathname);
400 switch (which) { /* Which file descriptor to open? */
401 case FD_CTL:
402 if (pi->tid)
403 strcat (tmp, "/lwpctl");
404 else
405 strcat (tmp, "/ctl");
406 fd = open_with_retry (tmp, O_WRONLY);
407 if (fd < 0)
408 return 0; /* fail */
409 pi->ctl_fd = fd;
410 break;
411 case FD_AS:
412 if (pi->tid)
413 return 0; /* There is no 'as' file descriptor for an lwp. */
414 strcat (tmp, "/as");
415 fd = open_with_retry (tmp, O_RDWR);
416 if (fd < 0)
417 return 0; /* fail */
418 pi->as_fd = fd;
419 break;
420 case FD_STATUS:
421 if (pi->tid)
422 strcat (tmp, "/lwpstatus");
423 else
424 strcat (tmp, "/status");
425 fd = open_with_retry (tmp, O_RDONLY);
426 if (fd < 0)
427 return 0; /* fail */
428 pi->status_fd = fd;
429 break;
430 default:
431 return 0; /* unknown file descriptor */
434 return 1; /* success */
437 /* Allocate a data structure and link it into the procinfo list.
438 First tries to find a pre-existing one (FIXME: why?). Returns the
439 pointer to new procinfo struct. */
441 static procinfo *
442 create_procinfo (int pid, int tid)
444 procinfo *pi, *parent = NULL;
446 pi = find_procinfo (pid, tid);
447 if (pi != NULL)
448 return pi; /* Already exists, nothing to do. */
450 /* Find parent before doing malloc, to save having to cleanup. */
451 if (tid != 0)
452 parent = find_procinfo_or_die (pid, 0); /* FIXME: should I
453 create it if it
454 doesn't exist yet? */
456 pi = XNEW (procinfo);
457 memset (pi, 0, sizeof (procinfo));
458 pi->pid = pid;
459 pi->tid = tid;
461 pi->saved_entryset = XNEW (sysset_t);
462 pi->saved_exitset = XNEW (sysset_t);
464 /* Chain into list. */
465 if (tid == 0)
467 xsnprintf (pi->pathname, sizeof (pi->pathname), "/proc/%d", pid);
468 pi->next = procinfo_list;
469 procinfo_list = pi;
471 else
473 xsnprintf (pi->pathname, sizeof (pi->pathname), "/proc/%d/lwp/%d",
474 pid, tid);
475 pi->next = parent->thread_list;
476 parent->thread_list = pi;
478 return pi;
481 /* Close all file descriptors associated with the procinfo. */
483 static void
484 close_procinfo_files (procinfo *pi)
486 if (pi->ctl_fd > 0)
487 close (pi->ctl_fd);
488 if (pi->as_fd > 0)
489 close (pi->as_fd);
490 if (pi->status_fd > 0)
491 close (pi->status_fd);
492 pi->ctl_fd = pi->as_fd = pi->status_fd = 0;
495 /* Destructor function. Close, unlink and deallocate the object. */
497 static void
498 destroy_one_procinfo (procinfo **list, procinfo *pi)
500 procinfo *ptr;
502 /* Step one: unlink the procinfo from its list. */
503 if (pi == *list)
504 *list = pi->next;
505 else
506 for (ptr = *list; ptr; ptr = ptr->next)
507 if (ptr->next == pi)
509 ptr->next = pi->next;
510 break;
513 /* Step two: close any open file descriptors. */
514 close_procinfo_files (pi);
516 /* Step three: free the memory. */
517 xfree (pi->saved_entryset);
518 xfree (pi->saved_exitset);
519 xfree (pi);
522 static void
523 destroy_procinfo (procinfo *pi)
525 procinfo *tmp;
527 if (pi->tid != 0) /* Destroy a thread procinfo. */
529 tmp = find_procinfo (pi->pid, 0); /* Find the parent process. */
530 destroy_one_procinfo (&tmp->thread_list, pi);
532 else /* Destroy a process procinfo and all its threads. */
534 /* First destroy the children, if any; */
535 while (pi->thread_list != NULL)
536 destroy_one_procinfo (&pi->thread_list, pi->thread_list);
537 /* Then destroy the parent. Genocide!!! */
538 destroy_one_procinfo (&procinfo_list, pi);
542 /* A deleter that calls destroy_procinfo. */
543 struct procinfo_deleter
545 void operator() (procinfo *pi) const
547 destroy_procinfo (pi);
551 typedef std::unique_ptr<procinfo, procinfo_deleter> procinfo_up;
553 enum { NOKILL, KILL };
555 /* To be called on a non_recoverable error for a procinfo. Prints
556 error messages, optionally sends a SIGKILL to the process, then
557 destroys the data structure. */
559 static void
560 dead_procinfo (procinfo *pi, const char *msg, int kill_p)
562 warning_filename_and_errno (pi->pathname, errno);
563 if (kill_p == KILL)
564 kill (pi->pid, SIGKILL);
566 destroy_procinfo (pi);
567 error ("%s", msg);
570 /* =================== END, STRUCT PROCINFO "MODULE" =================== */
572 /* =================== /proc "MODULE" =================== */
574 /* This "module" is the interface layer between the /proc system API
575 and the gdb target vector functions. This layer consists of access
576 functions that encapsulate each of the basic operations that we
577 need to use from the /proc API.
579 The main motivation for this layer is to hide the fact that there
580 were two very different implementations of the /proc API. */
582 static long proc_flags (procinfo *pi);
583 static int proc_why (procinfo *pi);
584 static int proc_what (procinfo *pi);
585 static int proc_set_current_signal (procinfo *pi, int signo);
586 static int proc_get_current_thread (procinfo *pi);
587 static int proc_iterate_over_threads
588 (procinfo *pi,
589 int (*func) (procinfo *, procinfo *, void *),
590 void *ptr);
591 static void proc_resume (procinfo *pi, ptid_t scope_ptid,
592 int step, enum gdb_signal signo);
594 static void
595 proc_warn (procinfo *pi, const char *func, int line)
597 int saved_errno = errno;
598 warning ("procfs: %s line %d, %ps: %s",
599 func, line, styled_string (file_name_style.style (),
600 pi->pathname),
601 safe_strerror (saved_errno));
604 static void
605 proc_error (procinfo *pi, const char *func, int line)
607 int saved_errno = errno;
608 error ("procfs: %s line %d, %s: %s",
609 func, line, pi->pathname, safe_strerror (saved_errno));
612 /* Updates the status struct in the procinfo. There is a 'valid'
613 flag, to let other functions know when this function needs to be
614 called (so the status is only read when it is needed). The status
615 file descriptor is also only opened when it is needed. Returns
616 non-zero for success, zero for failure. */
618 static int
619 proc_get_status (procinfo *pi)
621 /* Status file descriptor is opened "lazily". */
622 if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
624 pi->status_valid = 0;
625 return 0;
628 if (lseek (pi->status_fd, 0, SEEK_SET) < 0)
629 pi->status_valid = 0; /* fail */
630 else
632 /* Sigh... I have to read a different data structure,
633 depending on whether this is a main process or an LWP. */
634 if (pi->tid)
635 pi->status_valid = (read (pi->status_fd,
636 (char *) &pi->prstatus.pr_lwp,
637 sizeof (lwpstatus_t))
638 == sizeof (lwpstatus_t));
639 else
641 pi->status_valid = (read (pi->status_fd,
642 (char *) &pi->prstatus,
643 sizeof (pstatus_t))
644 == sizeof (pstatus_t));
648 if (pi->status_valid)
650 PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
651 proc_why (pi),
652 proc_what (pi),
653 proc_get_current_thread (pi));
656 /* The status struct includes general regs, so mark them valid too. */
657 pi->gregs_valid = pi->status_valid;
658 /* In the read/write multiple-fd model, the status struct includes
659 the fp regs too, so mark them valid too. */
660 pi->fpregs_valid = pi->status_valid;
661 return pi->status_valid; /* True if success, false if failure. */
664 /* Returns the process flags (pr_flags field). */
666 static long
667 proc_flags (procinfo *pi)
669 if (!pi->status_valid)
670 if (!proc_get_status (pi))
671 return 0; /* FIXME: not a good failure value (but what is?) */
673 return pi->prstatus.pr_lwp.pr_flags;
676 /* Returns the pr_why field (why the process stopped). */
678 static int
679 proc_why (procinfo *pi)
681 if (!pi->status_valid)
682 if (!proc_get_status (pi))
683 return 0; /* FIXME: not a good failure value (but what is?) */
685 return pi->prstatus.pr_lwp.pr_why;
688 /* Returns the pr_what field (details of why the process stopped). */
690 static int
691 proc_what (procinfo *pi)
693 if (!pi->status_valid)
694 if (!proc_get_status (pi))
695 return 0; /* FIXME: not a good failure value (but what is?) */
697 return pi->prstatus.pr_lwp.pr_what;
700 /* This function is only called when PI is stopped by a watchpoint.
701 Assuming the OS supports it, write to *ADDR the data address which
702 triggered it and return 1. Return 0 if it is not possible to know
703 the address. */
705 static int
706 proc_watchpoint_address (procinfo *pi, CORE_ADDR *addr)
708 if (!pi->status_valid)
709 if (!proc_get_status (pi))
710 return 0;
712 gdbarch *arch = current_inferior ()->arch ();
713 *addr = gdbarch_pointer_to_address
714 (arch, builtin_type (arch)->builtin_data_ptr,
715 (gdb_byte *) &pi->prstatus.pr_lwp.pr_info.si_addr);
716 return 1;
719 /* Returns the pr_nsysarg field (number of args to the current
720 syscall). */
722 static int
723 proc_nsysarg (procinfo *pi)
725 if (!pi->status_valid)
726 if (!proc_get_status (pi))
727 return 0;
729 return pi->prstatus.pr_lwp.pr_nsysarg;
732 /* Returns the pr_sysarg field (pointer to the arguments of current
733 syscall). */
735 static long *
736 proc_sysargs (procinfo *pi)
738 if (!pi->status_valid)
739 if (!proc_get_status (pi))
740 return NULL;
742 return (long *) &pi->prstatus.pr_lwp.pr_sysarg;
745 /* Set or reset any of the following process flags:
746 PR_FORK -- forked child will inherit trace flags
747 PR_RLC -- traced process runs when last /proc file closed.
748 PR_KLC -- traced process is killed when last /proc file closed.
749 PR_ASYNC -- LWP's get to run/stop independently.
751 This function is done using read/write [PCSET/PCRESET/PCUNSET].
753 Arguments:
754 pi -- the procinfo
755 flag -- one of PR_FORK, PR_RLC, or PR_ASYNC
756 mode -- 1 for set, 0 for reset.
758 Returns non-zero for success, zero for failure. */
760 enum { FLAG_RESET, FLAG_SET };
762 static int
763 proc_modify_flag (procinfo *pi, long flag, long mode)
765 long win = 0; /* default to fail */
767 /* These operations affect the process as a whole, and applying them
768 to an individual LWP has the same meaning as applying them to the
769 main process. Therefore, if we're ever called with a pointer to
770 an LWP's procinfo, let's substitute the process's procinfo and
771 avoid opening the LWP's file descriptor unnecessarily. */
773 if (pi->pid != 0)
774 pi = find_procinfo_or_die (pi->pid, 0);
776 procfs_ctl_t arg[2];
778 if (mode == FLAG_SET) /* Set the flag (RLC, FORK, or ASYNC). */
779 arg[0] = PCSET;
780 else /* Reset the flag. */
781 arg[0] = PCUNSET;
783 arg[1] = flag;
784 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
786 /* The above operation renders the procinfo's cached pstatus
787 obsolete. */
788 pi->status_valid = 0;
790 if (!win)
791 warning (_("procfs: modify_flag failed to turn %s %s"),
792 flag == PR_FORK ? "PR_FORK" :
793 flag == PR_RLC ? "PR_RLC" :
794 flag == PR_ASYNC ? "PR_ASYNC" :
795 flag == PR_KLC ? "PR_KLC" :
796 "<unknown flag>",
797 mode == FLAG_RESET ? "off" : "on");
799 return win;
802 /* Set the run_on_last_close flag. Process with all threads will
803 become runnable when debugger closes all /proc fds. Returns
804 non-zero for success, zero for failure. */
806 static int
807 proc_set_run_on_last_close (procinfo *pi)
809 return proc_modify_flag (pi, PR_RLC, FLAG_SET);
812 /* Reset the run_on_last_close flag. The process will NOT become
813 runnable when debugger closes its file handles. Returns non-zero
814 for success, zero for failure. */
816 static int
817 proc_unset_run_on_last_close (procinfo *pi)
819 return proc_modify_flag (pi, PR_RLC, FLAG_RESET);
822 /* Reset inherit_on_fork flag. If the process forks a child while we
823 are registered for events in the parent, then we will NOT receive
824 events from the child. Returns non-zero for success, zero for
825 failure. */
827 static int
828 proc_unset_inherit_on_fork (procinfo *pi)
830 return proc_modify_flag (pi, PR_FORK, FLAG_RESET);
833 /* Set PR_ASYNC flag. If one LWP stops because of a debug event
834 (signal etc.), the remaining LWPs will continue to run. Returns
835 non-zero for success, zero for failure. */
837 static int
838 proc_set_async (procinfo *pi)
840 return proc_modify_flag (pi, PR_ASYNC, FLAG_SET);
843 /* Reset PR_ASYNC flag. If one LWP stops because of a debug event
844 (signal etc.), then all other LWPs will stop as well. Returns
845 non-zero for success, zero for failure. */
847 static int
848 proc_unset_async (procinfo *pi)
850 return proc_modify_flag (pi, PR_ASYNC, FLAG_RESET);
853 /* Request the process/LWP to stop. Does not wait. Returns non-zero
854 for success, zero for failure. */
856 static int
857 proc_stop_process (procinfo *pi)
859 int win;
861 /* We might conceivably apply this operation to an LWP, and the
862 LWP's ctl file descriptor might not be open. */
864 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
865 return 0;
866 else
868 procfs_ctl_t cmd = PCSTOP;
870 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
873 return win;
876 /* Wait for the process or LWP to stop (block until it does). Returns
877 non-zero for success, zero for failure. */
879 static int
880 proc_wait_for_stop (procinfo *pi)
882 int win;
884 /* We should never have to apply this operation to any procinfo
885 except the one for the main process. If that ever changes for
886 any reason, then take out the following clause and replace it
887 with one that makes sure the ctl_fd is open. */
889 if (pi->tid != 0)
890 pi = find_procinfo_or_die (pi->pid, 0);
892 procfs_ctl_t cmd = PCWSTOP;
894 set_sigint_trap ();
896 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
898 clear_sigint_trap ();
900 /* We been runnin' and we stopped -- need to update status. */
901 pi->status_valid = 0;
903 return win;
906 /* Make the process or LWP runnable.
908 Options (not all are implemented):
909 - single-step
910 - clear current fault
911 - clear current signal
912 - abort the current system call
913 - stop as soon as finished with system call
915 Always clears the current fault. PI is the process or LWP to
916 operate on. If STEP is true, set the process or LWP to trap after
917 one instruction. If SIGNO is zero, clear the current signal if
918 any; if non-zero, set the current signal to this one. Returns
919 non-zero for success, zero for failure. */
921 static int
922 proc_run_process (procinfo *pi, int step, int signo)
924 int win;
925 int runflags;
927 /* We will probably have to apply this operation to individual
928 threads, so make sure the control file descriptor is open. */
930 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
931 return 0;
933 runflags = PRCFAULT; /* Always clear current fault. */
934 if (step)
935 runflags |= PRSTEP;
936 if (signo == 0)
937 runflags |= PRCSIG;
938 else if (signo != -1) /* -1 means do nothing W.R.T. signals. */
939 proc_set_current_signal (pi, signo);
941 procfs_ctl_t cmd[2];
943 cmd[0] = PCRUN;
944 cmd[1] = runflags;
945 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
947 return win;
950 /* Register to trace signals in the process or LWP. Returns non-zero
951 for success, zero for failure. */
953 static int
954 proc_set_traced_signals (procinfo *pi, sigset_t *sigset)
956 int win;
958 /* We should never have to apply this operation to any procinfo
959 except the one for the main process. If that ever changes for
960 any reason, then take out the following clause and replace it
961 with one that makes sure the ctl_fd is open. */
963 if (pi->tid != 0)
964 pi = find_procinfo_or_die (pi->pid, 0);
966 struct {
967 procfs_ctl_t cmd;
968 /* Use char array to avoid alignment issues. */
969 char sigset[sizeof (sigset_t)];
970 } arg;
972 arg.cmd = PCSTRACE;
973 memcpy (&arg.sigset, sigset, sizeof (sigset_t));
975 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
977 /* The above operation renders the procinfo's cached pstatus obsolete. */
978 pi->status_valid = 0;
980 if (!win)
981 warning (_("procfs: set_traced_signals failed"));
982 return win;
985 /* Register to trace hardware faults in the process or LWP. Returns
986 non-zero for success, zero for failure. */
988 static int
989 proc_set_traced_faults (procinfo *pi, fltset_t *fltset)
991 int win;
993 /* We should never have to apply this operation to any procinfo
994 except the one for the main process. If that ever changes for
995 any reason, then take out the following clause and replace it
996 with one that makes sure the ctl_fd is open. */
998 if (pi->tid != 0)
999 pi = find_procinfo_or_die (pi->pid, 0);
1001 struct {
1002 procfs_ctl_t cmd;
1003 /* Use char array to avoid alignment issues. */
1004 char fltset[sizeof (fltset_t)];
1005 } arg;
1007 arg.cmd = PCSFAULT;
1008 memcpy (&arg.fltset, fltset, sizeof (fltset_t));
1010 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1012 /* The above operation renders the procinfo's cached pstatus obsolete. */
1013 pi->status_valid = 0;
1015 return win;
1018 /* Register to trace entry to system calls in the process or LWP.
1019 Returns non-zero for success, zero for failure. */
1021 static int
1022 proc_set_traced_sysentry (procinfo *pi, sysset_t *sysset)
1024 int win;
1026 /* We should never have to apply this operation to any procinfo
1027 except the one for the main process. If that ever changes for
1028 any reason, then take out the following clause and replace it
1029 with one that makes sure the ctl_fd is open. */
1031 if (pi->tid != 0)
1032 pi = find_procinfo_or_die (pi->pid, 0);
1034 struct {
1035 procfs_ctl_t cmd;
1036 /* Use char array to avoid alignment issues. */
1037 char sysset[sizeof (sysset_t)];
1038 } arg;
1040 arg.cmd = PCSENTRY;
1041 memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1043 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1045 /* The above operation renders the procinfo's cached pstatus
1046 obsolete. */
1047 pi->status_valid = 0;
1049 return win;
1052 /* Register to trace exit from system calls in the process or LWP.
1053 Returns non-zero for success, zero for failure. */
1055 static int
1056 proc_set_traced_sysexit (procinfo *pi, sysset_t *sysset)
1058 int win;
1060 /* We should never have to apply this operation to any procinfo
1061 except the one for the main process. If that ever changes for
1062 any reason, then take out the following clause and replace it
1063 with one that makes sure the ctl_fd is open. */
1065 if (pi->tid != 0)
1066 pi = find_procinfo_or_die (pi->pid, 0);
1068 struct gdb_proc_ctl_pcsexit {
1069 procfs_ctl_t cmd;
1070 /* Use char array to avoid alignment issues. */
1071 char sysset[sizeof (sysset_t)];
1072 } arg;
1074 arg.cmd = PCSEXIT;
1075 memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1077 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1079 /* The above operation renders the procinfo's cached pstatus
1080 obsolete. */
1081 pi->status_valid = 0;
1083 return win;
1086 /* Specify the set of blocked / held signals in the process or LWP.
1087 Returns non-zero for success, zero for failure. */
1089 static int
1090 proc_set_held_signals (procinfo *pi, sigset_t *sighold)
1092 int win;
1094 /* We should never have to apply this operation to any procinfo
1095 except the one for the main process. If that ever changes for
1096 any reason, then take out the following clause and replace it
1097 with one that makes sure the ctl_fd is open. */
1099 if (pi->tid != 0)
1100 pi = find_procinfo_or_die (pi->pid, 0);
1102 struct {
1103 procfs_ctl_t cmd;
1104 /* Use char array to avoid alignment issues. */
1105 char hold[sizeof (sigset_t)];
1106 } arg;
1108 arg.cmd = PCSHOLD;
1109 memcpy (&arg.hold, sighold, sizeof (sigset_t));
1110 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1112 /* The above operation renders the procinfo's cached pstatus
1113 obsolete. */
1114 pi->status_valid = 0;
1116 return win;
1119 /* Returns the set of signals that are held / blocked. Will also copy
1120 the sigset if SAVE is non-zero. */
1122 static sigset_t *
1123 proc_get_held_signals (procinfo *pi, sigset_t *save)
1125 sigset_t *ret = NULL;
1127 /* We should never have to apply this operation to any procinfo
1128 except the one for the main process. If that ever changes for
1129 any reason, then take out the following clause and replace it
1130 with one that makes sure the ctl_fd is open. */
1132 if (pi->tid != 0)
1133 pi = find_procinfo_or_die (pi->pid, 0);
1135 if (!pi->status_valid)
1136 if (!proc_get_status (pi))
1137 return NULL;
1139 ret = &pi->prstatus.pr_lwp.pr_lwphold;
1140 if (save && ret)
1141 memcpy (save, ret, sizeof (sigset_t));
1143 return ret;
1146 /* Returns the set of signals that are traced / debugged. Will also
1147 copy the sigset if SAVE is non-zero. */
1149 static sigset_t *
1150 proc_get_traced_signals (procinfo *pi, sigset_t *save)
1152 sigset_t *ret = NULL;
1154 /* We should never have to apply this operation to any procinfo
1155 except the one for the main process. If that ever changes for
1156 any reason, then take out the following clause and replace it
1157 with one that makes sure the ctl_fd is open. */
1159 if (pi->tid != 0)
1160 pi = find_procinfo_or_die (pi->pid, 0);
1162 if (!pi->status_valid)
1163 if (!proc_get_status (pi))
1164 return NULL;
1166 ret = &pi->prstatus.pr_sigtrace;
1167 if (save && ret)
1168 memcpy (save, ret, sizeof (sigset_t));
1170 return ret;
1173 /* Returns the set of hardware faults that are traced /debugged. Will
1174 also copy the faultset if SAVE is non-zero. */
1176 static fltset_t *
1177 proc_get_traced_faults (procinfo *pi, fltset_t *save)
1179 fltset_t *ret = NULL;
1181 /* We should never have to apply this operation to any procinfo
1182 except the one for the main process. If that ever changes for
1183 any reason, then take out the following clause and replace it
1184 with one that makes sure the ctl_fd is open. */
1186 if (pi->tid != 0)
1187 pi = find_procinfo_or_die (pi->pid, 0);
1189 if (!pi->status_valid)
1190 if (!proc_get_status (pi))
1191 return NULL;
1193 ret = &pi->prstatus.pr_flttrace;
1194 if (save && ret)
1195 memcpy (save, ret, sizeof (fltset_t));
1197 return ret;
1200 /* Returns the set of syscalls that are traced /debugged on entry.
1201 Will also copy the syscall set if SAVE is non-zero. */
1203 static sysset_t *
1204 proc_get_traced_sysentry (procinfo *pi, sysset_t *save)
1206 sysset_t *ret = NULL;
1208 /* We should never have to apply this operation to any procinfo
1209 except the one for the main process. If that ever changes for
1210 any reason, then take out the following clause and replace it
1211 with one that makes sure the ctl_fd is open. */
1213 if (pi->tid != 0)
1214 pi = find_procinfo_or_die (pi->pid, 0);
1216 if (!pi->status_valid)
1217 if (!proc_get_status (pi))
1218 return NULL;
1220 ret = &pi->prstatus.pr_sysentry;
1221 if (save && ret)
1222 memcpy (save, ret, sizeof (sysset_t));
1224 return ret;
1227 /* Returns the set of syscalls that are traced /debugged on exit.
1228 Will also copy the syscall set if SAVE is non-zero. */
1230 static sysset_t *
1231 proc_get_traced_sysexit (procinfo *pi, sysset_t *save)
1233 sysset_t *ret = NULL;
1235 /* We should never have to apply this operation to any procinfo
1236 except the one for the main process. If that ever changes for
1237 any reason, then take out the following clause and replace it
1238 with one that makes sure the ctl_fd is open. */
1240 if (pi->tid != 0)
1241 pi = find_procinfo_or_die (pi->pid, 0);
1243 if (!pi->status_valid)
1244 if (!proc_get_status (pi))
1245 return NULL;
1247 ret = &pi->prstatus.pr_sysexit;
1248 if (save && ret)
1249 memcpy (save, ret, sizeof (sysset_t));
1251 return ret;
1254 /* The current fault (if any) is cleared; the associated signal will
1255 not be sent to the process or LWP when it resumes. Returns
1256 non-zero for success, zero for failure. */
1258 static int
1259 proc_clear_current_fault (procinfo *pi)
1261 int win;
1263 /* We should never have to apply this operation to any procinfo
1264 except the one for the main process. If that ever changes for
1265 any reason, then take out the following clause and replace it
1266 with one that makes sure the ctl_fd is open. */
1268 if (pi->tid != 0)
1269 pi = find_procinfo_or_die (pi->pid, 0);
1271 procfs_ctl_t cmd = PCCFAULT;
1273 win = (write (pi->ctl_fd, (void *) &cmd, sizeof (cmd)) == sizeof (cmd));
1275 return win;
1278 /* Set the "current signal" that will be delivered next to the
1279 process. NOTE: semantics are different from those of KILL. This
1280 signal will be delivered to the process or LWP immediately when it
1281 is resumed (even if the signal is held/blocked); it will NOT
1282 immediately cause another event of interest, and will NOT first
1283 trap back to the debugger. Returns non-zero for success, zero for
1284 failure. */
1286 static int
1287 proc_set_current_signal (procinfo *pi, int signo)
1289 int win;
1290 struct {
1291 procfs_ctl_t cmd;
1292 /* Use char array to avoid alignment issues. */
1293 char sinfo[sizeof (siginfo_t)];
1294 } arg;
1295 siginfo_t mysinfo;
1296 process_stratum_target *wait_target;
1297 ptid_t wait_ptid;
1298 struct target_waitstatus wait_status;
1300 /* We should never have to apply this operation to any procinfo
1301 except the one for the main process. If that ever changes for
1302 any reason, then take out the following clause and replace it
1303 with one that makes sure the ctl_fd is open. */
1305 if (pi->tid != 0)
1306 pi = find_procinfo_or_die (pi->pid, 0);
1308 /* The pointer is just a type alias. */
1309 get_last_target_status (&wait_target, &wait_ptid, &wait_status);
1310 if (wait_target == &the_procfs_target
1311 && wait_ptid == inferior_ptid
1312 && wait_status.kind () == TARGET_WAITKIND_STOPPED
1313 && wait_status.sig () == gdb_signal_from_host (signo)
1314 && proc_get_status (pi)
1315 && pi->prstatus.pr_lwp.pr_info.si_signo == signo
1317 /* Use the siginfo associated with the signal being
1318 redelivered. */
1319 memcpy (arg.sinfo, &pi->prstatus.pr_lwp.pr_info, sizeof (siginfo_t));
1320 else
1322 mysinfo.si_signo = signo;
1323 mysinfo.si_code = 0;
1324 mysinfo.si_pid = getpid (); /* ?why? */
1325 mysinfo.si_uid = getuid (); /* ?why? */
1326 memcpy (arg.sinfo, &mysinfo, sizeof (siginfo_t));
1329 arg.cmd = PCSSIG;
1330 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1332 return win;
1335 /* The current signal (if any) is cleared, and is not sent to the
1336 process or LWP when it resumes. Returns non-zero for success, zero
1337 for failure. */
1339 static int
1340 proc_clear_current_signal (procinfo *pi)
1342 int win;
1344 /* We should never have to apply this operation to any procinfo
1345 except the one for the main process. If that ever changes for
1346 any reason, then take out the following clause and replace it
1347 with one that makes sure the ctl_fd is open. */
1349 if (pi->tid != 0)
1350 pi = find_procinfo_or_die (pi->pid, 0);
1352 struct {
1353 procfs_ctl_t cmd;
1354 /* Use char array to avoid alignment issues. */
1355 char sinfo[sizeof (siginfo_t)];
1356 } arg;
1357 siginfo_t mysinfo;
1359 arg.cmd = PCSSIG;
1360 /* The pointer is just a type alias. */
1361 mysinfo.si_signo = 0;
1362 mysinfo.si_code = 0;
1363 mysinfo.si_errno = 0;
1364 mysinfo.si_pid = getpid (); /* ?why? */
1365 mysinfo.si_uid = getuid (); /* ?why? */
1366 memcpy (arg.sinfo, &mysinfo, sizeof (siginfo_t));
1368 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1370 return win;
1373 /* Return the general-purpose registers for the process or LWP
1374 corresponding to PI. Upon failure, return NULL. */
1376 static gdb_gregset_t *
1377 proc_get_gregs (procinfo *pi)
1379 if (!pi->status_valid || !pi->gregs_valid)
1380 if (!proc_get_status (pi))
1381 return NULL;
1383 return &pi->prstatus.pr_lwp.pr_reg;
1386 /* Return the general-purpose registers for the process or LWP
1387 corresponding to PI. Upon failure, return NULL. */
1389 static gdb_fpregset_t *
1390 proc_get_fpregs (procinfo *pi)
1392 if (!pi->status_valid || !pi->fpregs_valid)
1393 if (!proc_get_status (pi))
1394 return NULL;
1396 return &pi->prstatus.pr_lwp.pr_fpreg;
1399 /* Write the general-purpose registers back to the process or LWP
1400 corresponding to PI. Return non-zero for success, zero for
1401 failure. */
1403 static int
1404 proc_set_gregs (procinfo *pi)
1406 gdb_gregset_t *gregs;
1407 int win;
1409 gregs = proc_get_gregs (pi);
1410 if (gregs == NULL)
1411 return 0; /* proc_get_regs has already warned. */
1413 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1414 return 0;
1415 else
1417 struct {
1418 procfs_ctl_t cmd;
1419 /* Use char array to avoid alignment issues. */
1420 char gregs[sizeof (gdb_gregset_t)];
1421 } arg;
1423 arg.cmd = PCSREG;
1424 memcpy (&arg.gregs, gregs, sizeof (arg.gregs));
1425 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1428 /* Policy: writing the registers invalidates our cache. */
1429 pi->gregs_valid = 0;
1430 return win;
1433 /* Write the floating-pointer registers back to the process or LWP
1434 corresponding to PI. Return non-zero for success, zero for
1435 failure. */
1437 static int
1438 proc_set_fpregs (procinfo *pi)
1440 gdb_fpregset_t *fpregs;
1441 int win;
1443 fpregs = proc_get_fpregs (pi);
1444 if (fpregs == NULL)
1445 return 0; /* proc_get_fpregs has already warned. */
1447 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1448 return 0;
1449 else
1451 struct {
1452 procfs_ctl_t cmd;
1453 /* Use char array to avoid alignment issues. */
1454 char fpregs[sizeof (gdb_fpregset_t)];
1455 } arg;
1457 arg.cmd = PCSFPREG;
1458 memcpy (&arg.fpregs, fpregs, sizeof (arg.fpregs));
1459 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1462 /* Policy: writing the registers invalidates our cache. */
1463 pi->fpregs_valid = 0;
1464 return win;
1467 /* Send a signal to the proc or lwp with the semantics of "kill()".
1468 Returns non-zero for success, zero for failure. */
1470 static int
1471 proc_kill (procinfo *pi, int signo)
1473 int win;
1475 /* We might conceivably apply this operation to an LWP, and the
1476 LWP's ctl file descriptor might not be open. */
1478 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1479 return 0;
1480 else
1482 procfs_ctl_t cmd[2];
1484 cmd[0] = PCKILL;
1485 cmd[1] = signo;
1486 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
1489 return win;
1492 /* Find the pid of the process that started this one. Returns the
1493 parent process pid, or zero. */
1495 static int
1496 proc_parent_pid (procinfo *pi)
1498 /* We should never have to apply this operation to any procinfo
1499 except the one for the main process. If that ever changes for
1500 any reason, then take out the following clause and replace it
1501 with one that makes sure the ctl_fd is open. */
1503 if (pi->tid != 0)
1504 pi = find_procinfo_or_die (pi->pid, 0);
1506 if (!pi->status_valid)
1507 if (!proc_get_status (pi))
1508 return 0;
1510 return pi->prstatus.pr_ppid;
1513 /* Convert a target address (a.k.a. CORE_ADDR) into a host address
1514 (a.k.a void pointer)! */
1516 static void *
1517 procfs_address_to_host_pointer (CORE_ADDR addr)
1519 gdbarch *arch = current_inferior ()->arch ();
1520 type *ptr_type = builtin_type (arch)->builtin_data_ptr;
1521 void *ptr;
1523 gdb_assert (sizeof (ptr) == ptr_type->length ());
1524 gdbarch_address_to_pointer (arch, ptr_type, (gdb_byte *) &ptr, addr);
1525 return ptr;
1528 static int
1529 proc_set_watchpoint (procinfo *pi, CORE_ADDR addr, int len, int wflags)
1531 struct {
1532 procfs_ctl_t cmd;
1533 char watch[sizeof (prwatch_t)];
1534 } arg;
1535 prwatch_t pwatch;
1537 /* NOTE: cagney/2003-02-01: Even more horrible hack. Need to
1538 convert a target address into something that can be stored in a
1539 native data structure. */
1540 pwatch.pr_vaddr = (uintptr_t) procfs_address_to_host_pointer (addr);
1541 pwatch.pr_size = len;
1542 pwatch.pr_wflags = wflags;
1543 arg.cmd = PCWATCH;
1544 memcpy (arg.watch, &pwatch, sizeof (prwatch_t));
1545 return (write (pi->ctl_fd, &arg, sizeof (arg)) == sizeof (arg));
1548 /* =============== END, non-thread part of /proc "MODULE" =============== */
1550 /* =================== Thread "MODULE" =================== */
1552 /* Returns the number of threads for the process. */
1554 static int
1555 proc_get_nthreads (procinfo *pi)
1557 if (!pi->status_valid)
1558 if (!proc_get_status (pi))
1559 return 0;
1561 /* Only works for the process procinfo, because the LWP procinfos do not
1562 get prstatus filled in. */
1563 if (pi->tid != 0) /* Find the parent process procinfo. */
1564 pi = find_procinfo_or_die (pi->pid, 0);
1565 return pi->prstatus.pr_nlwp;
1568 /* Return the ID of the thread that had an event of interest.
1569 (ie. the one that hit a breakpoint or other traced event). All
1570 other things being equal, this should be the ID of a thread that is
1571 currently executing. */
1573 static int
1574 proc_get_current_thread (procinfo *pi)
1576 /* Note: this should be applied to the root procinfo for the
1577 process, not to the procinfo for an LWP. If applied to the
1578 procinfo for an LWP, it will simply return that LWP's ID. In
1579 that case, find the parent process procinfo. */
1581 if (pi->tid != 0)
1582 pi = find_procinfo_or_die (pi->pid, 0);
1584 if (!pi->status_valid)
1585 if (!proc_get_status (pi))
1586 return 0;
1588 return pi->prstatus.pr_lwp.pr_lwpid;
1591 /* Discover the IDs of all the threads within the process, and create
1592 a procinfo for each of them (chained to the parent). Returns
1593 non-zero for success, zero for failure. */
1595 static int
1596 proc_delete_dead_threads (procinfo *parent, procinfo *thread, void *ignore)
1598 if (thread && parent) /* sanity */
1600 thread->status_valid = 0;
1601 if (!proc_get_status (thread))
1602 destroy_one_procinfo (&parent->thread_list, thread);
1604 return 0; /* keep iterating */
1607 static int
1608 proc_update_threads (procinfo *pi)
1610 char pathname[MAX_PROC_NAME_SIZE + 16];
1611 struct dirent *direntry;
1612 procinfo *thread;
1613 gdb_dir_up dirp;
1614 int lwpid;
1616 /* We should never have to apply this operation to any procinfo
1617 except the one for the main process. If that ever changes for
1618 any reason, then take out the following clause and replace it
1619 with one that makes sure the ctl_fd is open. */
1621 if (pi->tid != 0)
1622 pi = find_procinfo_or_die (pi->pid, 0);
1624 proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
1626 /* Note: this brute-force method was originally devised for Unixware
1627 (support removed since), and will also work on Solaris 2.6 and
1628 2.7. The original comment mentioned the existence of a much
1629 simpler and more elegant way to do this on Solaris, but didn't
1630 point out what that was. */
1632 strcpy (pathname, pi->pathname);
1633 strcat (pathname, "/lwp");
1634 dirp.reset (opendir (pathname));
1635 if (dirp == NULL)
1636 proc_error (pi, "update_threads, opendir", __LINE__);
1638 while ((direntry = readdir (dirp.get ())) != NULL)
1639 if (direntry->d_name[0] != '.') /* skip '.' and '..' */
1641 lwpid = atoi (&direntry->d_name[0]);
1642 thread = create_procinfo (pi->pid, lwpid);
1643 if (thread == NULL)
1644 proc_error (pi, "update_threads, create_procinfo", __LINE__);
1646 pi->threads_valid = 1;
1647 return 1;
1650 /* Given a pointer to a function, call that function once for each lwp
1651 in the procinfo list, until the function returns non-zero, in which
1652 event return the value returned by the function.
1654 Note: this function does NOT call update_threads. If you want to
1655 discover new threads first, you must call that function explicitly.
1656 This function just makes a quick pass over the currently-known
1657 procinfos.
1659 PI is the parent process procinfo. FUNC is the per-thread
1660 function. PTR is an opaque parameter for function. Returns the
1661 first non-zero return value from the callee, or zero. */
1663 static int
1664 proc_iterate_over_threads (procinfo *pi,
1665 int (*func) (procinfo *, procinfo *, void *),
1666 void *ptr)
1668 procinfo *thread, *next;
1669 int retval = 0;
1671 /* We should never have to apply this operation to any procinfo
1672 except the one for the main process. If that ever changes for
1673 any reason, then take out the following clause and replace it
1674 with one that makes sure the ctl_fd is open. */
1676 if (pi->tid != 0)
1677 pi = find_procinfo_or_die (pi->pid, 0);
1679 for (thread = pi->thread_list; thread != NULL; thread = next)
1681 next = thread->next; /* In case thread is destroyed. */
1682 retval = (*func) (pi, thread, ptr);
1683 if (retval != 0)
1684 break;
1687 return retval;
1690 /* =================== END, Thread "MODULE" =================== */
1692 /* =================== END, /proc "MODULE" =================== */
1694 /* =================== GDB "MODULE" =================== */
1696 /* Here are all of the gdb target vector functions and their
1697 friends. */
1699 static void do_attach (ptid_t ptid);
1700 static void do_detach ();
1701 static void proc_trace_syscalls_1 (procinfo *pi, int syscallnum,
1702 int entry_or_exit, int mode, int from_tty);
1704 /* Sets up the inferior to be debugged. Registers to trace signals,
1705 hardware faults, and syscalls. Note: does not set RLC flag: caller
1706 may want to customize that. Returns zero for success (note!
1707 unlike most functions in this module); on failure, returns the LINE
1708 NUMBER where it failed! */
1710 static int
1711 procfs_debug_inferior (procinfo *pi)
1713 fltset_t traced_faults;
1714 sigset_t traced_signals;
1715 sysset_t *traced_syscall_entries;
1716 sysset_t *traced_syscall_exits;
1717 int status;
1719 /* Register to trace hardware faults in the child. */
1720 prfillset (&traced_faults); /* trace all faults... */
1721 prdelset (&traced_faults, FLTPAGE); /* except page fault. */
1722 if (!proc_set_traced_faults (pi, &traced_faults))
1723 return __LINE__;
1725 /* Initially, register to trace all signals in the child. */
1726 prfillset (&traced_signals);
1727 if (!proc_set_traced_signals (pi, &traced_signals))
1728 return __LINE__;
1731 /* Register to trace the 'exit' system call (on entry). */
1732 traced_syscall_entries = XNEW (sysset_t);
1733 premptyset (traced_syscall_entries);
1734 praddset (traced_syscall_entries, SYS_exit);
1735 praddset (traced_syscall_entries, SYS_lwp_exit);
1737 status = proc_set_traced_sysentry (pi, traced_syscall_entries);
1738 xfree (traced_syscall_entries);
1739 if (!status)
1740 return __LINE__;
1742 /* Method for tracing exec syscalls. */
1743 traced_syscall_exits = XNEW (sysset_t);
1744 premptyset (traced_syscall_exits);
1745 praddset (traced_syscall_exits, SYS_execve);
1746 praddset (traced_syscall_exits, SYS_lwp_create);
1747 praddset (traced_syscall_exits, SYS_lwp_exit);
1749 status = proc_set_traced_sysexit (pi, traced_syscall_exits);
1750 xfree (traced_syscall_exits);
1751 if (!status)
1752 return __LINE__;
1754 return 0;
1757 void
1758 procfs_target::attach (const char *args, int from_tty)
1760 int pid;
1762 pid = parse_pid_to_attach (args);
1764 if (pid == getpid ())
1765 error (_("Attaching GDB to itself is not a good idea..."));
1767 /* Push the target if needed, ensure it gets un-pushed it if attach fails. */
1768 inferior *inf = current_inferior ();
1769 target_unpush_up unpusher;
1770 if (!inf->target_is_pushed (this))
1772 inf->push_target (this);
1773 unpusher.reset (this);
1776 target_announce_attach (from_tty, pid);
1778 do_attach (ptid_t (pid));
1780 /* Everything went fine, keep the target pushed. */
1781 unpusher.release ();
1784 void
1785 procfs_target::detach (inferior *inf, int from_tty)
1787 target_announce_detach (from_tty);
1789 do_detach ();
1791 switch_to_no_thread ();
1792 detach_inferior (inf);
1793 maybe_unpush_target ();
1796 static void
1797 do_attach (ptid_t ptid)
1799 procinfo *pi;
1800 struct inferior *inf;
1801 int fail;
1802 int lwpid;
1804 pi = create_procinfo (ptid.pid (), 0);
1805 if (pi == NULL)
1806 perror (_("procfs: out of memory in 'attach'"));
1808 if (!open_procinfo_files (pi, FD_CTL))
1810 int saved_errno = errno;
1811 std::string errmsg
1812 = string_printf ("procfs:%d -- do_attach: couldn't open /proc "
1813 "file for process %d", __LINE__, ptid.pid ());
1814 errno = saved_errno;
1815 dead_procinfo (pi, errmsg.c_str (), NOKILL);
1818 /* Stop the process (if it isn't already stopped). */
1819 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1821 pi->was_stopped = 1;
1822 proc_prettyprint_why (proc_why (pi), proc_what (pi), 1);
1824 else
1826 pi->was_stopped = 0;
1827 /* Set the process to run again when we close it. */
1828 if (!proc_set_run_on_last_close (pi))
1829 dead_procinfo (pi, "do_attach: couldn't set RLC.", NOKILL);
1831 /* Now stop the process. */
1832 if (!proc_stop_process (pi))
1833 dead_procinfo (pi, "do_attach: couldn't stop the process.", NOKILL);
1834 pi->ignore_next_sigstop = 1;
1836 /* Save some of the /proc state to be restored if we detach. */
1837 if (!proc_get_traced_faults (pi, &pi->saved_fltset))
1838 dead_procinfo (pi, "do_attach: couldn't save traced faults.", NOKILL);
1839 if (!proc_get_traced_signals (pi, &pi->saved_sigset))
1840 dead_procinfo (pi, "do_attach: couldn't save traced signals.", NOKILL);
1841 if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
1842 dead_procinfo (pi, "do_attach: couldn't save traced syscall entries.",
1843 NOKILL);
1844 if (!proc_get_traced_sysexit (pi, pi->saved_exitset))
1845 dead_procinfo (pi, "do_attach: couldn't save traced syscall exits.",
1846 NOKILL);
1847 if (!proc_get_held_signals (pi, &pi->saved_sighold))
1848 dead_procinfo (pi, "do_attach: couldn't save held signals.", NOKILL);
1850 fail = procfs_debug_inferior (pi);
1851 if (fail != 0)
1852 dead_procinfo (pi, "do_attach: failed in procfs_debug_inferior", NOKILL);
1854 inf = current_inferior ();
1855 inferior_appeared (inf, pi->pid);
1856 /* Let GDB know that the inferior was attached. */
1857 inf->attach_flag = true;
1859 /* Create a procinfo for the current lwp. */
1860 lwpid = proc_get_current_thread (pi);
1861 create_procinfo (pi->pid, lwpid);
1863 /* Add it to gdb's thread list. */
1864 ptid = ptid_t (pi->pid, lwpid, 0);
1865 thread_info *thr = add_thread (&the_procfs_target, ptid);
1866 switch_to_thread (thr);
1869 static void
1870 do_detach ()
1872 procinfo *pi;
1874 /* Find procinfo for the main process. */
1875 pi = find_procinfo_or_die (inferior_ptid.pid (),
1876 0); /* FIXME: threads */
1878 if (!proc_set_traced_signals (pi, &pi->saved_sigset))
1879 proc_warn (pi, "do_detach, set_traced_signal", __LINE__);
1881 if (!proc_set_traced_faults (pi, &pi->saved_fltset))
1882 proc_warn (pi, "do_detach, set_traced_faults", __LINE__);
1884 if (!proc_set_traced_sysentry (pi, pi->saved_entryset))
1885 proc_warn (pi, "do_detach, set_traced_sysentry", __LINE__);
1887 if (!proc_set_traced_sysexit (pi, pi->saved_exitset))
1888 proc_warn (pi, "do_detach, set_traced_sysexit", __LINE__);
1890 if (!proc_set_held_signals (pi, &pi->saved_sighold))
1891 proc_warn (pi, "do_detach, set_held_signals", __LINE__);
1893 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1894 if (!(pi->was_stopped)
1895 || query (_("Was stopped when attached, make it runnable again? ")))
1897 /* Clear any pending signal. */
1898 if (!proc_clear_current_fault (pi))
1899 proc_warn (pi, "do_detach, clear_current_fault", __LINE__);
1901 if (!proc_clear_current_signal (pi))
1902 proc_warn (pi, "do_detach, clear_current_signal", __LINE__);
1904 if (!proc_set_run_on_last_close (pi))
1905 proc_warn (pi, "do_detach, set_rlc", __LINE__);
1908 destroy_procinfo (pi);
1911 /* Fetch register REGNUM from the inferior. If REGNUM is -1, do this
1912 for all registers.
1914 NOTE: Since the /proc interface cannot give us individual
1915 registers, we pay no attention to REGNUM, and just fetch them all.
1916 This results in the possibility that we will do unnecessarily many
1917 fetches, since we may be called repeatedly for individual
1918 registers. So we cache the results, and mark the cache invalid
1919 when the process is resumed. */
1921 void
1922 procfs_target::fetch_registers (struct regcache *regcache, int regnum)
1924 gdb_gregset_t *gregs;
1925 procinfo *pi;
1926 ptid_t ptid = regcache->ptid ();
1927 int pid = ptid.pid ();
1928 int tid = ptid.lwp ();
1929 struct gdbarch *gdbarch = regcache->arch ();
1931 pi = find_procinfo_or_die (pid, tid);
1933 if (pi == NULL)
1934 error (_("procfs: fetch_registers failed to find procinfo for %s"),
1935 target_pid_to_str (ptid).c_str ());
1937 gregs = proc_get_gregs (pi);
1938 if (gregs == NULL)
1939 proc_error (pi, "fetch_registers, get_gregs", __LINE__);
1941 supply_gregset (regcache, (const gdb_gregset_t *) gregs);
1943 if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU? */
1945 gdb_fpregset_t *fpregs;
1947 if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
1948 || regnum == gdbarch_pc_regnum (gdbarch)
1949 || regnum == gdbarch_sp_regnum (gdbarch))
1950 return; /* Not a floating point register. */
1952 fpregs = proc_get_fpregs (pi);
1953 if (fpregs == NULL)
1954 proc_error (pi, "fetch_registers, get_fpregs", __LINE__);
1956 supply_fpregset (regcache, (const gdb_fpregset_t *) fpregs);
1960 /* Store register REGNUM back into the inferior. If REGNUM is -1, do
1961 this for all registers.
1963 NOTE: Since the /proc interface will not read individual registers,
1964 we will cache these requests until the process is resumed, and only
1965 then write them back to the inferior process.
1967 FIXME: is that a really bad idea? Have to think about cases where
1968 writing one register might affect the value of others, etc. */
1970 void
1971 procfs_target::store_registers (struct regcache *regcache, int regnum)
1973 gdb_gregset_t *gregs;
1974 procinfo *pi;
1975 ptid_t ptid = regcache->ptid ();
1976 int pid = ptid.pid ();
1977 int tid = ptid.lwp ();
1978 struct gdbarch *gdbarch = regcache->arch ();
1980 pi = find_procinfo_or_die (pid, tid);
1982 if (pi == NULL)
1983 error (_("procfs: store_registers: failed to find procinfo for %s"),
1984 target_pid_to_str (ptid).c_str ());
1986 gregs = proc_get_gregs (pi);
1987 if (gregs == NULL)
1988 proc_error (pi, "store_registers, get_gregs", __LINE__);
1990 fill_gregset (regcache, gregs, regnum);
1991 if (!proc_set_gregs (pi))
1992 proc_error (pi, "store_registers, set_gregs", __LINE__);
1994 if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU? */
1996 gdb_fpregset_t *fpregs;
1998 if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
1999 || regnum == gdbarch_pc_regnum (gdbarch)
2000 || regnum == gdbarch_sp_regnum (gdbarch))
2001 return; /* Not a floating point register. */
2003 fpregs = proc_get_fpregs (pi);
2004 if (fpregs == NULL)
2005 proc_error (pi, "store_registers, get_fpregs", __LINE__);
2007 fill_fpregset (regcache, fpregs, regnum);
2008 if (!proc_set_fpregs (pi))
2009 proc_error (pi, "store_registers, set_fpregs", __LINE__);
2013 /* Retrieve the next stop event from the child process. If child has
2014 not stopped yet, wait for it to stop. Translate /proc eventcodes
2015 (or possibly wait eventcodes) into gdb internal event codes.
2016 Returns the id of process (and possibly thread) that incurred the
2017 event. Event codes are returned through a pointer parameter. */
2019 ptid_t
2020 procfs_target::wait (ptid_t ptid, struct target_waitstatus *status,
2021 target_wait_flags options)
2023 /* First cut: loosely based on original version 2.1. */
2024 procinfo *pi;
2025 int wstat;
2026 int temp_tid;
2027 ptid_t retval, temp_ptid;
2028 int why, what, flags;
2029 int retry = 0;
2031 wait_again:
2033 retry++;
2034 wstat = 0;
2035 retval = ptid_t (-1);
2037 /* Find procinfo for main process. */
2039 /* procfs_target currently only supports one inferior. */
2040 inferior *inf = current_inferior ();
2042 pi = find_procinfo_or_die (inf->pid, 0);
2043 if (pi)
2045 /* We must assume that the status is stale now... */
2046 pi->status_valid = 0;
2047 pi->gregs_valid = 0;
2048 pi->fpregs_valid = 0;
2050 #if 0 /* just try this out... */
2051 flags = proc_flags (pi);
2052 why = proc_why (pi);
2053 if ((flags & PR_STOPPED) && (why == PR_REQUESTED))
2054 pi->status_valid = 0; /* re-read again, IMMEDIATELY... */
2055 #endif
2056 /* If child is not stopped, wait for it to stop. */
2057 if (!(proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
2058 && !proc_wait_for_stop (pi))
2060 /* wait_for_stop failed: has the child terminated? */
2061 if (errno == ENOENT)
2063 int wait_retval;
2065 /* /proc file not found; presumably child has terminated. */
2066 wait_retval = ::wait (&wstat); /* "wait" for the child's exit. */
2068 /* Wrong child? */
2069 if (wait_retval != inf->pid)
2070 error (_("procfs: couldn't stop "
2071 "process %d: wait returned %d."),
2072 inf->pid, wait_retval);
2073 /* FIXME: might I not just use waitpid?
2074 Or try find_procinfo to see if I know about this child? */
2075 retval = ptid_t (wait_retval);
2077 else if (errno == EINTR)
2078 goto wait_again;
2079 else
2081 /* Unknown error from wait_for_stop. */
2082 proc_error (pi, "target_wait (wait_for_stop)", __LINE__);
2085 else
2087 /* This long block is reached if either:
2088 a) the child was already stopped, or
2089 b) we successfully waited for the child with wait_for_stop.
2090 This block will analyze the /proc status, and translate it
2091 into a waitstatus for GDB.
2093 If we actually had to call wait because the /proc file
2094 is gone (child terminated), then we skip this block,
2095 because we already have a waitstatus. */
2097 flags = proc_flags (pi);
2098 why = proc_why (pi);
2099 what = proc_what (pi);
2101 if (flags & (PR_STOPPED | PR_ISTOP))
2103 /* If it's running async (for single_thread control),
2104 set it back to normal again. */
2105 if (flags & PR_ASYNC)
2106 if (!proc_unset_async (pi))
2107 proc_error (pi, "target_wait, unset_async", __LINE__);
2109 if (info_verbose)
2110 proc_prettyprint_why (why, what, 1);
2112 /* The 'pid' we will return to GDB is composed of
2113 the process ID plus the lwp ID. */
2114 retval = ptid_t (pi->pid, proc_get_current_thread (pi), 0);
2116 switch (why) {
2117 case PR_SIGNALLED:
2118 wstat = (what << 8) | 0177;
2119 break;
2120 case PR_SYSENTRY:
2121 if (what == SYS_lwp_exit)
2123 delete_thread (this->find_thread (retval));
2124 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2125 goto wait_again;
2127 else if (what == SYS_exit)
2129 /* Handle SYS_exit call only. */
2130 /* Stopped at entry to SYS_exit.
2131 Make it runnable, resume it, then use
2132 the wait system call to get its exit code.
2133 Proc_run_process always clears the current
2134 fault and signal.
2135 Then return its exit status. */
2136 pi->status_valid = 0;
2137 wstat = 0;
2138 /* FIXME: what we should do is return
2139 TARGET_WAITKIND_SPURIOUS. */
2140 if (!proc_run_process (pi, 0, 0))
2141 proc_error (pi, "target_wait, run_process", __LINE__);
2143 if (inf->attach_flag)
2145 /* Don't call wait: simulate waiting for exit,
2146 return a "success" exit code. Bogus: what if
2147 it returns something else? */
2148 wstat = 0;
2149 retval = ptid_t (inf->pid); /* ? ? ? */
2151 else
2153 int temp = ::wait (&wstat);
2155 /* FIXME: shouldn't I make sure I get the right
2156 event from the right process? If (for
2157 instance) I have killed an earlier inferior
2158 process but failed to clean up after it
2159 somehow, I could get its termination event
2160 here. */
2162 /* If wait returns -1, that's what we return
2163 to GDB. */
2164 if (temp < 0)
2165 retval = ptid_t (temp);
2168 else
2170 gdb_printf (_("procfs: trapped on entry to "));
2171 proc_prettyprint_syscall (proc_what (pi), 0);
2172 gdb_printf ("\n");
2174 long i, nsysargs, *sysargs;
2176 nsysargs = proc_nsysarg (pi);
2177 sysargs = proc_sysargs (pi);
2179 if (nsysargs > 0 && sysargs != NULL)
2181 gdb_printf (_("%ld syscall arguments:\n"),
2182 nsysargs);
2183 for (i = 0; i < nsysargs; i++)
2184 gdb_printf ("#%ld: 0x%08lx\n",
2185 i, sysargs[i]);
2188 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2189 goto wait_again;
2191 break;
2192 case PR_SYSEXIT:
2193 if (what == SYS_execve)
2195 /* Hopefully this is our own "fork-child" execing
2196 the real child. Hoax this event into a trap, and
2197 GDB will see the child about to execute its start
2198 address. */
2199 wstat = (SIGTRAP << 8) | 0177;
2201 else if (what == SYS_lwp_create)
2203 /* This syscall is somewhat like fork/exec. We
2204 will get the event twice: once for the parent
2205 LWP, and once for the child. We should already
2206 know about the parent LWP, but the child will
2207 be new to us. So, whenever we get this event,
2208 if it represents a new thread, simply add the
2209 thread to the list. */
2211 /* If not in procinfo list, add it. */
2212 temp_tid = proc_get_current_thread (pi);
2213 if (!find_procinfo (pi->pid, temp_tid))
2214 create_procinfo (pi->pid, temp_tid);
2216 temp_ptid = ptid_t (pi->pid, temp_tid, 0);
2217 /* If not in GDB's thread list, add it. */
2218 if (!in_thread_list (this, temp_ptid))
2219 add_thread (this, temp_ptid);
2221 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2222 goto wait_again;
2224 else if (what == SYS_lwp_exit)
2226 delete_thread (this->find_thread (retval));
2227 status->set_spurious ();
2228 return retval;
2230 else
2232 gdb_printf (_("procfs: trapped on exit from "));
2233 proc_prettyprint_syscall (proc_what (pi), 0);
2234 gdb_printf ("\n");
2236 long i, nsysargs, *sysargs;
2238 nsysargs = proc_nsysarg (pi);
2239 sysargs = proc_sysargs (pi);
2241 if (nsysargs > 0 && sysargs != NULL)
2243 gdb_printf (_("%ld syscall arguments:\n"),
2244 nsysargs);
2245 for (i = 0; i < nsysargs; i++)
2246 gdb_printf ("#%ld: 0x%08lx\n",
2247 i, sysargs[i]);
2250 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2251 goto wait_again;
2253 break;
2254 case PR_REQUESTED:
2255 #if 0 /* FIXME */
2256 wstat = (SIGSTOP << 8) | 0177;
2257 break;
2258 #else
2259 if (retry < 5)
2261 gdb_printf (_("Retry #%d:\n"), retry);
2262 pi->status_valid = 0;
2263 goto wait_again;
2265 else
2267 /* If not in procinfo list, add it. */
2268 temp_tid = proc_get_current_thread (pi);
2269 if (!find_procinfo (pi->pid, temp_tid))
2270 create_procinfo (pi->pid, temp_tid);
2272 /* If not in GDB's thread list, add it. */
2273 temp_ptid = ptid_t (pi->pid, temp_tid, 0);
2274 if (!in_thread_list (this, temp_ptid))
2275 add_thread (this, temp_ptid);
2277 status->set_stopped (GDB_SIGNAL_0);
2278 return retval;
2280 #endif
2281 case PR_JOBCONTROL:
2282 wstat = (what << 8) | 0177;
2283 break;
2284 case PR_FAULTED:
2286 int signo = pi->prstatus.pr_lwp.pr_info.si_signo;
2287 if (signo != 0)
2288 wstat = (signo << 8) | 0177;
2290 break;
2291 default: /* switch (why) unmatched */
2292 gdb_printf ("procfs:%d -- ", __LINE__);
2293 gdb_printf (_("child stopped for unknown reason:\n"));
2294 proc_prettyprint_why (why, what, 1);
2295 error (_("... giving up..."));
2296 break;
2298 /* Got this far without error: If retval isn't in the
2299 threads database, add it. */
2300 if (retval.pid () > 0
2301 && !in_thread_list (this, retval))
2303 /* We have a new thread. We need to add it both to
2304 GDB's list and to our own. If we don't create a
2305 procinfo, resume may be unhappy later. */
2306 add_thread (this, retval);
2307 if (find_procinfo (retval.pid (),
2308 retval.lwp ()) == NULL)
2309 create_procinfo (retval.pid (),
2310 retval.lwp ());
2313 else /* Flags do not indicate STOPPED. */
2315 /* surely this can't happen... */
2316 gdb_printf ("procfs:%d -- process not stopped.\n",
2317 __LINE__);
2318 proc_prettyprint_flags (flags, 1);
2319 error (_("procfs: ...giving up..."));
2323 if (status)
2324 *status = host_status_to_waitstatus (wstat);
2327 return retval;
2330 /* Perform a partial transfer to/from the specified object. For
2331 memory transfers, fall back to the old memory xfer functions. */
2333 enum target_xfer_status
2334 procfs_target::xfer_partial (enum target_object object,
2335 const char *annex, gdb_byte *readbuf,
2336 const gdb_byte *writebuf, ULONGEST offset,
2337 ULONGEST len, ULONGEST *xfered_len)
2339 switch (object)
2341 case TARGET_OBJECT_MEMORY:
2342 return procfs_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2344 case TARGET_OBJECT_AUXV:
2345 return memory_xfer_auxv (this, object, annex, readbuf, writebuf,
2346 offset, len, xfered_len);
2348 default:
2349 return this->beneath ()->xfer_partial (object, annex,
2350 readbuf, writebuf, offset, len,
2351 xfered_len);
2355 /* Helper for procfs_xfer_partial that handles memory transfers.
2356 Arguments are like target_xfer_partial. */
2358 static enum target_xfer_status
2359 procfs_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2360 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2362 procinfo *pi;
2363 int nbytes;
2365 /* Find procinfo for main process. */
2366 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2367 if (pi->as_fd == 0 && open_procinfo_files (pi, FD_AS) == 0)
2369 proc_warn (pi, "xfer_memory, open_proc_files", __LINE__);
2370 return TARGET_XFER_E_IO;
2373 if (lseek (pi->as_fd, (off_t) memaddr, SEEK_SET) != (off_t) memaddr)
2374 return TARGET_XFER_E_IO;
2376 if (writebuf != NULL)
2378 PROCFS_NOTE ("write memory:\n");
2379 nbytes = write (pi->as_fd, writebuf, len);
2381 else
2383 PROCFS_NOTE ("read memory:\n");
2384 nbytes = read (pi->as_fd, readbuf, len);
2386 if (nbytes <= 0)
2387 return TARGET_XFER_E_IO;
2388 *xfered_len = nbytes;
2389 return TARGET_XFER_OK;
2392 /* Called by target_resume before making child runnable. Mark cached
2393 registers and status's invalid. If there are "dirty" caches that
2394 need to be written back to the child process, do that.
2396 File descriptors are also cached. As they are a limited resource,
2397 we cannot hold onto them indefinitely. However, as they are
2398 expensive to open, we don't want to throw them away
2399 indiscriminately either. As a compromise, we will keep the file
2400 descriptors for the parent process, but discard any file
2401 descriptors we may have accumulated for the threads.
2403 As this function is called by iterate_over_threads, it always
2404 returns zero (so that iterate_over_threads will keep
2405 iterating). */
2407 static int
2408 invalidate_cache (procinfo *parent, procinfo *pi, void *ptr)
2410 /* About to run the child; invalidate caches and do any other
2411 cleanup. */
2413 if (parent != NULL)
2415 /* The presence of a parent indicates that this is an LWP.
2416 Close any file descriptors that it might have open.
2417 We don't do this to the master (parent) procinfo. */
2419 close_procinfo_files (pi);
2421 pi->gregs_valid = 0;
2422 pi->fpregs_valid = 0;
2423 pi->status_valid = 0;
2424 pi->threads_valid = 0;
2426 return 0;
2429 /* Make child process PI runnable.
2431 If STEP is true, then arrange for the child to stop again after
2432 executing a single instruction. SCOPE_PTID, STEP and SIGNO are
2433 like in the target_resume interface. */
2435 static void
2436 proc_resume (procinfo *pi, ptid_t scope_ptid, int step, enum gdb_signal signo)
2438 procinfo *thread;
2439 int native_signo;
2441 /* FIXME: Check/reword. */
2443 /* prrun.prflags |= PRCFAULT; clear current fault.
2444 PRCFAULT may be replaced by a PCCFAULT call (proc_clear_current_fault)
2445 This basically leaves PRSTEP and PRCSIG.
2446 PRCSIG is like PCSSIG (proc_clear_current_signal).
2447 So basically PR_STEP is the sole argument that must be passed
2448 to proc_run_process. */
2450 errno = 0;
2452 /* Convert signal to host numbering. */
2453 if (signo == 0 || (signo == GDB_SIGNAL_STOP && pi->ignore_next_sigstop))
2454 native_signo = 0;
2455 else
2456 native_signo = gdb_signal_to_host (signo);
2458 pi->ignore_next_sigstop = 0;
2460 /* Running the process voids all cached registers and status. */
2461 /* Void the threads' caches first. */
2462 proc_iterate_over_threads (pi, invalidate_cache, NULL);
2463 /* Void the process procinfo's caches. */
2464 invalidate_cache (NULL, pi, NULL);
2466 if (scope_ptid.pid () != -1)
2468 /* Resume a specific thread, presumably suppressing the
2469 others. */
2470 thread = find_procinfo (scope_ptid.pid (), scope_ptid.lwp ());
2471 if (thread != NULL)
2473 if (thread->tid != 0)
2475 /* We're to resume a specific thread, and not the
2476 others. Set the child process's PR_ASYNC flag. */
2477 if (!proc_set_async (pi))
2478 proc_error (pi, "target_resume, set_async", __LINE__);
2479 pi = thread; /* Substitute the thread's procinfo
2480 for run. */
2485 if (!proc_run_process (pi, step, native_signo))
2487 if (errno == EBUSY)
2488 warning (_("resume: target already running. "
2489 "Pretend to resume, and hope for the best!"));
2490 else
2491 proc_error (pi, "target_resume", __LINE__);
2495 /* Implementation of target_ops::resume. */
2497 void
2498 procfs_target::resume (ptid_t scope_ptid, int step, enum gdb_signal signo)
2500 /* Find procinfo for main process. */
2501 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2503 proc_resume (pi, scope_ptid, step, signo);
2506 /* Set up to trace signals in the child process. */
2508 void
2509 procfs_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2511 sigset_t signals;
2512 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2513 int signo;
2515 prfillset (&signals);
2517 for (signo = 0; signo < NSIG; signo++)
2519 int target_signo = gdb_signal_from_host (signo);
2520 if (target_signo < pass_signals.size () && pass_signals[target_signo])
2521 prdelset (&signals, signo);
2524 if (!proc_set_traced_signals (pi, &signals))
2525 proc_error (pi, "pass_signals", __LINE__);
2528 /* Print status information about the child process. */
2530 void
2531 procfs_target::files_info ()
2533 struct inferior *inf = current_inferior ();
2535 gdb_printf (_("\tUsing the running image of %s %s via /proc.\n"),
2536 inf->attach_flag? "attached": "child",
2537 target_pid_to_str (ptid_t (inf->pid)).c_str ());
2540 /* Make it die. Wait for it to die. Clean up after it. Note: this
2541 should only be applied to the real process, not to an LWP, because
2542 of the check for parent-process. If we need this to work for an
2543 LWP, it needs some more logic. */
2545 static void
2546 unconditionally_kill_inferior (procinfo *pi)
2548 int parent_pid;
2550 parent_pid = proc_parent_pid (pi);
2551 if (!proc_kill (pi, SIGKILL))
2552 proc_error (pi, "unconditionally_kill, proc_kill", __LINE__);
2553 destroy_procinfo (pi);
2555 /* If pi is GDB's child, wait for it to die. */
2556 if (parent_pid == getpid ())
2557 /* FIXME: should we use waitpid to make sure we get the right event?
2558 Should we check the returned event? */
2560 #if 0
2561 int status, ret;
2563 ret = waitpid (pi->pid, &status, 0);
2564 #else
2565 wait (NULL);
2566 #endif
2570 /* We're done debugging it, and we want it to go away. Then we want
2571 GDB to forget all about it. */
2573 void
2574 procfs_target::kill ()
2576 if (inferior_ptid != null_ptid) /* ? */
2578 /* Find procinfo for main process. */
2579 procinfo *pi = find_procinfo (inferior_ptid.pid (), 0);
2581 if (pi)
2582 unconditionally_kill_inferior (pi);
2583 target_mourn_inferior (inferior_ptid);
2587 /* Forget we ever debugged this thing! */
2589 void
2590 procfs_target::mourn_inferior ()
2592 procinfo *pi;
2594 if (inferior_ptid != null_ptid)
2596 /* Find procinfo for main process. */
2597 pi = find_procinfo (inferior_ptid.pid (), 0);
2598 if (pi)
2599 destroy_procinfo (pi);
2602 generic_mourn_inferior ();
2604 maybe_unpush_target ();
2607 /* When GDB forks to create a runnable inferior process, this function
2608 is called on the parent side of the fork. It's job is to do
2609 whatever is necessary to make the child ready to be debugged, and
2610 then wait for the child to synchronize. */
2612 void
2613 procfs_target::procfs_init_inferior (int pid)
2615 procinfo *pi;
2616 int fail;
2617 int lwpid;
2619 pi = create_procinfo (pid, 0);
2620 if (pi == NULL)
2621 perror (_("procfs: out of memory in 'init_inferior'"));
2623 if (!open_procinfo_files (pi, FD_CTL))
2624 proc_error (pi, "init_inferior, open_proc_files", __LINE__);
2627 xmalloc // done
2628 open_procinfo_files // done
2629 link list // done
2630 prfillset (trace)
2631 procfs_notice_signals
2632 prfillset (fault)
2633 prdelset (FLTPAGE)
2636 /* If not stopped yet, wait for it to stop. */
2637 if (!(proc_flags (pi) & PR_STOPPED) && !(proc_wait_for_stop (pi)))
2638 dead_procinfo (pi, "init_inferior: wait_for_stop failed", KILL);
2640 /* Save some of the /proc state to be restored if we detach. */
2641 /* FIXME: Why? In case another debugger was debugging it?
2642 We're it's parent, for Ghu's sake! */
2643 if (!proc_get_traced_signals (pi, &pi->saved_sigset))
2644 proc_error (pi, "init_inferior, get_traced_signals", __LINE__);
2645 if (!proc_get_held_signals (pi, &pi->saved_sighold))
2646 proc_error (pi, "init_inferior, get_held_signals", __LINE__);
2647 if (!proc_get_traced_faults (pi, &pi->saved_fltset))
2648 proc_error (pi, "init_inferior, get_traced_faults", __LINE__);
2649 if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
2650 proc_error (pi, "init_inferior, get_traced_sysentry", __LINE__);
2651 if (!proc_get_traced_sysexit (pi, pi->saved_exitset))
2652 proc_error (pi, "init_inferior, get_traced_sysexit", __LINE__);
2654 fail = procfs_debug_inferior (pi);
2655 if (fail != 0)
2656 proc_error (pi, "init_inferior (procfs_debug_inferior)", fail);
2658 /* FIXME: logically, we should really be turning OFF run-on-last-close,
2659 and possibly even turning ON kill-on-last-close at this point. But
2660 I can't make that change without careful testing which I don't have
2661 time to do right now... */
2662 /* Turn on run-on-last-close flag so that the child
2663 will die if GDB goes away for some reason. */
2664 if (!proc_set_run_on_last_close (pi))
2665 proc_error (pi, "init_inferior, set_RLC", __LINE__);
2667 /* We now have have access to the lwpid of the main thread/lwp. */
2668 lwpid = proc_get_current_thread (pi);
2670 /* Create a procinfo for the main lwp. */
2671 create_procinfo (pid, lwpid);
2673 /* We already have a main thread registered in the thread table at
2674 this point, but it didn't have any lwp info yet. Notify the core
2675 about it. This changes inferior_ptid as well. */
2676 thread_change_ptid (this, ptid_t (pid), ptid_t (pid, lwpid, 0));
2678 gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
2681 /* When GDB forks to create a new process, this function is called on
2682 the child side of the fork before GDB exec's the user program. Its
2683 job is to make the child minimally debuggable, so that the parent
2684 GDB process can connect to the child and take over. This function
2685 should do only the minimum to make that possible, and to
2686 synchronize with the parent process. The parent process should
2687 take care of the details. */
2689 static void
2690 procfs_set_exec_trap (void)
2692 /* This routine called on the child side (inferior side)
2693 after GDB forks the inferior. It must use only local variables,
2694 because it may be sharing data space with its parent. */
2696 procinfo *pi;
2697 sysset_t *exitset;
2699 pi = create_procinfo (getpid (), 0);
2700 if (pi == NULL)
2701 perror_with_name (_("procfs: create_procinfo failed in child"));
2703 if (open_procinfo_files (pi, FD_CTL) == 0)
2705 proc_warn (pi, "set_exec_trap, open_proc_files", __LINE__);
2706 gdb_flush (gdb_stderr);
2707 /* No need to call "dead_procinfo", because we're going to
2708 exit. */
2709 _exit (127);
2712 exitset = XNEW (sysset_t);
2713 premptyset (exitset);
2714 praddset (exitset, SYS_execve);
2716 if (!proc_set_traced_sysexit (pi, exitset))
2718 proc_warn (pi, "set_exec_trap, set_traced_sysexit", __LINE__);
2719 gdb_flush (gdb_stderr);
2720 _exit (127);
2723 /* FIXME: should this be done in the parent instead? */
2724 /* Turn off inherit on fork flag so that all grand-children
2725 of gdb start with tracing flags cleared. */
2726 if (!proc_unset_inherit_on_fork (pi))
2727 proc_warn (pi, "set_exec_trap, unset_inherit", __LINE__);
2729 /* Turn off run on last close flag, so that the child process
2730 cannot run away just because we close our handle on it.
2731 We want it to wait for the parent to attach. */
2732 if (!proc_unset_run_on_last_close (pi))
2733 proc_warn (pi, "set_exec_trap, unset_RLC", __LINE__);
2735 /* FIXME: No need to destroy the procinfo --
2736 we have our own address space, and we're about to do an exec! */
2737 /*destroy_procinfo (pi);*/
2740 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2).
2741 This avoids a possible deadlock gdb and its vfork'ed child. */
2742 static void
2743 procfs_pre_trace (void)
2747 /* This function is called BEFORE gdb forks the inferior process. Its
2748 only real responsibility is to set things up for the fork, and tell
2749 GDB which two functions to call after the fork (one for the parent,
2750 and one for the child).
2752 This function does a complicated search for a unix shell program,
2753 which it then uses to parse arguments and environment variables to
2754 be sent to the child. I wonder whether this code could not be
2755 abstracted out and shared with other unix targets such as
2756 inf-ptrace? */
2758 void
2759 procfs_target::create_inferior (const char *exec_file,
2760 const std::string &allargs,
2761 char **env, int from_tty)
2763 const char *shell_file = get_shell ();
2764 char *tryname;
2765 int pid;
2767 if (strchr (shell_file, '/') == NULL)
2770 /* We will be looking down the PATH to find shell_file. If we
2771 just do this the normal way (via execlp, which operates by
2772 attempting an exec for each element of the PATH until it
2773 finds one which succeeds), then there will be an exec for
2774 each failed attempt, each of which will cause a PR_SYSEXIT
2775 stop, and we won't know how to distinguish the PR_SYSEXIT's
2776 for these failed execs with the ones for successful execs
2777 (whether the exec has succeeded is stored at that time in the
2778 carry bit or some such architecture-specific and
2779 non-ABI-specified place).
2781 So I can't think of anything better than to search the PATH
2782 now. This has several disadvantages: (1) There is a race
2783 condition; if we find a file now and it is deleted before we
2784 exec it, we lose, even if the deletion leaves a valid file
2785 further down in the PATH, (2) there is no way to know exactly
2786 what an executable (in the sense of "capable of being
2787 exec'd") file is. Using access() loses because it may lose
2788 if the caller is the superuser; failing to use it loses if
2789 there are ACLs or some such. */
2791 const char *p;
2792 const char *p1;
2793 /* FIXME-maybe: might want "set path" command so user can change what
2794 path is used from within GDB. */
2795 const char *path = getenv ("PATH");
2796 int len;
2797 struct stat statbuf;
2799 if (path == NULL)
2800 path = "/bin:/usr/bin";
2802 tryname = (char *) alloca (strlen (path) + strlen (shell_file) + 2);
2803 for (p = path; p != NULL; p = p1 ? p1 + 1: NULL)
2805 p1 = strchr (p, ':');
2806 if (p1 != NULL)
2807 len = p1 - p;
2808 else
2809 len = strlen (p);
2810 memcpy (tryname, p, len);
2811 tryname[len] = '\0';
2812 strcat (tryname, "/");
2813 strcat (tryname, shell_file);
2814 if (access (tryname, X_OK) < 0)
2815 continue;
2816 if (stat (tryname, &statbuf) < 0)
2817 continue;
2818 if (!S_ISREG (statbuf.st_mode))
2819 /* We certainly need to reject directories. I'm not quite
2820 as sure about FIFOs, sockets, etc., but I kind of doubt
2821 that people want to exec() these things. */
2822 continue;
2823 break;
2825 if (p == NULL)
2826 /* Not found. This must be an error rather than merely passing
2827 the file to execlp(), because execlp() would try all the
2828 exec()s, causing GDB to get confused. */
2829 error (_("procfs:%d -- Can't find shell %s in PATH"),
2830 __LINE__, shell_file);
2832 shell_file = tryname;
2835 inferior *inf = current_inferior ();
2836 if (!inf->target_is_pushed (this))
2837 inf->push_target (this);
2839 pid = fork_inferior (exec_file, allargs, env, procfs_set_exec_trap,
2840 NULL, procfs_pre_trace, shell_file, NULL);
2842 /* We have something that executes now. We'll be running through
2843 the shell at this point (if startup-with-shell is true), but the
2844 pid shouldn't change. */
2845 thread_info *thr = add_thread_silent (this, ptid_t (pid));
2846 switch_to_thread (thr);
2848 procfs_init_inferior (pid);
2851 /* Callback for update_thread_list. Calls "add_thread". */
2853 static int
2854 procfs_notice_thread (procinfo *pi, procinfo *thread, void *ptr)
2856 ptid_t gdb_threadid = ptid_t (pi->pid, thread->tid, 0);
2858 thread_info *thr = the_procfs_target.find_thread (gdb_threadid);
2859 if (thr == NULL || thr->state == THREAD_EXITED)
2860 add_thread (&the_procfs_target, gdb_threadid);
2862 return 0;
2865 /* Query all the threads that the target knows about, and give them
2866 back to GDB to add to its list. */
2868 void
2869 procfs_target::update_thread_list ()
2871 procinfo *pi;
2873 prune_threads ();
2875 /* Find procinfo for main process. */
2876 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2877 proc_update_threads (pi);
2878 proc_iterate_over_threads (pi, procfs_notice_thread, NULL);
2881 /* Return true if the thread is still 'alive'. This guy doesn't
2882 really seem to be doing his job. Got to investigate how to tell
2883 when a thread is really gone. */
2885 bool
2886 procfs_target::thread_alive (ptid_t ptid)
2888 int proc, thread;
2889 procinfo *pi;
2891 proc = ptid.pid ();
2892 thread = ptid.lwp ();
2893 /* If I don't know it, it ain't alive! */
2894 pi = find_procinfo (proc, thread);
2895 if (pi == NULL)
2896 return false;
2898 /* If I can't get its status, it ain't alive!
2899 What's more, I need to forget about it! */
2900 if (!proc_get_status (pi))
2902 destroy_procinfo (pi);
2903 return false;
2905 /* I couldn't have got its status if it weren't alive, so it's
2906 alive. */
2907 return true;
2910 /* Convert PTID to a string. */
2912 std::string
2913 procfs_target::pid_to_str (ptid_t ptid)
2915 if (ptid.lwp () == 0)
2916 return string_printf ("process %d", ptid.pid ());
2917 else
2918 return string_printf ("LWP %ld", ptid.lwp ());
2921 /* Accepts an integer PID; Returns a string representing a file that
2922 can be opened to get the symbols for the child process. */
2924 const char *
2925 procfs_target::pid_to_exec_file (int pid)
2927 static char buf[PATH_MAX];
2928 char name[PATH_MAX];
2930 /* Solaris 11 introduced /proc/<proc-id>/execname. */
2931 xsnprintf (name, sizeof (name), "/proc/%d/execname", pid);
2932 scoped_fd fd (gdb_open_cloexec (name, O_RDONLY, 0));
2933 if (fd.get () < 0 || read (fd.get (), buf, PATH_MAX - 1) < 0)
2935 /* If that fails, fall back to /proc/<proc-id>/path/a.out introduced in
2936 Solaris 10. */
2937 ssize_t len;
2939 xsnprintf (name, sizeof (name), "/proc/%d/path/a.out", pid);
2940 len = readlink (name, buf, PATH_MAX - 1);
2941 if (len <= 0)
2942 strcpy (buf, name);
2943 else
2944 buf[len] = '\0';
2947 return buf;
2950 /* Insert a watchpoint. */
2952 static int
2953 procfs_set_watchpoint (ptid_t ptid, CORE_ADDR addr, int len, int rwflag,
2954 int after)
2956 int pflags = 0;
2957 procinfo *pi;
2959 pi = find_procinfo_or_die (ptid.pid () == -1 ?
2960 inferior_ptid.pid () : ptid.pid (),
2963 /* Translate from GDB's flags to /proc's. */
2964 if (len > 0) /* len == 0 means delete watchpoint. */
2966 switch (rwflag) { /* FIXME: need an enum! */
2967 case hw_write: /* default watchpoint (write) */
2968 pflags = WA_WRITE;
2969 break;
2970 case hw_read: /* read watchpoint */
2971 pflags = WA_READ;
2972 break;
2973 case hw_access: /* access watchpoint */
2974 pflags = WA_READ | WA_WRITE;
2975 break;
2976 case hw_execute: /* execution HW breakpoint */
2977 pflags = WA_EXEC;
2978 break;
2979 default: /* Something weird. Return error. */
2980 return -1;
2982 if (after) /* Stop after r/w access is completed. */
2983 pflags |= WA_TRAPAFTER;
2986 if (!proc_set_watchpoint (pi, addr, len, pflags))
2988 if (errno == E2BIG) /* Typical error for no resources. */
2989 return -1; /* fail */
2990 /* GDB may try to remove the same watchpoint twice.
2991 If a remove request returns no match, don't error. */
2992 if (errno == ESRCH && len == 0)
2993 return 0; /* ignore */
2994 proc_error (pi, "set_watchpoint", __LINE__);
2996 return 0;
2999 /* Return non-zero if we can set a hardware watchpoint of type TYPE. TYPE
3000 is one of bp_hardware_watchpoint, bp_read_watchpoint, bp_write_watchpoint,
3001 or bp_hardware_watchpoint. CNT is the number of watchpoints used so
3002 far. */
3005 procfs_target::can_use_hw_breakpoint (enum bptype type, int cnt, int othertype)
3007 /* Due to the way that proc_set_watchpoint() is implemented, host
3008 and target pointers must be of the same size. If they are not,
3009 we can't use hardware watchpoints. This limitation is due to the
3010 fact that proc_set_watchpoint() calls
3011 procfs_address_to_host_pointer(); a close inspection of
3012 procfs_address_to_host_pointer will reveal that an internal error
3013 will be generated when the host and target pointer sizes are
3014 different. */
3015 struct type *ptr_type
3016 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
3018 if (sizeof (void *) != ptr_type->length ())
3019 return 0;
3021 /* Other tests here??? */
3023 return 1;
3026 /* Returns non-zero if process is stopped on a hardware watchpoint
3027 fault, else returns zero. */
3029 bool
3030 procfs_target::stopped_by_watchpoint ()
3032 procinfo *pi;
3034 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3036 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
3037 if (proc_why (pi) == PR_FAULTED)
3038 if (proc_what (pi) == FLTWATCH)
3039 return true;
3040 return false;
3043 /* Returns 1 if the OS knows the position of the triggered watchpoint,
3044 and sets *ADDR to that address. Returns 0 if OS cannot report that
3045 address. This function is only called if
3046 procfs_stopped_by_watchpoint returned 1, thus no further checks are
3047 done. The function also assumes that ADDR is not NULL. */
3049 bool
3050 procfs_target::stopped_data_address (CORE_ADDR *addr)
3052 procinfo *pi;
3054 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3055 return proc_watchpoint_address (pi, addr);
3059 procfs_target::insert_watchpoint (CORE_ADDR addr, int len,
3060 enum target_hw_bp_type type,
3061 struct expression *cond)
3063 if (!target_have_steppable_watchpoint ()
3064 && !gdbarch_have_nonsteppable_watchpoint (current_inferior ()->arch ()))
3065 /* When a hardware watchpoint fires off the PC will be left at
3066 the instruction following the one which caused the
3067 watchpoint. It will *NOT* be necessary for GDB to step over
3068 the watchpoint. */
3069 return procfs_set_watchpoint (inferior_ptid, addr, len, type, 1);
3070 else
3071 /* When a hardware watchpoint fires off the PC will be left at
3072 the instruction which caused the watchpoint. It will be
3073 necessary for GDB to step over the watchpoint. */
3074 return procfs_set_watchpoint (inferior_ptid, addr, len, type, 0);
3078 procfs_target::remove_watchpoint (CORE_ADDR addr, int len,
3079 enum target_hw_bp_type type,
3080 struct expression *cond)
3082 return procfs_set_watchpoint (inferior_ptid, addr, 0, 0, 0);
3086 procfs_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
3088 /* The man page for proc(4) on Solaris 2.6 and up says that the
3089 system can support "thousands" of hardware watchpoints, but gives
3090 no method for finding out how many; It doesn't say anything about
3091 the allowed size for the watched area either. So we just tell
3092 GDB 'yes'. */
3093 return 1;
3096 /* Memory Mappings Functions: */
3098 /* Call a callback function once for each mapping, passing it the
3099 mapping, an optional secondary callback function, and some optional
3100 opaque data. Quit and return the first non-zero value returned
3101 from the callback.
3103 PI is the procinfo struct for the process to be mapped. FUNC is
3104 the callback function to be called by this iterator. DATA is the
3105 optional opaque data to be passed to the callback function.
3106 CHILD_FUNC is the optional secondary function pointer to be passed
3107 to the child function. Returns the first non-zero return value
3108 from the callback function, or zero. */
3110 static int
3111 iterate_over_mappings (procinfo *pi, find_memory_region_ftype child_func,
3112 void *data,
3113 int (*func) (struct prmap *map,
3114 find_memory_region_ftype child_func,
3115 void *data))
3117 char pathname[MAX_PROC_NAME_SIZE];
3118 struct prmap *prmaps;
3119 struct prmap *prmap;
3120 int funcstat;
3121 int nmap;
3122 struct stat sbuf;
3124 /* Get the number of mappings, allocate space,
3125 and read the mappings into prmaps. */
3126 /* Open map fd. */
3127 xsnprintf (pathname, sizeof (pathname), "/proc/%d/map", pi->pid);
3129 scoped_fd map_fd (open (pathname, O_RDONLY));
3130 if (map_fd.get () < 0)
3131 proc_error (pi, "iterate_over_mappings (open)", __LINE__);
3133 /* Use stat to determine the file size, and compute
3134 the number of prmap_t objects it contains. */
3135 if (fstat (map_fd.get (), &sbuf) != 0)
3136 proc_error (pi, "iterate_over_mappings (fstat)", __LINE__);
3138 nmap = sbuf.st_size / sizeof (prmap_t);
3139 prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
3140 if (read (map_fd.get (), (char *) prmaps, nmap * sizeof (*prmaps))
3141 != (nmap * sizeof (*prmaps)))
3142 proc_error (pi, "iterate_over_mappings (read)", __LINE__);
3144 for (prmap = prmaps; nmap > 0; prmap++, nmap--)
3146 funcstat = (*func) (prmap, child_func, data);
3147 if (funcstat != 0)
3148 return funcstat;
3151 return 0;
3154 /* Implements the to_find_memory_regions method. Calls an external
3155 function for each memory region.
3156 Returns the integer value returned by the callback. */
3158 static int
3159 find_memory_regions_callback (struct prmap *map,
3160 find_memory_region_ftype func, void *data)
3162 return (*func) ((CORE_ADDR) map->pr_vaddr,
3163 map->pr_size,
3164 (map->pr_mflags & MA_READ) != 0,
3165 (map->pr_mflags & MA_WRITE) != 0,
3166 (map->pr_mflags & MA_EXEC) != 0,
3167 1, /* MODIFIED is unknown, pass it as true. */
3168 false,
3169 data);
3172 /* External interface. Calls a callback function once for each
3173 mapped memory region in the child process, passing as arguments:
3175 CORE_ADDR virtual_address,
3176 unsigned long size,
3177 int read, TRUE if region is readable by the child
3178 int write, TRUE if region is writable by the child
3179 int execute TRUE if region is executable by the child.
3181 Stops iterating and returns the first non-zero value returned by
3182 the callback. */
3185 procfs_target::find_memory_regions (find_memory_region_ftype func, void *data)
3187 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3189 return iterate_over_mappings (pi, func, data,
3190 find_memory_regions_callback);
3193 /* Returns an ascii representation of a memory mapping's flags. */
3195 static char *
3196 mappingflags (long flags)
3198 static char asciiflags[8];
3200 strcpy (asciiflags, "-------");
3201 if (flags & MA_STACK)
3202 asciiflags[1] = 's';
3203 if (flags & MA_BREAK)
3204 asciiflags[2] = 'b';
3205 if (flags & MA_SHARED)
3206 asciiflags[3] = 's';
3207 if (flags & MA_READ)
3208 asciiflags[4] = 'r';
3209 if (flags & MA_WRITE)
3210 asciiflags[5] = 'w';
3211 if (flags & MA_EXEC)
3212 asciiflags[6] = 'x';
3213 return (asciiflags);
3216 /* Callback function, does the actual work for 'info proc
3217 mappings'. */
3219 static int
3220 info_mappings_callback (struct prmap *map, find_memory_region_ftype ignore,
3221 void *unused)
3223 unsigned int pr_off;
3225 pr_off = (unsigned int) map->pr_offset;
3227 if (gdbarch_addr_bit (current_inferior ()->arch ()) == 32)
3228 gdb_printf ("\t%#10lx %#10lx %#10lx %#10x %7s\n",
3229 (unsigned long) map->pr_vaddr,
3230 (unsigned long) map->pr_vaddr + map->pr_size - 1,
3231 (unsigned long) map->pr_size,
3232 pr_off,
3233 mappingflags (map->pr_mflags));
3234 else
3235 gdb_printf (" %#18lx %#18lx %#10lx %#10x %7s\n",
3236 (unsigned long) map->pr_vaddr,
3237 (unsigned long) map->pr_vaddr + map->pr_size - 1,
3238 (unsigned long) map->pr_size,
3239 pr_off,
3240 mappingflags (map->pr_mflags));
3242 return 0;
3245 /* Implement the "info proc mappings" subcommand. */
3247 static void
3248 info_proc_mappings (procinfo *pi, int summary)
3250 if (summary)
3251 return; /* No output for summary mode. */
3253 gdb_printf (_("Mapped address spaces:\n\n"));
3254 if (gdbarch_ptr_bit (current_inferior ()->arch ()) == 32)
3255 gdb_printf ("\t%10s %10s %10s %10s %7s\n",
3256 "Start Addr",
3257 " End Addr",
3258 " Size",
3259 " Offset",
3260 "Flags");
3261 else
3262 gdb_printf (" %18s %18s %10s %10s %7s\n",
3263 "Start Addr",
3264 " End Addr",
3265 " Size",
3266 " Offset",
3267 "Flags");
3269 iterate_over_mappings (pi, NULL, NULL, info_mappings_callback);
3270 gdb_printf ("\n");
3273 /* Implement the "info proc" command. */
3275 bool
3276 procfs_target::info_proc (const char *args, enum info_proc_what what)
3278 procinfo *process = NULL;
3279 procinfo *thread = NULL;
3280 char *tmp = NULL;
3281 int pid = 0;
3282 int tid = 0;
3283 int mappings = 0;
3285 switch (what)
3287 case IP_MINIMAL:
3288 break;
3290 case IP_MAPPINGS:
3291 case IP_ALL:
3292 mappings = 1;
3293 break;
3295 default:
3296 error (_("Not supported on this target."));
3299 gdb_argv built_argv (args);
3300 for (char *arg : built_argv)
3302 if (isdigit (arg[0]))
3304 pid = strtoul (arg, &tmp, 10);
3305 if (*tmp == '/')
3306 tid = strtoul (++tmp, NULL, 10);
3308 else if (arg[0] == '/')
3310 tid = strtoul (arg + 1, NULL, 10);
3314 procinfo_up temporary_procinfo;
3315 if (pid == 0)
3316 pid = inferior_ptid.pid ();
3317 if (pid == 0)
3318 error (_("No current process: you must name one."));
3319 else
3321 /* Have pid, will travel.
3322 First see if it's a process we're already debugging. */
3323 process = find_procinfo (pid, 0);
3324 if (process == NULL)
3326 /* No. So open a procinfo for it, but
3327 remember to close it again when finished. */
3328 process = create_procinfo (pid, 0);
3329 temporary_procinfo.reset (process);
3330 if (!open_procinfo_files (process, FD_CTL))
3331 proc_error (process, "info proc, open_procinfo_files", __LINE__);
3334 if (tid != 0)
3335 thread = create_procinfo (pid, tid);
3337 if (process)
3339 gdb_printf (_("process %d flags:\n"), process->pid);
3340 proc_prettyprint_flags (proc_flags (process), 1);
3341 if (proc_flags (process) & (PR_STOPPED | PR_ISTOP))
3342 proc_prettyprint_why (proc_why (process), proc_what (process), 1);
3343 if (proc_get_nthreads (process) > 1)
3344 gdb_printf ("Process has %d threads.\n",
3345 proc_get_nthreads (process));
3347 if (thread)
3349 gdb_printf (_("thread %d flags:\n"), thread->tid);
3350 proc_prettyprint_flags (proc_flags (thread), 1);
3351 if (proc_flags (thread) & (PR_STOPPED | PR_ISTOP))
3352 proc_prettyprint_why (proc_why (thread), proc_what (thread), 1);
3355 if (mappings)
3356 info_proc_mappings (process, 0);
3358 return true;
3361 /* Modify the status of the system call identified by SYSCALLNUM in
3362 the set of syscalls that are currently traced/debugged.
3364 If ENTRY_OR_EXIT is set to PR_SYSENTRY, then the entry syscalls set
3365 will be updated. Otherwise, the exit syscalls set will be updated.
3367 If MODE is FLAG_SET, then traces will be enabled. Otherwise, they
3368 will be disabled. */
3370 static void
3371 proc_trace_syscalls_1 (procinfo *pi, int syscallnum, int entry_or_exit,
3372 int mode, int from_tty)
3374 sysset_t *sysset;
3376 if (entry_or_exit == PR_SYSENTRY)
3377 sysset = proc_get_traced_sysentry (pi, NULL);
3378 else
3379 sysset = proc_get_traced_sysexit (pi, NULL);
3381 if (sysset == NULL)
3382 proc_error (pi, "proc-trace, get_traced_sysset", __LINE__);
3384 if (mode == FLAG_SET)
3385 praddset (sysset, syscallnum);
3386 else
3387 prdelset (sysset, syscallnum);
3389 if (entry_or_exit == PR_SYSENTRY)
3391 if (!proc_set_traced_sysentry (pi, sysset))
3392 proc_error (pi, "proc-trace, set_traced_sysentry", __LINE__);
3394 else
3396 if (!proc_set_traced_sysexit (pi, sysset))
3397 proc_error (pi, "proc-trace, set_traced_sysexit", __LINE__);
3401 static void
3402 proc_trace_syscalls (const char *args, int from_tty, int entry_or_exit, int mode)
3404 procinfo *pi;
3406 if (inferior_ptid.pid () <= 0)
3407 error (_("you must be debugging a process to use this command."));
3409 if (args == NULL || args[0] == 0)
3410 error_no_arg (_("system call to trace"));
3412 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3413 if (isdigit (args[0]))
3415 const int syscallnum = atoi (args);
3417 proc_trace_syscalls_1 (pi, syscallnum, entry_or_exit, mode, from_tty);
3421 static void
3422 proc_trace_sysentry_cmd (const char *args, int from_tty)
3424 proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_SET);
3427 static void
3428 proc_trace_sysexit_cmd (const char *args, int from_tty)
3430 proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_SET);
3433 static void
3434 proc_untrace_sysentry_cmd (const char *args, int from_tty)
3436 proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_RESET);
3439 static void
3440 proc_untrace_sysexit_cmd (const char *args, int from_tty)
3442 proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_RESET);
3445 void _initialize_procfs ();
3446 void
3447 _initialize_procfs ()
3449 add_com ("proc-trace-entry", no_class, proc_trace_sysentry_cmd,
3450 _("Give a trace of entries into the syscall."));
3451 add_com ("proc-trace-exit", no_class, proc_trace_sysexit_cmd,
3452 _("Give a trace of exits from the syscall."));
3453 add_com ("proc-untrace-entry", no_class, proc_untrace_sysentry_cmd,
3454 _("Cancel a trace of entries into the syscall."));
3455 add_com ("proc-untrace-exit", no_class, proc_untrace_sysexit_cmd,
3456 _("Cancel a trace of exits from the syscall."));
3458 add_inf_child_target (&the_procfs_target);
3461 /* =================== END, GDB "MODULE" =================== */
3465 /* miscellaneous stubs: */
3467 /* The following satisfy a few random symbols mostly created by the
3468 solaris threads implementation, which I will chase down later. */
3470 /* Return a pid for which we guarantee we will be able to find a
3471 'live' procinfo. */
3473 ptid_t
3474 procfs_first_available (void)
3476 return ptid_t (procinfo_list ? procinfo_list->pid : -1);
3479 /* =================== GCORE .NOTE "MODULE" =================== */
3481 static void
3482 procfs_do_thread_registers (bfd *obfd, ptid_t ptid,
3483 gdb::unique_xmalloc_ptr<char> &note_data,
3484 int *note_size, enum gdb_signal stop_signal)
3486 struct regcache *regcache = get_thread_regcache (&the_procfs_target, ptid);
3487 gdb_gregset_t gregs;
3488 gdb_fpregset_t fpregs;
3489 unsigned long merged_pid;
3491 merged_pid = ptid.lwp () << 16 | ptid.pid ();
3493 /* This part is the old method for fetching registers.
3494 It should be replaced by the newer one using regsets
3495 once it is implemented in this platform:
3496 gdbarch_iterate_over_regset_sections(). */
3498 target_fetch_registers (regcache, -1);
3500 fill_gregset (regcache, &gregs, -1);
3501 note_data.reset (elfcore_write_lwpstatus (obfd,
3502 note_data.release (),
3503 note_size,
3504 merged_pid,
3505 stop_signal,
3506 &gregs));
3507 fill_fpregset (regcache, &fpregs, -1);
3508 note_data.reset (elfcore_write_prfpreg (obfd,
3509 note_data.release (),
3510 note_size,
3511 &fpregs,
3512 sizeof (fpregs)));
3515 struct procfs_corefile_thread_data
3517 procfs_corefile_thread_data (bfd *obfd,
3518 gdb::unique_xmalloc_ptr<char> &note_data,
3519 int *note_size, gdb_signal stop_signal)
3520 : obfd (obfd), note_data (note_data), note_size (note_size),
3521 stop_signal (stop_signal)
3524 bfd *obfd;
3525 gdb::unique_xmalloc_ptr<char> &note_data;
3526 int *note_size;
3527 enum gdb_signal stop_signal;
3530 static int
3531 procfs_corefile_thread_callback (procinfo *pi, procinfo *thread, void *data)
3533 struct procfs_corefile_thread_data *args
3534 = (struct procfs_corefile_thread_data *) data;
3536 if (pi != NULL)
3538 ptid_t ptid = ptid_t (pi->pid, thread->tid, 0);
3540 procfs_do_thread_registers (args->obfd, ptid,
3541 args->note_data,
3542 args->note_size,
3543 args->stop_signal);
3545 return 0;
3548 static int
3549 find_signalled_thread (struct thread_info *info, void *data)
3551 if (info->stop_signal () != GDB_SIGNAL_0
3552 && info->ptid.pid () == inferior_ptid.pid ())
3553 return 1;
3555 return 0;
3558 static enum gdb_signal
3559 find_stop_signal (void)
3561 struct thread_info *info =
3562 iterate_over_threads (find_signalled_thread, NULL);
3564 if (info)
3565 return info->stop_signal ();
3566 else
3567 return GDB_SIGNAL_0;
3570 gdb::unique_xmalloc_ptr<char>
3571 procfs_target::make_corefile_notes (bfd *obfd, int *note_size)
3573 gdb_gregset_t gregs;
3574 char fname[16] = {'\0'};
3575 char psargs[80] = {'\0'};
3576 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3577 gdb::unique_xmalloc_ptr<char> note_data;
3578 enum gdb_signal stop_signal;
3580 if (get_exec_file (0))
3582 strncpy (fname, lbasename (get_exec_file (0)), sizeof (fname));
3583 fname[sizeof (fname) - 1] = 0;
3584 strncpy (psargs, get_exec_file (0), sizeof (psargs));
3585 psargs[sizeof (psargs) - 1] = 0;
3587 const std::string &inf_args = current_inferior ()->args ();
3588 if (!inf_args.empty () &&
3589 inf_args.length () < ((int) sizeof (psargs) - (int) strlen (psargs)))
3591 strncat (psargs, " ",
3592 sizeof (psargs) - strlen (psargs));
3593 strncat (psargs, inf_args.c_str (),
3594 sizeof (psargs) - strlen (psargs));
3598 note_data.reset (elfcore_write_prpsinfo (obfd,
3599 note_data.release (),
3600 note_size,
3601 fname,
3602 psargs));
3604 stop_signal = find_stop_signal ();
3606 fill_gregset (get_thread_regcache (inferior_thread ()), &gregs, -1);
3607 note_data.reset (elfcore_write_pstatus (obfd, note_data.release (), note_size,
3608 inferior_ptid.pid (),
3609 stop_signal, &gregs));
3611 procfs_corefile_thread_data thread_args (obfd, note_data, note_size,
3612 stop_signal);
3613 proc_iterate_over_threads (pi, procfs_corefile_thread_callback,
3614 &thread_args);
3616 std::optional<gdb::byte_vector> auxv =
3617 target_read_alloc (current_inferior ()->top_target (),
3618 TARGET_OBJECT_AUXV, NULL);
3619 if (auxv && !auxv->empty ())
3620 note_data.reset (elfcore_write_note (obfd, note_data.release (), note_size,
3621 "CORE", NT_AUXV, auxv->data (),
3622 auxv->size ()));
3624 return note_data;
3626 /* =================== END GCORE .NOTE "MODULE" =================== */