Automatic date update in version.in
[binutils-gdb.git] / gdb / procfs.c
blob77fdacfd61e1ba94f203cc65acd566860255d0f0
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 "inferior.h"
24 #include "infrun.h"
25 #include "target.h"
26 #include "gdbcore.h"
27 #include "elf-bfd.h"
28 #include "gdbcmd.h"
29 #include "gdbthread.h"
30 #include "regcache.h"
31 #include "inf-child.h"
32 #include "nat/fork-inferior.h"
33 #include "gdbarch.h"
35 #include <sys/procfs.h>
36 #include <sys/fault.h>
37 #include <sys/syscall.h>
38 #include "gdbsupport/gdb_wait.h"
39 #include <signal.h>
40 #include <ctype.h>
41 #include "gdb_bfd.h"
42 #include "auxv.h"
43 #include "procfs.h"
44 #include "observable.h"
45 #include "gdbsupport/scoped_fd.h"
46 #include "gdbsupport/pathstuff.h"
47 #include "gdbsupport/buildargv.h"
48 #include "cli/cli-style.h"
50 /* This module provides the interface between GDB and the
51 /proc file system, which is used on many versions of Unix
52 as a means for debuggers to control other processes.
54 /proc works by imitating a file system: you open a simulated file
55 that represents the process you wish to interact with, and perform
56 operations on that "file" in order to examine or change the state
57 of the other process.
59 The most important thing to know about /proc and this module is
60 that there are two very different interfaces to /proc:
62 One that uses the ioctl system call, and another that uses read
63 and write system calls.
65 This module supports only the Solaris version of the read/write
66 interface. */
68 #include <sys/types.h>
69 #include <dirent.h>
71 #include <fcntl.h>
72 #include <unistd.h>
73 #include <sys/stat.h>
75 /* Note: procfs-utils.h must be included after the above system header
76 files, because it redefines various system calls using macros.
77 This may be incompatible with the prototype declarations. */
79 #include "proc-utils.h"
81 /* Prototypes for supply_gregset etc. */
82 #include "gregset.h"
84 /* =================== TARGET_OPS "MODULE" =================== */
86 /* This module defines the GDB target vector and its methods. */
89 static enum target_xfer_status procfs_xfer_memory (gdb_byte *,
90 const gdb_byte *,
91 ULONGEST, ULONGEST,
92 ULONGEST *);
94 class procfs_target final : public inf_child_target
96 public:
97 void create_inferior (const char *, const std::string &,
98 char **, int) override;
100 void kill () override;
102 void mourn_inferior () override;
104 void attach (const char *, int) override;
105 void detach (inferior *inf, int) override;
107 void resume (ptid_t, int, enum gdb_signal) override;
108 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
110 void fetch_registers (struct regcache *, int) override;
111 void store_registers (struct regcache *, int) override;
113 enum target_xfer_status xfer_partial (enum target_object object,
114 const char *annex,
115 gdb_byte *readbuf,
116 const gdb_byte *writebuf,
117 ULONGEST offset, ULONGEST len,
118 ULONGEST *xfered_len) override;
120 void pass_signals (gdb::array_view<const unsigned char>) override;
122 void files_info () override;
124 void update_thread_list () override;
126 bool thread_alive (ptid_t ptid) override;
128 std::string pid_to_str (ptid_t) override;
130 const char *pid_to_exec_file (int pid) override;
132 thread_control_capabilities get_thread_control_capabilities () override
133 { return tc_schedlock; }
135 /* find_memory_regions support method for gcore */
136 int find_memory_regions (find_memory_region_ftype func, void *data)
137 override;
139 gdb::unique_xmalloc_ptr<char> make_corefile_notes (bfd *, int *) override;
141 bool info_proc (const char *, enum info_proc_what) override;
143 #if PR_MODEL_NATIVE == PR_MODEL_LP64
144 int auxv_parse (const gdb_byte **readptr,
145 const gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
146 override;
147 #endif
149 bool stopped_by_watchpoint () override;
151 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
152 struct expression *) override;
154 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
155 struct expression *) override;
157 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
159 int can_use_hw_breakpoint (enum bptype, int, int) override;
160 bool stopped_data_address (CORE_ADDR *) override;
162 void procfs_init_inferior (int pid);
165 static procfs_target the_procfs_target;
167 #if PR_MODEL_NATIVE == PR_MODEL_LP64
168 /* When GDB is built as 64-bit application on Solaris, the auxv data
169 is presented in 64-bit format. We need to provide a custom parser
170 to handle that. */
172 procfs_target::auxv_parse (const gdb_byte **readptr,
173 const gdb_byte *endptr, CORE_ADDR *typep,
174 CORE_ADDR *valp)
176 bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
177 const gdb_byte *ptr = *readptr;
179 if (endptr == ptr)
180 return 0;
182 if (endptr - ptr < 8 * 2)
183 return -1;
185 *typep = extract_unsigned_integer (ptr, 4, byte_order);
186 ptr += 8;
187 /* The size of data is always 64-bit. If the application is 32-bit,
188 it will be zero extended, as expected. */
189 *valp = extract_unsigned_integer (ptr, 8, byte_order);
190 ptr += 8;
192 *readptr = ptr;
193 return 1;
195 #endif
197 /* =================== END, TARGET_OPS "MODULE" =================== */
199 /* =================== STRUCT PROCINFO "MODULE" =================== */
201 /* FIXME: this comment will soon be out of date W.R.T. threads. */
203 /* The procinfo struct is a wrapper to hold all the state information
204 concerning a /proc process. There should be exactly one procinfo
205 for each process, and since GDB currently can debug only one
206 process at a time, that means there should be only one procinfo.
207 All of the LWP's of a process can be accessed indirectly thru the
208 single process procinfo.
210 However, against the day when GDB may debug more than one process,
211 this data structure is kept in a list (which for now will hold no
212 more than one member), and many functions will have a pointer to a
213 procinfo as an argument.
215 There will be a separate procinfo structure for use by the (not yet
216 implemented) "info proc" command, so that we can print useful
217 information about any random process without interfering with the
218 inferior's procinfo information. */
220 /* format strings for /proc paths */
221 #define CTL_PROC_NAME_FMT "/proc/%d/ctl"
222 #define AS_PROC_NAME_FMT "/proc/%d/as"
223 #define MAP_PROC_NAME_FMT "/proc/%d/map"
224 #define STATUS_PROC_NAME_FMT "/proc/%d/status"
225 #define MAX_PROC_NAME_SIZE sizeof("/proc/999999/lwp/0123456789/lwpstatus")
227 typedef struct procinfo {
228 struct procinfo *next;
229 int pid; /* Process ID */
230 int tid; /* Thread/LWP id */
232 /* process state */
233 int was_stopped;
234 int ignore_next_sigstop;
236 int ctl_fd; /* File descriptor for /proc control file */
237 int status_fd; /* File descriptor for /proc status file */
238 int as_fd; /* File descriptor for /proc as file */
240 char pathname[MAX_PROC_NAME_SIZE]; /* Pathname to /proc entry */
242 fltset_t saved_fltset; /* Saved traced hardware fault set */
243 sigset_t saved_sigset; /* Saved traced signal set */
244 sigset_t saved_sighold; /* Saved held signal set */
245 sysset_t *saved_exitset; /* Saved traced system call exit set */
246 sysset_t *saved_entryset; /* Saved traced system call entry set */
248 pstatus_t prstatus; /* Current process status info */
250 struct procinfo *thread_list;
252 int status_valid : 1;
253 int gregs_valid : 1;
254 int fpregs_valid : 1;
255 int threads_valid: 1;
256 } procinfo;
258 /* Function prototypes for procinfo module: */
260 static procinfo *find_procinfo_or_die (int pid, int tid);
261 static procinfo *find_procinfo (int pid, int tid);
262 static procinfo *create_procinfo (int pid, int tid);
263 static void destroy_procinfo (procinfo *p);
264 static void dead_procinfo (procinfo *p, const char *msg, int killp);
265 static int open_procinfo_files (procinfo *p, int which);
266 static void close_procinfo_files (procinfo *p);
268 static int iterate_over_mappings
269 (procinfo *pi, find_memory_region_ftype child_func, void *data,
270 int (*func) (struct prmap *map, find_memory_region_ftype child_func,
271 void *data));
273 /* The head of the procinfo list: */
274 static procinfo *procinfo_list;
276 /* Search the procinfo list. Return a pointer to procinfo, or NULL if
277 not found. */
279 static procinfo *
280 find_procinfo (int pid, int tid)
282 procinfo *pi;
284 for (pi = procinfo_list; pi; pi = pi->next)
285 if (pi->pid == pid)
286 break;
288 if (pi)
289 if (tid)
291 /* Don't check threads_valid. If we're updating the
292 thread_list, we want to find whatever threads are already
293 here. This means that in general it is the caller's
294 responsibility to check threads_valid and update before
295 calling find_procinfo, if the caller wants to find a new
296 thread. */
298 for (pi = pi->thread_list; pi; pi = pi->next)
299 if (pi->tid == tid)
300 break;
303 return pi;
306 /* Calls find_procinfo, but errors on failure. */
308 static procinfo *
309 find_procinfo_or_die (int pid, int tid)
311 procinfo *pi = find_procinfo (pid, tid);
313 if (pi == NULL)
315 if (tid)
316 error (_("procfs: couldn't find pid %d "
317 "(kernel thread %d) in procinfo list."),
318 pid, tid);
319 else
320 error (_("procfs: couldn't find pid %d in procinfo list."), pid);
322 return pi;
325 /* Wrapper for `open'. The appropriate open call is attempted; if
326 unsuccessful, it will be retried as many times as needed for the
327 EAGAIN and EINTR conditions.
329 For other conditions, retry the open a limited number of times. In
330 addition, a short sleep is imposed prior to retrying the open. The
331 reason for this sleep is to give the kernel a chance to catch up
332 and create the file in question in the event that GDB "wins" the
333 race to open a file before the kernel has created it. */
335 static int
336 open_with_retry (const char *pathname, int flags)
338 int retries_remaining, status;
340 retries_remaining = 2;
342 while (1)
344 status = open (pathname, flags);
346 if (status >= 0 || retries_remaining == 0)
347 break;
348 else if (errno != EINTR && errno != EAGAIN)
350 retries_remaining--;
351 sleep (1);
355 return status;
358 /* Open the file descriptor for the process or LWP. We only open the
359 control file descriptor; the others are opened lazily as needed.
360 Returns the file descriptor, or zero for failure. */
362 enum { FD_CTL, FD_STATUS, FD_AS };
364 static int
365 open_procinfo_files (procinfo *pi, int which)
367 char tmp[MAX_PROC_NAME_SIZE];
368 int fd;
370 /* This function is getting ALMOST long enough to break up into
371 several. Here is some rationale:
373 There are several file descriptors that may need to be open
374 for any given process or LWP. The ones we're interested in are:
375 - control (ctl) write-only change the state
376 - status (status) read-only query the state
377 - address space (as) read/write access memory
378 - map (map) read-only virtual addr map
379 Most of these are opened lazily as they are needed.
380 The pathnames for the 'files' for an LWP look slightly
381 different from those of a first-class process:
382 Pathnames for a process (<proc-id>):
383 /proc/<proc-id>/ctl
384 /proc/<proc-id>/status
385 /proc/<proc-id>/as
386 /proc/<proc-id>/map
387 Pathnames for an LWP (lwp-id):
388 /proc/<proc-id>/lwp/<lwp-id>/lwpctl
389 /proc/<proc-id>/lwp/<lwp-id>/lwpstatus
390 An LWP has no map or address space file descriptor, since
391 the memory map and address space are shared by all LWPs. */
393 /* In this case, there are several different file descriptors that
394 we might be asked to open. The control file descriptor will be
395 opened early, but the others will be opened lazily as they are
396 needed. */
398 strcpy (tmp, pi->pathname);
399 switch (which) { /* Which file descriptor to open? */
400 case FD_CTL:
401 if (pi->tid)
402 strcat (tmp, "/lwpctl");
403 else
404 strcat (tmp, "/ctl");
405 fd = open_with_retry (tmp, O_WRONLY);
406 if (fd < 0)
407 return 0; /* fail */
408 pi->ctl_fd = fd;
409 break;
410 case FD_AS:
411 if (pi->tid)
412 return 0; /* There is no 'as' file descriptor for an lwp. */
413 strcat (tmp, "/as");
414 fd = open_with_retry (tmp, O_RDWR);
415 if (fd < 0)
416 return 0; /* fail */
417 pi->as_fd = fd;
418 break;
419 case FD_STATUS:
420 if (pi->tid)
421 strcat (tmp, "/lwpstatus");
422 else
423 strcat (tmp, "/status");
424 fd = open_with_retry (tmp, O_RDONLY);
425 if (fd < 0)
426 return 0; /* fail */
427 pi->status_fd = fd;
428 break;
429 default:
430 return 0; /* unknown file descriptor */
433 return 1; /* success */
436 /* Allocate a data structure and link it into the procinfo list.
437 First tries to find a pre-existing one (FIXME: why?). Returns the
438 pointer to new procinfo struct. */
440 static procinfo *
441 create_procinfo (int pid, int tid)
443 procinfo *pi, *parent = NULL;
445 pi = find_procinfo (pid, tid);
446 if (pi != NULL)
447 return pi; /* Already exists, nothing to do. */
449 /* Find parent before doing malloc, to save having to cleanup. */
450 if (tid != 0)
451 parent = find_procinfo_or_die (pid, 0); /* FIXME: should I
452 create it if it
453 doesn't exist yet? */
455 pi = XNEW (procinfo);
456 memset (pi, 0, sizeof (procinfo));
457 pi->pid = pid;
458 pi->tid = tid;
460 pi->saved_entryset = XNEW (sysset_t);
461 pi->saved_exitset = XNEW (sysset_t);
463 /* Chain into list. */
464 if (tid == 0)
466 xsnprintf (pi->pathname, sizeof (pi->pathname), "/proc/%d", pid);
467 pi->next = procinfo_list;
468 procinfo_list = pi;
470 else
472 xsnprintf (pi->pathname, sizeof (pi->pathname), "/proc/%d/lwp/%d",
473 pid, tid);
474 pi->next = parent->thread_list;
475 parent->thread_list = pi;
477 return pi;
480 /* Close all file descriptors associated with the procinfo. */
482 static void
483 close_procinfo_files (procinfo *pi)
485 if (pi->ctl_fd > 0)
486 close (pi->ctl_fd);
487 if (pi->as_fd > 0)
488 close (pi->as_fd);
489 if (pi->status_fd > 0)
490 close (pi->status_fd);
491 pi->ctl_fd = pi->as_fd = pi->status_fd = 0;
494 /* Destructor function. Close, unlink and deallocate the object. */
496 static void
497 destroy_one_procinfo (procinfo **list, procinfo *pi)
499 procinfo *ptr;
501 /* Step one: unlink the procinfo from its list. */
502 if (pi == *list)
503 *list = pi->next;
504 else
505 for (ptr = *list; ptr; ptr = ptr->next)
506 if (ptr->next == pi)
508 ptr->next = pi->next;
509 break;
512 /* Step two: close any open file descriptors. */
513 close_procinfo_files (pi);
515 /* Step three: free the memory. */
516 xfree (pi->saved_entryset);
517 xfree (pi->saved_exitset);
518 xfree (pi);
521 static void
522 destroy_procinfo (procinfo *pi)
524 procinfo *tmp;
526 if (pi->tid != 0) /* Destroy a thread procinfo. */
528 tmp = find_procinfo (pi->pid, 0); /* Find the parent process. */
529 destroy_one_procinfo (&tmp->thread_list, pi);
531 else /* Destroy a process procinfo and all its threads. */
533 /* First destroy the children, if any; */
534 while (pi->thread_list != NULL)
535 destroy_one_procinfo (&pi->thread_list, pi->thread_list);
536 /* Then destroy the parent. Genocide!!! */
537 destroy_one_procinfo (&procinfo_list, pi);
541 /* A deleter that calls destroy_procinfo. */
542 struct procinfo_deleter
544 void operator() (procinfo *pi) const
546 destroy_procinfo (pi);
550 typedef std::unique_ptr<procinfo, procinfo_deleter> procinfo_up;
552 enum { NOKILL, KILL };
554 /* To be called on a non_recoverable error for a procinfo. Prints
555 error messages, optionally sends a SIGKILL to the process, then
556 destroys the data structure. */
558 static void
559 dead_procinfo (procinfo *pi, const char *msg, int kill_p)
561 warning_filename_and_errno (pi->pathname, errno);
562 if (kill_p == KILL)
563 kill (pi->pid, SIGKILL);
565 destroy_procinfo (pi);
566 error ("%s", msg);
569 /* =================== END, STRUCT PROCINFO "MODULE" =================== */
571 /* =================== /proc "MODULE" =================== */
573 /* This "module" is the interface layer between the /proc system API
574 and the gdb target vector functions. This layer consists of access
575 functions that encapsulate each of the basic operations that we
576 need to use from the /proc API.
578 The main motivation for this layer is to hide the fact that there
579 were two very different implementations of the /proc API. */
581 static long proc_flags (procinfo *pi);
582 static int proc_why (procinfo *pi);
583 static int proc_what (procinfo *pi);
584 static int proc_set_current_signal (procinfo *pi, int signo);
585 static int proc_get_current_thread (procinfo *pi);
586 static int proc_iterate_over_threads
587 (procinfo *pi,
588 int (*func) (procinfo *, procinfo *, void *),
589 void *ptr);
590 static void proc_resume (procinfo *pi, ptid_t scope_ptid,
591 int step, enum gdb_signal signo);
593 static void
594 proc_warn (procinfo *pi, const char *func, int line)
596 int saved_errno = errno;
597 warning ("procfs: %s line %d, %ps: %s",
598 func, line, styled_string (file_name_style.style (),
599 pi->pathname),
600 safe_strerror (saved_errno));
603 static void
604 proc_error (procinfo *pi, const char *func, int line)
606 int saved_errno = errno;
607 error ("procfs: %s line %d, %s: %s",
608 func, line, pi->pathname, safe_strerror (saved_errno));
611 /* Updates the status struct in the procinfo. There is a 'valid'
612 flag, to let other functions know when this function needs to be
613 called (so the status is only read when it is needed). The status
614 file descriptor is also only opened when it is needed. Returns
615 non-zero for success, zero for failure. */
617 static int
618 proc_get_status (procinfo *pi)
620 /* Status file descriptor is opened "lazily". */
621 if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
623 pi->status_valid = 0;
624 return 0;
627 if (lseek (pi->status_fd, 0, SEEK_SET) < 0)
628 pi->status_valid = 0; /* fail */
629 else
631 /* Sigh... I have to read a different data structure,
632 depending on whether this is a main process or an LWP. */
633 if (pi->tid)
634 pi->status_valid = (read (pi->status_fd,
635 (char *) &pi->prstatus.pr_lwp,
636 sizeof (lwpstatus_t))
637 == sizeof (lwpstatus_t));
638 else
640 pi->status_valid = (read (pi->status_fd,
641 (char *) &pi->prstatus,
642 sizeof (pstatus_t))
643 == sizeof (pstatus_t));
647 if (pi->status_valid)
649 PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
650 proc_why (pi),
651 proc_what (pi),
652 proc_get_current_thread (pi));
655 /* The status struct includes general regs, so mark them valid too. */
656 pi->gregs_valid = pi->status_valid;
657 /* In the read/write multiple-fd model, the status struct includes
658 the fp regs too, so mark them valid too. */
659 pi->fpregs_valid = pi->status_valid;
660 return pi->status_valid; /* True if success, false if failure. */
663 /* Returns the process flags (pr_flags field). */
665 static long
666 proc_flags (procinfo *pi)
668 if (!pi->status_valid)
669 if (!proc_get_status (pi))
670 return 0; /* FIXME: not a good failure value (but what is?) */
672 return pi->prstatus.pr_lwp.pr_flags;
675 /* Returns the pr_why field (why the process stopped). */
677 static int
678 proc_why (procinfo *pi)
680 if (!pi->status_valid)
681 if (!proc_get_status (pi))
682 return 0; /* FIXME: not a good failure value (but what is?) */
684 return pi->prstatus.pr_lwp.pr_why;
687 /* Returns the pr_what field (details of why the process stopped). */
689 static int
690 proc_what (procinfo *pi)
692 if (!pi->status_valid)
693 if (!proc_get_status (pi))
694 return 0; /* FIXME: not a good failure value (but what is?) */
696 return pi->prstatus.pr_lwp.pr_what;
699 /* This function is only called when PI is stopped by a watchpoint.
700 Assuming the OS supports it, write to *ADDR the data address which
701 triggered it and return 1. Return 0 if it is not possible to know
702 the address. */
704 static int
705 proc_watchpoint_address (procinfo *pi, CORE_ADDR *addr)
707 if (!pi->status_valid)
708 if (!proc_get_status (pi))
709 return 0;
711 gdbarch *arch = current_inferior ()->arch ();
712 *addr = gdbarch_pointer_to_address
713 (arch, builtin_type (arch)->builtin_data_ptr,
714 (gdb_byte *) &pi->prstatus.pr_lwp.pr_info.si_addr);
715 return 1;
718 /* Returns the pr_nsysarg field (number of args to the current
719 syscall). */
721 static int
722 proc_nsysarg (procinfo *pi)
724 if (!pi->status_valid)
725 if (!proc_get_status (pi))
726 return 0;
728 return pi->prstatus.pr_lwp.pr_nsysarg;
731 /* Returns the pr_sysarg field (pointer to the arguments of current
732 syscall). */
734 static long *
735 proc_sysargs (procinfo *pi)
737 if (!pi->status_valid)
738 if (!proc_get_status (pi))
739 return NULL;
741 return (long *) &pi->prstatus.pr_lwp.pr_sysarg;
744 /* Set or reset any of the following process flags:
745 PR_FORK -- forked child will inherit trace flags
746 PR_RLC -- traced process runs when last /proc file closed.
747 PR_KLC -- traced process is killed when last /proc file closed.
748 PR_ASYNC -- LWP's get to run/stop independently.
750 This function is done using read/write [PCSET/PCRESET/PCUNSET].
752 Arguments:
753 pi -- the procinfo
754 flag -- one of PR_FORK, PR_RLC, or PR_ASYNC
755 mode -- 1 for set, 0 for reset.
757 Returns non-zero for success, zero for failure. */
759 enum { FLAG_RESET, FLAG_SET };
761 static int
762 proc_modify_flag (procinfo *pi, long flag, long mode)
764 long win = 0; /* default to fail */
766 /* These operations affect the process as a whole, and applying them
767 to an individual LWP has the same meaning as applying them to the
768 main process. Therefore, if we're ever called with a pointer to
769 an LWP's procinfo, let's substitute the process's procinfo and
770 avoid opening the LWP's file descriptor unnecessarily. */
772 if (pi->pid != 0)
773 pi = find_procinfo_or_die (pi->pid, 0);
775 procfs_ctl_t arg[2];
777 if (mode == FLAG_SET) /* Set the flag (RLC, FORK, or ASYNC). */
778 arg[0] = PCSET;
779 else /* Reset the flag. */
780 arg[0] = PCUNSET;
782 arg[1] = flag;
783 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
785 /* The above operation renders the procinfo's cached pstatus
786 obsolete. */
787 pi->status_valid = 0;
789 if (!win)
790 warning (_("procfs: modify_flag failed to turn %s %s"),
791 flag == PR_FORK ? "PR_FORK" :
792 flag == PR_RLC ? "PR_RLC" :
793 flag == PR_ASYNC ? "PR_ASYNC" :
794 flag == PR_KLC ? "PR_KLC" :
795 "<unknown flag>",
796 mode == FLAG_RESET ? "off" : "on");
798 return win;
801 /* Set the run_on_last_close flag. Process with all threads will
802 become runnable when debugger closes all /proc fds. Returns
803 non-zero for success, zero for failure. */
805 static int
806 proc_set_run_on_last_close (procinfo *pi)
808 return proc_modify_flag (pi, PR_RLC, FLAG_SET);
811 /* Reset the run_on_last_close flag. The process will NOT become
812 runnable when debugger closes its file handles. Returns non-zero
813 for success, zero for failure. */
815 static int
816 proc_unset_run_on_last_close (procinfo *pi)
818 return proc_modify_flag (pi, PR_RLC, FLAG_RESET);
821 /* Reset inherit_on_fork flag. If the process forks a child while we
822 are registered for events in the parent, then we will NOT receive
823 events from the child. Returns non-zero for success, zero for
824 failure. */
826 static int
827 proc_unset_inherit_on_fork (procinfo *pi)
829 return proc_modify_flag (pi, PR_FORK, FLAG_RESET);
832 /* Set PR_ASYNC flag. If one LWP stops because of a debug event
833 (signal etc.), the remaining LWPs will continue to run. Returns
834 non-zero for success, zero for failure. */
836 static int
837 proc_set_async (procinfo *pi)
839 return proc_modify_flag (pi, PR_ASYNC, FLAG_SET);
842 /* Reset PR_ASYNC flag. If one LWP stops because of a debug event
843 (signal etc.), then all other LWPs will stop as well. Returns
844 non-zero for success, zero for failure. */
846 static int
847 proc_unset_async (procinfo *pi)
849 return proc_modify_flag (pi, PR_ASYNC, FLAG_RESET);
852 /* Request the process/LWP to stop. Does not wait. Returns non-zero
853 for success, zero for failure. */
855 static int
856 proc_stop_process (procinfo *pi)
858 int win;
860 /* We might conceivably apply this operation to an LWP, and the
861 LWP's ctl file descriptor might not be open. */
863 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
864 return 0;
865 else
867 procfs_ctl_t cmd = PCSTOP;
869 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
872 return win;
875 /* Wait for the process or LWP to stop (block until it does). Returns
876 non-zero for success, zero for failure. */
878 static int
879 proc_wait_for_stop (procinfo *pi)
881 int win;
883 /* We should never have to apply this operation to any procinfo
884 except the one for the main process. If that ever changes for
885 any reason, then take out the following clause and replace it
886 with one that makes sure the ctl_fd is open. */
888 if (pi->tid != 0)
889 pi = find_procinfo_or_die (pi->pid, 0);
891 procfs_ctl_t cmd = PCWSTOP;
893 set_sigint_trap ();
895 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
897 clear_sigint_trap ();
899 /* We been runnin' and we stopped -- need to update status. */
900 pi->status_valid = 0;
902 return win;
905 /* Make the process or LWP runnable.
907 Options (not all are implemented):
908 - single-step
909 - clear current fault
910 - clear current signal
911 - abort the current system call
912 - stop as soon as finished with system call
914 Always clears the current fault. PI is the process or LWP to
915 operate on. If STEP is true, set the process or LWP to trap after
916 one instruction. If SIGNO is zero, clear the current signal if
917 any; if non-zero, set the current signal to this one. Returns
918 non-zero for success, zero for failure. */
920 static int
921 proc_run_process (procinfo *pi, int step, int signo)
923 int win;
924 int runflags;
926 /* We will probably have to apply this operation to individual
927 threads, so make sure the control file descriptor is open. */
929 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
930 return 0;
932 runflags = PRCFAULT; /* Always clear current fault. */
933 if (step)
934 runflags |= PRSTEP;
935 if (signo == 0)
936 runflags |= PRCSIG;
937 else if (signo != -1) /* -1 means do nothing W.R.T. signals. */
938 proc_set_current_signal (pi, signo);
940 procfs_ctl_t cmd[2];
942 cmd[0] = PCRUN;
943 cmd[1] = runflags;
944 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
946 return win;
949 /* Register to trace signals in the process or LWP. Returns non-zero
950 for success, zero for failure. */
952 static int
953 proc_set_traced_signals (procinfo *pi, sigset_t *sigset)
955 int win;
957 /* We should never have to apply this operation to any procinfo
958 except the one for the main process. If that ever changes for
959 any reason, then take out the following clause and replace it
960 with one that makes sure the ctl_fd is open. */
962 if (pi->tid != 0)
963 pi = find_procinfo_or_die (pi->pid, 0);
965 struct {
966 procfs_ctl_t cmd;
967 /* Use char array to avoid alignment issues. */
968 char sigset[sizeof (sigset_t)];
969 } arg;
971 arg.cmd = PCSTRACE;
972 memcpy (&arg.sigset, sigset, sizeof (sigset_t));
974 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
976 /* The above operation renders the procinfo's cached pstatus obsolete. */
977 pi->status_valid = 0;
979 if (!win)
980 warning (_("procfs: set_traced_signals failed"));
981 return win;
984 /* Register to trace hardware faults in the process or LWP. Returns
985 non-zero for success, zero for failure. */
987 static int
988 proc_set_traced_faults (procinfo *pi, fltset_t *fltset)
990 int win;
992 /* We should never have to apply this operation to any procinfo
993 except the one for the main process. If that ever changes for
994 any reason, then take out the following clause and replace it
995 with one that makes sure the ctl_fd is open. */
997 if (pi->tid != 0)
998 pi = find_procinfo_or_die (pi->pid, 0);
1000 struct {
1001 procfs_ctl_t cmd;
1002 /* Use char array to avoid alignment issues. */
1003 char fltset[sizeof (fltset_t)];
1004 } arg;
1006 arg.cmd = PCSFAULT;
1007 memcpy (&arg.fltset, fltset, sizeof (fltset_t));
1009 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1011 /* The above operation renders the procinfo's cached pstatus obsolete. */
1012 pi->status_valid = 0;
1014 return win;
1017 /* Register to trace entry to system calls in the process or LWP.
1018 Returns non-zero for success, zero for failure. */
1020 static int
1021 proc_set_traced_sysentry (procinfo *pi, sysset_t *sysset)
1023 int win;
1025 /* We should never have to apply this operation to any procinfo
1026 except the one for the main process. If that ever changes for
1027 any reason, then take out the following clause and replace it
1028 with one that makes sure the ctl_fd is open. */
1030 if (pi->tid != 0)
1031 pi = find_procinfo_or_die (pi->pid, 0);
1033 struct {
1034 procfs_ctl_t cmd;
1035 /* Use char array to avoid alignment issues. */
1036 char sysset[sizeof (sysset_t)];
1037 } arg;
1039 arg.cmd = PCSENTRY;
1040 memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1042 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1044 /* The above operation renders the procinfo's cached pstatus
1045 obsolete. */
1046 pi->status_valid = 0;
1048 return win;
1051 /* Register to trace exit from system calls in the process or LWP.
1052 Returns non-zero for success, zero for failure. */
1054 static int
1055 proc_set_traced_sysexit (procinfo *pi, sysset_t *sysset)
1057 int win;
1059 /* We should never have to apply this operation to any procinfo
1060 except the one for the main process. If that ever changes for
1061 any reason, then take out the following clause and replace it
1062 with one that makes sure the ctl_fd is open. */
1064 if (pi->tid != 0)
1065 pi = find_procinfo_or_die (pi->pid, 0);
1067 struct gdb_proc_ctl_pcsexit {
1068 procfs_ctl_t cmd;
1069 /* Use char array to avoid alignment issues. */
1070 char sysset[sizeof (sysset_t)];
1071 } arg;
1073 arg.cmd = PCSEXIT;
1074 memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1076 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1078 /* The above operation renders the procinfo's cached pstatus
1079 obsolete. */
1080 pi->status_valid = 0;
1082 return win;
1085 /* Specify the set of blocked / held signals in the process or LWP.
1086 Returns non-zero for success, zero for failure. */
1088 static int
1089 proc_set_held_signals (procinfo *pi, sigset_t *sighold)
1091 int win;
1093 /* We should never have to apply this operation to any procinfo
1094 except the one for the main process. If that ever changes for
1095 any reason, then take out the following clause and replace it
1096 with one that makes sure the ctl_fd is open. */
1098 if (pi->tid != 0)
1099 pi = find_procinfo_or_die (pi->pid, 0);
1101 struct {
1102 procfs_ctl_t cmd;
1103 /* Use char array to avoid alignment issues. */
1104 char hold[sizeof (sigset_t)];
1105 } arg;
1107 arg.cmd = PCSHOLD;
1108 memcpy (&arg.hold, sighold, sizeof (sigset_t));
1109 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1111 /* The above operation renders the procinfo's cached pstatus
1112 obsolete. */
1113 pi->status_valid = 0;
1115 return win;
1118 /* Returns the set of signals that are held / blocked. Will also copy
1119 the sigset if SAVE is non-zero. */
1121 static sigset_t *
1122 proc_get_held_signals (procinfo *pi, sigset_t *save)
1124 sigset_t *ret = NULL;
1126 /* We should never have to apply this operation to any procinfo
1127 except the one for the main process. If that ever changes for
1128 any reason, then take out the following clause and replace it
1129 with one that makes sure the ctl_fd is open. */
1131 if (pi->tid != 0)
1132 pi = find_procinfo_or_die (pi->pid, 0);
1134 if (!pi->status_valid)
1135 if (!proc_get_status (pi))
1136 return NULL;
1138 ret = &pi->prstatus.pr_lwp.pr_lwphold;
1139 if (save && ret)
1140 memcpy (save, ret, sizeof (sigset_t));
1142 return ret;
1145 /* Returns the set of signals that are traced / debugged. Will also
1146 copy the sigset if SAVE is non-zero. */
1148 static sigset_t *
1149 proc_get_traced_signals (procinfo *pi, sigset_t *save)
1151 sigset_t *ret = NULL;
1153 /* We should never have to apply this operation to any procinfo
1154 except the one for the main process. If that ever changes for
1155 any reason, then take out the following clause and replace it
1156 with one that makes sure the ctl_fd is open. */
1158 if (pi->tid != 0)
1159 pi = find_procinfo_or_die (pi->pid, 0);
1161 if (!pi->status_valid)
1162 if (!proc_get_status (pi))
1163 return NULL;
1165 ret = &pi->prstatus.pr_sigtrace;
1166 if (save && ret)
1167 memcpy (save, ret, sizeof (sigset_t));
1169 return ret;
1172 /* Returns the set of hardware faults that are traced /debugged. Will
1173 also copy the faultset if SAVE is non-zero. */
1175 static fltset_t *
1176 proc_get_traced_faults (procinfo *pi, fltset_t *save)
1178 fltset_t *ret = NULL;
1180 /* We should never have to apply this operation to any procinfo
1181 except the one for the main process. If that ever changes for
1182 any reason, then take out the following clause and replace it
1183 with one that makes sure the ctl_fd is open. */
1185 if (pi->tid != 0)
1186 pi = find_procinfo_or_die (pi->pid, 0);
1188 if (!pi->status_valid)
1189 if (!proc_get_status (pi))
1190 return NULL;
1192 ret = &pi->prstatus.pr_flttrace;
1193 if (save && ret)
1194 memcpy (save, ret, sizeof (fltset_t));
1196 return ret;
1199 /* Returns the set of syscalls that are traced /debugged on entry.
1200 Will also copy the syscall set if SAVE is non-zero. */
1202 static sysset_t *
1203 proc_get_traced_sysentry (procinfo *pi, sysset_t *save)
1205 sysset_t *ret = NULL;
1207 /* We should never have to apply this operation to any procinfo
1208 except the one for the main process. If that ever changes for
1209 any reason, then take out the following clause and replace it
1210 with one that makes sure the ctl_fd is open. */
1212 if (pi->tid != 0)
1213 pi = find_procinfo_or_die (pi->pid, 0);
1215 if (!pi->status_valid)
1216 if (!proc_get_status (pi))
1217 return NULL;
1219 ret = &pi->prstatus.pr_sysentry;
1220 if (save && ret)
1221 memcpy (save, ret, sizeof (sysset_t));
1223 return ret;
1226 /* Returns the set of syscalls that are traced /debugged on exit.
1227 Will also copy the syscall set if SAVE is non-zero. */
1229 static sysset_t *
1230 proc_get_traced_sysexit (procinfo *pi, sysset_t *save)
1232 sysset_t *ret = NULL;
1234 /* We should never have to apply this operation to any procinfo
1235 except the one for the main process. If that ever changes for
1236 any reason, then take out the following clause and replace it
1237 with one that makes sure the ctl_fd is open. */
1239 if (pi->tid != 0)
1240 pi = find_procinfo_or_die (pi->pid, 0);
1242 if (!pi->status_valid)
1243 if (!proc_get_status (pi))
1244 return NULL;
1246 ret = &pi->prstatus.pr_sysexit;
1247 if (save && ret)
1248 memcpy (save, ret, sizeof (sysset_t));
1250 return ret;
1253 /* The current fault (if any) is cleared; the associated signal will
1254 not be sent to the process or LWP when it resumes. Returns
1255 non-zero for success, zero for failure. */
1257 static int
1258 proc_clear_current_fault (procinfo *pi)
1260 int win;
1262 /* We should never have to apply this operation to any procinfo
1263 except the one for the main process. If that ever changes for
1264 any reason, then take out the following clause and replace it
1265 with one that makes sure the ctl_fd is open. */
1267 if (pi->tid != 0)
1268 pi = find_procinfo_or_die (pi->pid, 0);
1270 procfs_ctl_t cmd = PCCFAULT;
1272 win = (write (pi->ctl_fd, (void *) &cmd, sizeof (cmd)) == sizeof (cmd));
1274 return win;
1277 /* Set the "current signal" that will be delivered next to the
1278 process. NOTE: semantics are different from those of KILL. This
1279 signal will be delivered to the process or LWP immediately when it
1280 is resumed (even if the signal is held/blocked); it will NOT
1281 immediately cause another event of interest, and will NOT first
1282 trap back to the debugger. Returns non-zero for success, zero for
1283 failure. */
1285 static int
1286 proc_set_current_signal (procinfo *pi, int signo)
1288 int win;
1289 struct {
1290 procfs_ctl_t cmd;
1291 /* Use char array to avoid alignment issues. */
1292 char sinfo[sizeof (siginfo_t)];
1293 } arg;
1294 siginfo_t mysinfo;
1295 process_stratum_target *wait_target;
1296 ptid_t wait_ptid;
1297 struct target_waitstatus wait_status;
1299 /* We should never have to apply this operation to any procinfo
1300 except the one for the main process. If that ever changes for
1301 any reason, then take out the following clause and replace it
1302 with one that makes sure the ctl_fd is open. */
1304 if (pi->tid != 0)
1305 pi = find_procinfo_or_die (pi->pid, 0);
1307 /* The pointer is just a type alias. */
1308 get_last_target_status (&wait_target, &wait_ptid, &wait_status);
1309 if (wait_target == &the_procfs_target
1310 && wait_ptid == inferior_ptid
1311 && wait_status.kind () == TARGET_WAITKIND_STOPPED
1312 && wait_status.sig () == gdb_signal_from_host (signo)
1313 && proc_get_status (pi)
1314 && pi->prstatus.pr_lwp.pr_info.si_signo == signo
1316 /* Use the siginfo associated with the signal being
1317 redelivered. */
1318 memcpy (arg.sinfo, &pi->prstatus.pr_lwp.pr_info, sizeof (siginfo_t));
1319 else
1321 mysinfo.si_signo = signo;
1322 mysinfo.si_code = 0;
1323 mysinfo.si_pid = getpid (); /* ?why? */
1324 mysinfo.si_uid = getuid (); /* ?why? */
1325 memcpy (arg.sinfo, &mysinfo, sizeof (siginfo_t));
1328 arg.cmd = PCSSIG;
1329 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1331 return win;
1334 /* The current signal (if any) is cleared, and is not sent to the
1335 process or LWP when it resumes. Returns non-zero for success, zero
1336 for failure. */
1338 static int
1339 proc_clear_current_signal (procinfo *pi)
1341 int win;
1343 /* We should never have to apply this operation to any procinfo
1344 except the one for the main process. If that ever changes for
1345 any reason, then take out the following clause and replace it
1346 with one that makes sure the ctl_fd is open. */
1348 if (pi->tid != 0)
1349 pi = find_procinfo_or_die (pi->pid, 0);
1351 struct {
1352 procfs_ctl_t cmd;
1353 /* Use char array to avoid alignment issues. */
1354 char sinfo[sizeof (siginfo_t)];
1355 } arg;
1356 siginfo_t mysinfo;
1358 arg.cmd = PCSSIG;
1359 /* The pointer is just a type alias. */
1360 mysinfo.si_signo = 0;
1361 mysinfo.si_code = 0;
1362 mysinfo.si_errno = 0;
1363 mysinfo.si_pid = getpid (); /* ?why? */
1364 mysinfo.si_uid = getuid (); /* ?why? */
1365 memcpy (arg.sinfo, &mysinfo, sizeof (siginfo_t));
1367 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1369 return win;
1372 /* Return the general-purpose registers for the process or LWP
1373 corresponding to PI. Upon failure, return NULL. */
1375 static gdb_gregset_t *
1376 proc_get_gregs (procinfo *pi)
1378 if (!pi->status_valid || !pi->gregs_valid)
1379 if (!proc_get_status (pi))
1380 return NULL;
1382 return &pi->prstatus.pr_lwp.pr_reg;
1385 /* Return the general-purpose registers for the process or LWP
1386 corresponding to PI. Upon failure, return NULL. */
1388 static gdb_fpregset_t *
1389 proc_get_fpregs (procinfo *pi)
1391 if (!pi->status_valid || !pi->fpregs_valid)
1392 if (!proc_get_status (pi))
1393 return NULL;
1395 return &pi->prstatus.pr_lwp.pr_fpreg;
1398 /* Write the general-purpose registers back to the process or LWP
1399 corresponding to PI. Return non-zero for success, zero for
1400 failure. */
1402 static int
1403 proc_set_gregs (procinfo *pi)
1405 gdb_gregset_t *gregs;
1406 int win;
1408 gregs = proc_get_gregs (pi);
1409 if (gregs == NULL)
1410 return 0; /* proc_get_regs has already warned. */
1412 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1413 return 0;
1414 else
1416 struct {
1417 procfs_ctl_t cmd;
1418 /* Use char array to avoid alignment issues. */
1419 char gregs[sizeof (gdb_gregset_t)];
1420 } arg;
1422 arg.cmd = PCSREG;
1423 memcpy (&arg.gregs, gregs, sizeof (arg.gregs));
1424 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1427 /* Policy: writing the registers invalidates our cache. */
1428 pi->gregs_valid = 0;
1429 return win;
1432 /* Write the floating-pointer registers back to the process or LWP
1433 corresponding to PI. Return non-zero for success, zero for
1434 failure. */
1436 static int
1437 proc_set_fpregs (procinfo *pi)
1439 gdb_fpregset_t *fpregs;
1440 int win;
1442 fpregs = proc_get_fpregs (pi);
1443 if (fpregs == NULL)
1444 return 0; /* proc_get_fpregs has already warned. */
1446 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1447 return 0;
1448 else
1450 struct {
1451 procfs_ctl_t cmd;
1452 /* Use char array to avoid alignment issues. */
1453 char fpregs[sizeof (gdb_fpregset_t)];
1454 } arg;
1456 arg.cmd = PCSFPREG;
1457 memcpy (&arg.fpregs, fpregs, sizeof (arg.fpregs));
1458 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1461 /* Policy: writing the registers invalidates our cache. */
1462 pi->fpregs_valid = 0;
1463 return win;
1466 /* Send a signal to the proc or lwp with the semantics of "kill()".
1467 Returns non-zero for success, zero for failure. */
1469 static int
1470 proc_kill (procinfo *pi, int signo)
1472 int win;
1474 /* We might conceivably apply this operation to an LWP, and the
1475 LWP's ctl file descriptor might not be open. */
1477 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1478 return 0;
1479 else
1481 procfs_ctl_t cmd[2];
1483 cmd[0] = PCKILL;
1484 cmd[1] = signo;
1485 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
1488 return win;
1491 /* Find the pid of the process that started this one. Returns the
1492 parent process pid, or zero. */
1494 static int
1495 proc_parent_pid (procinfo *pi)
1497 /* We should never have to apply this operation to any procinfo
1498 except the one for the main process. If that ever changes for
1499 any reason, then take out the following clause and replace it
1500 with one that makes sure the ctl_fd is open. */
1502 if (pi->tid != 0)
1503 pi = find_procinfo_or_die (pi->pid, 0);
1505 if (!pi->status_valid)
1506 if (!proc_get_status (pi))
1507 return 0;
1509 return pi->prstatus.pr_ppid;
1512 /* Convert a target address (a.k.a. CORE_ADDR) into a host address
1513 (a.k.a void pointer)! */
1515 static void *
1516 procfs_address_to_host_pointer (CORE_ADDR addr)
1518 gdbarch *arch = current_inferior ()->arch ();
1519 type *ptr_type = builtin_type (arch)->builtin_data_ptr;
1520 void *ptr;
1522 gdb_assert (sizeof (ptr) == ptr_type->length ());
1523 gdbarch_address_to_pointer (arch, ptr_type, (gdb_byte *) &ptr, addr);
1524 return ptr;
1527 static int
1528 proc_set_watchpoint (procinfo *pi, CORE_ADDR addr, int len, int wflags)
1530 struct {
1531 procfs_ctl_t cmd;
1532 char watch[sizeof (prwatch_t)];
1533 } arg;
1534 prwatch_t pwatch;
1536 /* NOTE: cagney/2003-02-01: Even more horrible hack. Need to
1537 convert a target address into something that can be stored in a
1538 native data structure. */
1539 pwatch.pr_vaddr = (uintptr_t) procfs_address_to_host_pointer (addr);
1540 pwatch.pr_size = len;
1541 pwatch.pr_wflags = wflags;
1542 arg.cmd = PCWATCH;
1543 memcpy (arg.watch, &pwatch, sizeof (prwatch_t));
1544 return (write (pi->ctl_fd, &arg, sizeof (arg)) == sizeof (arg));
1547 /* =============== END, non-thread part of /proc "MODULE" =============== */
1549 /* =================== Thread "MODULE" =================== */
1551 /* Returns the number of threads for the process. */
1553 static int
1554 proc_get_nthreads (procinfo *pi)
1556 if (!pi->status_valid)
1557 if (!proc_get_status (pi))
1558 return 0;
1560 /* Only works for the process procinfo, because the LWP procinfos do not
1561 get prstatus filled in. */
1562 if (pi->tid != 0) /* Find the parent process procinfo. */
1563 pi = find_procinfo_or_die (pi->pid, 0);
1564 return pi->prstatus.pr_nlwp;
1567 /* Return the ID of the thread that had an event of interest.
1568 (ie. the one that hit a breakpoint or other traced event). All
1569 other things being equal, this should be the ID of a thread that is
1570 currently executing. */
1572 static int
1573 proc_get_current_thread (procinfo *pi)
1575 /* Note: this should be applied to the root procinfo for the
1576 process, not to the procinfo for an LWP. If applied to the
1577 procinfo for an LWP, it will simply return that LWP's ID. In
1578 that case, find the parent process procinfo. */
1580 if (pi->tid != 0)
1581 pi = find_procinfo_or_die (pi->pid, 0);
1583 if (!pi->status_valid)
1584 if (!proc_get_status (pi))
1585 return 0;
1587 return pi->prstatus.pr_lwp.pr_lwpid;
1590 /* Discover the IDs of all the threads within the process, and create
1591 a procinfo for each of them (chained to the parent). Returns
1592 non-zero for success, zero for failure. */
1594 static int
1595 proc_delete_dead_threads (procinfo *parent, procinfo *thread, void *ignore)
1597 if (thread && parent) /* sanity */
1599 thread->status_valid = 0;
1600 if (!proc_get_status (thread))
1601 destroy_one_procinfo (&parent->thread_list, thread);
1603 return 0; /* keep iterating */
1606 static int
1607 proc_update_threads (procinfo *pi)
1609 char pathname[MAX_PROC_NAME_SIZE + 16];
1610 struct dirent *direntry;
1611 procinfo *thread;
1612 gdb_dir_up dirp;
1613 int lwpid;
1615 /* We should never have to apply this operation to any procinfo
1616 except the one for the main process. If that ever changes for
1617 any reason, then take out the following clause and replace it
1618 with one that makes sure the ctl_fd is open. */
1620 if (pi->tid != 0)
1621 pi = find_procinfo_or_die (pi->pid, 0);
1623 proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
1625 /* Note: this brute-force method was originally devised for Unixware
1626 (support removed since), and will also work on Solaris 2.6 and
1627 2.7. The original comment mentioned the existence of a much
1628 simpler and more elegant way to do this on Solaris, but didn't
1629 point out what that was. */
1631 strcpy (pathname, pi->pathname);
1632 strcat (pathname, "/lwp");
1633 dirp.reset (opendir (pathname));
1634 if (dirp == NULL)
1635 proc_error (pi, "update_threads, opendir", __LINE__);
1637 while ((direntry = readdir (dirp.get ())) != NULL)
1638 if (direntry->d_name[0] != '.') /* skip '.' and '..' */
1640 lwpid = atoi (&direntry->d_name[0]);
1641 thread = create_procinfo (pi->pid, lwpid);
1642 if (thread == NULL)
1643 proc_error (pi, "update_threads, create_procinfo", __LINE__);
1645 pi->threads_valid = 1;
1646 return 1;
1649 /* Given a pointer to a function, call that function once for each lwp
1650 in the procinfo list, until the function returns non-zero, in which
1651 event return the value returned by the function.
1653 Note: this function does NOT call update_threads. If you want to
1654 discover new threads first, you must call that function explicitly.
1655 This function just makes a quick pass over the currently-known
1656 procinfos.
1658 PI is the parent process procinfo. FUNC is the per-thread
1659 function. PTR is an opaque parameter for function. Returns the
1660 first non-zero return value from the callee, or zero. */
1662 static int
1663 proc_iterate_over_threads (procinfo *pi,
1664 int (*func) (procinfo *, procinfo *, void *),
1665 void *ptr)
1667 procinfo *thread, *next;
1668 int retval = 0;
1670 /* We should never have to apply this operation to any procinfo
1671 except the one for the main process. If that ever changes for
1672 any reason, then take out the following clause and replace it
1673 with one that makes sure the ctl_fd is open. */
1675 if (pi->tid != 0)
1676 pi = find_procinfo_or_die (pi->pid, 0);
1678 for (thread = pi->thread_list; thread != NULL; thread = next)
1680 next = thread->next; /* In case thread is destroyed. */
1681 retval = (*func) (pi, thread, ptr);
1682 if (retval != 0)
1683 break;
1686 return retval;
1689 /* =================== END, Thread "MODULE" =================== */
1691 /* =================== END, /proc "MODULE" =================== */
1693 /* =================== GDB "MODULE" =================== */
1695 /* Here are all of the gdb target vector functions and their
1696 friends. */
1698 static void do_attach (ptid_t ptid);
1699 static void do_detach ();
1700 static void proc_trace_syscalls_1 (procinfo *pi, int syscallnum,
1701 int entry_or_exit, int mode, int from_tty);
1703 /* Sets up the inferior to be debugged. Registers to trace signals,
1704 hardware faults, and syscalls. Note: does not set RLC flag: caller
1705 may want to customize that. Returns zero for success (note!
1706 unlike most functions in this module); on failure, returns the LINE
1707 NUMBER where it failed! */
1709 static int
1710 procfs_debug_inferior (procinfo *pi)
1712 fltset_t traced_faults;
1713 sigset_t traced_signals;
1714 sysset_t *traced_syscall_entries;
1715 sysset_t *traced_syscall_exits;
1716 int status;
1718 /* Register to trace hardware faults in the child. */
1719 prfillset (&traced_faults); /* trace all faults... */
1720 prdelset (&traced_faults, FLTPAGE); /* except page fault. */
1721 if (!proc_set_traced_faults (pi, &traced_faults))
1722 return __LINE__;
1724 /* Initially, register to trace all signals in the child. */
1725 prfillset (&traced_signals);
1726 if (!proc_set_traced_signals (pi, &traced_signals))
1727 return __LINE__;
1730 /* Register to trace the 'exit' system call (on entry). */
1731 traced_syscall_entries = XNEW (sysset_t);
1732 premptyset (traced_syscall_entries);
1733 praddset (traced_syscall_entries, SYS_exit);
1734 praddset (traced_syscall_entries, SYS_lwp_exit);
1736 status = proc_set_traced_sysentry (pi, traced_syscall_entries);
1737 xfree (traced_syscall_entries);
1738 if (!status)
1739 return __LINE__;
1741 /* Method for tracing exec syscalls. */
1742 traced_syscall_exits = XNEW (sysset_t);
1743 premptyset (traced_syscall_exits);
1744 praddset (traced_syscall_exits, SYS_execve);
1745 praddset (traced_syscall_exits, SYS_lwp_create);
1746 praddset (traced_syscall_exits, SYS_lwp_exit);
1748 status = proc_set_traced_sysexit (pi, traced_syscall_exits);
1749 xfree (traced_syscall_exits);
1750 if (!status)
1751 return __LINE__;
1753 return 0;
1756 void
1757 procfs_target::attach (const char *args, int from_tty)
1759 int pid;
1761 pid = parse_pid_to_attach (args);
1763 if (pid == getpid ())
1764 error (_("Attaching GDB to itself is not a good idea..."));
1766 /* Push the target if needed, ensure it gets un-pushed it if attach fails. */
1767 inferior *inf = current_inferior ();
1768 target_unpush_up unpusher;
1769 if (!inf->target_is_pushed (this))
1771 inf->push_target (this);
1772 unpusher.reset (this);
1775 target_announce_attach (from_tty, pid);
1777 do_attach (ptid_t (pid));
1779 /* Everything went fine, keep the target pushed. */
1780 unpusher.release ();
1783 void
1784 procfs_target::detach (inferior *inf, int from_tty)
1786 target_announce_detach (from_tty);
1788 do_detach ();
1790 switch_to_no_thread ();
1791 detach_inferior (inf);
1792 maybe_unpush_target ();
1795 static void
1796 do_attach (ptid_t ptid)
1798 procinfo *pi;
1799 struct inferior *inf;
1800 int fail;
1801 int lwpid;
1803 pi = create_procinfo (ptid.pid (), 0);
1804 if (pi == NULL)
1805 perror (_("procfs: out of memory in 'attach'"));
1807 if (!open_procinfo_files (pi, FD_CTL))
1809 int saved_errno = errno;
1810 std::string errmsg
1811 = string_printf ("procfs:%d -- do_attach: couldn't open /proc "
1812 "file for process %d", __LINE__, ptid.pid ());
1813 errno = saved_errno;
1814 dead_procinfo (pi, errmsg.c_str (), NOKILL);
1817 /* Stop the process (if it isn't already stopped). */
1818 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1820 pi->was_stopped = 1;
1821 proc_prettyprint_why (proc_why (pi), proc_what (pi), 1);
1823 else
1825 pi->was_stopped = 0;
1826 /* Set the process to run again when we close it. */
1827 if (!proc_set_run_on_last_close (pi))
1828 dead_procinfo (pi, "do_attach: couldn't set RLC.", NOKILL);
1830 /* Now stop the process. */
1831 if (!proc_stop_process (pi))
1832 dead_procinfo (pi, "do_attach: couldn't stop the process.", NOKILL);
1833 pi->ignore_next_sigstop = 1;
1835 /* Save some of the /proc state to be restored if we detach. */
1836 if (!proc_get_traced_faults (pi, &pi->saved_fltset))
1837 dead_procinfo (pi, "do_attach: couldn't save traced faults.", NOKILL);
1838 if (!proc_get_traced_signals (pi, &pi->saved_sigset))
1839 dead_procinfo (pi, "do_attach: couldn't save traced signals.", NOKILL);
1840 if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
1841 dead_procinfo (pi, "do_attach: couldn't save traced syscall entries.",
1842 NOKILL);
1843 if (!proc_get_traced_sysexit (pi, pi->saved_exitset))
1844 dead_procinfo (pi, "do_attach: couldn't save traced syscall exits.",
1845 NOKILL);
1846 if (!proc_get_held_signals (pi, &pi->saved_sighold))
1847 dead_procinfo (pi, "do_attach: couldn't save held signals.", NOKILL);
1849 fail = procfs_debug_inferior (pi);
1850 if (fail != 0)
1851 dead_procinfo (pi, "do_attach: failed in procfs_debug_inferior", NOKILL);
1853 inf = current_inferior ();
1854 inferior_appeared (inf, pi->pid);
1855 /* Let GDB know that the inferior was attached. */
1856 inf->attach_flag = true;
1858 /* Create a procinfo for the current lwp. */
1859 lwpid = proc_get_current_thread (pi);
1860 create_procinfo (pi->pid, lwpid);
1862 /* Add it to gdb's thread list. */
1863 ptid = ptid_t (pi->pid, lwpid, 0);
1864 thread_info *thr = add_thread (&the_procfs_target, ptid);
1865 switch_to_thread (thr);
1868 static void
1869 do_detach ()
1871 procinfo *pi;
1873 /* Find procinfo for the main process. */
1874 pi = find_procinfo_or_die (inferior_ptid.pid (),
1875 0); /* FIXME: threads */
1877 if (!proc_set_traced_signals (pi, &pi->saved_sigset))
1878 proc_warn (pi, "do_detach, set_traced_signal", __LINE__);
1880 if (!proc_set_traced_faults (pi, &pi->saved_fltset))
1881 proc_warn (pi, "do_detach, set_traced_faults", __LINE__);
1883 if (!proc_set_traced_sysentry (pi, pi->saved_entryset))
1884 proc_warn (pi, "do_detach, set_traced_sysentry", __LINE__);
1886 if (!proc_set_traced_sysexit (pi, pi->saved_exitset))
1887 proc_warn (pi, "do_detach, set_traced_sysexit", __LINE__);
1889 if (!proc_set_held_signals (pi, &pi->saved_sighold))
1890 proc_warn (pi, "do_detach, set_held_signals", __LINE__);
1892 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1893 if (!(pi->was_stopped)
1894 || query (_("Was stopped when attached, make it runnable again? ")))
1896 /* Clear any pending signal. */
1897 if (!proc_clear_current_fault (pi))
1898 proc_warn (pi, "do_detach, clear_current_fault", __LINE__);
1900 if (!proc_clear_current_signal (pi))
1901 proc_warn (pi, "do_detach, clear_current_signal", __LINE__);
1903 if (!proc_set_run_on_last_close (pi))
1904 proc_warn (pi, "do_detach, set_rlc", __LINE__);
1907 destroy_procinfo (pi);
1910 /* Fetch register REGNUM from the inferior. If REGNUM is -1, do this
1911 for all registers.
1913 NOTE: Since the /proc interface cannot give us individual
1914 registers, we pay no attention to REGNUM, and just fetch them all.
1915 This results in the possibility that we will do unnecessarily many
1916 fetches, since we may be called repeatedly for individual
1917 registers. So we cache the results, and mark the cache invalid
1918 when the process is resumed. */
1920 void
1921 procfs_target::fetch_registers (struct regcache *regcache, int regnum)
1923 gdb_gregset_t *gregs;
1924 procinfo *pi;
1925 ptid_t ptid = regcache->ptid ();
1926 int pid = ptid.pid ();
1927 int tid = ptid.lwp ();
1928 struct gdbarch *gdbarch = regcache->arch ();
1930 pi = find_procinfo_or_die (pid, tid);
1932 if (pi == NULL)
1933 error (_("procfs: fetch_registers failed to find procinfo for %s"),
1934 target_pid_to_str (ptid).c_str ());
1936 gregs = proc_get_gregs (pi);
1937 if (gregs == NULL)
1938 proc_error (pi, "fetch_registers, get_gregs", __LINE__);
1940 supply_gregset (regcache, (const gdb_gregset_t *) gregs);
1942 if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU? */
1944 gdb_fpregset_t *fpregs;
1946 if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
1947 || regnum == gdbarch_pc_regnum (gdbarch)
1948 || regnum == gdbarch_sp_regnum (gdbarch))
1949 return; /* Not a floating point register. */
1951 fpregs = proc_get_fpregs (pi);
1952 if (fpregs == NULL)
1953 proc_error (pi, "fetch_registers, get_fpregs", __LINE__);
1955 supply_fpregset (regcache, (const gdb_fpregset_t *) fpregs);
1959 /* Store register REGNUM back into the inferior. If REGNUM is -1, do
1960 this for all registers.
1962 NOTE: Since the /proc interface will not read individual registers,
1963 we will cache these requests until the process is resumed, and only
1964 then write them back to the inferior process.
1966 FIXME: is that a really bad idea? Have to think about cases where
1967 writing one register might affect the value of others, etc. */
1969 void
1970 procfs_target::store_registers (struct regcache *regcache, int regnum)
1972 gdb_gregset_t *gregs;
1973 procinfo *pi;
1974 ptid_t ptid = regcache->ptid ();
1975 int pid = ptid.pid ();
1976 int tid = ptid.lwp ();
1977 struct gdbarch *gdbarch = regcache->arch ();
1979 pi = find_procinfo_or_die (pid, tid);
1981 if (pi == NULL)
1982 error (_("procfs: store_registers: failed to find procinfo for %s"),
1983 target_pid_to_str (ptid).c_str ());
1985 gregs = proc_get_gregs (pi);
1986 if (gregs == NULL)
1987 proc_error (pi, "store_registers, get_gregs", __LINE__);
1989 fill_gregset (regcache, gregs, regnum);
1990 if (!proc_set_gregs (pi))
1991 proc_error (pi, "store_registers, set_gregs", __LINE__);
1993 if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU? */
1995 gdb_fpregset_t *fpregs;
1997 if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
1998 || regnum == gdbarch_pc_regnum (gdbarch)
1999 || regnum == gdbarch_sp_regnum (gdbarch))
2000 return; /* Not a floating point register. */
2002 fpregs = proc_get_fpregs (pi);
2003 if (fpregs == NULL)
2004 proc_error (pi, "store_registers, get_fpregs", __LINE__);
2006 fill_fpregset (regcache, fpregs, regnum);
2007 if (!proc_set_fpregs (pi))
2008 proc_error (pi, "store_registers, set_fpregs", __LINE__);
2012 /* Retrieve the next stop event from the child process. If child has
2013 not stopped yet, wait for it to stop. Translate /proc eventcodes
2014 (or possibly wait eventcodes) into gdb internal event codes.
2015 Returns the id of process (and possibly thread) that incurred the
2016 event. Event codes are returned through a pointer parameter. */
2018 ptid_t
2019 procfs_target::wait (ptid_t ptid, struct target_waitstatus *status,
2020 target_wait_flags options)
2022 /* First cut: loosely based on original version 2.1. */
2023 procinfo *pi;
2024 int wstat;
2025 int temp_tid;
2026 ptid_t retval, temp_ptid;
2027 int why, what, flags;
2028 int retry = 0;
2030 wait_again:
2032 retry++;
2033 wstat = 0;
2034 retval = ptid_t (-1);
2036 /* Find procinfo for main process. */
2038 /* procfs_target currently only supports one inferior. */
2039 inferior *inf = current_inferior ();
2041 pi = find_procinfo_or_die (inf->pid, 0);
2042 if (pi)
2044 /* We must assume that the status is stale now... */
2045 pi->status_valid = 0;
2046 pi->gregs_valid = 0;
2047 pi->fpregs_valid = 0;
2049 #if 0 /* just try this out... */
2050 flags = proc_flags (pi);
2051 why = proc_why (pi);
2052 if ((flags & PR_STOPPED) && (why == PR_REQUESTED))
2053 pi->status_valid = 0; /* re-read again, IMMEDIATELY... */
2054 #endif
2055 /* If child is not stopped, wait for it to stop. */
2056 if (!(proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
2057 && !proc_wait_for_stop (pi))
2059 /* wait_for_stop failed: has the child terminated? */
2060 if (errno == ENOENT)
2062 int wait_retval;
2064 /* /proc file not found; presumably child has terminated. */
2065 wait_retval = ::wait (&wstat); /* "wait" for the child's exit. */
2067 /* Wrong child? */
2068 if (wait_retval != inf->pid)
2069 error (_("procfs: couldn't stop "
2070 "process %d: wait returned %d."),
2071 inf->pid, wait_retval);
2072 /* FIXME: might I not just use waitpid?
2073 Or try find_procinfo to see if I know about this child? */
2074 retval = ptid_t (wait_retval);
2076 else if (errno == EINTR)
2077 goto wait_again;
2078 else
2080 /* Unknown error from wait_for_stop. */
2081 proc_error (pi, "target_wait (wait_for_stop)", __LINE__);
2084 else
2086 /* This long block is reached if either:
2087 a) the child was already stopped, or
2088 b) we successfully waited for the child with wait_for_stop.
2089 This block will analyze the /proc status, and translate it
2090 into a waitstatus for GDB.
2092 If we actually had to call wait because the /proc file
2093 is gone (child terminated), then we skip this block,
2094 because we already have a waitstatus. */
2096 flags = proc_flags (pi);
2097 why = proc_why (pi);
2098 what = proc_what (pi);
2100 if (flags & (PR_STOPPED | PR_ISTOP))
2102 /* If it's running async (for single_thread control),
2103 set it back to normal again. */
2104 if (flags & PR_ASYNC)
2105 if (!proc_unset_async (pi))
2106 proc_error (pi, "target_wait, unset_async", __LINE__);
2108 if (info_verbose)
2109 proc_prettyprint_why (why, what, 1);
2111 /* The 'pid' we will return to GDB is composed of
2112 the process ID plus the lwp ID. */
2113 retval = ptid_t (pi->pid, proc_get_current_thread (pi), 0);
2115 switch (why) {
2116 case PR_SIGNALLED:
2117 wstat = (what << 8) | 0177;
2118 break;
2119 case PR_SYSENTRY:
2120 if (what == SYS_lwp_exit)
2122 delete_thread (this->find_thread (retval));
2123 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2124 goto wait_again;
2126 else if (what == SYS_exit)
2128 /* Handle SYS_exit call only. */
2129 /* Stopped at entry to SYS_exit.
2130 Make it runnable, resume it, then use
2131 the wait system call to get its exit code.
2132 Proc_run_process always clears the current
2133 fault and signal.
2134 Then return its exit status. */
2135 pi->status_valid = 0;
2136 wstat = 0;
2137 /* FIXME: what we should do is return
2138 TARGET_WAITKIND_SPURIOUS. */
2139 if (!proc_run_process (pi, 0, 0))
2140 proc_error (pi, "target_wait, run_process", __LINE__);
2142 if (inf->attach_flag)
2144 /* Don't call wait: simulate waiting for exit,
2145 return a "success" exit code. Bogus: what if
2146 it returns something else? */
2147 wstat = 0;
2148 retval = ptid_t (inf->pid); /* ? ? ? */
2150 else
2152 int temp = ::wait (&wstat);
2154 /* FIXME: shouldn't I make sure I get the right
2155 event from the right process? If (for
2156 instance) I have killed an earlier inferior
2157 process but failed to clean up after it
2158 somehow, I could get its termination event
2159 here. */
2161 /* If wait returns -1, that's what we return
2162 to GDB. */
2163 if (temp < 0)
2164 retval = ptid_t (temp);
2167 else
2169 gdb_printf (_("procfs: trapped on entry to "));
2170 proc_prettyprint_syscall (proc_what (pi), 0);
2171 gdb_printf ("\n");
2173 long i, nsysargs, *sysargs;
2175 nsysargs = proc_nsysarg (pi);
2176 sysargs = proc_sysargs (pi);
2178 if (nsysargs > 0 && sysargs != NULL)
2180 gdb_printf (_("%ld syscall arguments:\n"),
2181 nsysargs);
2182 for (i = 0; i < nsysargs; i++)
2183 gdb_printf ("#%ld: 0x%08lx\n",
2184 i, sysargs[i]);
2187 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2188 goto wait_again;
2190 break;
2191 case PR_SYSEXIT:
2192 if (what == SYS_execve)
2194 /* Hopefully this is our own "fork-child" execing
2195 the real child. Hoax this event into a trap, and
2196 GDB will see the child about to execute its start
2197 address. */
2198 wstat = (SIGTRAP << 8) | 0177;
2200 else if (what == SYS_lwp_create)
2202 /* This syscall is somewhat like fork/exec. We
2203 will get the event twice: once for the parent
2204 LWP, and once for the child. We should already
2205 know about the parent LWP, but the child will
2206 be new to us. So, whenever we get this event,
2207 if it represents a new thread, simply add the
2208 thread to the list. */
2210 /* If not in procinfo list, add it. */
2211 temp_tid = proc_get_current_thread (pi);
2212 if (!find_procinfo (pi->pid, temp_tid))
2213 create_procinfo (pi->pid, temp_tid);
2215 temp_ptid = ptid_t (pi->pid, temp_tid, 0);
2216 /* If not in GDB's thread list, add it. */
2217 if (!in_thread_list (this, temp_ptid))
2218 add_thread (this, temp_ptid);
2220 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2221 goto wait_again;
2223 else if (what == SYS_lwp_exit)
2225 delete_thread (this->find_thread (retval));
2226 status->set_spurious ();
2227 return retval;
2229 else
2231 gdb_printf (_("procfs: trapped on exit from "));
2232 proc_prettyprint_syscall (proc_what (pi), 0);
2233 gdb_printf ("\n");
2235 long i, nsysargs, *sysargs;
2237 nsysargs = proc_nsysarg (pi);
2238 sysargs = proc_sysargs (pi);
2240 if (nsysargs > 0 && sysargs != NULL)
2242 gdb_printf (_("%ld syscall arguments:\n"),
2243 nsysargs);
2244 for (i = 0; i < nsysargs; i++)
2245 gdb_printf ("#%ld: 0x%08lx\n",
2246 i, sysargs[i]);
2249 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2250 goto wait_again;
2252 break;
2253 case PR_REQUESTED:
2254 #if 0 /* FIXME */
2255 wstat = (SIGSTOP << 8) | 0177;
2256 break;
2257 #else
2258 if (retry < 5)
2260 gdb_printf (_("Retry #%d:\n"), retry);
2261 pi->status_valid = 0;
2262 goto wait_again;
2264 else
2266 /* If not in procinfo list, add it. */
2267 temp_tid = proc_get_current_thread (pi);
2268 if (!find_procinfo (pi->pid, temp_tid))
2269 create_procinfo (pi->pid, temp_tid);
2271 /* If not in GDB's thread list, add it. */
2272 temp_ptid = ptid_t (pi->pid, temp_tid, 0);
2273 if (!in_thread_list (this, temp_ptid))
2274 add_thread (this, temp_ptid);
2276 status->set_stopped (GDB_SIGNAL_0);
2277 return retval;
2279 #endif
2280 case PR_JOBCONTROL:
2281 wstat = (what << 8) | 0177;
2282 break;
2283 case PR_FAULTED:
2285 int signo = pi->prstatus.pr_lwp.pr_info.si_signo;
2286 if (signo != 0)
2287 wstat = (signo << 8) | 0177;
2289 break;
2290 default: /* switch (why) unmatched */
2291 gdb_printf ("procfs:%d -- ", __LINE__);
2292 gdb_printf (_("child stopped for unknown reason:\n"));
2293 proc_prettyprint_why (why, what, 1);
2294 error (_("... giving up..."));
2295 break;
2297 /* Got this far without error: If retval isn't in the
2298 threads database, add it. */
2299 if (retval.pid () > 0
2300 && !in_thread_list (this, retval))
2302 /* We have a new thread. We need to add it both to
2303 GDB's list and to our own. If we don't create a
2304 procinfo, resume may be unhappy later. */
2305 add_thread (this, retval);
2306 if (find_procinfo (retval.pid (),
2307 retval.lwp ()) == NULL)
2308 create_procinfo (retval.pid (),
2309 retval.lwp ());
2312 else /* Flags do not indicate STOPPED. */
2314 /* surely this can't happen... */
2315 gdb_printf ("procfs:%d -- process not stopped.\n",
2316 __LINE__);
2317 proc_prettyprint_flags (flags, 1);
2318 error (_("procfs: ...giving up..."));
2322 if (status)
2323 *status = host_status_to_waitstatus (wstat);
2326 return retval;
2329 /* Perform a partial transfer to/from the specified object. For
2330 memory transfers, fall back to the old memory xfer functions. */
2332 enum target_xfer_status
2333 procfs_target::xfer_partial (enum target_object object,
2334 const char *annex, gdb_byte *readbuf,
2335 const gdb_byte *writebuf, ULONGEST offset,
2336 ULONGEST len, ULONGEST *xfered_len)
2338 switch (object)
2340 case TARGET_OBJECT_MEMORY:
2341 return procfs_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2343 case TARGET_OBJECT_AUXV:
2344 return memory_xfer_auxv (this, object, annex, readbuf, writebuf,
2345 offset, len, xfered_len);
2347 default:
2348 return this->beneath ()->xfer_partial (object, annex,
2349 readbuf, writebuf, offset, len,
2350 xfered_len);
2354 /* Helper for procfs_xfer_partial that handles memory transfers.
2355 Arguments are like target_xfer_partial. */
2357 static enum target_xfer_status
2358 procfs_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2359 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2361 procinfo *pi;
2362 int nbytes;
2364 /* Find procinfo for main process. */
2365 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2366 if (pi->as_fd == 0 && open_procinfo_files (pi, FD_AS) == 0)
2368 proc_warn (pi, "xfer_memory, open_proc_files", __LINE__);
2369 return TARGET_XFER_E_IO;
2372 if (lseek (pi->as_fd, (off_t) memaddr, SEEK_SET) != (off_t) memaddr)
2373 return TARGET_XFER_E_IO;
2375 if (writebuf != NULL)
2377 PROCFS_NOTE ("write memory:\n");
2378 nbytes = write (pi->as_fd, writebuf, len);
2380 else
2382 PROCFS_NOTE ("read memory:\n");
2383 nbytes = read (pi->as_fd, readbuf, len);
2385 if (nbytes <= 0)
2386 return TARGET_XFER_E_IO;
2387 *xfered_len = nbytes;
2388 return TARGET_XFER_OK;
2391 /* Called by target_resume before making child runnable. Mark cached
2392 registers and status's invalid. If there are "dirty" caches that
2393 need to be written back to the child process, do that.
2395 File descriptors are also cached. As they are a limited resource,
2396 we cannot hold onto them indefinitely. However, as they are
2397 expensive to open, we don't want to throw them away
2398 indiscriminately either. As a compromise, we will keep the file
2399 descriptors for the parent process, but discard any file
2400 descriptors we may have accumulated for the threads.
2402 As this function is called by iterate_over_threads, it always
2403 returns zero (so that iterate_over_threads will keep
2404 iterating). */
2406 static int
2407 invalidate_cache (procinfo *parent, procinfo *pi, void *ptr)
2409 /* About to run the child; invalidate caches and do any other
2410 cleanup. */
2412 if (parent != NULL)
2414 /* The presence of a parent indicates that this is an LWP.
2415 Close any file descriptors that it might have open.
2416 We don't do this to the master (parent) procinfo. */
2418 close_procinfo_files (pi);
2420 pi->gregs_valid = 0;
2421 pi->fpregs_valid = 0;
2422 pi->status_valid = 0;
2423 pi->threads_valid = 0;
2425 return 0;
2428 /* Make child process PI runnable.
2430 If STEP is true, then arrange for the child to stop again after
2431 executing a single instruction. SCOPE_PTID, STEP and SIGNO are
2432 like in the target_resume interface. */
2434 static void
2435 proc_resume (procinfo *pi, ptid_t scope_ptid, int step, enum gdb_signal signo)
2437 procinfo *thread;
2438 int native_signo;
2440 /* FIXME: Check/reword. */
2442 /* prrun.prflags |= PRCFAULT; clear current fault.
2443 PRCFAULT may be replaced by a PCCFAULT call (proc_clear_current_fault)
2444 This basically leaves PRSTEP and PRCSIG.
2445 PRCSIG is like PCSSIG (proc_clear_current_signal).
2446 So basically PR_STEP is the sole argument that must be passed
2447 to proc_run_process. */
2449 errno = 0;
2451 /* Convert signal to host numbering. */
2452 if (signo == 0 || (signo == GDB_SIGNAL_STOP && pi->ignore_next_sigstop))
2453 native_signo = 0;
2454 else
2455 native_signo = gdb_signal_to_host (signo);
2457 pi->ignore_next_sigstop = 0;
2459 /* Running the process voids all cached registers and status. */
2460 /* Void the threads' caches first. */
2461 proc_iterate_over_threads (pi, invalidate_cache, NULL);
2462 /* Void the process procinfo's caches. */
2463 invalidate_cache (NULL, pi, NULL);
2465 if (scope_ptid.pid () != -1)
2467 /* Resume a specific thread, presumably suppressing the
2468 others. */
2469 thread = find_procinfo (scope_ptid.pid (), scope_ptid.lwp ());
2470 if (thread != NULL)
2472 if (thread->tid != 0)
2474 /* We're to resume a specific thread, and not the
2475 others. Set the child process's PR_ASYNC flag. */
2476 if (!proc_set_async (pi))
2477 proc_error (pi, "target_resume, set_async", __LINE__);
2478 pi = thread; /* Substitute the thread's procinfo
2479 for run. */
2484 if (!proc_run_process (pi, step, native_signo))
2486 if (errno == EBUSY)
2487 warning (_("resume: target already running. "
2488 "Pretend to resume, and hope for the best!"));
2489 else
2490 proc_error (pi, "target_resume", __LINE__);
2494 /* Implementation of target_ops::resume. */
2496 void
2497 procfs_target::resume (ptid_t scope_ptid, int step, enum gdb_signal signo)
2499 /* Find procinfo for main process. */
2500 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2502 proc_resume (pi, scope_ptid, step, signo);
2505 /* Set up to trace signals in the child process. */
2507 void
2508 procfs_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2510 sigset_t signals;
2511 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2512 int signo;
2514 prfillset (&signals);
2516 for (signo = 0; signo < NSIG; signo++)
2518 int target_signo = gdb_signal_from_host (signo);
2519 if (target_signo < pass_signals.size () && pass_signals[target_signo])
2520 prdelset (&signals, signo);
2523 if (!proc_set_traced_signals (pi, &signals))
2524 proc_error (pi, "pass_signals", __LINE__);
2527 /* Print status information about the child process. */
2529 void
2530 procfs_target::files_info ()
2532 struct inferior *inf = current_inferior ();
2534 gdb_printf (_("\tUsing the running image of %s %s via /proc.\n"),
2535 inf->attach_flag? "attached": "child",
2536 target_pid_to_str (ptid_t (inf->pid)).c_str ());
2539 /* Make it die. Wait for it to die. Clean up after it. Note: this
2540 should only be applied to the real process, not to an LWP, because
2541 of the check for parent-process. If we need this to work for an
2542 LWP, it needs some more logic. */
2544 static void
2545 unconditionally_kill_inferior (procinfo *pi)
2547 int parent_pid;
2549 parent_pid = proc_parent_pid (pi);
2550 if (!proc_kill (pi, SIGKILL))
2551 proc_error (pi, "unconditionally_kill, proc_kill", __LINE__);
2552 destroy_procinfo (pi);
2554 /* If pi is GDB's child, wait for it to die. */
2555 if (parent_pid == getpid ())
2556 /* FIXME: should we use waitpid to make sure we get the right event?
2557 Should we check the returned event? */
2559 #if 0
2560 int status, ret;
2562 ret = waitpid (pi->pid, &status, 0);
2563 #else
2564 wait (NULL);
2565 #endif
2569 /* We're done debugging it, and we want it to go away. Then we want
2570 GDB to forget all about it. */
2572 void
2573 procfs_target::kill ()
2575 if (inferior_ptid != null_ptid) /* ? */
2577 /* Find procinfo for main process. */
2578 procinfo *pi = find_procinfo (inferior_ptid.pid (), 0);
2580 if (pi)
2581 unconditionally_kill_inferior (pi);
2582 target_mourn_inferior (inferior_ptid);
2586 /* Forget we ever debugged this thing! */
2588 void
2589 procfs_target::mourn_inferior ()
2591 procinfo *pi;
2593 if (inferior_ptid != null_ptid)
2595 /* Find procinfo for main process. */
2596 pi = find_procinfo (inferior_ptid.pid (), 0);
2597 if (pi)
2598 destroy_procinfo (pi);
2601 generic_mourn_inferior ();
2603 maybe_unpush_target ();
2606 /* When GDB forks to create a runnable inferior process, this function
2607 is called on the parent side of the fork. It's job is to do
2608 whatever is necessary to make the child ready to be debugged, and
2609 then wait for the child to synchronize. */
2611 void
2612 procfs_target::procfs_init_inferior (int pid)
2614 procinfo *pi;
2615 int fail;
2616 int lwpid;
2618 pi = create_procinfo (pid, 0);
2619 if (pi == NULL)
2620 perror (_("procfs: out of memory in 'init_inferior'"));
2622 if (!open_procinfo_files (pi, FD_CTL))
2623 proc_error (pi, "init_inferior, open_proc_files", __LINE__);
2626 xmalloc // done
2627 open_procinfo_files // done
2628 link list // done
2629 prfillset (trace)
2630 procfs_notice_signals
2631 prfillset (fault)
2632 prdelset (FLTPAGE)
2635 /* If not stopped yet, wait for it to stop. */
2636 if (!(proc_flags (pi) & PR_STOPPED) && !(proc_wait_for_stop (pi)))
2637 dead_procinfo (pi, "init_inferior: wait_for_stop failed", KILL);
2639 /* Save some of the /proc state to be restored if we detach. */
2640 /* FIXME: Why? In case another debugger was debugging it?
2641 We're it's parent, for Ghu's sake! */
2642 if (!proc_get_traced_signals (pi, &pi->saved_sigset))
2643 proc_error (pi, "init_inferior, get_traced_signals", __LINE__);
2644 if (!proc_get_held_signals (pi, &pi->saved_sighold))
2645 proc_error (pi, "init_inferior, get_held_signals", __LINE__);
2646 if (!proc_get_traced_faults (pi, &pi->saved_fltset))
2647 proc_error (pi, "init_inferior, get_traced_faults", __LINE__);
2648 if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
2649 proc_error (pi, "init_inferior, get_traced_sysentry", __LINE__);
2650 if (!proc_get_traced_sysexit (pi, pi->saved_exitset))
2651 proc_error (pi, "init_inferior, get_traced_sysexit", __LINE__);
2653 fail = procfs_debug_inferior (pi);
2654 if (fail != 0)
2655 proc_error (pi, "init_inferior (procfs_debug_inferior)", fail);
2657 /* FIXME: logically, we should really be turning OFF run-on-last-close,
2658 and possibly even turning ON kill-on-last-close at this point. But
2659 I can't make that change without careful testing which I don't have
2660 time to do right now... */
2661 /* Turn on run-on-last-close flag so that the child
2662 will die if GDB goes away for some reason. */
2663 if (!proc_set_run_on_last_close (pi))
2664 proc_error (pi, "init_inferior, set_RLC", __LINE__);
2666 /* We now have have access to the lwpid of the main thread/lwp. */
2667 lwpid = proc_get_current_thread (pi);
2669 /* Create a procinfo for the main lwp. */
2670 create_procinfo (pid, lwpid);
2672 /* We already have a main thread registered in the thread table at
2673 this point, but it didn't have any lwp info yet. Notify the core
2674 about it. This changes inferior_ptid as well. */
2675 thread_change_ptid (this, ptid_t (pid), ptid_t (pid, lwpid, 0));
2677 gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
2680 /* When GDB forks to create a new process, this function is called on
2681 the child side of the fork before GDB exec's the user program. Its
2682 job is to make the child minimally debuggable, so that the parent
2683 GDB process can connect to the child and take over. This function
2684 should do only the minimum to make that possible, and to
2685 synchronize with the parent process. The parent process should
2686 take care of the details. */
2688 static void
2689 procfs_set_exec_trap (void)
2691 /* This routine called on the child side (inferior side)
2692 after GDB forks the inferior. It must use only local variables,
2693 because it may be sharing data space with its parent. */
2695 procinfo *pi;
2696 sysset_t *exitset;
2698 pi = create_procinfo (getpid (), 0);
2699 if (pi == NULL)
2700 perror_with_name (_("procfs: create_procinfo failed in child"));
2702 if (open_procinfo_files (pi, FD_CTL) == 0)
2704 proc_warn (pi, "set_exec_trap, open_proc_files", __LINE__);
2705 gdb_flush (gdb_stderr);
2706 /* No need to call "dead_procinfo", because we're going to
2707 exit. */
2708 _exit (127);
2711 exitset = XNEW (sysset_t);
2712 premptyset (exitset);
2713 praddset (exitset, SYS_execve);
2715 if (!proc_set_traced_sysexit (pi, exitset))
2717 proc_warn (pi, "set_exec_trap, set_traced_sysexit", __LINE__);
2718 gdb_flush (gdb_stderr);
2719 _exit (127);
2722 /* FIXME: should this be done in the parent instead? */
2723 /* Turn off inherit on fork flag so that all grand-children
2724 of gdb start with tracing flags cleared. */
2725 if (!proc_unset_inherit_on_fork (pi))
2726 proc_warn (pi, "set_exec_trap, unset_inherit", __LINE__);
2728 /* Turn off run on last close flag, so that the child process
2729 cannot run away just because we close our handle on it.
2730 We want it to wait for the parent to attach. */
2731 if (!proc_unset_run_on_last_close (pi))
2732 proc_warn (pi, "set_exec_trap, unset_RLC", __LINE__);
2734 /* FIXME: No need to destroy the procinfo --
2735 we have our own address space, and we're about to do an exec! */
2736 /*destroy_procinfo (pi);*/
2739 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2).
2740 This avoids a possible deadlock gdb and its vfork'ed child. */
2741 static void
2742 procfs_pre_trace (void)
2746 /* This function is called BEFORE gdb forks the inferior process. Its
2747 only real responsibility is to set things up for the fork, and tell
2748 GDB which two functions to call after the fork (one for the parent,
2749 and one for the child).
2751 This function does a complicated search for a unix shell program,
2752 which it then uses to parse arguments and environment variables to
2753 be sent to the child. I wonder whether this code could not be
2754 abstracted out and shared with other unix targets such as
2755 inf-ptrace? */
2757 void
2758 procfs_target::create_inferior (const char *exec_file,
2759 const std::string &allargs,
2760 char **env, int from_tty)
2762 const char *shell_file = get_shell ();
2763 char *tryname;
2764 int pid;
2766 if (strchr (shell_file, '/') == NULL)
2769 /* We will be looking down the PATH to find shell_file. If we
2770 just do this the normal way (via execlp, which operates by
2771 attempting an exec for each element of the PATH until it
2772 finds one which succeeds), then there will be an exec for
2773 each failed attempt, each of which will cause a PR_SYSEXIT
2774 stop, and we won't know how to distinguish the PR_SYSEXIT's
2775 for these failed execs with the ones for successful execs
2776 (whether the exec has succeeded is stored at that time in the
2777 carry bit or some such architecture-specific and
2778 non-ABI-specified place).
2780 So I can't think of anything better than to search the PATH
2781 now. This has several disadvantages: (1) There is a race
2782 condition; if we find a file now and it is deleted before we
2783 exec it, we lose, even if the deletion leaves a valid file
2784 further down in the PATH, (2) there is no way to know exactly
2785 what an executable (in the sense of "capable of being
2786 exec'd") file is. Using access() loses because it may lose
2787 if the caller is the superuser; failing to use it loses if
2788 there are ACLs or some such. */
2790 const char *p;
2791 const char *p1;
2792 /* FIXME-maybe: might want "set path" command so user can change what
2793 path is used from within GDB. */
2794 const char *path = getenv ("PATH");
2795 int len;
2796 struct stat statbuf;
2798 if (path == NULL)
2799 path = "/bin:/usr/bin";
2801 tryname = (char *) alloca (strlen (path) + strlen (shell_file) + 2);
2802 for (p = path; p != NULL; p = p1 ? p1 + 1: NULL)
2804 p1 = strchr (p, ':');
2805 if (p1 != NULL)
2806 len = p1 - p;
2807 else
2808 len = strlen (p);
2809 memcpy (tryname, p, len);
2810 tryname[len] = '\0';
2811 strcat (tryname, "/");
2812 strcat (tryname, shell_file);
2813 if (access (tryname, X_OK) < 0)
2814 continue;
2815 if (stat (tryname, &statbuf) < 0)
2816 continue;
2817 if (!S_ISREG (statbuf.st_mode))
2818 /* We certainly need to reject directories. I'm not quite
2819 as sure about FIFOs, sockets, etc., but I kind of doubt
2820 that people want to exec() these things. */
2821 continue;
2822 break;
2824 if (p == NULL)
2825 /* Not found. This must be an error rather than merely passing
2826 the file to execlp(), because execlp() would try all the
2827 exec()s, causing GDB to get confused. */
2828 error (_("procfs:%d -- Can't find shell %s in PATH"),
2829 __LINE__, shell_file);
2831 shell_file = tryname;
2834 inferior *inf = current_inferior ();
2835 if (!inf->target_is_pushed (this))
2836 inf->push_target (this);
2838 pid = fork_inferior (exec_file, allargs, env, procfs_set_exec_trap,
2839 NULL, procfs_pre_trace, shell_file, NULL);
2841 /* We have something that executes now. We'll be running through
2842 the shell at this point (if startup-with-shell is true), but the
2843 pid shouldn't change. */
2844 thread_info *thr = add_thread_silent (this, ptid_t (pid));
2845 switch_to_thread (thr);
2847 procfs_init_inferior (pid);
2850 /* Callback for update_thread_list. Calls "add_thread". */
2852 static int
2853 procfs_notice_thread (procinfo *pi, procinfo *thread, void *ptr)
2855 ptid_t gdb_threadid = ptid_t (pi->pid, thread->tid, 0);
2857 thread_info *thr = the_procfs_target.find_thread (gdb_threadid);
2858 if (thr == NULL || thr->state == THREAD_EXITED)
2859 add_thread (&the_procfs_target, gdb_threadid);
2861 return 0;
2864 /* Query all the threads that the target knows about, and give them
2865 back to GDB to add to its list. */
2867 void
2868 procfs_target::update_thread_list ()
2870 procinfo *pi;
2872 prune_threads ();
2874 /* Find procinfo for main process. */
2875 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2876 proc_update_threads (pi);
2877 proc_iterate_over_threads (pi, procfs_notice_thread, NULL);
2880 /* Return true if the thread is still 'alive'. This guy doesn't
2881 really seem to be doing his job. Got to investigate how to tell
2882 when a thread is really gone. */
2884 bool
2885 procfs_target::thread_alive (ptid_t ptid)
2887 int proc, thread;
2888 procinfo *pi;
2890 proc = ptid.pid ();
2891 thread = ptid.lwp ();
2892 /* If I don't know it, it ain't alive! */
2893 pi = find_procinfo (proc, thread);
2894 if (pi == NULL)
2895 return false;
2897 /* If I can't get its status, it ain't alive!
2898 What's more, I need to forget about it! */
2899 if (!proc_get_status (pi))
2901 destroy_procinfo (pi);
2902 return false;
2904 /* I couldn't have got its status if it weren't alive, so it's
2905 alive. */
2906 return true;
2909 /* Convert PTID to a string. */
2911 std::string
2912 procfs_target::pid_to_str (ptid_t ptid)
2914 if (ptid.lwp () == 0)
2915 return string_printf ("process %d", ptid.pid ());
2916 else
2917 return string_printf ("LWP %ld", ptid.lwp ());
2920 /* Accepts an integer PID; Returns a string representing a file that
2921 can be opened to get the symbols for the child process. */
2923 const char *
2924 procfs_target::pid_to_exec_file (int pid)
2926 static char buf[PATH_MAX];
2927 char name[PATH_MAX];
2929 /* Solaris 11 introduced /proc/<proc-id>/execname. */
2930 xsnprintf (name, sizeof (name), "/proc/%d/execname", pid);
2931 scoped_fd fd (gdb_open_cloexec (name, O_RDONLY, 0));
2932 if (fd.get () < 0 || read (fd.get (), buf, PATH_MAX - 1) < 0)
2934 /* If that fails, fall back to /proc/<proc-id>/path/a.out introduced in
2935 Solaris 10. */
2936 ssize_t len;
2938 xsnprintf (name, sizeof (name), "/proc/%d/path/a.out", pid);
2939 len = readlink (name, buf, PATH_MAX - 1);
2940 if (len <= 0)
2941 strcpy (buf, name);
2942 else
2943 buf[len] = '\0';
2946 return buf;
2949 /* Insert a watchpoint. */
2951 static int
2952 procfs_set_watchpoint (ptid_t ptid, CORE_ADDR addr, int len, int rwflag,
2953 int after)
2955 int pflags = 0;
2956 procinfo *pi;
2958 pi = find_procinfo_or_die (ptid.pid () == -1 ?
2959 inferior_ptid.pid () : ptid.pid (),
2962 /* Translate from GDB's flags to /proc's. */
2963 if (len > 0) /* len == 0 means delete watchpoint. */
2965 switch (rwflag) { /* FIXME: need an enum! */
2966 case hw_write: /* default watchpoint (write) */
2967 pflags = WA_WRITE;
2968 break;
2969 case hw_read: /* read watchpoint */
2970 pflags = WA_READ;
2971 break;
2972 case hw_access: /* access watchpoint */
2973 pflags = WA_READ | WA_WRITE;
2974 break;
2975 case hw_execute: /* execution HW breakpoint */
2976 pflags = WA_EXEC;
2977 break;
2978 default: /* Something weird. Return error. */
2979 return -1;
2981 if (after) /* Stop after r/w access is completed. */
2982 pflags |= WA_TRAPAFTER;
2985 if (!proc_set_watchpoint (pi, addr, len, pflags))
2987 if (errno == E2BIG) /* Typical error for no resources. */
2988 return -1; /* fail */
2989 /* GDB may try to remove the same watchpoint twice.
2990 If a remove request returns no match, don't error. */
2991 if (errno == ESRCH && len == 0)
2992 return 0; /* ignore */
2993 proc_error (pi, "set_watchpoint", __LINE__);
2995 return 0;
2998 /* Return non-zero if we can set a hardware watchpoint of type TYPE. TYPE
2999 is one of bp_hardware_watchpoint, bp_read_watchpoint, bp_write_watchpoint,
3000 or bp_hardware_watchpoint. CNT is the number of watchpoints used so
3001 far. */
3004 procfs_target::can_use_hw_breakpoint (enum bptype type, int cnt, int othertype)
3006 /* Due to the way that proc_set_watchpoint() is implemented, host
3007 and target pointers must be of the same size. If they are not,
3008 we can't use hardware watchpoints. This limitation is due to the
3009 fact that proc_set_watchpoint() calls
3010 procfs_address_to_host_pointer(); a close inspection of
3011 procfs_address_to_host_pointer will reveal that an internal error
3012 will be generated when the host and target pointer sizes are
3013 different. */
3014 struct type *ptr_type
3015 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
3017 if (sizeof (void *) != ptr_type->length ())
3018 return 0;
3020 /* Other tests here??? */
3022 return 1;
3025 /* Returns non-zero if process is stopped on a hardware watchpoint
3026 fault, else returns zero. */
3028 bool
3029 procfs_target::stopped_by_watchpoint ()
3031 procinfo *pi;
3033 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3035 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
3036 if (proc_why (pi) == PR_FAULTED)
3037 if (proc_what (pi) == FLTWATCH)
3038 return true;
3039 return false;
3042 /* Returns 1 if the OS knows the position of the triggered watchpoint,
3043 and sets *ADDR to that address. Returns 0 if OS cannot report that
3044 address. This function is only called if
3045 procfs_stopped_by_watchpoint returned 1, thus no further checks are
3046 done. The function also assumes that ADDR is not NULL. */
3048 bool
3049 procfs_target::stopped_data_address (CORE_ADDR *addr)
3051 procinfo *pi;
3053 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3054 return proc_watchpoint_address (pi, addr);
3058 procfs_target::insert_watchpoint (CORE_ADDR addr, int len,
3059 enum target_hw_bp_type type,
3060 struct expression *cond)
3062 if (!target_have_steppable_watchpoint ()
3063 && !gdbarch_have_nonsteppable_watchpoint (current_inferior ()->arch ()))
3064 /* When a hardware watchpoint fires off the PC will be left at
3065 the instruction following the one which caused the
3066 watchpoint. It will *NOT* be necessary for GDB to step over
3067 the watchpoint. */
3068 return procfs_set_watchpoint (inferior_ptid, addr, len, type, 1);
3069 else
3070 /* When a hardware watchpoint fires off the PC will be left at
3071 the instruction which caused the watchpoint. It will be
3072 necessary for GDB to step over the watchpoint. */
3073 return procfs_set_watchpoint (inferior_ptid, addr, len, type, 0);
3077 procfs_target::remove_watchpoint (CORE_ADDR addr, int len,
3078 enum target_hw_bp_type type,
3079 struct expression *cond)
3081 return procfs_set_watchpoint (inferior_ptid, addr, 0, 0, 0);
3085 procfs_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
3087 /* The man page for proc(4) on Solaris 2.6 and up says that the
3088 system can support "thousands" of hardware watchpoints, but gives
3089 no method for finding out how many; It doesn't say anything about
3090 the allowed size for the watched area either. So we just tell
3091 GDB 'yes'. */
3092 return 1;
3095 /* Memory Mappings Functions: */
3097 /* Call a callback function once for each mapping, passing it the
3098 mapping, an optional secondary callback function, and some optional
3099 opaque data. Quit and return the first non-zero value returned
3100 from the callback.
3102 PI is the procinfo struct for the process to be mapped. FUNC is
3103 the callback function to be called by this iterator. DATA is the
3104 optional opaque data to be passed to the callback function.
3105 CHILD_FUNC is the optional secondary function pointer to be passed
3106 to the child function. Returns the first non-zero return value
3107 from the callback function, or zero. */
3109 static int
3110 iterate_over_mappings (procinfo *pi, find_memory_region_ftype child_func,
3111 void *data,
3112 int (*func) (struct prmap *map,
3113 find_memory_region_ftype child_func,
3114 void *data))
3116 char pathname[MAX_PROC_NAME_SIZE];
3117 struct prmap *prmaps;
3118 struct prmap *prmap;
3119 int funcstat;
3120 int nmap;
3121 struct stat sbuf;
3123 /* Get the number of mappings, allocate space,
3124 and read the mappings into prmaps. */
3125 /* Open map fd. */
3126 xsnprintf (pathname, sizeof (pathname), "/proc/%d/map", pi->pid);
3128 scoped_fd map_fd (open (pathname, O_RDONLY));
3129 if (map_fd.get () < 0)
3130 proc_error (pi, "iterate_over_mappings (open)", __LINE__);
3132 /* Use stat to determine the file size, and compute
3133 the number of prmap_t objects it contains. */
3134 if (fstat (map_fd.get (), &sbuf) != 0)
3135 proc_error (pi, "iterate_over_mappings (fstat)", __LINE__);
3137 nmap = sbuf.st_size / sizeof (prmap_t);
3138 prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
3139 if (read (map_fd.get (), (char *) prmaps, nmap * sizeof (*prmaps))
3140 != (nmap * sizeof (*prmaps)))
3141 proc_error (pi, "iterate_over_mappings (read)", __LINE__);
3143 for (prmap = prmaps; nmap > 0; prmap++, nmap--)
3145 funcstat = (*func) (prmap, child_func, data);
3146 if (funcstat != 0)
3147 return funcstat;
3150 return 0;
3153 /* Implements the to_find_memory_regions method. Calls an external
3154 function for each memory region.
3155 Returns the integer value returned by the callback. */
3157 static int
3158 find_memory_regions_callback (struct prmap *map,
3159 find_memory_region_ftype func, void *data)
3161 return (*func) ((CORE_ADDR) map->pr_vaddr,
3162 map->pr_size,
3163 (map->pr_mflags & MA_READ) != 0,
3164 (map->pr_mflags & MA_WRITE) != 0,
3165 (map->pr_mflags & MA_EXEC) != 0,
3166 1, /* MODIFIED is unknown, pass it as true. */
3167 false,
3168 data);
3171 /* External interface. Calls a callback function once for each
3172 mapped memory region in the child process, passing as arguments:
3174 CORE_ADDR virtual_address,
3175 unsigned long size,
3176 int read, TRUE if region is readable by the child
3177 int write, TRUE if region is writable by the child
3178 int execute TRUE if region is executable by the child.
3180 Stops iterating and returns the first non-zero value returned by
3181 the callback. */
3184 procfs_target::find_memory_regions (find_memory_region_ftype func, void *data)
3186 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3188 return iterate_over_mappings (pi, func, data,
3189 find_memory_regions_callback);
3192 /* Returns an ascii representation of a memory mapping's flags. */
3194 static char *
3195 mappingflags (long flags)
3197 static char asciiflags[8];
3199 strcpy (asciiflags, "-------");
3200 if (flags & MA_STACK)
3201 asciiflags[1] = 's';
3202 if (flags & MA_BREAK)
3203 asciiflags[2] = 'b';
3204 if (flags & MA_SHARED)
3205 asciiflags[3] = 's';
3206 if (flags & MA_READ)
3207 asciiflags[4] = 'r';
3208 if (flags & MA_WRITE)
3209 asciiflags[5] = 'w';
3210 if (flags & MA_EXEC)
3211 asciiflags[6] = 'x';
3212 return (asciiflags);
3215 /* Callback function, does the actual work for 'info proc
3216 mappings'. */
3218 static int
3219 info_mappings_callback (struct prmap *map, find_memory_region_ftype ignore,
3220 void *unused)
3222 unsigned int pr_off;
3224 pr_off = (unsigned int) map->pr_offset;
3226 if (gdbarch_addr_bit (current_inferior ()->arch ()) == 32)
3227 gdb_printf ("\t%#10lx %#10lx %#10lx %#10x %7s\n",
3228 (unsigned long) map->pr_vaddr,
3229 (unsigned long) map->pr_vaddr + map->pr_size - 1,
3230 (unsigned long) map->pr_size,
3231 pr_off,
3232 mappingflags (map->pr_mflags));
3233 else
3234 gdb_printf (" %#18lx %#18lx %#10lx %#10x %7s\n",
3235 (unsigned long) map->pr_vaddr,
3236 (unsigned long) map->pr_vaddr + map->pr_size - 1,
3237 (unsigned long) map->pr_size,
3238 pr_off,
3239 mappingflags (map->pr_mflags));
3241 return 0;
3244 /* Implement the "info proc mappings" subcommand. */
3246 static void
3247 info_proc_mappings (procinfo *pi, int summary)
3249 if (summary)
3250 return; /* No output for summary mode. */
3252 gdb_printf (_("Mapped address spaces:\n\n"));
3253 if (gdbarch_ptr_bit (current_inferior ()->arch ()) == 32)
3254 gdb_printf ("\t%10s %10s %10s %10s %7s\n",
3255 "Start Addr",
3256 " End Addr",
3257 " Size",
3258 " Offset",
3259 "Flags");
3260 else
3261 gdb_printf (" %18s %18s %10s %10s %7s\n",
3262 "Start Addr",
3263 " End Addr",
3264 " Size",
3265 " Offset",
3266 "Flags");
3268 iterate_over_mappings (pi, NULL, NULL, info_mappings_callback);
3269 gdb_printf ("\n");
3272 /* Implement the "info proc" command. */
3274 bool
3275 procfs_target::info_proc (const char *args, enum info_proc_what what)
3277 procinfo *process = NULL;
3278 procinfo *thread = NULL;
3279 char *tmp = NULL;
3280 int pid = 0;
3281 int tid = 0;
3282 int mappings = 0;
3284 switch (what)
3286 case IP_MINIMAL:
3287 break;
3289 case IP_MAPPINGS:
3290 case IP_ALL:
3291 mappings = 1;
3292 break;
3294 default:
3295 error (_("Not supported on this target."));
3298 gdb_argv built_argv (args);
3299 for (char *arg : built_argv)
3301 if (isdigit (arg[0]))
3303 pid = strtoul (arg, &tmp, 10);
3304 if (*tmp == '/')
3305 tid = strtoul (++tmp, NULL, 10);
3307 else if (arg[0] == '/')
3309 tid = strtoul (arg + 1, NULL, 10);
3313 procinfo_up temporary_procinfo;
3314 if (pid == 0)
3315 pid = inferior_ptid.pid ();
3316 if (pid == 0)
3317 error (_("No current process: you must name one."));
3318 else
3320 /* Have pid, will travel.
3321 First see if it's a process we're already debugging. */
3322 process = find_procinfo (pid, 0);
3323 if (process == NULL)
3325 /* No. So open a procinfo for it, but
3326 remember to close it again when finished. */
3327 process = create_procinfo (pid, 0);
3328 temporary_procinfo.reset (process);
3329 if (!open_procinfo_files (process, FD_CTL))
3330 proc_error (process, "info proc, open_procinfo_files", __LINE__);
3333 if (tid != 0)
3334 thread = create_procinfo (pid, tid);
3336 if (process)
3338 gdb_printf (_("process %d flags:\n"), process->pid);
3339 proc_prettyprint_flags (proc_flags (process), 1);
3340 if (proc_flags (process) & (PR_STOPPED | PR_ISTOP))
3341 proc_prettyprint_why (proc_why (process), proc_what (process), 1);
3342 if (proc_get_nthreads (process) > 1)
3343 gdb_printf ("Process has %d threads.\n",
3344 proc_get_nthreads (process));
3346 if (thread)
3348 gdb_printf (_("thread %d flags:\n"), thread->tid);
3349 proc_prettyprint_flags (proc_flags (thread), 1);
3350 if (proc_flags (thread) & (PR_STOPPED | PR_ISTOP))
3351 proc_prettyprint_why (proc_why (thread), proc_what (thread), 1);
3354 if (mappings)
3355 info_proc_mappings (process, 0);
3357 return true;
3360 /* Modify the status of the system call identified by SYSCALLNUM in
3361 the set of syscalls that are currently traced/debugged.
3363 If ENTRY_OR_EXIT is set to PR_SYSENTRY, then the entry syscalls set
3364 will be updated. Otherwise, the exit syscalls set will be updated.
3366 If MODE is FLAG_SET, then traces will be enabled. Otherwise, they
3367 will be disabled. */
3369 static void
3370 proc_trace_syscalls_1 (procinfo *pi, int syscallnum, int entry_or_exit,
3371 int mode, int from_tty)
3373 sysset_t *sysset;
3375 if (entry_or_exit == PR_SYSENTRY)
3376 sysset = proc_get_traced_sysentry (pi, NULL);
3377 else
3378 sysset = proc_get_traced_sysexit (pi, NULL);
3380 if (sysset == NULL)
3381 proc_error (pi, "proc-trace, get_traced_sysset", __LINE__);
3383 if (mode == FLAG_SET)
3384 praddset (sysset, syscallnum);
3385 else
3386 prdelset (sysset, syscallnum);
3388 if (entry_or_exit == PR_SYSENTRY)
3390 if (!proc_set_traced_sysentry (pi, sysset))
3391 proc_error (pi, "proc-trace, set_traced_sysentry", __LINE__);
3393 else
3395 if (!proc_set_traced_sysexit (pi, sysset))
3396 proc_error (pi, "proc-trace, set_traced_sysexit", __LINE__);
3400 static void
3401 proc_trace_syscalls (const char *args, int from_tty, int entry_or_exit, int mode)
3403 procinfo *pi;
3405 if (inferior_ptid.pid () <= 0)
3406 error (_("you must be debugging a process to use this command."));
3408 if (args == NULL || args[0] == 0)
3409 error_no_arg (_("system call to trace"));
3411 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3412 if (isdigit (args[0]))
3414 const int syscallnum = atoi (args);
3416 proc_trace_syscalls_1 (pi, syscallnum, entry_or_exit, mode, from_tty);
3420 static void
3421 proc_trace_sysentry_cmd (const char *args, int from_tty)
3423 proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_SET);
3426 static void
3427 proc_trace_sysexit_cmd (const char *args, int from_tty)
3429 proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_SET);
3432 static void
3433 proc_untrace_sysentry_cmd (const char *args, int from_tty)
3435 proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_RESET);
3438 static void
3439 proc_untrace_sysexit_cmd (const char *args, int from_tty)
3441 proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_RESET);
3444 void _initialize_procfs ();
3445 void
3446 _initialize_procfs ()
3448 add_com ("proc-trace-entry", no_class, proc_trace_sysentry_cmd,
3449 _("Give a trace of entries into the syscall."));
3450 add_com ("proc-trace-exit", no_class, proc_trace_sysexit_cmd,
3451 _("Give a trace of exits from the syscall."));
3452 add_com ("proc-untrace-entry", no_class, proc_untrace_sysentry_cmd,
3453 _("Cancel a trace of entries into the syscall."));
3454 add_com ("proc-untrace-exit", no_class, proc_untrace_sysexit_cmd,
3455 _("Cancel a trace of exits from the syscall."));
3457 add_inf_child_target (&the_procfs_target);
3460 /* =================== END, GDB "MODULE" =================== */
3464 /* miscellaneous stubs: */
3466 /* The following satisfy a few random symbols mostly created by the
3467 solaris threads implementation, which I will chase down later. */
3469 /* Return a pid for which we guarantee we will be able to find a
3470 'live' procinfo. */
3472 ptid_t
3473 procfs_first_available (void)
3475 return ptid_t (procinfo_list ? procinfo_list->pid : -1);
3478 /* =================== GCORE .NOTE "MODULE" =================== */
3480 static void
3481 procfs_do_thread_registers (bfd *obfd, ptid_t ptid,
3482 gdb::unique_xmalloc_ptr<char> &note_data,
3483 int *note_size, enum gdb_signal stop_signal)
3485 struct regcache *regcache = get_thread_regcache (&the_procfs_target, ptid);
3486 gdb_gregset_t gregs;
3487 gdb_fpregset_t fpregs;
3488 unsigned long merged_pid;
3490 merged_pid = ptid.lwp () << 16 | ptid.pid ();
3492 /* This part is the old method for fetching registers.
3493 It should be replaced by the newer one using regsets
3494 once it is implemented in this platform:
3495 gdbarch_iterate_over_regset_sections(). */
3497 target_fetch_registers (regcache, -1);
3499 fill_gregset (regcache, &gregs, -1);
3500 note_data.reset (elfcore_write_lwpstatus (obfd,
3501 note_data.release (),
3502 note_size,
3503 merged_pid,
3504 stop_signal,
3505 &gregs));
3506 fill_fpregset (regcache, &fpregs, -1);
3507 note_data.reset (elfcore_write_prfpreg (obfd,
3508 note_data.release (),
3509 note_size,
3510 &fpregs,
3511 sizeof (fpregs)));
3514 struct procfs_corefile_thread_data
3516 procfs_corefile_thread_data (bfd *obfd,
3517 gdb::unique_xmalloc_ptr<char> &note_data,
3518 int *note_size, gdb_signal stop_signal)
3519 : obfd (obfd), note_data (note_data), note_size (note_size),
3520 stop_signal (stop_signal)
3523 bfd *obfd;
3524 gdb::unique_xmalloc_ptr<char> &note_data;
3525 int *note_size;
3526 enum gdb_signal stop_signal;
3529 static int
3530 procfs_corefile_thread_callback (procinfo *pi, procinfo *thread, void *data)
3532 struct procfs_corefile_thread_data *args
3533 = (struct procfs_corefile_thread_data *) data;
3535 if (pi != NULL)
3537 ptid_t ptid = ptid_t (pi->pid, thread->tid, 0);
3539 procfs_do_thread_registers (args->obfd, ptid,
3540 args->note_data,
3541 args->note_size,
3542 args->stop_signal);
3544 return 0;
3547 static int
3548 find_signalled_thread (struct thread_info *info, void *data)
3550 if (info->stop_signal () != GDB_SIGNAL_0
3551 && info->ptid.pid () == inferior_ptid.pid ())
3552 return 1;
3554 return 0;
3557 static enum gdb_signal
3558 find_stop_signal (void)
3560 struct thread_info *info =
3561 iterate_over_threads (find_signalled_thread, NULL);
3563 if (info)
3564 return info->stop_signal ();
3565 else
3566 return GDB_SIGNAL_0;
3569 gdb::unique_xmalloc_ptr<char>
3570 procfs_target::make_corefile_notes (bfd *obfd, int *note_size)
3572 gdb_gregset_t gregs;
3573 char fname[16] = {'\0'};
3574 char psargs[80] = {'\0'};
3575 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3576 gdb::unique_xmalloc_ptr<char> note_data;
3577 enum gdb_signal stop_signal;
3579 if (get_exec_file (0))
3581 strncpy (fname, lbasename (get_exec_file (0)), sizeof (fname));
3582 fname[sizeof (fname) - 1] = 0;
3583 strncpy (psargs, get_exec_file (0), sizeof (psargs));
3584 psargs[sizeof (psargs) - 1] = 0;
3586 const std::string &inf_args = current_inferior ()->args ();
3587 if (!inf_args.empty () &&
3588 inf_args.length () < ((int) sizeof (psargs) - (int) strlen (psargs)))
3590 strncat (psargs, " ",
3591 sizeof (psargs) - strlen (psargs));
3592 strncat (psargs, inf_args.c_str (),
3593 sizeof (psargs) - strlen (psargs));
3597 note_data.reset (elfcore_write_prpsinfo (obfd,
3598 note_data.release (),
3599 note_size,
3600 fname,
3601 psargs));
3603 stop_signal = find_stop_signal ();
3605 fill_gregset (get_thread_regcache (inferior_thread ()), &gregs, -1);
3606 note_data.reset (elfcore_write_pstatus (obfd, note_data.release (), note_size,
3607 inferior_ptid.pid (),
3608 stop_signal, &gregs));
3610 procfs_corefile_thread_data thread_args (obfd, note_data, note_size,
3611 stop_signal);
3612 proc_iterate_over_threads (pi, procfs_corefile_thread_callback,
3613 &thread_args);
3615 std::optional<gdb::byte_vector> auxv =
3616 target_read_alloc (current_inferior ()->top_target (),
3617 TARGET_OBJECT_AUXV, NULL);
3618 if (auxv && !auxv->empty ())
3619 note_data.reset (elfcore_write_note (obfd, note_data.release (), note_size,
3620 "CORE", NT_AUXV, auxv->data (),
3621 auxv->size ()));
3623 return note_data;
3625 /* =================== END GCORE .NOTE "MODULE" =================== */