Add translations for various sub-directories
[binutils-gdb.git] / gdb / procfs.c
blobbe95a35f0167909f1a77fbf22b3f6b9f26a8060d
1 /* Machine independent support for Solaris /proc (process file system) for GDB.
3 Copyright (C) 1999-2024 Free Software Foundation, Inc.
5 Written by Michael Snyder at Cygnus Solutions.
6 Based on work by Fred Fish, Stu Grossman, Geoff Noer, and others.
8 This file is part of GDB.
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 #include "extract-store-integer.h"
24 #include "inferior.h"
25 #include "infrun.h"
26 #include "target.h"
27 #include "gdbcore.h"
28 #include "elf-bfd.h"
29 #include "cli/cli-cmds.h"
30 #include "gdbthread.h"
31 #include "regcache.h"
32 #include "inf-child.h"
33 #include "nat/fork-inferior.h"
34 #include "gdbarch.h"
36 #include <sys/procfs.h>
37 #include <sys/fault.h>
38 #include <sys/syscall.h>
39 #include "gdbsupport/gdb_wait.h"
40 #include <signal.h>
41 #include <ctype.h>
42 #include "gdb_bfd.h"
43 #include "auxv.h"
44 #include "procfs.h"
45 #include "observable.h"
46 #include "gdbsupport/scoped_fd.h"
47 #include "gdbsupport/pathstuff.h"
48 #include "gdbsupport/buildargv.h"
49 #include "gdbsupport/eintr.h"
50 #include "cli/cli-style.h"
52 /* This module provides the interface between GDB and the
53 /proc file system, which is used on many versions of Unix
54 as a means for debuggers to control other processes.
56 /proc works by imitating a file system: you open a simulated file
57 that represents the process you wish to interact with, and perform
58 operations on that "file" in order to examine or change the state
59 of the other process.
61 The most important thing to know about /proc and this module is
62 that there are two very different interfaces to /proc:
64 One that uses the ioctl system call, and another that uses read
65 and write system calls.
67 This module supports only the Solaris version of the read/write
68 interface. */
70 #include <sys/types.h>
71 #include <dirent.h>
73 #include <fcntl.h>
74 #include <unistd.h>
75 #include <sys/stat.h>
77 /* Note: procfs-utils.h must be included after the above system header
78 files, because it redefines various system calls using macros.
79 This may be incompatible with the prototype declarations. */
81 #include "proc-utils.h"
83 /* Prototypes for supply_gregset etc. */
84 #include "gregset.h"
86 /* =================== TARGET_OPS "MODULE" =================== */
88 /* This module defines the GDB target vector and its methods. */
91 static enum target_xfer_status procfs_xfer_memory (gdb_byte *,
92 const gdb_byte *,
93 ULONGEST, ULONGEST,
94 ULONGEST *);
96 class procfs_target final : public inf_child_target
98 public:
99 void create_inferior (const char *, const std::string &,
100 char **, int) override;
102 void kill () override;
104 void mourn_inferior () override;
106 void attach (const char *, int) override;
107 void detach (inferior *inf, int) override;
109 void resume (ptid_t, int, enum gdb_signal) override;
110 ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
112 void fetch_registers (struct regcache *, int) override;
113 void store_registers (struct regcache *, int) override;
115 enum target_xfer_status xfer_partial (enum target_object object,
116 const char *annex,
117 gdb_byte *readbuf,
118 const gdb_byte *writebuf,
119 ULONGEST offset, ULONGEST len,
120 ULONGEST *xfered_len) override;
122 void pass_signals (gdb::array_view<const unsigned char>) override;
124 void files_info () override;
126 void update_thread_list () override;
128 bool thread_alive (ptid_t ptid) override;
130 std::string pid_to_str (ptid_t) override;
132 const char *pid_to_exec_file (int pid) override;
134 thread_control_capabilities get_thread_control_capabilities () override
135 { return tc_schedlock; }
137 /* find_memory_regions support method for gcore */
138 int find_memory_regions (find_memory_region_ftype func, void *data)
139 override;
141 gdb::unique_xmalloc_ptr<char> make_corefile_notes (bfd *, int *) override;
143 bool info_proc (const char *, enum info_proc_what) override;
145 #if PR_MODEL_NATIVE == PR_MODEL_LP64
146 int auxv_parse (const gdb_byte **readptr,
147 const gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
148 override;
149 #endif
151 bool stopped_by_watchpoint () override;
153 int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
154 struct expression *) override;
156 int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
157 struct expression *) override;
159 int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
161 int can_use_hw_breakpoint (enum bptype, int, int) override;
162 bool stopped_data_address (CORE_ADDR *) override;
164 void procfs_init_inferior (int pid);
167 static procfs_target the_procfs_target;
169 #if PR_MODEL_NATIVE == PR_MODEL_LP64
170 /* When GDB is built as 64-bit application on Solaris, the auxv data
171 is presented in 64-bit format. We need to provide a custom parser
172 to handle that. */
174 procfs_target::auxv_parse (const gdb_byte **readptr,
175 const gdb_byte *endptr, CORE_ADDR *typep,
176 CORE_ADDR *valp)
178 bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
179 const gdb_byte *ptr = *readptr;
181 if (endptr == ptr)
182 return 0;
184 if (endptr - ptr < 8 * 2)
185 return -1;
187 *typep = extract_unsigned_integer (ptr, 4, byte_order);
188 ptr += 8;
189 /* The size of data is always 64-bit. If the application is 32-bit,
190 it will be zero extended, as expected. */
191 *valp = extract_unsigned_integer (ptr, 8, byte_order);
192 ptr += 8;
194 *readptr = ptr;
195 return 1;
197 #endif
199 /* =================== END, TARGET_OPS "MODULE" =================== */
201 /* =================== STRUCT PROCINFO "MODULE" =================== */
203 /* FIXME: this comment will soon be out of date W.R.T. threads. */
205 /* The procinfo struct is a wrapper to hold all the state information
206 concerning a /proc process. There should be exactly one procinfo
207 for each process, and since GDB currently can debug only one
208 process at a time, that means there should be only one procinfo.
209 All of the LWP's of a process can be accessed indirectly through the
210 single process procinfo.
212 However, against the day when GDB may debug more than one process,
213 this data structure is kept in a list (which for now will hold no
214 more than one member), and many functions will have a pointer to a
215 procinfo as an argument.
217 There will be a separate procinfo structure for use by the (not yet
218 implemented) "info proc" command, so that we can print useful
219 information about any random process without interfering with the
220 inferior's procinfo information. */
222 /* format strings for /proc paths */
223 #define CTL_PROC_NAME_FMT "/proc/%d/ctl"
224 #define AS_PROC_NAME_FMT "/proc/%d/as"
225 #define MAP_PROC_NAME_FMT "/proc/%d/map"
226 #define STATUS_PROC_NAME_FMT "/proc/%d/status"
227 #define MAX_PROC_NAME_SIZE sizeof("/proc/999999/lwp/0123456789/lwpstatus")
229 typedef struct procinfo {
230 struct procinfo *next;
231 int pid; /* Process ID */
232 int tid; /* Thread/LWP id */
234 /* process state */
235 int was_stopped;
236 int ignore_next_sigstop;
238 int ctl_fd; /* File descriptor for /proc control file */
239 int status_fd; /* File descriptor for /proc status file */
240 int as_fd; /* File descriptor for /proc as file */
242 char pathname[MAX_PROC_NAME_SIZE]; /* Pathname to /proc entry */
244 fltset_t saved_fltset; /* Saved traced hardware fault set */
245 sigset_t saved_sigset; /* Saved traced signal set */
246 sigset_t saved_sighold; /* Saved held signal set */
247 sysset_t *saved_exitset; /* Saved traced system call exit set */
248 sysset_t *saved_entryset; /* Saved traced system call entry set */
250 pstatus_t prstatus; /* Current process status info */
252 struct procinfo *thread_list;
254 int status_valid : 1;
255 int gregs_valid : 1;
256 int fpregs_valid : 1;
257 int threads_valid: 1;
258 } procinfo;
260 /* Function prototypes for procinfo module: */
262 static procinfo *find_procinfo_or_die (int pid, int tid);
263 static procinfo *find_procinfo (int pid, int tid);
264 static procinfo *create_procinfo (int pid, int tid);
265 static void destroy_procinfo (procinfo *p);
266 static void dead_procinfo (procinfo *p, const char *msg, int killp);
267 static int open_procinfo_files (procinfo *p, int which);
268 static void close_procinfo_files (procinfo *p);
270 static int iterate_over_mappings
271 (procinfo *pi, find_memory_region_ftype child_func, void *data,
272 int (*func) (struct prmap *map, find_memory_region_ftype child_func,
273 void *data));
275 /* The head of the procinfo list: */
276 static procinfo *procinfo_list;
278 /* Search the procinfo list. Return a pointer to procinfo, or NULL if
279 not found. */
281 static procinfo *
282 find_procinfo (int pid, int tid)
284 procinfo *pi;
286 for (pi = procinfo_list; pi; pi = pi->next)
287 if (pi->pid == pid)
288 break;
290 if (pi)
291 if (tid)
293 /* Don't check threads_valid. If we're updating the
294 thread_list, we want to find whatever threads are already
295 here. This means that in general it is the caller's
296 responsibility to check threads_valid and update before
297 calling find_procinfo, if the caller wants to find a new
298 thread. */
300 for (pi = pi->thread_list; pi; pi = pi->next)
301 if (pi->tid == tid)
302 break;
305 return pi;
308 /* Calls find_procinfo, but errors on failure. */
310 static procinfo *
311 find_procinfo_or_die (int pid, int tid)
313 procinfo *pi = find_procinfo (pid, tid);
315 if (pi == NULL)
317 if (tid)
318 error (_("procfs: couldn't find pid %d "
319 "(kernel thread %d) in procinfo list."),
320 pid, tid);
321 else
322 error (_("procfs: couldn't find pid %d in procinfo list."), pid);
324 return pi;
327 /* Wrapper for `open'. The appropriate open call is attempted; if
328 unsuccessful, it will be retried as many times as needed for the
329 EAGAIN and EINTR conditions.
331 For other conditions, retry the open a limited number of times. In
332 addition, a short sleep is imposed prior to retrying the open. The
333 reason for this sleep is to give the kernel a chance to catch up
334 and create the file in question in the event that GDB "wins" the
335 race to open a file before the kernel has created it. */
337 static int
338 open_with_retry (const char *pathname, int flags)
340 int retries_remaining, status;
342 retries_remaining = 2;
344 while (1)
346 status = open (pathname, flags);
348 if (status >= 0 || retries_remaining == 0)
349 break;
350 else if (errno != EINTR && errno != EAGAIN)
352 retries_remaining--;
353 sleep (1);
357 return status;
360 /* Open the file descriptor for the process or LWP. We only open the
361 control file descriptor; the others are opened lazily as needed.
362 Returns the file descriptor, or zero for failure. */
364 enum { FD_CTL, FD_STATUS, FD_AS };
366 static int
367 open_procinfo_files (procinfo *pi, int which)
369 char tmp[MAX_PROC_NAME_SIZE];
370 int fd;
372 /* This function is getting ALMOST long enough to break up into
373 several. Here is some rationale:
375 There are several file descriptors that may need to be open
376 for any given process or LWP. The ones we're interested in are:
377 - control (ctl) write-only change the state
378 - status (status) read-only query the state
379 - address space (as) read/write access memory
380 - map (map) read-only virtual addr map
381 Most of these are opened lazily as they are needed.
382 The pathnames for the 'files' for an LWP look slightly
383 different from those of a first-class process:
384 Pathnames for a process (<proc-id>):
385 /proc/<proc-id>/ctl
386 /proc/<proc-id>/status
387 /proc/<proc-id>/as
388 /proc/<proc-id>/map
389 Pathnames for an LWP (lwp-id):
390 /proc/<proc-id>/lwp/<lwp-id>/lwpctl
391 /proc/<proc-id>/lwp/<lwp-id>/lwpstatus
392 An LWP has no map or address space file descriptor, since
393 the memory map and address space are shared by all LWPs. */
395 /* In this case, there are several different file descriptors that
396 we might be asked to open. The control file descriptor will be
397 opened early, but the others will be opened lazily as they are
398 needed. */
400 strcpy (tmp, pi->pathname);
401 switch (which) { /* Which file descriptor to open? */
402 case FD_CTL:
403 if (pi->tid)
404 strcat (tmp, "/lwpctl");
405 else
406 strcat (tmp, "/ctl");
407 fd = open_with_retry (tmp, O_WRONLY);
408 if (fd < 0)
409 return 0; /* fail */
410 pi->ctl_fd = fd;
411 break;
412 case FD_AS:
413 if (pi->tid)
414 return 0; /* There is no 'as' file descriptor for an lwp. */
415 strcat (tmp, "/as");
416 fd = open_with_retry (tmp, O_RDWR);
417 if (fd < 0)
418 return 0; /* fail */
419 pi->as_fd = fd;
420 break;
421 case FD_STATUS:
422 if (pi->tid)
423 strcat (tmp, "/lwpstatus");
424 else
425 strcat (tmp, "/status");
426 fd = open_with_retry (tmp, O_RDONLY);
427 if (fd < 0)
428 return 0; /* fail */
429 pi->status_fd = fd;
430 break;
431 default:
432 return 0; /* unknown file descriptor */
435 return 1; /* success */
438 /* Allocate a data structure and link it into the procinfo list.
439 First tries to find a pre-existing one (FIXME: why?). Returns the
440 pointer to new procinfo struct. */
442 static procinfo *
443 create_procinfo (int pid, int tid)
445 procinfo *pi, *parent = NULL;
447 pi = find_procinfo (pid, tid);
448 if (pi != NULL)
449 return pi; /* Already exists, nothing to do. */
451 /* Find parent before doing malloc, to save having to cleanup. */
452 if (tid != 0)
453 parent = find_procinfo_or_die (pid, 0); /* FIXME: should I
454 create it if it
455 doesn't exist yet? */
457 pi = XNEW (procinfo);
458 memset (pi, 0, sizeof (procinfo));
459 pi->pid = pid;
460 pi->tid = tid;
462 pi->saved_entryset = XNEW (sysset_t);
463 pi->saved_exitset = XNEW (sysset_t);
465 /* Chain into list. */
466 if (tid == 0)
468 xsnprintf (pi->pathname, sizeof (pi->pathname), "/proc/%d", pid);
469 pi->next = procinfo_list;
470 procinfo_list = pi;
472 else
474 xsnprintf (pi->pathname, sizeof (pi->pathname), "/proc/%d/lwp/%d",
475 pid, tid);
476 pi->next = parent->thread_list;
477 parent->thread_list = pi;
479 return pi;
482 /* Close all file descriptors associated with the procinfo. */
484 static void
485 close_procinfo_files (procinfo *pi)
487 if (pi->ctl_fd > 0)
488 close (pi->ctl_fd);
489 if (pi->as_fd > 0)
490 close (pi->as_fd);
491 if (pi->status_fd > 0)
492 close (pi->status_fd);
493 pi->ctl_fd = pi->as_fd = pi->status_fd = 0;
496 /* Destructor function. Close, unlink and deallocate the object. */
498 static void
499 destroy_one_procinfo (procinfo **list, procinfo *pi)
501 procinfo *ptr;
503 /* Step one: unlink the procinfo from its list. */
504 if (pi == *list)
505 *list = pi->next;
506 else
507 for (ptr = *list; ptr; ptr = ptr->next)
508 if (ptr->next == pi)
510 ptr->next = pi->next;
511 break;
514 /* Step two: close any open file descriptors. */
515 close_procinfo_files (pi);
517 /* Step three: free the memory. */
518 xfree (pi->saved_entryset);
519 xfree (pi->saved_exitset);
520 xfree (pi);
523 static void
524 destroy_procinfo (procinfo *pi)
526 procinfo *tmp;
528 if (pi->tid != 0) /* Destroy a thread procinfo. */
530 tmp = find_procinfo (pi->pid, 0); /* Find the parent process. */
531 destroy_one_procinfo (&tmp->thread_list, pi);
533 else /* Destroy a process procinfo and all its threads. */
535 /* First destroy the children, if any; */
536 while (pi->thread_list != NULL)
537 destroy_one_procinfo (&pi->thread_list, pi->thread_list);
538 /* Then destroy the parent. Genocide!!! */
539 destroy_one_procinfo (&procinfo_list, pi);
543 /* A deleter that calls destroy_procinfo. */
544 struct procinfo_deleter
546 void operator() (procinfo *pi) const
548 destroy_procinfo (pi);
552 typedef std::unique_ptr<procinfo, procinfo_deleter> procinfo_up;
554 enum { NOKILL, KILL };
556 /* To be called on a non_recoverable error for a procinfo. Prints
557 error messages, optionally sends a SIGKILL to the process, then
558 destroys the data structure. */
560 static void
561 dead_procinfo (procinfo *pi, const char *msg, int kill_p)
563 warning_filename_and_errno (pi->pathname, errno);
564 if (kill_p == KILL)
565 kill (pi->pid, SIGKILL);
567 destroy_procinfo (pi);
568 error ("%s", msg);
571 /* =================== END, STRUCT PROCINFO "MODULE" =================== */
573 /* =================== /proc "MODULE" =================== */
575 /* This "module" is the interface layer between the /proc system API
576 and the gdb target vector functions. This layer consists of access
577 functions that encapsulate each of the basic operations that we
578 need to use from the /proc API.
580 The main motivation for this layer is to hide the fact that there
581 were two very different implementations of the /proc API. */
583 static long proc_flags (procinfo *pi);
584 static int proc_why (procinfo *pi);
585 static int proc_what (procinfo *pi);
586 static int proc_set_current_signal (procinfo *pi, int signo);
587 static int proc_get_current_thread (procinfo *pi);
588 static int proc_iterate_over_threads
589 (procinfo *pi,
590 int (*func) (procinfo *, procinfo *, void *),
591 void *ptr);
592 static void proc_resume (procinfo *pi, ptid_t scope_ptid,
593 int step, enum gdb_signal signo);
595 static void
596 proc_warn (procinfo *pi, const char *func, int line)
598 int saved_errno = errno;
599 warning ("procfs: %s line %d, %ps: %s",
600 func, line, styled_string (file_name_style.style (),
601 pi->pathname),
602 safe_strerror (saved_errno));
605 static void
606 proc_error (procinfo *pi, const char *func, int line)
608 int saved_errno = errno;
609 error ("procfs: %s line %d, %s: %s",
610 func, line, pi->pathname, safe_strerror (saved_errno));
613 /* Updates the status struct in the procinfo. There is a 'valid'
614 flag, to let other functions know when this function needs to be
615 called (so the status is only read when it is needed). The status
616 file descriptor is also only opened when it is needed. Returns
617 non-zero for success, zero for failure. */
619 static int
620 proc_get_status (procinfo *pi)
622 /* Status file descriptor is opened "lazily". */
623 if (pi->status_fd == 0 && open_procinfo_files (pi, FD_STATUS) == 0)
625 pi->status_valid = 0;
626 return 0;
629 if (lseek (pi->status_fd, 0, SEEK_SET) < 0)
630 pi->status_valid = 0; /* fail */
631 else
633 /* Sigh... I have to read a different data structure,
634 depending on whether this is a main process or an LWP. */
635 if (pi->tid)
636 pi->status_valid = (read (pi->status_fd,
637 (char *) &pi->prstatus.pr_lwp,
638 sizeof (lwpstatus_t))
639 == sizeof (lwpstatus_t));
640 else
642 pi->status_valid = (read (pi->status_fd,
643 (char *) &pi->prstatus,
644 sizeof (pstatus_t))
645 == sizeof (pstatus_t));
649 if (pi->status_valid)
651 PROC_PRETTYFPRINT_STATUS (proc_flags (pi),
652 proc_why (pi),
653 proc_what (pi),
654 proc_get_current_thread (pi));
657 /* The status struct includes general regs, so mark them valid too. */
658 pi->gregs_valid = pi->status_valid;
659 /* In the read/write multiple-fd model, the status struct includes
660 the fp regs too, so mark them valid too. */
661 pi->fpregs_valid = pi->status_valid;
662 return pi->status_valid; /* True if success, false if failure. */
665 /* Returns the process flags (pr_flags field). */
667 static long
668 proc_flags (procinfo *pi)
670 if (!pi->status_valid)
671 if (!proc_get_status (pi))
672 return 0; /* FIXME: not a good failure value (but what is?) */
674 return pi->prstatus.pr_lwp.pr_flags;
677 /* Returns the pr_why field (why the process stopped). */
679 static int
680 proc_why (procinfo *pi)
682 if (!pi->status_valid)
683 if (!proc_get_status (pi))
684 return 0; /* FIXME: not a good failure value (but what is?) */
686 return pi->prstatus.pr_lwp.pr_why;
689 /* Returns the pr_what field (details of why the process stopped). */
691 static int
692 proc_what (procinfo *pi)
694 if (!pi->status_valid)
695 if (!proc_get_status (pi))
696 return 0; /* FIXME: not a good failure value (but what is?) */
698 return pi->prstatus.pr_lwp.pr_what;
701 /* This function is only called when PI is stopped by a watchpoint.
702 Assuming the OS supports it, write to *ADDR the data address which
703 triggered it and return 1. Return 0 if it is not possible to know
704 the address. */
706 static int
707 proc_watchpoint_address (procinfo *pi, CORE_ADDR *addr)
709 if (!pi->status_valid)
710 if (!proc_get_status (pi))
711 return 0;
713 gdbarch *arch = current_inferior ()->arch ();
714 *addr = gdbarch_pointer_to_address
715 (arch, builtin_type (arch)->builtin_data_ptr,
716 (gdb_byte *) &pi->prstatus.pr_lwp.pr_info.si_addr);
717 return 1;
720 /* Returns the pr_nsysarg field (number of args to the current
721 syscall). */
723 static int
724 proc_nsysarg (procinfo *pi)
726 if (!pi->status_valid)
727 if (!proc_get_status (pi))
728 return 0;
730 return pi->prstatus.pr_lwp.pr_nsysarg;
733 /* Returns the pr_sysarg field (pointer to the arguments of current
734 syscall). */
736 static long *
737 proc_sysargs (procinfo *pi)
739 if (!pi->status_valid)
740 if (!proc_get_status (pi))
741 return NULL;
743 return (long *) &pi->prstatus.pr_lwp.pr_sysarg;
746 /* Set or reset any of the following process flags:
747 PR_FORK -- forked child will inherit trace flags
748 PR_RLC -- traced process runs when last /proc file closed.
749 PR_KLC -- traced process is killed when last /proc file closed.
750 PR_ASYNC -- LWP's get to run/stop independently.
752 This function is done using read/write [PCSET/PCRESET/PCUNSET].
754 Arguments:
755 pi -- the procinfo
756 flag -- one of PR_FORK, PR_RLC, or PR_ASYNC
757 mode -- 1 for set, 0 for reset.
759 Returns non-zero for success, zero for failure. */
761 enum { FLAG_RESET, FLAG_SET };
763 static int
764 proc_modify_flag (procinfo *pi, long flag, long mode)
766 long win = 0; /* default to fail */
768 /* These operations affect the process as a whole, and applying them
769 to an individual LWP has the same meaning as applying them to the
770 main process. Therefore, if we're ever called with a pointer to
771 an LWP's procinfo, let's substitute the process's procinfo and
772 avoid opening the LWP's file descriptor unnecessarily. */
774 if (pi->pid != 0)
775 pi = find_procinfo_or_die (pi->pid, 0);
777 procfs_ctl_t arg[2];
779 if (mode == FLAG_SET) /* Set the flag (RLC, FORK, or ASYNC). */
780 arg[0] = PCSET;
781 else /* Reset the flag. */
782 arg[0] = PCUNSET;
784 arg[1] = flag;
785 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
787 /* The above operation renders the procinfo's cached pstatus
788 obsolete. */
789 pi->status_valid = 0;
791 if (!win)
792 warning (_("procfs: modify_flag failed to turn %s %s"),
793 flag == PR_FORK ? "PR_FORK" :
794 flag == PR_RLC ? "PR_RLC" :
795 flag == PR_ASYNC ? "PR_ASYNC" :
796 flag == PR_KLC ? "PR_KLC" :
797 "<unknown flag>",
798 mode == FLAG_RESET ? "off" : "on");
800 return win;
803 /* Set the run_on_last_close flag. Process with all threads will
804 become runnable when debugger closes all /proc fds. Returns
805 non-zero for success, zero for failure. */
807 static int
808 proc_set_run_on_last_close (procinfo *pi)
810 return proc_modify_flag (pi, PR_RLC, FLAG_SET);
813 /* Reset the run_on_last_close flag. The process will NOT become
814 runnable when debugger closes its file handles. Returns non-zero
815 for success, zero for failure. */
817 static int
818 proc_unset_run_on_last_close (procinfo *pi)
820 return proc_modify_flag (pi, PR_RLC, FLAG_RESET);
823 /* Reset inherit_on_fork flag. If the process forks a child while we
824 are registered for events in the parent, then we will NOT receive
825 events from the child. Returns non-zero for success, zero for
826 failure. */
828 static int
829 proc_unset_inherit_on_fork (procinfo *pi)
831 return proc_modify_flag (pi, PR_FORK, FLAG_RESET);
834 /* Set PR_ASYNC flag. If one LWP stops because of a debug event
835 (signal etc.), the remaining LWPs will continue to run. Returns
836 non-zero for success, zero for failure. */
838 static int
839 proc_set_async (procinfo *pi)
841 return proc_modify_flag (pi, PR_ASYNC, FLAG_SET);
844 /* Reset PR_ASYNC flag. If one LWP stops because of a debug event
845 (signal etc.), then all other LWPs will stop as well. Returns
846 non-zero for success, zero for failure. */
848 static int
849 proc_unset_async (procinfo *pi)
851 return proc_modify_flag (pi, PR_ASYNC, FLAG_RESET);
854 /* Request the process/LWP to stop. Does not wait. Returns non-zero
855 for success, zero for failure. */
857 static int
858 proc_stop_process (procinfo *pi)
860 int win;
862 /* We might conceivably apply this operation to an LWP, and the
863 LWP's ctl file descriptor might not be open. */
865 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
866 return 0;
867 else
869 procfs_ctl_t cmd = PCSTOP;
871 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
874 return win;
877 /* Wait for the process or LWP to stop (block until it does). Returns
878 non-zero for success, zero for failure. */
880 static int
881 proc_wait_for_stop (procinfo *pi)
883 int win;
885 /* We should never have to apply this operation to any procinfo
886 except the one for the main process. If that ever changes for
887 any reason, then take out the following clause and replace it
888 with one that makes sure the ctl_fd is open. */
890 if (pi->tid != 0)
891 pi = find_procinfo_or_die (pi->pid, 0);
893 procfs_ctl_t cmd = PCWSTOP;
895 set_sigint_trap ();
897 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
899 clear_sigint_trap ();
901 /* We been runnin' and we stopped -- need to update status. */
902 pi->status_valid = 0;
904 return win;
907 /* Make the process or LWP runnable.
909 Options (not all are implemented):
910 - single-step
911 - clear current fault
912 - clear current signal
913 - abort the current system call
914 - stop as soon as finished with system call
916 Always clears the current fault. PI is the process or LWP to
917 operate on. If STEP is true, set the process or LWP to trap after
918 one instruction. If SIGNO is zero, clear the current signal if
919 any; if non-zero, set the current signal to this one. Returns
920 non-zero for success, zero for failure. */
922 static int
923 proc_run_process (procinfo *pi, int step, int signo)
925 int win;
926 int runflags;
928 /* We will probably have to apply this operation to individual
929 threads, so make sure the control file descriptor is open. */
931 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
932 return 0;
934 runflags = PRCFAULT; /* Always clear current fault. */
935 if (step)
936 runflags |= PRSTEP;
937 if (signo == 0)
938 runflags |= PRCSIG;
939 else if (signo != -1) /* -1 means do nothing W.R.T. signals. */
940 proc_set_current_signal (pi, signo);
942 procfs_ctl_t cmd[2];
944 cmd[0] = PCRUN;
945 cmd[1] = runflags;
946 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
948 return win;
951 /* Register to trace signals in the process or LWP. Returns non-zero
952 for success, zero for failure. */
954 static int
955 proc_set_traced_signals (procinfo *pi, sigset_t *sigset)
957 int win;
959 /* We should never have to apply this operation to any procinfo
960 except the one for the main process. If that ever changes for
961 any reason, then take out the following clause and replace it
962 with one that makes sure the ctl_fd is open. */
964 if (pi->tid != 0)
965 pi = find_procinfo_or_die (pi->pid, 0);
967 struct {
968 procfs_ctl_t cmd;
969 /* Use char array to avoid alignment issues. */
970 char sigset[sizeof (sigset_t)];
971 } arg;
973 arg.cmd = PCSTRACE;
974 memcpy (&arg.sigset, sigset, sizeof (sigset_t));
976 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
978 /* The above operation renders the procinfo's cached pstatus obsolete. */
979 pi->status_valid = 0;
981 if (!win)
982 warning (_("procfs: set_traced_signals failed"));
983 return win;
986 /* Register to trace hardware faults in the process or LWP. Returns
987 non-zero for success, zero for failure. */
989 static int
990 proc_set_traced_faults (procinfo *pi, fltset_t *fltset)
992 int win;
994 /* We should never have to apply this operation to any procinfo
995 except the one for the main process. If that ever changes for
996 any reason, then take out the following clause and replace it
997 with one that makes sure the ctl_fd is open. */
999 if (pi->tid != 0)
1000 pi = find_procinfo_or_die (pi->pid, 0);
1002 struct {
1003 procfs_ctl_t cmd;
1004 /* Use char array to avoid alignment issues. */
1005 char fltset[sizeof (fltset_t)];
1006 } arg;
1008 arg.cmd = PCSFAULT;
1009 memcpy (&arg.fltset, fltset, sizeof (fltset_t));
1011 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1013 /* The above operation renders the procinfo's cached pstatus obsolete. */
1014 pi->status_valid = 0;
1016 return win;
1019 /* Register to trace entry to system calls in the process or LWP.
1020 Returns non-zero for success, zero for failure. */
1022 static int
1023 proc_set_traced_sysentry (procinfo *pi, sysset_t *sysset)
1025 int win;
1027 /* We should never have to apply this operation to any procinfo
1028 except the one for the main process. If that ever changes for
1029 any reason, then take out the following clause and replace it
1030 with one that makes sure the ctl_fd is open. */
1032 if (pi->tid != 0)
1033 pi = find_procinfo_or_die (pi->pid, 0);
1035 struct {
1036 procfs_ctl_t cmd;
1037 /* Use char array to avoid alignment issues. */
1038 char sysset[sizeof (sysset_t)];
1039 } arg;
1041 arg.cmd = PCSENTRY;
1042 memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1044 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1046 /* The above operation renders the procinfo's cached pstatus
1047 obsolete. */
1048 pi->status_valid = 0;
1050 return win;
1053 /* Register to trace exit from system calls in the process or LWP.
1054 Returns non-zero for success, zero for failure. */
1056 static int
1057 proc_set_traced_sysexit (procinfo *pi, sysset_t *sysset)
1059 int win;
1061 /* We should never have to apply this operation to any procinfo
1062 except the one for the main process. If that ever changes for
1063 any reason, then take out the following clause and replace it
1064 with one that makes sure the ctl_fd is open. */
1066 if (pi->tid != 0)
1067 pi = find_procinfo_or_die (pi->pid, 0);
1069 struct gdb_proc_ctl_pcsexit {
1070 procfs_ctl_t cmd;
1071 /* Use char array to avoid alignment issues. */
1072 char sysset[sizeof (sysset_t)];
1073 } arg;
1075 arg.cmd = PCSEXIT;
1076 memcpy (&arg.sysset, sysset, sizeof (sysset_t));
1078 win = (write (pi->ctl_fd, (char *) &arg, sizeof (arg)) == sizeof (arg));
1080 /* The above operation renders the procinfo's cached pstatus
1081 obsolete. */
1082 pi->status_valid = 0;
1084 return win;
1087 /* Specify the set of blocked / held signals in the process or LWP.
1088 Returns non-zero for success, zero for failure. */
1090 static int
1091 proc_set_held_signals (procinfo *pi, sigset_t *sighold)
1093 int win;
1095 /* We should never have to apply this operation to any procinfo
1096 except the one for the main process. If that ever changes for
1097 any reason, then take out the following clause and replace it
1098 with one that makes sure the ctl_fd is open. */
1100 if (pi->tid != 0)
1101 pi = find_procinfo_or_die (pi->pid, 0);
1103 struct {
1104 procfs_ctl_t cmd;
1105 /* Use char array to avoid alignment issues. */
1106 char hold[sizeof (sigset_t)];
1107 } arg;
1109 arg.cmd = PCSHOLD;
1110 memcpy (&arg.hold, sighold, sizeof (sigset_t));
1111 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1113 /* The above operation renders the procinfo's cached pstatus
1114 obsolete. */
1115 pi->status_valid = 0;
1117 return win;
1120 /* Returns the set of signals that are held / blocked. Will also copy
1121 the sigset if SAVE is non-zero. */
1123 static sigset_t *
1124 proc_get_held_signals (procinfo *pi, sigset_t *save)
1126 sigset_t *ret = NULL;
1128 /* We should never have to apply this operation to any procinfo
1129 except the one for the main process. If that ever changes for
1130 any reason, then take out the following clause and replace it
1131 with one that makes sure the ctl_fd is open. */
1133 if (pi->tid != 0)
1134 pi = find_procinfo_or_die (pi->pid, 0);
1136 if (!pi->status_valid)
1137 if (!proc_get_status (pi))
1138 return NULL;
1140 ret = &pi->prstatus.pr_lwp.pr_lwphold;
1141 if (save && ret)
1142 memcpy (save, ret, sizeof (sigset_t));
1144 return ret;
1147 /* Returns the set of signals that are traced / debugged. Will also
1148 copy the sigset if SAVE is non-zero. */
1150 static sigset_t *
1151 proc_get_traced_signals (procinfo *pi, sigset_t *save)
1153 sigset_t *ret = NULL;
1155 /* We should never have to apply this operation to any procinfo
1156 except the one for the main process. If that ever changes for
1157 any reason, then take out the following clause and replace it
1158 with one that makes sure the ctl_fd is open. */
1160 if (pi->tid != 0)
1161 pi = find_procinfo_or_die (pi->pid, 0);
1163 if (!pi->status_valid)
1164 if (!proc_get_status (pi))
1165 return NULL;
1167 ret = &pi->prstatus.pr_sigtrace;
1168 if (save && ret)
1169 memcpy (save, ret, sizeof (sigset_t));
1171 return ret;
1174 /* Returns the set of hardware faults that are traced /debugged. Will
1175 also copy the faultset if SAVE is non-zero. */
1177 static fltset_t *
1178 proc_get_traced_faults (procinfo *pi, fltset_t *save)
1180 fltset_t *ret = NULL;
1182 /* We should never have to apply this operation to any procinfo
1183 except the one for the main process. If that ever changes for
1184 any reason, then take out the following clause and replace it
1185 with one that makes sure the ctl_fd is open. */
1187 if (pi->tid != 0)
1188 pi = find_procinfo_or_die (pi->pid, 0);
1190 if (!pi->status_valid)
1191 if (!proc_get_status (pi))
1192 return NULL;
1194 ret = &pi->prstatus.pr_flttrace;
1195 if (save && ret)
1196 memcpy (save, ret, sizeof (fltset_t));
1198 return ret;
1201 /* Returns the set of syscalls that are traced /debugged on entry.
1202 Will also copy the syscall set if SAVE is non-zero. */
1204 static sysset_t *
1205 proc_get_traced_sysentry (procinfo *pi, sysset_t *save)
1207 sysset_t *ret = NULL;
1209 /* We should never have to apply this operation to any procinfo
1210 except the one for the main process. If that ever changes for
1211 any reason, then take out the following clause and replace it
1212 with one that makes sure the ctl_fd is open. */
1214 if (pi->tid != 0)
1215 pi = find_procinfo_or_die (pi->pid, 0);
1217 if (!pi->status_valid)
1218 if (!proc_get_status (pi))
1219 return NULL;
1221 ret = &pi->prstatus.pr_sysentry;
1222 if (save && ret)
1223 memcpy (save, ret, sizeof (sysset_t));
1225 return ret;
1228 /* Returns the set of syscalls that are traced /debugged on exit.
1229 Will also copy the syscall set if SAVE is non-zero. */
1231 static sysset_t *
1232 proc_get_traced_sysexit (procinfo *pi, sysset_t *save)
1234 sysset_t *ret = NULL;
1236 /* We should never have to apply this operation to any procinfo
1237 except the one for the main process. If that ever changes for
1238 any reason, then take out the following clause and replace it
1239 with one that makes sure the ctl_fd is open. */
1241 if (pi->tid != 0)
1242 pi = find_procinfo_or_die (pi->pid, 0);
1244 if (!pi->status_valid)
1245 if (!proc_get_status (pi))
1246 return NULL;
1248 ret = &pi->prstatus.pr_sysexit;
1249 if (save && ret)
1250 memcpy (save, ret, sizeof (sysset_t));
1252 return ret;
1255 /* The current fault (if any) is cleared; the associated signal will
1256 not be sent to the process or LWP when it resumes. Returns
1257 non-zero for success, zero for failure. */
1259 static int
1260 proc_clear_current_fault (procinfo *pi)
1262 int win;
1264 /* We should never have to apply this operation to any procinfo
1265 except the one for the main process. If that ever changes for
1266 any reason, then take out the following clause and replace it
1267 with one that makes sure the ctl_fd is open. */
1269 if (pi->tid != 0)
1270 pi = find_procinfo_or_die (pi->pid, 0);
1272 procfs_ctl_t cmd = PCCFAULT;
1274 win = (write (pi->ctl_fd, (void *) &cmd, sizeof (cmd)) == sizeof (cmd));
1276 return win;
1279 /* Set the "current signal" that will be delivered next to the
1280 process. NOTE: semantics are different from those of KILL. This
1281 signal will be delivered to the process or LWP immediately when it
1282 is resumed (even if the signal is held/blocked); it will NOT
1283 immediately cause another event of interest, and will NOT first
1284 trap back to the debugger. Returns non-zero for success, zero for
1285 failure. */
1287 static int
1288 proc_set_current_signal (procinfo *pi, int signo)
1290 int win;
1291 struct {
1292 procfs_ctl_t cmd;
1293 /* Use char array to avoid alignment issues. */
1294 char sinfo[sizeof (siginfo_t)];
1295 } arg;
1296 siginfo_t mysinfo;
1297 process_stratum_target *wait_target;
1298 ptid_t wait_ptid;
1299 struct target_waitstatus wait_status;
1301 /* We should never have to apply this operation to any procinfo
1302 except the one for the main process. If that ever changes for
1303 any reason, then take out the following clause and replace it
1304 with one that makes sure the ctl_fd is open. */
1306 if (pi->tid != 0)
1307 pi = find_procinfo_or_die (pi->pid, 0);
1309 /* The pointer is just a type alias. */
1310 get_last_target_status (&wait_target, &wait_ptid, &wait_status);
1311 if (wait_target == &the_procfs_target
1312 && wait_ptid == inferior_ptid
1313 && wait_status.kind () == TARGET_WAITKIND_STOPPED
1314 && wait_status.sig () == gdb_signal_from_host (signo)
1315 && proc_get_status (pi)
1316 && pi->prstatus.pr_lwp.pr_info.si_signo == signo
1318 /* Use the siginfo associated with the signal being
1319 redelivered. */
1320 memcpy (arg.sinfo, &pi->prstatus.pr_lwp.pr_info, sizeof (siginfo_t));
1321 else
1323 mysinfo.si_signo = signo;
1324 mysinfo.si_code = 0;
1325 mysinfo.si_pid = getpid (); /* ?why? */
1326 mysinfo.si_uid = getuid (); /* ?why? */
1327 memcpy (arg.sinfo, &mysinfo, sizeof (siginfo_t));
1330 arg.cmd = PCSSIG;
1331 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1333 return win;
1336 /* The current signal (if any) is cleared, and is not sent to the
1337 process or LWP when it resumes. Returns non-zero for success, zero
1338 for failure. */
1340 static int
1341 proc_clear_current_signal (procinfo *pi)
1343 int win;
1345 /* We should never have to apply this operation to any procinfo
1346 except the one for the main process. If that ever changes for
1347 any reason, then take out the following clause and replace it
1348 with one that makes sure the ctl_fd is open. */
1350 if (pi->tid != 0)
1351 pi = find_procinfo_or_die (pi->pid, 0);
1353 struct {
1354 procfs_ctl_t cmd;
1355 /* Use char array to avoid alignment issues. */
1356 char sinfo[sizeof (siginfo_t)];
1357 } arg;
1358 siginfo_t mysinfo;
1360 arg.cmd = PCSSIG;
1361 /* The pointer is just a type alias. */
1362 mysinfo.si_signo = 0;
1363 mysinfo.si_code = 0;
1364 mysinfo.si_errno = 0;
1365 mysinfo.si_pid = getpid (); /* ?why? */
1366 mysinfo.si_uid = getuid (); /* ?why? */
1367 memcpy (arg.sinfo, &mysinfo, sizeof (siginfo_t));
1369 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1371 return win;
1374 /* Return the general-purpose registers for the process or LWP
1375 corresponding to PI. Upon failure, return NULL. */
1377 static gdb_gregset_t *
1378 proc_get_gregs (procinfo *pi)
1380 if (!pi->status_valid || !pi->gregs_valid)
1381 if (!proc_get_status (pi))
1382 return NULL;
1384 return &pi->prstatus.pr_lwp.pr_reg;
1387 /* Return the general-purpose registers for the process or LWP
1388 corresponding to PI. Upon failure, return NULL. */
1390 static gdb_fpregset_t *
1391 proc_get_fpregs (procinfo *pi)
1393 if (!pi->status_valid || !pi->fpregs_valid)
1394 if (!proc_get_status (pi))
1395 return NULL;
1397 return &pi->prstatus.pr_lwp.pr_fpreg;
1400 /* Write the general-purpose registers back to the process or LWP
1401 corresponding to PI. Return non-zero for success, zero for
1402 failure. */
1404 static int
1405 proc_set_gregs (procinfo *pi)
1407 gdb_gregset_t *gregs;
1408 int win;
1410 gregs = proc_get_gregs (pi);
1411 if (gregs == NULL)
1412 return 0; /* proc_get_regs has already warned. */
1414 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1415 return 0;
1416 else
1418 struct {
1419 procfs_ctl_t cmd;
1420 /* Use char array to avoid alignment issues. */
1421 char gregs[sizeof (gdb_gregset_t)];
1422 } arg;
1424 arg.cmd = PCSREG;
1425 memcpy (&arg.gregs, gregs, sizeof (arg.gregs));
1426 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1429 /* Policy: writing the registers invalidates our cache. */
1430 pi->gregs_valid = 0;
1431 return win;
1434 /* Write the floating-pointer registers back to the process or LWP
1435 corresponding to PI. Return non-zero for success, zero for
1436 failure. */
1438 static int
1439 proc_set_fpregs (procinfo *pi)
1441 gdb_fpregset_t *fpregs;
1442 int win;
1444 fpregs = proc_get_fpregs (pi);
1445 if (fpregs == NULL)
1446 return 0; /* proc_get_fpregs has already warned. */
1448 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1449 return 0;
1450 else
1452 struct {
1453 procfs_ctl_t cmd;
1454 /* Use char array to avoid alignment issues. */
1455 char fpregs[sizeof (gdb_fpregset_t)];
1456 } arg;
1458 arg.cmd = PCSFPREG;
1459 memcpy (&arg.fpregs, fpregs, sizeof (arg.fpregs));
1460 win = (write (pi->ctl_fd, (void *) &arg, sizeof (arg)) == sizeof (arg));
1463 /* Policy: writing the registers invalidates our cache. */
1464 pi->fpregs_valid = 0;
1465 return win;
1468 /* Send a signal to the proc or lwp with the semantics of "kill()".
1469 Returns non-zero for success, zero for failure. */
1471 static int
1472 proc_kill (procinfo *pi, int signo)
1474 int win;
1476 /* We might conceivably apply this operation to an LWP, and the
1477 LWP's ctl file descriptor might not be open. */
1479 if (pi->ctl_fd == 0 && open_procinfo_files (pi, FD_CTL) == 0)
1480 return 0;
1481 else
1483 procfs_ctl_t cmd[2];
1485 cmd[0] = PCKILL;
1486 cmd[1] = signo;
1487 win = (write (pi->ctl_fd, (char *) &cmd, sizeof (cmd)) == sizeof (cmd));
1490 return win;
1493 /* Find the pid of the process that started this one. Returns the
1494 parent process pid, or zero. */
1496 static int
1497 proc_parent_pid (procinfo *pi)
1499 /* We should never have to apply this operation to any procinfo
1500 except the one for the main process. If that ever changes for
1501 any reason, then take out the following clause and replace it
1502 with one that makes sure the ctl_fd is open. */
1504 if (pi->tid != 0)
1505 pi = find_procinfo_or_die (pi->pid, 0);
1507 if (!pi->status_valid)
1508 if (!proc_get_status (pi))
1509 return 0;
1511 return pi->prstatus.pr_ppid;
1514 /* Convert a target address (a.k.a. CORE_ADDR) into a host address
1515 (a.k.a void pointer)! */
1517 static void *
1518 procfs_address_to_host_pointer (CORE_ADDR addr)
1520 gdbarch *arch = current_inferior ()->arch ();
1521 type *ptr_type = builtin_type (arch)->builtin_data_ptr;
1522 void *ptr;
1524 gdb_assert (sizeof (ptr) == ptr_type->length ());
1525 gdbarch_address_to_pointer (arch, ptr_type, (gdb_byte *) &ptr, addr);
1526 return ptr;
1529 static int
1530 proc_set_watchpoint (procinfo *pi, CORE_ADDR addr, int len, int wflags)
1532 struct {
1533 procfs_ctl_t cmd;
1534 char watch[sizeof (prwatch_t)];
1535 } arg;
1536 prwatch_t pwatch;
1538 /* NOTE: cagney/2003-02-01: Even more horrible hack. Need to
1539 convert a target address into something that can be stored in a
1540 native data structure. */
1541 pwatch.pr_vaddr = (uintptr_t) procfs_address_to_host_pointer (addr);
1542 pwatch.pr_size = len;
1543 pwatch.pr_wflags = wflags;
1544 arg.cmd = PCWATCH;
1545 memcpy (arg.watch, &pwatch, sizeof (prwatch_t));
1546 return (write (pi->ctl_fd, &arg, sizeof (arg)) == sizeof (arg));
1549 /* =============== END, non-thread part of /proc "MODULE" =============== */
1551 /* =================== Thread "MODULE" =================== */
1553 /* Returns the number of threads for the process. */
1555 static int
1556 proc_get_nthreads (procinfo *pi)
1558 if (!pi->status_valid)
1559 if (!proc_get_status (pi))
1560 return 0;
1562 /* Only works for the process procinfo, because the LWP procinfos do not
1563 get prstatus filled in. */
1564 if (pi->tid != 0) /* Find the parent process procinfo. */
1565 pi = find_procinfo_or_die (pi->pid, 0);
1566 return pi->prstatus.pr_nlwp;
1569 /* Return the ID of the thread that had an event of interest.
1570 (ie. the one that hit a breakpoint or other traced event). All
1571 other things being equal, this should be the ID of a thread that is
1572 currently executing. */
1574 static int
1575 proc_get_current_thread (procinfo *pi)
1577 /* Note: this should be applied to the root procinfo for the
1578 process, not to the procinfo for an LWP. If applied to the
1579 procinfo for an LWP, it will simply return that LWP's ID. In
1580 that case, find the parent process procinfo. */
1582 if (pi->tid != 0)
1583 pi = find_procinfo_or_die (pi->pid, 0);
1585 if (!pi->status_valid)
1586 if (!proc_get_status (pi))
1587 return 0;
1589 return pi->prstatus.pr_lwp.pr_lwpid;
1592 /* Discover the IDs of all the threads within the process, and create
1593 a procinfo for each of them (chained to the parent). Returns
1594 non-zero for success, zero for failure. */
1596 static int
1597 proc_delete_dead_threads (procinfo *parent, procinfo *thread, void *ignore)
1599 if (thread && parent) /* sanity */
1601 thread->status_valid = 0;
1602 if (!proc_get_status (thread))
1603 destroy_one_procinfo (&parent->thread_list, thread);
1605 return 0; /* keep iterating */
1608 static int
1609 proc_update_threads (procinfo *pi)
1611 char pathname[MAX_PROC_NAME_SIZE + 16];
1612 struct dirent *direntry;
1613 procinfo *thread;
1614 gdb_dir_up dirp;
1615 int lwpid;
1617 /* We should never have to apply this operation to any procinfo
1618 except the one for the main process. If that ever changes for
1619 any reason, then take out the following clause and replace it
1620 with one that makes sure the ctl_fd is open. */
1622 if (pi->tid != 0)
1623 pi = find_procinfo_or_die (pi->pid, 0);
1625 proc_iterate_over_threads (pi, proc_delete_dead_threads, NULL);
1627 /* Note: this brute-force method was originally devised for Unixware
1628 (support removed since), and will also work on Solaris 2.6 and
1629 2.7. The original comment mentioned the existence of a much
1630 simpler and more elegant way to do this on Solaris, but didn't
1631 point out what that was. */
1633 strcpy (pathname, pi->pathname);
1634 strcat (pathname, "/lwp");
1635 dirp.reset (opendir (pathname));
1636 if (dirp == NULL)
1637 proc_error (pi, "update_threads, opendir", __LINE__);
1639 while ((direntry = readdir (dirp.get ())) != NULL)
1640 if (direntry->d_name[0] != '.') /* skip '.' and '..' */
1642 lwpid = atoi (&direntry->d_name[0]);
1643 thread = create_procinfo (pi->pid, lwpid);
1644 if (thread == NULL)
1645 proc_error (pi, "update_threads, create_procinfo", __LINE__);
1647 pi->threads_valid = 1;
1648 return 1;
1651 /* Given a pointer to a function, call that function once for each lwp
1652 in the procinfo list, until the function returns non-zero, in which
1653 event return the value returned by the function.
1655 Note: this function does NOT call update_threads. If you want to
1656 discover new threads first, you must call that function explicitly.
1657 This function just makes a quick pass over the currently-known
1658 procinfos.
1660 PI is the parent process procinfo. FUNC is the per-thread
1661 function. PTR is an opaque parameter for function. Returns the
1662 first non-zero return value from the callee, or zero. */
1664 static int
1665 proc_iterate_over_threads (procinfo *pi,
1666 int (*func) (procinfo *, procinfo *, void *),
1667 void *ptr)
1669 procinfo *thread, *next;
1670 int retval = 0;
1672 /* We should never have to apply this operation to any procinfo
1673 except the one for the main process. If that ever changes for
1674 any reason, then take out the following clause and replace it
1675 with one that makes sure the ctl_fd is open. */
1677 if (pi->tid != 0)
1678 pi = find_procinfo_or_die (pi->pid, 0);
1680 for (thread = pi->thread_list; thread != NULL; thread = next)
1682 next = thread->next; /* In case thread is destroyed. */
1683 retval = (*func) (pi, thread, ptr);
1684 if (retval != 0)
1685 break;
1688 return retval;
1691 /* =================== END, Thread "MODULE" =================== */
1693 /* =================== END, /proc "MODULE" =================== */
1695 /* =================== GDB "MODULE" =================== */
1697 /* Here are all of the gdb target vector functions and their
1698 friends. */
1700 static void do_attach (ptid_t ptid);
1701 static void do_detach ();
1702 static void proc_trace_syscalls_1 (procinfo *pi, int syscallnum,
1703 int entry_or_exit, int mode, int from_tty);
1705 /* Sets up the inferior to be debugged. Registers to trace signals,
1706 hardware faults, and syscalls. Note: does not set RLC flag: caller
1707 may want to customize that. Returns zero for success (note!
1708 unlike most functions in this module); on failure, returns the LINE
1709 NUMBER where it failed! */
1711 static int
1712 procfs_debug_inferior (procinfo *pi)
1714 fltset_t traced_faults;
1715 sigset_t traced_signals;
1716 sysset_t *traced_syscall_entries;
1717 sysset_t *traced_syscall_exits;
1718 int status;
1720 /* Register to trace hardware faults in the child. */
1721 prfillset (&traced_faults); /* trace all faults... */
1722 prdelset (&traced_faults, FLTPAGE); /* except page fault. */
1723 if (!proc_set_traced_faults (pi, &traced_faults))
1724 return __LINE__;
1726 /* Initially, register to trace all signals in the child. */
1727 prfillset (&traced_signals);
1728 if (!proc_set_traced_signals (pi, &traced_signals))
1729 return __LINE__;
1732 /* Register to trace the 'exit' system call (on entry). */
1733 traced_syscall_entries = XNEW (sysset_t);
1734 premptyset (traced_syscall_entries);
1735 praddset (traced_syscall_entries, SYS_exit);
1736 praddset (traced_syscall_entries, SYS_lwp_exit);
1738 status = proc_set_traced_sysentry (pi, traced_syscall_entries);
1739 xfree (traced_syscall_entries);
1740 if (!status)
1741 return __LINE__;
1743 /* Method for tracing exec syscalls. */
1744 traced_syscall_exits = XNEW (sysset_t);
1745 premptyset (traced_syscall_exits);
1746 praddset (traced_syscall_exits, SYS_execve);
1747 praddset (traced_syscall_exits, SYS_lwp_create);
1748 praddset (traced_syscall_exits, SYS_lwp_exit);
1750 status = proc_set_traced_sysexit (pi, traced_syscall_exits);
1751 xfree (traced_syscall_exits);
1752 if (!status)
1753 return __LINE__;
1755 return 0;
1758 void
1759 procfs_target::attach (const char *args, int from_tty)
1761 int pid;
1763 pid = parse_pid_to_attach (args);
1765 if (pid == getpid ())
1766 error (_("Attaching GDB to itself is not a good idea..."));
1768 /* Push the target if needed, ensure it gets un-pushed it if attach fails. */
1769 inferior *inf = current_inferior ();
1770 target_unpush_up unpusher;
1771 if (!inf->target_is_pushed (this))
1773 inf->push_target (this);
1774 unpusher.reset (this);
1777 target_announce_attach (from_tty, pid);
1779 do_attach (ptid_t (pid));
1781 /* Everything went fine, keep the target pushed. */
1782 unpusher.release ();
1785 void
1786 procfs_target::detach (inferior *inf, int from_tty)
1788 target_announce_detach (from_tty);
1790 do_detach ();
1792 switch_to_no_thread ();
1793 detach_inferior (inf);
1794 maybe_unpush_target ();
1797 static void
1798 do_attach (ptid_t ptid)
1800 procinfo *pi;
1801 struct inferior *inf;
1802 int fail;
1803 int lwpid;
1805 pi = create_procinfo (ptid.pid (), 0);
1806 if (pi == NULL)
1807 perror (_("procfs: out of memory in 'attach'"));
1809 if (!open_procinfo_files (pi, FD_CTL))
1811 int saved_errno = errno;
1812 std::string errmsg
1813 = string_printf ("procfs:%d -- do_attach: couldn't open /proc "
1814 "file for process %d", __LINE__, ptid.pid ());
1815 errno = saved_errno;
1816 dead_procinfo (pi, errmsg.c_str (), NOKILL);
1819 /* Stop the process (if it isn't already stopped). */
1820 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1822 pi->was_stopped = 1;
1823 proc_prettyprint_why (proc_why (pi), proc_what (pi), 1);
1825 else
1827 pi->was_stopped = 0;
1828 /* Set the process to run again when we close it. */
1829 if (!proc_set_run_on_last_close (pi))
1830 dead_procinfo (pi, "do_attach: couldn't set RLC.", NOKILL);
1832 /* Now stop the process. */
1833 if (!proc_stop_process (pi))
1834 dead_procinfo (pi, "do_attach: couldn't stop the process.", NOKILL);
1835 pi->ignore_next_sigstop = 1;
1837 /* Save some of the /proc state to be restored if we detach. */
1838 if (!proc_get_traced_faults (pi, &pi->saved_fltset))
1839 dead_procinfo (pi, "do_attach: couldn't save traced faults.", NOKILL);
1840 if (!proc_get_traced_signals (pi, &pi->saved_sigset))
1841 dead_procinfo (pi, "do_attach: couldn't save traced signals.", NOKILL);
1842 if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
1843 dead_procinfo (pi, "do_attach: couldn't save traced syscall entries.",
1844 NOKILL);
1845 if (!proc_get_traced_sysexit (pi, pi->saved_exitset))
1846 dead_procinfo (pi, "do_attach: couldn't save traced syscall exits.",
1847 NOKILL);
1848 if (!proc_get_held_signals (pi, &pi->saved_sighold))
1849 dead_procinfo (pi, "do_attach: couldn't save held signals.", NOKILL);
1851 fail = procfs_debug_inferior (pi);
1852 if (fail != 0)
1853 dead_procinfo (pi, "do_attach: failed in procfs_debug_inferior", NOKILL);
1855 inf = current_inferior ();
1856 inferior_appeared (inf, pi->pid);
1857 /* Let GDB know that the inferior was attached. */
1858 inf->attach_flag = true;
1860 /* Create a procinfo for the current lwp. */
1861 lwpid = proc_get_current_thread (pi);
1862 create_procinfo (pi->pid, lwpid);
1864 /* Add it to gdb's thread list. */
1865 ptid = ptid_t (pi->pid, lwpid, 0);
1866 thread_info *thr = add_thread (&the_procfs_target, ptid);
1867 switch_to_thread (thr);
1870 static void
1871 do_detach ()
1873 procinfo *pi;
1875 /* Find procinfo for the main process. */
1876 pi = find_procinfo_or_die (inferior_ptid.pid (),
1877 0); /* FIXME: threads */
1879 if (!proc_set_traced_signals (pi, &pi->saved_sigset))
1880 proc_warn (pi, "do_detach, set_traced_signal", __LINE__);
1882 if (!proc_set_traced_faults (pi, &pi->saved_fltset))
1883 proc_warn (pi, "do_detach, set_traced_faults", __LINE__);
1885 if (!proc_set_traced_sysentry (pi, pi->saved_entryset))
1886 proc_warn (pi, "do_detach, set_traced_sysentry", __LINE__);
1888 if (!proc_set_traced_sysexit (pi, pi->saved_exitset))
1889 proc_warn (pi, "do_detach, set_traced_sysexit", __LINE__);
1891 if (!proc_set_held_signals (pi, &pi->saved_sighold))
1892 proc_warn (pi, "do_detach, set_held_signals", __LINE__);
1894 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
1895 if (!(pi->was_stopped)
1896 || query (_("Was stopped when attached, make it runnable again? ")))
1898 /* Clear any pending signal. */
1899 if (!proc_clear_current_fault (pi))
1900 proc_warn (pi, "do_detach, clear_current_fault", __LINE__);
1902 if (!proc_clear_current_signal (pi))
1903 proc_warn (pi, "do_detach, clear_current_signal", __LINE__);
1905 if (!proc_set_run_on_last_close (pi))
1906 proc_warn (pi, "do_detach, set_rlc", __LINE__);
1909 destroy_procinfo (pi);
1912 /* Fetch register REGNUM from the inferior. If REGNUM is -1, do this
1913 for all registers.
1915 NOTE: Since the /proc interface cannot give us individual
1916 registers, we pay no attention to REGNUM, and just fetch them all.
1917 This results in the possibility that we will do unnecessarily many
1918 fetches, since we may be called repeatedly for individual
1919 registers. So we cache the results, and mark the cache invalid
1920 when the process is resumed. */
1922 void
1923 procfs_target::fetch_registers (struct regcache *regcache, int regnum)
1925 gdb_gregset_t *gregs;
1926 procinfo *pi;
1927 ptid_t ptid = regcache->ptid ();
1928 int pid = ptid.pid ();
1929 int tid = ptid.lwp ();
1930 struct gdbarch *gdbarch = regcache->arch ();
1932 pi = find_procinfo_or_die (pid, tid);
1934 if (pi == NULL)
1935 error (_("procfs: fetch_registers failed to find procinfo for %s"),
1936 target_pid_to_str (ptid).c_str ());
1938 gregs = proc_get_gregs (pi);
1939 if (gregs == NULL)
1940 proc_error (pi, "fetch_registers, get_gregs", __LINE__);
1942 supply_gregset (regcache, (const gdb_gregset_t *) gregs);
1944 if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU? */
1946 gdb_fpregset_t *fpregs;
1948 if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
1949 || regnum == gdbarch_pc_regnum (gdbarch)
1950 || regnum == gdbarch_sp_regnum (gdbarch))
1951 return; /* Not a floating point register. */
1953 fpregs = proc_get_fpregs (pi);
1954 if (fpregs == NULL)
1955 proc_error (pi, "fetch_registers, get_fpregs", __LINE__);
1957 supply_fpregset (regcache, (const gdb_fpregset_t *) fpregs);
1961 /* Store register REGNUM back into the inferior. If REGNUM is -1, do
1962 this for all registers.
1964 NOTE: Since the /proc interface will not read individual registers,
1965 we will cache these requests until the process is resumed, and only
1966 then write them back to the inferior process.
1968 FIXME: is that a really bad idea? Have to think about cases where
1969 writing one register might affect the value of others, etc. */
1971 void
1972 procfs_target::store_registers (struct regcache *regcache, int regnum)
1974 gdb_gregset_t *gregs;
1975 procinfo *pi;
1976 ptid_t ptid = regcache->ptid ();
1977 int pid = ptid.pid ();
1978 int tid = ptid.lwp ();
1979 struct gdbarch *gdbarch = regcache->arch ();
1981 pi = find_procinfo_or_die (pid, tid);
1983 if (pi == NULL)
1984 error (_("procfs: store_registers: failed to find procinfo for %s"),
1985 target_pid_to_str (ptid).c_str ());
1987 gregs = proc_get_gregs (pi);
1988 if (gregs == NULL)
1989 proc_error (pi, "store_registers, get_gregs", __LINE__);
1991 fill_gregset (regcache, gregs, regnum);
1992 if (!proc_set_gregs (pi))
1993 proc_error (pi, "store_registers, set_gregs", __LINE__);
1995 if (gdbarch_fp0_regnum (gdbarch) >= 0) /* Do we have an FPU? */
1997 gdb_fpregset_t *fpregs;
1999 if ((regnum >= 0 && regnum < gdbarch_fp0_regnum (gdbarch))
2000 || regnum == gdbarch_pc_regnum (gdbarch)
2001 || regnum == gdbarch_sp_regnum (gdbarch))
2002 return; /* Not a floating point register. */
2004 fpregs = proc_get_fpregs (pi);
2005 if (fpregs == NULL)
2006 proc_error (pi, "store_registers, get_fpregs", __LINE__);
2008 fill_fpregset (regcache, fpregs, regnum);
2009 if (!proc_set_fpregs (pi))
2010 proc_error (pi, "store_registers, set_fpregs", __LINE__);
2014 /* Retrieve the next stop event from the child process. If child has
2015 not stopped yet, wait for it to stop. Translate /proc eventcodes
2016 (or possibly wait eventcodes) into gdb internal event codes.
2017 Returns the id of process (and possibly thread) that incurred the
2018 event. Event codes are returned through a pointer parameter. */
2020 ptid_t
2021 procfs_target::wait (ptid_t ptid, struct target_waitstatus *status,
2022 target_wait_flags options)
2024 /* First cut: loosely based on original version 2.1. */
2025 procinfo *pi;
2026 int wstat;
2027 int temp_tid;
2028 ptid_t retval, temp_ptid;
2029 int why, what, flags;
2030 int retry = 0;
2032 wait_again:
2034 retry++;
2035 wstat = 0;
2036 retval = ptid_t (-1);
2038 /* Find procinfo for main process. */
2040 /* procfs_target currently only supports one inferior. */
2041 inferior *inf = current_inferior ();
2043 pi = find_procinfo_or_die (inf->pid, 0);
2044 if (pi)
2046 /* We must assume that the status is stale now... */
2047 pi->status_valid = 0;
2048 pi->gregs_valid = 0;
2049 pi->fpregs_valid = 0;
2051 #if 0 /* just try this out... */
2052 flags = proc_flags (pi);
2053 why = proc_why (pi);
2054 if ((flags & PR_STOPPED) && (why == PR_REQUESTED))
2055 pi->status_valid = 0; /* re-read again, IMMEDIATELY... */
2056 #endif
2057 /* If child is not stopped, wait for it to stop. */
2058 if (!(proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
2059 && !proc_wait_for_stop (pi))
2061 /* wait_for_stop failed: has the child terminated? */
2062 if (errno == ENOENT)
2064 int wait_retval;
2066 /* /proc file not found; presumably child has terminated. Wait
2067 for the child's exit. */
2068 wait_retval = gdb::wait (&wstat);
2070 /* Wrong child? */
2071 if (wait_retval != inf->pid)
2072 error (_("procfs: couldn't stop "
2073 "process %d: wait returned %d."),
2074 inf->pid, wait_retval);
2075 /* FIXME: might I not just use waitpid?
2076 Or try find_procinfo to see if I know about this child? */
2077 retval = ptid_t (wait_retval);
2079 else if (errno == EINTR)
2080 goto wait_again;
2081 else
2083 /* Unknown error from wait_for_stop. */
2084 proc_error (pi, "target_wait (wait_for_stop)", __LINE__);
2087 else
2089 /* This long block is reached if either:
2090 a) the child was already stopped, or
2091 b) we successfully waited for the child with wait_for_stop.
2092 This block will analyze the /proc status, and translate it
2093 into a waitstatus for GDB.
2095 If we actually had to call wait because the /proc file
2096 is gone (child terminated), then we skip this block,
2097 because we already have a waitstatus. */
2099 flags = proc_flags (pi);
2100 why = proc_why (pi);
2101 what = proc_what (pi);
2103 if (flags & (PR_STOPPED | PR_ISTOP))
2105 /* If it's running async (for single_thread control),
2106 set it back to normal again. */
2107 if (flags & PR_ASYNC)
2108 if (!proc_unset_async (pi))
2109 proc_error (pi, "target_wait, unset_async", __LINE__);
2111 if (info_verbose)
2112 proc_prettyprint_why (why, what, 1);
2114 /* The 'pid' we will return to GDB is composed of
2115 the process ID plus the lwp ID. */
2116 retval = ptid_t (pi->pid, proc_get_current_thread (pi), 0);
2118 switch (why) {
2119 case PR_SIGNALLED:
2120 wstat = (what << 8) | 0177;
2121 break;
2122 case PR_SYSENTRY:
2123 if (what == SYS_lwp_exit)
2125 delete_thread (this->find_thread (retval));
2126 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2127 goto wait_again;
2129 else if (what == SYS_exit)
2131 /* Handle SYS_exit call only. */
2132 /* Stopped at entry to SYS_exit.
2133 Make it runnable, resume it, then use
2134 the wait system call to get its exit code.
2135 Proc_run_process always clears the current
2136 fault and signal.
2137 Then return its exit status. */
2138 pi->status_valid = 0;
2139 wstat = 0;
2140 /* FIXME: what we should do is return
2141 TARGET_WAITKIND_SPURIOUS. */
2142 if (!proc_run_process (pi, 0, 0))
2143 proc_error (pi, "target_wait, run_process", __LINE__);
2145 if (inf->attach_flag)
2147 /* Don't call wait: simulate waiting for exit,
2148 return a "success" exit code. Bogus: what if
2149 it returns something else? */
2150 wstat = 0;
2151 retval = ptid_t (inf->pid); /* ? ? ? */
2153 else
2155 int temp = gdb::wait (&wstat);
2157 /* FIXME: shouldn't I make sure I get the right
2158 event from the right process? If (for
2159 instance) I have killed an earlier inferior
2160 process but failed to clean up after it
2161 somehow, I could get its termination event
2162 here. */
2164 /* If wait returns -1, that's what we return
2165 to GDB. */
2166 if (temp < 0)
2167 retval = ptid_t (temp);
2170 else
2172 gdb_printf (_("procfs: trapped on entry to "));
2173 proc_prettyprint_syscall (proc_what (pi), 0);
2174 gdb_printf ("\n");
2176 long i, nsysargs, *sysargs;
2178 nsysargs = proc_nsysarg (pi);
2179 sysargs = proc_sysargs (pi);
2181 if (nsysargs > 0 && sysargs != NULL)
2183 gdb_printf (_("%ld syscall arguments:\n"),
2184 nsysargs);
2185 for (i = 0; i < nsysargs; i++)
2186 gdb_printf ("#%ld: 0x%08lx\n",
2187 i, sysargs[i]);
2190 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2191 goto wait_again;
2193 break;
2194 case PR_SYSEXIT:
2195 if (what == SYS_execve)
2197 /* Hopefully this is our own "fork-child" execing
2198 the real child. Hoax this event into a trap, and
2199 GDB will see the child about to execute its start
2200 address. */
2201 wstat = (SIGTRAP << 8) | 0177;
2203 else if (what == SYS_lwp_create)
2205 /* This syscall is somewhat like fork/exec. We
2206 will get the event twice: once for the parent
2207 LWP, and once for the child. We should already
2208 know about the parent LWP, but the child will
2209 be new to us. So, whenever we get this event,
2210 if it represents a new thread, simply add the
2211 thread to the list. */
2213 /* If not in procinfo list, add it. */
2214 temp_tid = proc_get_current_thread (pi);
2215 if (!find_procinfo (pi->pid, temp_tid))
2216 create_procinfo (pi->pid, temp_tid);
2218 temp_ptid = ptid_t (pi->pid, temp_tid, 0);
2219 /* If not in GDB's thread list, add it. */
2220 if (!in_thread_list (this, temp_ptid))
2221 add_thread (this, temp_ptid);
2223 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2224 goto wait_again;
2226 else if (what == SYS_lwp_exit)
2228 delete_thread (this->find_thread (retval));
2229 status->set_spurious ();
2230 return retval;
2232 else
2234 gdb_printf (_("procfs: trapped on exit from "));
2235 proc_prettyprint_syscall (proc_what (pi), 0);
2236 gdb_printf ("\n");
2238 long i, nsysargs, *sysargs;
2240 nsysargs = proc_nsysarg (pi);
2241 sysargs = proc_sysargs (pi);
2243 if (nsysargs > 0 && sysargs != NULL)
2245 gdb_printf (_("%ld syscall arguments:\n"),
2246 nsysargs);
2247 for (i = 0; i < nsysargs; i++)
2248 gdb_printf ("#%ld: 0x%08lx\n",
2249 i, sysargs[i]);
2252 proc_resume (pi, ptid, 0, GDB_SIGNAL_0);
2253 goto wait_again;
2255 break;
2256 case PR_REQUESTED:
2257 #if 0 /* FIXME */
2258 wstat = (SIGSTOP << 8) | 0177;
2259 break;
2260 #else
2261 if (retry < 5)
2263 gdb_printf (_("Retry #%d:\n"), retry);
2264 pi->status_valid = 0;
2265 goto wait_again;
2267 else
2269 /* If not in procinfo list, add it. */
2270 temp_tid = proc_get_current_thread (pi);
2271 if (!find_procinfo (pi->pid, temp_tid))
2272 create_procinfo (pi->pid, temp_tid);
2274 /* If not in GDB's thread list, add it. */
2275 temp_ptid = ptid_t (pi->pid, temp_tid, 0);
2276 if (!in_thread_list (this, temp_ptid))
2277 add_thread (this, temp_ptid);
2279 status->set_stopped (GDB_SIGNAL_0);
2280 return retval;
2282 #endif
2283 case PR_JOBCONTROL:
2284 wstat = (what << 8) | 0177;
2285 break;
2286 case PR_FAULTED:
2288 int signo = pi->prstatus.pr_lwp.pr_info.si_signo;
2289 if (signo != 0)
2290 wstat = (signo << 8) | 0177;
2292 break;
2293 default: /* switch (why) unmatched */
2294 gdb_printf ("procfs:%d -- ", __LINE__);
2295 gdb_printf (_("child stopped for unknown reason:\n"));
2296 proc_prettyprint_why (why, what, 1);
2297 error (_("... giving up..."));
2298 break;
2300 /* Got this far without error: If retval isn't in the
2301 threads database, add it. */
2302 if (retval.pid () > 0
2303 && !in_thread_list (this, retval))
2305 /* We have a new thread. We need to add it both to
2306 GDB's list and to our own. If we don't create a
2307 procinfo, resume may be unhappy later. */
2308 add_thread (this, retval);
2309 if (find_procinfo (retval.pid (),
2310 retval.lwp ()) == NULL)
2311 create_procinfo (retval.pid (),
2312 retval.lwp ());
2315 else /* Flags do not indicate STOPPED. */
2317 /* surely this can't happen... */
2318 gdb_printf ("procfs:%d -- process not stopped.\n",
2319 __LINE__);
2320 proc_prettyprint_flags (flags, 1);
2321 error (_("procfs: ...giving up..."));
2325 if (status)
2326 *status = host_status_to_waitstatus (wstat);
2329 return retval;
2332 /* Perform a partial transfer to/from the specified object. For
2333 memory transfers, fall back to the old memory xfer functions. */
2335 enum target_xfer_status
2336 procfs_target::xfer_partial (enum target_object object,
2337 const char *annex, gdb_byte *readbuf,
2338 const gdb_byte *writebuf, ULONGEST offset,
2339 ULONGEST len, ULONGEST *xfered_len)
2341 switch (object)
2343 case TARGET_OBJECT_MEMORY:
2344 return procfs_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
2346 case TARGET_OBJECT_AUXV:
2347 return memory_xfer_auxv (this, object, annex, readbuf, writebuf,
2348 offset, len, xfered_len);
2350 default:
2351 return this->beneath ()->xfer_partial (object, annex,
2352 readbuf, writebuf, offset, len,
2353 xfered_len);
2357 /* Helper for procfs_xfer_partial that handles memory transfers.
2358 Arguments are like target_xfer_partial. */
2360 static enum target_xfer_status
2361 procfs_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
2362 ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
2364 procinfo *pi;
2365 int nbytes;
2367 /* Find procinfo for main process. */
2368 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2369 if (pi->as_fd == 0 && open_procinfo_files (pi, FD_AS) == 0)
2371 proc_warn (pi, "xfer_memory, open_proc_files", __LINE__);
2372 return TARGET_XFER_E_IO;
2375 if (lseek (pi->as_fd, (off_t) memaddr, SEEK_SET) != (off_t) memaddr)
2376 return TARGET_XFER_E_IO;
2378 if (writebuf != NULL)
2380 PROCFS_NOTE ("write memory:\n");
2381 nbytes = write (pi->as_fd, writebuf, len);
2383 else
2385 PROCFS_NOTE ("read memory:\n");
2386 nbytes = read (pi->as_fd, readbuf, len);
2388 if (nbytes <= 0)
2389 return TARGET_XFER_E_IO;
2390 *xfered_len = nbytes;
2391 return TARGET_XFER_OK;
2394 /* Called by target_resume before making child runnable. Mark cached
2395 registers and status's invalid. If there are "dirty" caches that
2396 need to be written back to the child process, do that.
2398 File descriptors are also cached. As they are a limited resource,
2399 we cannot hold onto them indefinitely. However, as they are
2400 expensive to open, we don't want to throw them away
2401 indiscriminately either. As a compromise, we will keep the file
2402 descriptors for the parent process, but discard any file
2403 descriptors we may have accumulated for the threads.
2405 As this function is called by iterate_over_threads, it always
2406 returns zero (so that iterate_over_threads will keep
2407 iterating). */
2409 static int
2410 invalidate_cache (procinfo *parent, procinfo *pi, void *ptr)
2412 /* About to run the child; invalidate caches and do any other
2413 cleanup. */
2415 if (parent != NULL)
2417 /* The presence of a parent indicates that this is an LWP.
2418 Close any file descriptors that it might have open.
2419 We don't do this to the master (parent) procinfo. */
2421 close_procinfo_files (pi);
2423 pi->gregs_valid = 0;
2424 pi->fpregs_valid = 0;
2425 pi->status_valid = 0;
2426 pi->threads_valid = 0;
2428 return 0;
2431 /* Make child process PI runnable.
2433 If STEP is true, then arrange for the child to stop again after
2434 executing a single instruction. SCOPE_PTID, STEP and SIGNO are
2435 like in the target_resume interface. */
2437 static void
2438 proc_resume (procinfo *pi, ptid_t scope_ptid, int step, enum gdb_signal signo)
2440 procinfo *thread;
2441 int native_signo;
2443 /* FIXME: Check/reword. */
2445 /* prrun.prflags |= PRCFAULT; clear current fault.
2446 PRCFAULT may be replaced by a PCCFAULT call (proc_clear_current_fault)
2447 This basically leaves PRSTEP and PRCSIG.
2448 PRCSIG is like PCSSIG (proc_clear_current_signal).
2449 So basically PR_STEP is the sole argument that must be passed
2450 to proc_run_process. */
2452 errno = 0;
2454 /* Convert signal to host numbering. */
2455 if (signo == 0 || (signo == GDB_SIGNAL_STOP && pi->ignore_next_sigstop))
2456 native_signo = 0;
2457 else
2458 native_signo = gdb_signal_to_host (signo);
2460 pi->ignore_next_sigstop = 0;
2462 /* Running the process voids all cached registers and status. */
2463 /* Void the threads' caches first. */
2464 proc_iterate_over_threads (pi, invalidate_cache, NULL);
2465 /* Void the process procinfo's caches. */
2466 invalidate_cache (NULL, pi, NULL);
2468 if (scope_ptid.pid () != -1)
2470 /* Resume a specific thread, presumably suppressing the
2471 others. */
2472 thread = find_procinfo (scope_ptid.pid (), scope_ptid.lwp ());
2473 if (thread != NULL)
2475 if (thread->tid != 0)
2477 /* We're to resume a specific thread, and not the
2478 others. Set the child process's PR_ASYNC flag. */
2479 if (!proc_set_async (pi))
2480 proc_error (pi, "target_resume, set_async", __LINE__);
2481 pi = thread; /* Substitute the thread's procinfo
2482 for run. */
2487 if (!proc_run_process (pi, step, native_signo))
2489 if (errno == EBUSY)
2490 warning (_("resume: target already running. "
2491 "Pretend to resume, and hope for the best!"));
2492 else
2493 proc_error (pi, "target_resume", __LINE__);
2497 /* Implementation of target_ops::resume. */
2499 void
2500 procfs_target::resume (ptid_t scope_ptid, int step, enum gdb_signal signo)
2502 /* Find procinfo for main process. */
2503 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2505 proc_resume (pi, scope_ptid, step, signo);
2508 /* Set up to trace signals in the child process. */
2510 void
2511 procfs_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2513 sigset_t signals;
2514 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2515 int signo;
2517 prfillset (&signals);
2519 for (signo = 0; signo < NSIG; signo++)
2521 int target_signo = gdb_signal_from_host (signo);
2522 if (target_signo < pass_signals.size () && pass_signals[target_signo])
2523 prdelset (&signals, signo);
2526 if (!proc_set_traced_signals (pi, &signals))
2527 proc_error (pi, "pass_signals", __LINE__);
2530 /* Print status information about the child process. */
2532 void
2533 procfs_target::files_info ()
2535 struct inferior *inf = current_inferior ();
2537 gdb_printf (_("\tUsing the running image of %s %s via /proc.\n"),
2538 inf->attach_flag? "attached": "child",
2539 target_pid_to_str (ptid_t (inf->pid)).c_str ());
2542 /* Make it die. Wait for it to die. Clean up after it. Note: this
2543 should only be applied to the real process, not to an LWP, because
2544 of the check for parent-process. If we need this to work for an
2545 LWP, it needs some more logic. */
2547 static void
2548 unconditionally_kill_inferior (procinfo *pi)
2550 int parent_pid;
2552 parent_pid = proc_parent_pid (pi);
2553 if (!proc_kill (pi, SIGKILL))
2554 proc_error (pi, "unconditionally_kill, proc_kill", __LINE__);
2555 destroy_procinfo (pi);
2557 /* If pi is GDB's child, wait for it to die. */
2558 if (parent_pid == getpid ())
2559 /* FIXME: should we use waitpid to make sure we get the right event?
2560 Should we check the returned event? */
2562 #if 0
2563 int status, ret;
2565 ret = gdb::waitpid (pi->pid, &status, 0);
2566 #else
2567 gdb::wait (NULL);
2568 #endif
2572 /* We're done debugging it, and we want it to go away. Then we want
2573 GDB to forget all about it. */
2575 void
2576 procfs_target::kill ()
2578 if (inferior_ptid != null_ptid) /* ? */
2580 /* Find procinfo for main process. */
2581 procinfo *pi = find_procinfo (inferior_ptid.pid (), 0);
2583 if (pi)
2584 unconditionally_kill_inferior (pi);
2585 target_mourn_inferior (inferior_ptid);
2589 /* Forget we ever debugged this thing! */
2591 void
2592 procfs_target::mourn_inferior ()
2594 procinfo *pi;
2596 if (inferior_ptid != null_ptid)
2598 /* Find procinfo for main process. */
2599 pi = find_procinfo (inferior_ptid.pid (), 0);
2600 if (pi)
2601 destroy_procinfo (pi);
2604 generic_mourn_inferior ();
2606 maybe_unpush_target ();
2609 /* When GDB forks to create a runnable inferior process, this function
2610 is called on the parent side of the fork. It's job is to do
2611 whatever is necessary to make the child ready to be debugged, and
2612 then wait for the child to synchronize. */
2614 void
2615 procfs_target::procfs_init_inferior (int pid)
2617 procinfo *pi;
2618 int fail;
2619 int lwpid;
2621 pi = create_procinfo (pid, 0);
2622 if (pi == NULL)
2623 perror (_("procfs: out of memory in 'init_inferior'"));
2625 if (!open_procinfo_files (pi, FD_CTL))
2626 proc_error (pi, "init_inferior, open_proc_files", __LINE__);
2629 xmalloc // done
2630 open_procinfo_files // done
2631 link list // done
2632 prfillset (trace)
2633 procfs_notice_signals
2634 prfillset (fault)
2635 prdelset (FLTPAGE)
2638 /* If not stopped yet, wait for it to stop. */
2639 if (!(proc_flags (pi) & PR_STOPPED) && !(proc_wait_for_stop (pi)))
2640 dead_procinfo (pi, "init_inferior: wait_for_stop failed", KILL);
2642 /* Save some of the /proc state to be restored if we detach. */
2643 /* FIXME: Why? In case another debugger was debugging it?
2644 We're it's parent, for Ghu's sake! */
2645 if (!proc_get_traced_signals (pi, &pi->saved_sigset))
2646 proc_error (pi, "init_inferior, get_traced_signals", __LINE__);
2647 if (!proc_get_held_signals (pi, &pi->saved_sighold))
2648 proc_error (pi, "init_inferior, get_held_signals", __LINE__);
2649 if (!proc_get_traced_faults (pi, &pi->saved_fltset))
2650 proc_error (pi, "init_inferior, get_traced_faults", __LINE__);
2651 if (!proc_get_traced_sysentry (pi, pi->saved_entryset))
2652 proc_error (pi, "init_inferior, get_traced_sysentry", __LINE__);
2653 if (!proc_get_traced_sysexit (pi, pi->saved_exitset))
2654 proc_error (pi, "init_inferior, get_traced_sysexit", __LINE__);
2656 fail = procfs_debug_inferior (pi);
2657 if (fail != 0)
2658 proc_error (pi, "init_inferior (procfs_debug_inferior)", fail);
2660 /* FIXME: logically, we should really be turning OFF run-on-last-close,
2661 and possibly even turning ON kill-on-last-close at this point. But
2662 I can't make that change without careful testing which I don't have
2663 time to do right now... */
2664 /* Turn on run-on-last-close flag so that the child
2665 will die if GDB goes away for some reason. */
2666 if (!proc_set_run_on_last_close (pi))
2667 proc_error (pi, "init_inferior, set_RLC", __LINE__);
2669 /* We now have have access to the lwpid of the main thread/lwp. */
2670 lwpid = proc_get_current_thread (pi);
2672 /* Create a procinfo for the main lwp. */
2673 create_procinfo (pid, lwpid);
2675 /* We already have a main thread registered in the thread table at
2676 this point, but it didn't have any lwp info yet. Notify the core
2677 about it. This changes inferior_ptid as well. */
2678 thread_change_ptid (this, ptid_t (pid), ptid_t (pid, lwpid, 0));
2680 gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
2683 /* When GDB forks to create a new process, this function is called on
2684 the child side of the fork before GDB exec's the user program. Its
2685 job is to make the child minimally debuggable, so that the parent
2686 GDB process can connect to the child and take over. This function
2687 should do only the minimum to make that possible, and to
2688 synchronize with the parent process. The parent process should
2689 take care of the details. */
2691 static void
2692 procfs_set_exec_trap (void)
2694 /* This routine called on the child side (inferior side)
2695 after GDB forks the inferior. It must use only local variables,
2696 because it may be sharing data space with its parent. */
2698 procinfo *pi;
2699 sysset_t *exitset;
2701 pi = create_procinfo (getpid (), 0);
2702 if (pi == NULL)
2703 perror_with_name (_("procfs: create_procinfo failed in child"));
2705 if (open_procinfo_files (pi, FD_CTL) == 0)
2707 proc_warn (pi, "set_exec_trap, open_proc_files", __LINE__);
2708 gdb_flush (gdb_stderr);
2709 /* No need to call "dead_procinfo", because we're going to
2710 exit. */
2711 _exit (127);
2714 exitset = XNEW (sysset_t);
2715 premptyset (exitset);
2716 praddset (exitset, SYS_execve);
2718 if (!proc_set_traced_sysexit (pi, exitset))
2720 proc_warn (pi, "set_exec_trap, set_traced_sysexit", __LINE__);
2721 gdb_flush (gdb_stderr);
2722 _exit (127);
2725 /* FIXME: should this be done in the parent instead? */
2726 /* Turn off inherit on fork flag so that all grand-children
2727 of gdb start with tracing flags cleared. */
2728 if (!proc_unset_inherit_on_fork (pi))
2729 proc_warn (pi, "set_exec_trap, unset_inherit", __LINE__);
2731 /* Turn off run on last close flag, so that the child process
2732 cannot run away just because we close our handle on it.
2733 We want it to wait for the parent to attach. */
2734 if (!proc_unset_run_on_last_close (pi))
2735 proc_warn (pi, "set_exec_trap, unset_RLC", __LINE__);
2737 /* FIXME: No need to destroy the procinfo --
2738 we have our own address space, and we're about to do an exec! */
2739 /*destroy_procinfo (pi);*/
2742 /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2).
2743 This avoids a possible deadlock gdb and its vfork'ed child. */
2744 static void
2745 procfs_pre_trace (void)
2749 /* This function is called BEFORE gdb forks the inferior process. Its
2750 only real responsibility is to set things up for the fork, and tell
2751 GDB which two functions to call after the fork (one for the parent,
2752 and one for the child).
2754 This function does a complicated search for a unix shell program,
2755 which it then uses to parse arguments and environment variables to
2756 be sent to the child. I wonder whether this code could not be
2757 abstracted out and shared with other unix targets such as
2758 inf-ptrace? */
2760 void
2761 procfs_target::create_inferior (const char *exec_file,
2762 const std::string &allargs,
2763 char **env, int from_tty)
2765 if (exec_file == nullptr)
2766 no_executable_specified_error ();
2768 const char *shell_file = get_shell ();
2769 char *tryname;
2770 int pid;
2772 if (strchr (shell_file, '/') == NULL)
2775 /* We will be looking down the PATH to find shell_file. If we
2776 just do this the normal way (via execlp, which operates by
2777 attempting an exec for each element of the PATH until it
2778 finds one which succeeds), then there will be an exec for
2779 each failed attempt, each of which will cause a PR_SYSEXIT
2780 stop, and we won't know how to distinguish the PR_SYSEXIT's
2781 for these failed execs with the ones for successful execs
2782 (whether the exec has succeeded is stored at that time in the
2783 carry bit or some such architecture-specific and
2784 non-ABI-specified place).
2786 So I can't think of anything better than to search the PATH
2787 now. This has several disadvantages: (1) There is a race
2788 condition; if we find a file now and it is deleted before we
2789 exec it, we lose, even if the deletion leaves a valid file
2790 further down in the PATH, (2) there is no way to know exactly
2791 what an executable (in the sense of "capable of being
2792 exec'd") file is. Using access() loses because it may lose
2793 if the caller is the superuser; failing to use it loses if
2794 there are ACLs or some such. */
2796 const char *p;
2797 const char *p1;
2798 /* FIXME-maybe: might want "set path" command so user can change what
2799 path is used from within GDB. */
2800 const char *path = getenv ("PATH");
2801 int len;
2802 struct stat statbuf;
2804 if (path == NULL)
2805 path = "/bin:/usr/bin";
2807 tryname = (char *) alloca (strlen (path) + strlen (shell_file) + 2);
2808 for (p = path; p != NULL; p = p1 ? p1 + 1: NULL)
2810 p1 = strchr (p, ':');
2811 if (p1 != NULL)
2812 len = p1 - p;
2813 else
2814 len = strlen (p);
2815 memcpy (tryname, p, len);
2816 tryname[len] = '\0';
2817 strcat (tryname, "/");
2818 strcat (tryname, shell_file);
2819 if (access (tryname, X_OK) < 0)
2820 continue;
2821 if (stat (tryname, &statbuf) < 0)
2822 continue;
2823 if (!S_ISREG (statbuf.st_mode))
2824 /* We certainly need to reject directories. I'm not quite
2825 as sure about FIFOs, sockets, etc., but I kind of doubt
2826 that people want to exec() these things. */
2827 continue;
2828 break;
2830 if (p == NULL)
2831 /* Not found. This must be an error rather than merely passing
2832 the file to execlp(), because execlp() would try all the
2833 exec()s, causing GDB to get confused. */
2834 error (_("procfs:%d -- Can't find shell %s in PATH"),
2835 __LINE__, shell_file);
2837 shell_file = tryname;
2840 inferior *inf = current_inferior ();
2841 if (!inf->target_is_pushed (this))
2842 inf->push_target (this);
2844 pid = fork_inferior (exec_file, allargs, env, procfs_set_exec_trap,
2845 NULL, procfs_pre_trace, shell_file, NULL);
2847 /* We have something that executes now. We'll be running through
2848 the shell at this point (if startup-with-shell is true), but the
2849 pid shouldn't change. */
2850 thread_info *thr = add_thread_silent (this, ptid_t (pid));
2851 switch_to_thread (thr);
2853 procfs_init_inferior (pid);
2856 /* Callback for update_thread_list. Calls "add_thread". */
2858 static int
2859 procfs_notice_thread (procinfo *pi, procinfo *thread, void *ptr)
2861 ptid_t gdb_threadid = ptid_t (pi->pid, thread->tid, 0);
2863 thread_info *thr = the_procfs_target.find_thread (gdb_threadid);
2864 if (thr == NULL || thr->state == THREAD_EXITED)
2865 add_thread (&the_procfs_target, gdb_threadid);
2867 return 0;
2870 /* Query all the threads that the target knows about, and give them
2871 back to GDB to add to its list. */
2873 void
2874 procfs_target::update_thread_list ()
2876 procinfo *pi;
2878 prune_threads ();
2880 /* Find procinfo for main process. */
2881 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
2882 proc_update_threads (pi);
2883 proc_iterate_over_threads (pi, procfs_notice_thread, NULL);
2886 /* Return true if the thread is still 'alive'. This guy doesn't
2887 really seem to be doing his job. Got to investigate how to tell
2888 when a thread is really gone. */
2890 bool
2891 procfs_target::thread_alive (ptid_t ptid)
2893 int proc, thread;
2894 procinfo *pi;
2896 proc = ptid.pid ();
2897 thread = ptid.lwp ();
2898 /* If I don't know it, it ain't alive! */
2899 pi = find_procinfo (proc, thread);
2900 if (pi == NULL)
2901 return false;
2903 /* If I can't get its status, it ain't alive!
2904 What's more, I need to forget about it! */
2905 if (!proc_get_status (pi))
2907 destroy_procinfo (pi);
2908 return false;
2910 /* I couldn't have got its status if it weren't alive, so it's
2911 alive. */
2912 return true;
2915 /* Convert PTID to a string. */
2917 std::string
2918 procfs_target::pid_to_str (ptid_t ptid)
2920 if (ptid.lwp () == 0)
2921 return string_printf ("process %d", ptid.pid ());
2922 else
2923 return string_printf ("LWP %ld", ptid.lwp ());
2926 /* Accepts an integer PID; Returns a string representing a file that
2927 can be opened to get the symbols for the child process. */
2929 const char *
2930 procfs_target::pid_to_exec_file (int pid)
2932 static char buf[PATH_MAX];
2933 char name[PATH_MAX];
2935 /* Solaris 11 introduced /proc/<proc-id>/execname. */
2936 xsnprintf (name, sizeof (name), "/proc/%d/execname", pid);
2937 scoped_fd fd (gdb_open_cloexec (name, O_RDONLY, 0));
2938 if (fd.get () < 0 || read (fd.get (), buf, PATH_MAX - 1) < 0)
2940 /* If that fails, fall back to /proc/<proc-id>/path/a.out introduced in
2941 Solaris 10. */
2942 ssize_t len;
2944 xsnprintf (name, sizeof (name), "/proc/%d/path/a.out", pid);
2945 len = readlink (name, buf, PATH_MAX - 1);
2946 if (len <= 0)
2947 strcpy (buf, name);
2948 else
2949 buf[len] = '\0';
2952 return buf;
2955 /* Insert a watchpoint. */
2957 static int
2958 procfs_set_watchpoint (ptid_t ptid, CORE_ADDR addr, int len, int rwflag,
2959 int after)
2961 int pflags = 0;
2962 procinfo *pi;
2964 pi = find_procinfo_or_die (ptid.pid () == -1 ?
2965 inferior_ptid.pid () : ptid.pid (),
2968 /* Translate from GDB's flags to /proc's. */
2969 if (len > 0) /* len == 0 means delete watchpoint. */
2971 switch (rwflag) { /* FIXME: need an enum! */
2972 case hw_write: /* default watchpoint (write) */
2973 pflags = WA_WRITE;
2974 break;
2975 case hw_read: /* read watchpoint */
2976 pflags = WA_READ;
2977 break;
2978 case hw_access: /* access watchpoint */
2979 pflags = WA_READ | WA_WRITE;
2980 break;
2981 case hw_execute: /* execution HW breakpoint */
2982 pflags = WA_EXEC;
2983 break;
2984 default: /* Something weird. Return error. */
2985 return -1;
2987 if (after) /* Stop after r/w access is completed. */
2988 pflags |= WA_TRAPAFTER;
2991 if (!proc_set_watchpoint (pi, addr, len, pflags))
2993 if (errno == E2BIG) /* Typical error for no resources. */
2994 return -1; /* fail */
2995 /* GDB may try to remove the same watchpoint twice.
2996 If a remove request returns no match, don't error. */
2997 if (errno == ESRCH && len == 0)
2998 return 0; /* ignore */
2999 proc_error (pi, "set_watchpoint", __LINE__);
3001 return 0;
3004 /* Return non-zero if we can set a hardware watchpoint of type TYPE. TYPE
3005 is one of bp_hardware_watchpoint, bp_read_watchpoint, bp_write_watchpoint,
3006 or bp_hardware_watchpoint. CNT is the number of watchpoints used so
3007 far. */
3010 procfs_target::can_use_hw_breakpoint (enum bptype type, int cnt, int othertype)
3012 /* Due to the way that proc_set_watchpoint() is implemented, host
3013 and target pointers must be of the same size. If they are not,
3014 we can't use hardware watchpoints. This limitation is due to the
3015 fact that proc_set_watchpoint() calls
3016 procfs_address_to_host_pointer(); a close inspection of
3017 procfs_address_to_host_pointer will reveal that an internal error
3018 will be generated when the host and target pointer sizes are
3019 different. */
3020 struct type *ptr_type
3021 = builtin_type (current_inferior ()->arch ())->builtin_data_ptr;
3023 if (sizeof (void *) != ptr_type->length ())
3024 return 0;
3026 /* Other tests here??? */
3028 return 1;
3031 /* Returns non-zero if process is stopped on a hardware watchpoint
3032 fault, else returns zero. */
3034 bool
3035 procfs_target::stopped_by_watchpoint ()
3037 procinfo *pi;
3039 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3041 if (proc_flags (pi) & (PR_STOPPED | PR_ISTOP))
3042 if (proc_why (pi) == PR_FAULTED)
3043 if (proc_what (pi) == FLTWATCH)
3044 return true;
3045 return false;
3048 /* Returns 1 if the OS knows the position of the triggered watchpoint,
3049 and sets *ADDR to that address. Returns 0 if OS cannot report that
3050 address. This function is only called if
3051 procfs_stopped_by_watchpoint returned 1, thus no further checks are
3052 done. The function also assumes that ADDR is not NULL. */
3054 bool
3055 procfs_target::stopped_data_address (CORE_ADDR *addr)
3057 procinfo *pi;
3059 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3060 return proc_watchpoint_address (pi, addr);
3064 procfs_target::insert_watchpoint (CORE_ADDR addr, int len,
3065 enum target_hw_bp_type type,
3066 struct expression *cond)
3068 if (!target_have_steppable_watchpoint ()
3069 && !gdbarch_have_nonsteppable_watchpoint (current_inferior ()->arch ()))
3070 /* When a hardware watchpoint fires off the PC will be left at
3071 the instruction following the one which caused the
3072 watchpoint. It will *NOT* be necessary for GDB to step over
3073 the watchpoint. */
3074 return procfs_set_watchpoint (inferior_ptid, addr, len, type, 1);
3075 else
3076 /* When a hardware watchpoint fires off the PC will be left at
3077 the instruction which caused the watchpoint. It will be
3078 necessary for GDB to step over the watchpoint. */
3079 return procfs_set_watchpoint (inferior_ptid, addr, len, type, 0);
3083 procfs_target::remove_watchpoint (CORE_ADDR addr, int len,
3084 enum target_hw_bp_type type,
3085 struct expression *cond)
3087 return procfs_set_watchpoint (inferior_ptid, addr, 0, 0, 0);
3091 procfs_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
3093 /* The man page for proc(4) on Solaris 2.6 and up says that the
3094 system can support "thousands" of hardware watchpoints, but gives
3095 no method for finding out how many; It doesn't say anything about
3096 the allowed size for the watched area either. So we just tell
3097 GDB 'yes'. */
3098 return 1;
3101 /* Memory Mappings Functions: */
3103 /* Call a callback function once for each mapping, passing it the
3104 mapping, an optional secondary callback function, and some optional
3105 opaque data. Quit and return the first non-zero value returned
3106 from the callback.
3108 PI is the procinfo struct for the process to be mapped. FUNC is
3109 the callback function to be called by this iterator. DATA is the
3110 optional opaque data to be passed to the callback function.
3111 CHILD_FUNC is the optional secondary function pointer to be passed
3112 to the child function. Returns the first non-zero return value
3113 from the callback function, or zero. */
3115 static int
3116 iterate_over_mappings (procinfo *pi, find_memory_region_ftype child_func,
3117 void *data,
3118 int (*func) (struct prmap *map,
3119 find_memory_region_ftype child_func,
3120 void *data))
3122 char pathname[MAX_PROC_NAME_SIZE];
3123 struct prmap *prmaps;
3124 struct prmap *prmap;
3125 int funcstat;
3126 int nmap;
3127 struct stat sbuf;
3129 /* Get the number of mappings, allocate space,
3130 and read the mappings into prmaps. */
3131 /* Open map fd. */
3132 xsnprintf (pathname, sizeof (pathname), "/proc/%d/map", pi->pid);
3134 scoped_fd map_fd (open (pathname, O_RDONLY));
3135 if (map_fd.get () < 0)
3136 proc_error (pi, "iterate_over_mappings (open)", __LINE__);
3138 /* Use stat to determine the file size, and compute
3139 the number of prmap_t objects it contains. */
3140 if (fstat (map_fd.get (), &sbuf) != 0)
3141 proc_error (pi, "iterate_over_mappings (fstat)", __LINE__);
3143 nmap = sbuf.st_size / sizeof (prmap_t);
3144 prmaps = (struct prmap *) alloca ((nmap + 1) * sizeof (*prmaps));
3145 if (read (map_fd.get (), (char *) prmaps, nmap * sizeof (*prmaps))
3146 != (nmap * sizeof (*prmaps)))
3147 proc_error (pi, "iterate_over_mappings (read)", __LINE__);
3149 for (prmap = prmaps; nmap > 0; prmap++, nmap--)
3151 funcstat = (*func) (prmap, child_func, data);
3152 if (funcstat != 0)
3153 return funcstat;
3156 return 0;
3159 /* Implements the to_find_memory_regions method. Calls an external
3160 function for each memory region.
3161 Returns the integer value returned by the callback. */
3163 static int
3164 find_memory_regions_callback (struct prmap *map,
3165 find_memory_region_ftype func, void *data)
3167 return (*func) ((CORE_ADDR) map->pr_vaddr,
3168 map->pr_size,
3169 (map->pr_mflags & MA_READ) != 0,
3170 (map->pr_mflags & MA_WRITE) != 0,
3171 (map->pr_mflags & MA_EXEC) != 0,
3172 1, /* MODIFIED is unknown, pass it as true. */
3173 false,
3174 data);
3177 /* External interface. Calls a callback function once for each
3178 mapped memory region in the child process, passing as arguments:
3180 CORE_ADDR virtual_address,
3181 unsigned long size,
3182 int read, TRUE if region is readable by the child
3183 int write, TRUE if region is writable by the child
3184 int execute TRUE if region is executable by the child.
3186 Stops iterating and returns the first non-zero value returned by
3187 the callback. */
3190 procfs_target::find_memory_regions (find_memory_region_ftype func, void *data)
3192 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3194 return iterate_over_mappings (pi, func, data,
3195 find_memory_regions_callback);
3198 /* Returns an ascii representation of a memory mapping's flags. */
3200 static char *
3201 mappingflags (long flags)
3203 static char asciiflags[8];
3205 strcpy (asciiflags, "-------");
3206 if (flags & MA_STACK)
3207 asciiflags[1] = 's';
3208 if (flags & MA_BREAK)
3209 asciiflags[2] = 'b';
3210 if (flags & MA_SHARED)
3211 asciiflags[3] = 's';
3212 if (flags & MA_READ)
3213 asciiflags[4] = 'r';
3214 if (flags & MA_WRITE)
3215 asciiflags[5] = 'w';
3216 if (flags & MA_EXEC)
3217 asciiflags[6] = 'x';
3218 return (asciiflags);
3221 /* Callback function, does the actual work for 'info proc
3222 mappings'. */
3224 static int
3225 info_mappings_callback (struct prmap *map, find_memory_region_ftype ignore,
3226 void *unused)
3228 unsigned int pr_off;
3230 pr_off = (unsigned int) map->pr_offset;
3232 if (gdbarch_addr_bit (current_inferior ()->arch ()) == 32)
3233 gdb_printf ("\t%#10lx %#10lx %#10lx %#10x %7s\n",
3234 (unsigned long) map->pr_vaddr,
3235 (unsigned long) map->pr_vaddr + map->pr_size - 1,
3236 (unsigned long) map->pr_size,
3237 pr_off,
3238 mappingflags (map->pr_mflags));
3239 else
3240 gdb_printf (" %#18lx %#18lx %#10lx %#10x %7s\n",
3241 (unsigned long) map->pr_vaddr,
3242 (unsigned long) map->pr_vaddr + map->pr_size - 1,
3243 (unsigned long) map->pr_size,
3244 pr_off,
3245 mappingflags (map->pr_mflags));
3247 return 0;
3250 /* Implement the "info proc mappings" subcommand. */
3252 static void
3253 info_proc_mappings (procinfo *pi, int summary)
3255 if (summary)
3256 return; /* No output for summary mode. */
3258 gdb_printf (_("Mapped address spaces:\n\n"));
3259 if (gdbarch_ptr_bit (current_inferior ()->arch ()) == 32)
3260 gdb_printf ("\t%10s %10s %10s %10s %7s\n",
3261 "Start Addr",
3262 " End Addr",
3263 " Size",
3264 " Offset",
3265 "Flags");
3266 else
3267 gdb_printf (" %18s %18s %10s %10s %7s\n",
3268 "Start Addr",
3269 " End Addr",
3270 " Size",
3271 " Offset",
3272 "Flags");
3274 iterate_over_mappings (pi, NULL, NULL, info_mappings_callback);
3275 gdb_printf ("\n");
3278 /* Implement the "info proc" command. */
3280 bool
3281 procfs_target::info_proc (const char *args, enum info_proc_what what)
3283 procinfo *process = NULL;
3284 procinfo *thread = NULL;
3285 char *tmp = NULL;
3286 int pid = 0;
3287 int tid = 0;
3288 int mappings = 0;
3290 switch (what)
3292 case IP_MINIMAL:
3293 break;
3295 case IP_MAPPINGS:
3296 case IP_ALL:
3297 mappings = 1;
3298 break;
3300 default:
3301 error (_("Not supported on this target."));
3304 gdb_argv built_argv (args);
3305 for (char *arg : built_argv)
3307 if (isdigit (arg[0]))
3309 pid = strtoul (arg, &tmp, 10);
3310 if (*tmp == '/')
3311 tid = strtoul (++tmp, NULL, 10);
3313 else if (arg[0] == '/')
3315 tid = strtoul (arg + 1, NULL, 10);
3319 procinfo_up temporary_procinfo;
3320 if (pid == 0)
3321 pid = inferior_ptid.pid ();
3322 if (pid == 0)
3323 error (_("No current process: you must name one."));
3324 else
3326 /* Have pid, will travel.
3327 First see if it's a process we're already debugging. */
3328 process = find_procinfo (pid, 0);
3329 if (process == NULL)
3331 /* No. So open a procinfo for it, but
3332 remember to close it again when finished. */
3333 process = create_procinfo (pid, 0);
3334 temporary_procinfo.reset (process);
3335 if (!open_procinfo_files (process, FD_CTL))
3336 proc_error (process, "info proc, open_procinfo_files", __LINE__);
3339 if (tid != 0)
3340 thread = create_procinfo (pid, tid);
3342 if (process)
3344 gdb_printf (_("process %d flags:\n"), process->pid);
3345 proc_prettyprint_flags (proc_flags (process), 1);
3346 if (proc_flags (process) & (PR_STOPPED | PR_ISTOP))
3347 proc_prettyprint_why (proc_why (process), proc_what (process), 1);
3348 if (proc_get_nthreads (process) > 1)
3349 gdb_printf ("Process has %d threads.\n",
3350 proc_get_nthreads (process));
3352 if (thread)
3354 gdb_printf (_("thread %d flags:\n"), thread->tid);
3355 proc_prettyprint_flags (proc_flags (thread), 1);
3356 if (proc_flags (thread) & (PR_STOPPED | PR_ISTOP))
3357 proc_prettyprint_why (proc_why (thread), proc_what (thread), 1);
3360 if (mappings)
3361 info_proc_mappings (process, 0);
3363 return true;
3366 /* Modify the status of the system call identified by SYSCALLNUM in
3367 the set of syscalls that are currently traced/debugged.
3369 If ENTRY_OR_EXIT is set to PR_SYSENTRY, then the entry syscalls set
3370 will be updated. Otherwise, the exit syscalls set will be updated.
3372 If MODE is FLAG_SET, then traces will be enabled. Otherwise, they
3373 will be disabled. */
3375 static void
3376 proc_trace_syscalls_1 (procinfo *pi, int syscallnum, int entry_or_exit,
3377 int mode, int from_tty)
3379 sysset_t *sysset;
3381 if (entry_or_exit == PR_SYSENTRY)
3382 sysset = proc_get_traced_sysentry (pi, NULL);
3383 else
3384 sysset = proc_get_traced_sysexit (pi, NULL);
3386 if (sysset == NULL)
3387 proc_error (pi, "proc-trace, get_traced_sysset", __LINE__);
3389 if (mode == FLAG_SET)
3390 praddset (sysset, syscallnum);
3391 else
3392 prdelset (sysset, syscallnum);
3394 if (entry_or_exit == PR_SYSENTRY)
3396 if (!proc_set_traced_sysentry (pi, sysset))
3397 proc_error (pi, "proc-trace, set_traced_sysentry", __LINE__);
3399 else
3401 if (!proc_set_traced_sysexit (pi, sysset))
3402 proc_error (pi, "proc-trace, set_traced_sysexit", __LINE__);
3406 static void
3407 proc_trace_syscalls (const char *args, int from_tty, int entry_or_exit, int mode)
3409 procinfo *pi;
3411 if (inferior_ptid.pid () <= 0)
3412 error (_("you must be debugging a process to use this command."));
3414 if (args == NULL || args[0] == 0)
3415 error_no_arg (_("system call to trace"));
3417 pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3418 if (isdigit (args[0]))
3420 const int syscallnum = atoi (args);
3422 proc_trace_syscalls_1 (pi, syscallnum, entry_or_exit, mode, from_tty);
3426 static void
3427 proc_trace_sysentry_cmd (const char *args, int from_tty)
3429 proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_SET);
3432 static void
3433 proc_trace_sysexit_cmd (const char *args, int from_tty)
3435 proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_SET);
3438 static void
3439 proc_untrace_sysentry_cmd (const char *args, int from_tty)
3441 proc_trace_syscalls (args, from_tty, PR_SYSENTRY, FLAG_RESET);
3444 static void
3445 proc_untrace_sysexit_cmd (const char *args, int from_tty)
3447 proc_trace_syscalls (args, from_tty, PR_SYSEXIT, FLAG_RESET);
3450 void _initialize_procfs ();
3451 void
3452 _initialize_procfs ()
3454 add_com ("proc-trace-entry", no_class, proc_trace_sysentry_cmd,
3455 _("Give a trace of entries into the syscall."));
3456 add_com ("proc-trace-exit", no_class, proc_trace_sysexit_cmd,
3457 _("Give a trace of exits from the syscall."));
3458 add_com ("proc-untrace-entry", no_class, proc_untrace_sysentry_cmd,
3459 _("Cancel a trace of entries into the syscall."));
3460 add_com ("proc-untrace-exit", no_class, proc_untrace_sysexit_cmd,
3461 _("Cancel a trace of exits from the syscall."));
3463 add_inf_child_target (&the_procfs_target);
3466 /* =================== END, GDB "MODULE" =================== */
3470 /* miscellaneous stubs: */
3472 /* The following satisfy a few random symbols mostly created by the
3473 solaris threads implementation, which I will chase down later. */
3475 /* Return a pid for which we guarantee we will be able to find a
3476 'live' procinfo. */
3478 ptid_t
3479 procfs_first_available (void)
3481 return ptid_t (procinfo_list ? procinfo_list->pid : -1);
3484 /* =================== GCORE .NOTE "MODULE" =================== */
3486 static void
3487 procfs_do_thread_registers (bfd *obfd, ptid_t ptid,
3488 gdb::unique_xmalloc_ptr<char> &note_data,
3489 int *note_size, enum gdb_signal stop_signal)
3491 struct regcache *regcache = get_thread_regcache (&the_procfs_target, ptid);
3492 gdb_gregset_t gregs;
3493 gdb_fpregset_t fpregs;
3494 unsigned long merged_pid;
3496 merged_pid = ptid.lwp () << 16 | ptid.pid ();
3498 /* This part is the old method for fetching registers.
3499 It should be replaced by the newer one using regsets
3500 once it is implemented in this platform:
3501 gdbarch_iterate_over_regset_sections(). */
3503 target_fetch_registers (regcache, -1);
3505 fill_gregset (regcache, &gregs, -1);
3506 note_data.reset (elfcore_write_lwpstatus (obfd,
3507 note_data.release (),
3508 note_size,
3509 merged_pid,
3510 stop_signal,
3511 &gregs));
3512 fill_fpregset (regcache, &fpregs, -1);
3513 note_data.reset (elfcore_write_prfpreg (obfd,
3514 note_data.release (),
3515 note_size,
3516 &fpregs,
3517 sizeof (fpregs)));
3520 struct procfs_corefile_thread_data
3522 procfs_corefile_thread_data (bfd *obfd,
3523 gdb::unique_xmalloc_ptr<char> &note_data,
3524 int *note_size, gdb_signal stop_signal)
3525 : obfd (obfd), note_data (note_data), note_size (note_size),
3526 stop_signal (stop_signal)
3529 bfd *obfd;
3530 gdb::unique_xmalloc_ptr<char> &note_data;
3531 int *note_size;
3532 enum gdb_signal stop_signal;
3535 static int
3536 procfs_corefile_thread_callback (procinfo *pi, procinfo *thread, void *data)
3538 struct procfs_corefile_thread_data *args
3539 = (struct procfs_corefile_thread_data *) data;
3541 if (pi != NULL)
3543 ptid_t ptid = ptid_t (pi->pid, thread->tid, 0);
3545 procfs_do_thread_registers (args->obfd, ptid,
3546 args->note_data,
3547 args->note_size,
3548 args->stop_signal);
3550 return 0;
3553 static int
3554 find_signalled_thread (struct thread_info *info, void *data)
3556 if (info->stop_signal () != GDB_SIGNAL_0
3557 && info->ptid.pid () == inferior_ptid.pid ())
3558 return 1;
3560 return 0;
3563 static enum gdb_signal
3564 find_stop_signal (void)
3566 struct thread_info *info =
3567 iterate_over_threads (find_signalled_thread, NULL);
3569 if (info)
3570 return info->stop_signal ();
3571 else
3572 return GDB_SIGNAL_0;
3575 gdb::unique_xmalloc_ptr<char>
3576 procfs_target::make_corefile_notes (bfd *obfd, int *note_size)
3578 gdb_gregset_t gregs;
3579 char fname[16] = {'\0'};
3580 char psargs[80] = {'\0'};
3581 procinfo *pi = find_procinfo_or_die (inferior_ptid.pid (), 0);
3582 gdb::unique_xmalloc_ptr<char> note_data;
3583 enum gdb_signal stop_signal;
3585 if (const auto exec_filename = current_program_space->exec_filename ();
3586 exec_filename != nullptr)
3588 strncpy (fname, lbasename (exec_filename), sizeof (fname));
3589 fname[sizeof (fname) - 1] = 0;
3590 strncpy (psargs, exec_filename, sizeof (psargs));
3591 psargs[sizeof (psargs) - 1] = 0;
3593 const std::string &inf_args = current_inferior ()->args ();
3594 if (!inf_args.empty () &&
3595 inf_args.length () < ((int) sizeof (psargs) - (int) strlen (psargs)))
3597 strncat (psargs, " ",
3598 sizeof (psargs) - strlen (psargs));
3599 strncat (psargs, inf_args.c_str (),
3600 sizeof (psargs) - strlen (psargs));
3604 note_data.reset (elfcore_write_prpsinfo (obfd,
3605 note_data.release (),
3606 note_size,
3607 fname,
3608 psargs));
3610 stop_signal = find_stop_signal ();
3612 fill_gregset (get_thread_regcache (inferior_thread ()), &gregs, -1);
3613 note_data.reset (elfcore_write_pstatus (obfd, note_data.release (), note_size,
3614 inferior_ptid.pid (),
3615 stop_signal, &gregs));
3617 procfs_corefile_thread_data thread_args (obfd, note_data, note_size,
3618 stop_signal);
3619 proc_iterate_over_threads (pi, procfs_corefile_thread_callback,
3620 &thread_args);
3622 std::optional<gdb::byte_vector> auxv =
3623 target_read_alloc (current_inferior ()->top_target (),
3624 TARGET_OBJECT_AUXV, NULL);
3625 if (auxv && !auxv->empty ())
3626 note_data.reset (elfcore_write_note (obfd, note_data.release (), note_size,
3627 "CORE", NT_AUXV, auxv->data (),
3628 auxv->size ()));
3630 return note_data;
3632 /* =================== END GCORE .NOTE "MODULE" =================== */