dmake: do not set MAKEFLAGS=k
[unleashed/tickless.git] / usr / src / lib / libproc / common / Pcontrol.c
blob017d5c7b4bd19c9d9681b19f3b11a4320f060993
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
23 * Copyright 2010 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
26 * Portions Copyright 2007 Chad Mynhier
27 * Copyright 2012 DEY Storage Systems, Inc. All rights reserved.
28 * Copyright (c) 2013 by Delphix. All rights reserved.
29 * Copyright 2015, Joyent, Inc.
32 #include <assert.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <ctype.h>
37 #include <fcntl.h>
38 #include <string.h>
39 #include <strings.h>
40 #include <memory.h>
41 #include <errno.h>
42 #include <dirent.h>
43 #include <limits.h>
44 #include <signal.h>
45 #include <atomic.h>
46 #include <zone.h>
47 #include <sys/types.h>
48 #include <sys/uio.h>
49 #include <sys/stat.h>
50 #include <sys/resource.h>
51 #include <sys/param.h>
52 #include <sys/stack.h>
53 #include <sys/fault.h>
54 #include <sys/syscall.h>
55 #include <sys/sysmacros.h>
56 #include <sys/systeminfo.h>
57 #include <sys/secflags.h>
59 #include "libproc.h"
60 #include "Pcontrol.h"
61 #include "Putil.h"
62 #include "P32ton.h"
64 int _libproc_debug; /* set non-zero to enable debugging printfs */
65 int _libproc_no_qsort; /* set non-zero to inhibit sorting */
66 /* of symbol tables */
67 int _libproc_incore_elf; /* only use in-core elf data */
69 sigset_t blockable_sigs; /* signals to block when we need to be safe */
70 static int minfd; /* minimum file descriptor returned by dupfd(fd, 0) */
71 char procfs_path[PATH_MAX] = "/proc";
74 * Function prototypes for static routines in this module.
76 static void deadcheck(struct ps_prochandle *);
77 static void restore_tracing_flags(struct ps_prochandle *);
78 static void Lfree_internal(struct ps_prochandle *, struct ps_lwphandle *);
79 static prheader_t *read_lfile(struct ps_prochandle *, const char *);
82 * Ops vector functions for live processes.
85 /*ARGSUSED*/
86 static ssize_t
87 Pread_live(struct ps_prochandle *P, void *buf, size_t n, uintptr_t addr,
88 void *data)
90 return (pread(P->asfd, buf, n, (off_t)addr));
93 /*ARGSUSED*/
94 static ssize_t
95 Pwrite_live(struct ps_prochandle *P, const void *buf, size_t n, uintptr_t addr,
96 void *data)
98 return (pwrite(P->asfd, buf, n, (off_t)addr));
101 /*ARGSUSED*/
102 static int
103 Pread_maps_live(struct ps_prochandle *P, prmap_t **Pmapp, ssize_t *nmapp,
104 void *data)
106 char mapfile[PATH_MAX];
107 int mapfd;
108 struct stat statb;
109 ssize_t nmap;
110 prmap_t *Pmap = NULL;
112 (void) snprintf(mapfile, sizeof (mapfile), "%s/%d/map",
113 procfs_path, (int)P->pid);
114 if ((mapfd = open(mapfile, O_RDONLY)) < 0 ||
115 fstat(mapfd, &statb) != 0 ||
116 statb.st_size < sizeof (prmap_t) ||
117 (Pmap = malloc(statb.st_size)) == NULL ||
118 (nmap = pread(mapfd, Pmap, statb.st_size, 0L)) <= 0 ||
119 (nmap /= sizeof (prmap_t)) == 0) {
120 free(Pmap);
121 if (mapfd >= 0)
122 (void) close(mapfd);
123 Preset_maps(P); /* utter failure; destroy tables */
124 return (-1);
126 (void) close(mapfd);
128 *Pmapp = Pmap;
129 *nmapp = nmap;
131 return (0);
134 /*ARGSUSED*/
135 static void
136 Pread_aux_live(struct ps_prochandle *P, auxv_t **auxvp, int *nauxp, void *data)
138 char auxfile[64];
139 int fd;
140 struct stat statb;
141 auxv_t *auxv;
142 ssize_t naux;
144 (void) snprintf(auxfile, sizeof (auxfile), "%s/%d/auxv",
145 procfs_path, (int)P->pid);
146 if ((fd = open(auxfile, O_RDONLY)) < 0) {
147 dprintf("%s: failed to open %s: %s\n",
148 __func__, auxfile, strerror(errno));
149 return;
152 if (fstat(fd, &statb) == 0 &&
153 statb.st_size >= sizeof (auxv_t) &&
154 (auxv = malloc(statb.st_size + sizeof (auxv_t))) != NULL) {
155 if ((naux = read(fd, auxv, statb.st_size)) < 0 ||
156 (naux /= sizeof (auxv_t)) < 1) {
157 dprintf("%s: read failed: %s\n",
158 __func__, strerror(errno));
159 free(auxv);
160 } else {
161 auxv[naux].a_type = AT_NULL;
162 auxv[naux].a_un.a_val = 0L;
164 *auxvp = auxv;
165 *nauxp = (int)naux;
169 (void) close(fd);
172 /*ARGSUSED*/
173 static int
174 Pcred_live(struct ps_prochandle *P, prcred_t *pcrp, int ngroups, void *data)
176 return (proc_get_cred(P->pid, pcrp, ngroups));
179 /* ARGSUSED */
180 static int
181 Psecflags_live(struct ps_prochandle *P, prsecflags_t **psf, void *data)
183 return (proc_get_secflags(P->pid, psf));
186 /*ARGSUSED*/
187 static int
188 Ppriv_live(struct ps_prochandle *P, prpriv_t **pprv, void *data)
190 prpriv_t *pp;
192 pp = proc_get_priv(P->pid);
193 if (pp == NULL) {
194 return (-1);
197 *pprv = pp;
198 return (0);
201 /*ARGSUSED*/
202 static const psinfo_t *
203 Ppsinfo_live(struct ps_prochandle *P, psinfo_t *psinfo, void *data)
205 if (proc_get_psinfo(P->pid, psinfo) == -1)
206 return (NULL);
208 return (psinfo);
211 /*ARGSUSED*/
212 static prheader_t *
213 Plstatus_live(struct ps_prochandle *P, void *data)
215 return (read_lfile(P, "lstatus"));
218 /*ARGSUSED*/
219 static prheader_t *
220 Plpsinfo_live(struct ps_prochandle *P, void *data)
222 return (read_lfile(P, "lpsinfo"));
225 /*ARGSUSED*/
226 static char *
227 Pplatform_live(struct ps_prochandle *P, char *s, size_t n, void *data)
229 if (sysinfo(SI_PLATFORM, s, n) == -1)
230 return (NULL);
231 return (s);
234 /*ARGSUSED*/
235 static int
236 Puname_live(struct ps_prochandle *P, struct utsname *u, void *data)
238 return (uname(u));
241 /*ARGSUSED*/
242 static char *
243 Pzonename_live(struct ps_prochandle *P, char *s, size_t n, void *data)
245 if (getzonenamebyid(P->status.pr_zoneid, s, n) < 0)
246 return (NULL);
247 s[n - 1] = '\0';
248 return (s);
252 * Callback function for Pfindexec(). We return a match if we can stat the
253 * suggested pathname and confirm its device and inode number match our
254 * previous information about the /proc/<pid>/object/a.out file.
256 static int
257 stat_exec(const char *path, void *arg)
259 struct stat64 *stp = arg;
260 struct stat64 st;
262 return (stat64(path, &st) == 0 && S_ISREG(st.st_mode) &&
263 stp->st_dev == st.st_dev && stp->st_ino == st.st_ino);
266 /*ARGSUSED*/
267 static char *
268 Pexecname_live(struct ps_prochandle *P, char *buf, size_t buflen, void *data)
270 char exec_name[PATH_MAX];
271 char cwd[PATH_MAX];
272 char proc_cwd[64];
273 struct stat64 st;
274 int ret;
277 * Try to get the path information first.
279 (void) snprintf(exec_name, sizeof (exec_name),
280 "%s/%d/path/a.out", procfs_path, (int)P->pid);
281 if ((ret = readlink(exec_name, buf, buflen - 1)) > 0) {
282 buf[ret] = '\0';
283 (void) Pfindobj(P, buf, buf, buflen);
284 return (buf);
288 * Stat the executable file so we can compare Pfindexec's
289 * suggestions to the actual device and inode number.
291 (void) snprintf(exec_name, sizeof (exec_name),
292 "%s/%d/object/a.out", procfs_path, (int)P->pid);
294 if (stat64(exec_name, &st) != 0 || !S_ISREG(st.st_mode))
295 return (NULL);
298 * Attempt to figure out the current working directory of the
299 * target process. This only works if the target process has
300 * not changed its current directory since it was exec'd.
302 (void) snprintf(proc_cwd, sizeof (proc_cwd),
303 "%s/%d/path/cwd", procfs_path, (int)P->pid);
305 if ((ret = readlink(proc_cwd, cwd, PATH_MAX - 1)) > 0)
306 cwd[ret] = '\0';
308 (void) Pfindexec(P, ret > 0 ? cwd : NULL, stat_exec, &st);
310 return (NULL);
313 #if defined(__i386) || defined(__amd64)
314 /*ARGSUSED*/
315 static int
316 Pldt_live(struct ps_prochandle *P, struct ssd *pldt, int nldt, void *data)
318 return (proc_get_ldt(P->pid, pldt, nldt));
320 #endif
322 static const ps_ops_t P_live_ops = {
323 .pop_pread = Pread_live,
324 .pop_pwrite = Pwrite_live,
325 .pop_read_maps = Pread_maps_live,
326 .pop_read_aux = Pread_aux_live,
327 .pop_cred = Pcred_live,
328 .pop_priv = Ppriv_live,
329 .pop_psinfo = Ppsinfo_live,
330 .pop_lstatus = Plstatus_live,
331 .pop_lpsinfo = Plpsinfo_live,
332 .pop_platform = Pplatform_live,
333 .pop_uname = Puname_live,
334 .pop_zonename = Pzonename_live,
335 .pop_execname = Pexecname_live,
336 .pop_secflags = Psecflags_live,
337 #if defined(__i386) || defined(__amd64)
338 .pop_ldt = Pldt_live
339 #endif
343 * This is the library's .init handler.
345 #pragma init(_libproc_init)
346 void
347 _libproc_init(void)
349 _libproc_debug = getenv("LIBPROC_DEBUG") != NULL;
350 _libproc_no_qsort = getenv("LIBPROC_NO_QSORT") != NULL;
351 _libproc_incore_elf = getenv("LIBPROC_INCORE_ELF") != NULL;
353 (void) sigfillset(&blockable_sigs);
354 (void) sigdelset(&blockable_sigs, SIGKILL);
355 (void) sigdelset(&blockable_sigs, SIGSTOP);
358 void
359 Pset_procfs_path(const char *path)
361 (void) snprintf(procfs_path, sizeof (procfs_path), "%s", path);
365 * Call set_minfd() once before calling dupfd() several times.
366 * We assume that the application will not reduce its current file
367 * descriptor limit lower than 512 once it has set at least that value.
370 set_minfd(void)
372 static mutex_t minfd_lock = DEFAULTMUTEX;
373 struct rlimit rlim;
374 int fd;
376 if ((fd = minfd) < 256) {
377 (void) mutex_lock(&minfd_lock);
378 if ((fd = minfd) < 256) {
379 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0)
380 rlim.rlim_cur = rlim.rlim_max = 0;
381 if (rlim.rlim_cur >= 512)
382 fd = 256;
383 else if ((fd = rlim.rlim_cur / 2) < 3)
384 fd = 3;
385 membar_producer();
386 minfd = fd;
388 (void) mutex_unlock(&minfd_lock);
390 return (fd);
394 dupfd(int fd, int dfd)
396 int mfd;
399 * Make fd be greater than 255 (the 32-bit stdio limit),
400 * or at least make it greater than 2 so that the
401 * program will work when spawned by init(1m).
402 * Also, if dfd is non-zero, dup the fd to be dfd.
404 if ((mfd = minfd) == 0)
405 mfd = set_minfd();
406 if (dfd > 0 || (0 <= fd && fd < mfd)) {
407 if (dfd <= 0)
408 dfd = mfd;
409 dfd = fcntl(fd, F_DUPFD, dfd);
410 (void) close(fd);
411 fd = dfd;
414 * Mark it close-on-exec so any created process doesn't inherit it.
416 if (fd >= 0)
417 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
418 return (fd);
422 * Create a new controlled process.
423 * Leave it stopped on successful exit from exec() or execve().
424 * Return an opaque pointer to its process control structure.
425 * Return NULL if process cannot be created (fork()/exec() not successful).
427 struct ps_prochandle *
428 Pxcreate(const char *file, /* executable file name */
429 char *const *argv, /* argument vector */
430 char *const *envp, /* environment */
431 int *perr, /* pointer to error return code */
432 char *path, /* if non-null, holds exec path name on return */
433 size_t len) /* size of the path buffer */
435 char execpath[PATH_MAX];
436 char procname[PATH_MAX];
437 struct ps_prochandle *P;
438 pid_t pid;
439 int fd;
440 char *fname;
441 int rc;
442 int lasterrno = 0;
444 if (len == 0) /* zero length, no path */
445 path = NULL;
446 if (path != NULL)
447 *path = '\0';
449 if ((P = malloc(sizeof (struct ps_prochandle))) == NULL) {
450 *perr = C_STRANGE;
451 return (NULL);
454 if ((pid = fork1()) == -1) {
455 free(P);
456 *perr = C_FORK;
457 return (NULL);
460 if (pid == 0) { /* child process */
461 id_t id;
462 extern char **environ;
465 * If running setuid or setgid, reset credentials to normal.
467 if ((id = getgid()) != getegid())
468 (void) setgid(id);
469 if ((id = getuid()) != geteuid())
470 (void) setuid(id);
472 Pcreate_callback(P); /* execute callback (see below) */
473 (void) pause(); /* wait for PRSABORT from parent */
476 * This is ugly. There is no execvep() function that takes a
477 * path and an environment. We cheat here by replacing the
478 * global 'environ' variable right before we call this.
480 if (envp)
481 environ = (char **)envp;
483 (void) execvp(file, argv); /* execute the program */
484 _exit(127);
488 * Initialize the process structure.
490 (void) memset(P, 0, sizeof (*P));
491 (void) mutex_init(&P->proc_lock, USYNC_THREAD, NULL);
492 P->flags |= CREATED;
493 P->state = PS_RUN;
494 P->pid = pid;
495 P->asfd = -1;
496 P->ctlfd = -1;
497 P->statfd = -1;
498 P->agentctlfd = -1;
499 P->agentstatfd = -1;
500 Pinit_ops(&P->ops, &P_live_ops);
501 Pinitsym(P);
504 * Open the /proc/pid files.
506 (void) snprintf(procname, sizeof (procname), "%s/%d/",
507 procfs_path, (int)pid);
508 fname = procname + strlen(procname);
509 (void) set_minfd();
512 * Exclusive write open advises others not to interfere.
513 * There is no reason for any of these open()s to fail.
515 (void) strcpy(fname, "as");
516 if ((fd = open(procname, (O_RDWR|O_EXCL))) < 0 ||
517 (fd = dupfd(fd, 0)) < 0) {
518 dprintf("Pcreate: failed to open %s: %s\n",
519 procname, strerror(errno));
520 rc = C_STRANGE;
521 goto bad;
523 P->asfd = fd;
525 (void) strcpy(fname, "status");
526 if ((fd = open(procname, O_RDONLY)) < 0 ||
527 (fd = dupfd(fd, 0)) < 0) {
528 dprintf("Pcreate: failed to open %s: %s\n",
529 procname, strerror(errno));
530 rc = C_STRANGE;
531 goto bad;
533 P->statfd = fd;
535 (void) strcpy(fname, "ctl");
536 if ((fd = open(procname, O_WRONLY)) < 0 ||
537 (fd = dupfd(fd, 0)) < 0) {
538 dprintf("Pcreate: failed to open %s: %s\n",
539 procname, strerror(errno));
540 rc = C_STRANGE;
541 goto bad;
543 P->ctlfd = fd;
545 (void) Pstop(P, 0); /* stop the controlled process */
548 * Wait for process to sleep in pause().
549 * If the process has already called pause(), then it should be
550 * stopped (PR_REQUESTED) while asleep in pause and we are done.
551 * Else we set up to catch entry/exit to pause() and set the process
552 * running again, expecting it to stop when it reaches pause().
553 * There is no reason for this to fail other than an interrupt.
555 (void) Psysentry(P, SYS_pause, 1);
556 (void) Psysexit(P, SYS_pause, 1);
557 for (;;) {
558 if (P->state == PS_STOP &&
559 P->status.pr_lwp.pr_syscall == SYS_pause &&
560 (P->status.pr_lwp.pr_why == PR_REQUESTED ||
561 P->status.pr_lwp.pr_why == PR_SYSENTRY ||
562 P->status.pr_lwp.pr_why == PR_SYSEXIT))
563 break;
565 if (P->state != PS_STOP || /* interrupt or process died */
566 Psetrun(P, 0, 0) != 0) { /* can't restart */
567 if (errno == EINTR || errno == ERESTART)
568 rc = C_INTR;
569 else {
570 dprintf("Pcreate: Psetrun failed: %s\n",
571 strerror(errno));
572 rc = C_STRANGE;
574 goto bad;
577 (void) Pwait(P, 0);
579 (void) Psysentry(P, SYS_pause, 0);
580 (void) Psysexit(P, SYS_pause, 0);
583 * Kick the process off the pause() and catch
584 * it again on entry to exec() or exit().
586 (void) Psysentry(P, SYS_exit, 1);
587 (void) Psysentry(P, SYS_execve, 1);
588 if (Psetrun(P, 0, PRSABORT) == -1) {
589 dprintf("Pcreate: Psetrun failed: %s\n", strerror(errno));
590 rc = C_STRANGE;
591 goto bad;
593 (void) Pwait(P, 0);
594 if (P->state != PS_STOP) {
595 dprintf("Pcreate: Pwait failed: %s\n", strerror(errno));
596 rc = C_STRANGE;
597 goto bad;
601 * Move the process through instances of failed exec()s
602 * to reach the point of stopped on successful exec().
604 (void) Psysexit(P, SYS_execve, TRUE);
606 while (P->state == PS_STOP &&
607 P->status.pr_lwp.pr_why == PR_SYSENTRY &&
608 P->status.pr_lwp.pr_what == SYS_execve) {
610 * Fetch the exec path name now, before we complete
611 * the exec(). We may lose the process and be unable
612 * to get the information later.
614 (void) Pread_string(P, execpath, sizeof (execpath),
615 (off_t)P->status.pr_lwp.pr_sysarg[0]);
616 if (path != NULL)
617 (void) strncpy(path, execpath, len);
619 * Set the process running and wait for
620 * it to stop on exit from the exec().
622 (void) Psetrun(P, 0, 0);
623 (void) Pwait(P, 0);
625 if (P->state == PS_LOST && /* we lost control */
626 Preopen(P) != 0) { /* and we can't get it back */
627 rc = C_PERM;
628 goto bad;
632 * If the exec() failed, continue the loop, expecting
633 * there to be more attempts to exec(), based on PATH.
635 if (P->state == PS_STOP &&
636 P->status.pr_lwp.pr_why == PR_SYSEXIT &&
637 P->status.pr_lwp.pr_what == SYS_execve &&
638 (lasterrno = P->status.pr_lwp.pr_errno) != 0) {
640 * The exec() failed. Set the process running and
641 * wait for it to stop on entry to the next exec().
643 (void) Psetrun(P, 0, 0);
644 (void) Pwait(P, 0);
646 continue;
648 break;
651 if (P->state == PS_STOP &&
652 P->status.pr_lwp.pr_why == PR_SYSEXIT &&
653 P->status.pr_lwp.pr_what == SYS_execve &&
654 P->status.pr_lwp.pr_errno == 0) {
656 * The process is stopped on successful exec() or execve().
657 * Turn off all tracing flags and return success.
659 restore_tracing_flags(P);
660 #ifndef _LP64
661 /* We must be a 64-bit process to deal with a 64-bit process */
662 if (P->status.pr_dmodel == PR_MODEL_LP64) {
663 rc = C_LP64;
664 goto bad;
666 #endif
668 * Set run-on-last-close so the controlled process
669 * runs even if we die on a signal.
671 (void) Psetflags(P, PR_RLC);
672 *perr = 0;
673 return (P);
676 rc = lasterrno == ENOENT ? C_NOENT : C_NOEXEC;
678 bad:
679 (void) kill(pid, SIGKILL);
680 if (path != NULL && rc != C_PERM && rc != C_LP64)
681 *path = '\0';
682 Pfree(P);
683 *perr = rc;
684 return (NULL);
687 struct ps_prochandle *
688 Pcreate(
689 const char *file, /* executable file name */
690 char *const *argv, /* argument vector */
691 int *perr, /* pointer to error return code */
692 char *path, /* if non-null, holds exec path name on return */
693 size_t len) /* size of the path buffer */
695 return (Pxcreate(file, argv, NULL, perr, path, len));
699 * Return a printable string corresponding to a Pcreate() error return.
701 const char *
702 Pcreate_error(int error)
704 const char *str;
706 switch (error) {
707 case C_FORK:
708 str = "cannot fork";
709 break;
710 case C_PERM:
711 str = "file is set-id or unreadable";
712 break;
713 case C_NOEXEC:
714 str = "cannot execute file";
715 break;
716 case C_INTR:
717 str = "operation interrupted";
718 break;
719 case C_LP64:
720 str = "program is _LP64, self is not";
721 break;
722 case C_STRANGE:
723 str = "unanticipated system error";
724 break;
725 case C_NOENT:
726 str = "cannot find executable file";
727 break;
728 default:
729 str = "unknown error";
730 break;
733 return (str);
737 * Callback to execute in each child process created with Pcreate() after fork
738 * but before it execs the new process image. By default, we do nothing, but
739 * by calling this function we allow the client program to define its own
740 * version of the function which will interpose on our empty default. This
741 * may be useful for clients that need to modify signal dispositions, terminal
742 * attributes, or process group and session properties for each new victim.
744 /*ARGSUSED*/
745 void
746 Pcreate_callback(struct ps_prochandle *P)
748 /* nothing to do here */
752 * Grab an existing process.
753 * Return an opaque pointer to its process control structure.
755 * pid: UNIX process ID.
756 * flags:
757 * PGRAB_RETAIN Retain tracing flags (default clears all tracing flags).
758 * PGRAB_FORCE Grab regardless of whether process is already traced.
759 * PGRAB_RDONLY Open the address space file O_RDONLY instead of O_RDWR,
760 * and do not open the process control file.
761 * PGRAB_NOSTOP Open the process but do not force it to stop.
762 * perr: pointer to error return code.
764 struct ps_prochandle *
765 Pgrab(pid_t pid, int flags, int *perr)
767 struct ps_prochandle *P;
768 int fd, omode;
769 char procname[PATH_MAX];
770 char *fname;
771 int rc = 0;
774 * PGRAB_RDONLY means that we do not open the /proc/<pid>/control file,
775 * and so it implies RETAIN and NOSTOP since both require control.
777 if (flags & PGRAB_RDONLY)
778 flags |= PGRAB_RETAIN | PGRAB_NOSTOP;
780 if ((P = malloc(sizeof (struct ps_prochandle))) == NULL) {
781 *perr = G_STRANGE;
782 return (NULL);
785 P->asfd = -1;
786 P->ctlfd = -1;
787 P->statfd = -1;
789 again: /* Come back here if we lose it in the Window of Vulnerability */
790 if (P->ctlfd >= 0)
791 (void) close(P->ctlfd);
792 if (P->asfd >= 0)
793 (void) close(P->asfd);
794 if (P->statfd >= 0)
795 (void) close(P->statfd);
796 (void) memset(P, 0, sizeof (*P));
797 (void) mutex_init(&P->proc_lock, USYNC_THREAD, NULL);
798 P->ctlfd = -1;
799 P->asfd = -1;
800 P->statfd = -1;
801 P->agentctlfd = -1;
802 P->agentstatfd = -1;
803 Pinit_ops(&P->ops, &P_live_ops);
804 Pinitsym(P);
807 * Open the /proc/pid files
809 (void) snprintf(procname, sizeof (procname), "%s/%d/",
810 procfs_path, (int)pid);
811 fname = procname + strlen(procname);
812 (void) set_minfd();
815 * Request exclusive open to avoid grabbing someone else's
816 * process and to prevent others from interfering afterwards.
817 * If this fails and the 'PGRAB_FORCE' flag is set, attempt to
818 * open non-exclusively.
820 (void) strcpy(fname, "as");
821 omode = (flags & PGRAB_RDONLY) ? O_RDONLY : O_RDWR;
823 if (((fd = open(procname, omode | O_EXCL)) < 0 &&
824 (fd = ((flags & PGRAB_FORCE)? open(procname, omode) : -1)) < 0) ||
825 (fd = dupfd(fd, 0)) < 0) {
826 switch (errno) {
827 case ENOENT:
828 rc = G_NOPROC;
829 break;
830 case EACCES:
831 case EPERM:
832 rc = G_PERM;
833 break;
834 case EMFILE:
835 rc = G_NOFD;
836 break;
837 case EBUSY:
838 if (!(flags & PGRAB_FORCE) || geteuid() != 0) {
839 rc = G_BUSY;
840 break;
842 /* FALLTHROUGH */
843 default:
844 dprintf("Pgrab: failed to open %s: %s\n",
845 procname, strerror(errno));
846 rc = G_STRANGE;
847 break;
849 goto err;
851 P->asfd = fd;
853 (void) strcpy(fname, "status");
854 if ((fd = open(procname, O_RDONLY)) < 0 ||
855 (fd = dupfd(fd, 0)) < 0) {
856 switch (errno) {
857 case ENOENT:
858 rc = G_NOPROC;
859 break;
860 case EMFILE:
861 rc = G_NOFD;
862 break;
863 default:
864 dprintf("Pgrab: failed to open %s: %s\n",
865 procname, strerror(errno));
866 rc = G_STRANGE;
867 break;
869 goto err;
871 P->statfd = fd;
873 if (!(flags & PGRAB_RDONLY)) {
874 (void) strcpy(fname, "ctl");
875 if ((fd = open(procname, O_WRONLY)) < 0 ||
876 (fd = dupfd(fd, 0)) < 0) {
877 switch (errno) {
878 case ENOENT:
879 rc = G_NOPROC;
880 break;
881 case EMFILE:
882 rc = G_NOFD;
883 break;
884 default:
885 dprintf("Pgrab: failed to open %s: %s\n",
886 procname, strerror(errno));
887 rc = G_STRANGE;
888 break;
890 goto err;
892 P->ctlfd = fd;
895 P->state = PS_RUN;
896 P->pid = pid;
899 * We are now in the Window of Vulnerability (WoV). The process may
900 * exec() a setuid/setgid or unreadable object file between the open()
901 * and the PCSTOP. We will get EAGAIN in this case and must start over.
902 * As Pstopstatus will trigger the first read() from a /proc file,
903 * we also need to handle EOVERFLOW here when 32-bit as an indicator
904 * that this process is 64-bit. Finally, if the process has become
905 * a zombie (PS_UNDEAD) while we were trying to grab it, just remain
906 * silent about this and pretend there was no process.
908 if (Pstopstatus(P, PCNULL, 0) != 0) {
909 #ifndef _LP64
910 if (errno == EOVERFLOW) {
911 rc = G_LP64;
912 goto err;
914 #endif
915 if (P->state == PS_LOST) { /* WoV */
916 (void) mutex_destroy(&P->proc_lock);
917 goto again;
920 if (P->state == PS_UNDEAD)
921 rc = G_NOPROC;
922 else
923 rc = G_STRANGE;
925 goto err;
929 * If the process is a system process, we can't control it even as root
931 if (P->status.pr_flags & PR_ISSYS) {
932 rc = G_SYS;
933 goto err;
935 #ifndef _LP64
937 * We must be a 64-bit process to deal with a 64-bit process
939 if (P->status.pr_dmodel == PR_MODEL_LP64) {
940 rc = G_LP64;
941 goto err;
943 #endif
946 * Remember the status for use by Prelease().
948 P->orig_status = P->status; /* structure copy */
951 * Before stopping the process, make sure we are not grabbing ourselves.
952 * If we are, make sure we are doing it PGRAB_RDONLY.
954 if (pid == getpid()) {
956 * Verify that the process is really ourself:
957 * Set a magic number, read it through the
958 * /proc file and see if the results match.
960 uint32_t magic1 = 0;
961 uint32_t magic2 = 2;
963 errno = 0;
965 if (Pread(P, &magic2, sizeof (magic2), (uintptr_t)&magic1)
966 == sizeof (magic2) &&
967 magic2 == 0 &&
968 (magic1 = 0xfeedbeef) &&
969 Pread(P, &magic2, sizeof (magic2), (uintptr_t)&magic1)
970 == sizeof (magic2) &&
971 magic2 == 0xfeedbeef &&
972 !(flags & PGRAB_RDONLY)) {
973 rc = G_SELF;
974 goto err;
979 * If the process is already stopped or has been directed
980 * to stop via /proc, do not set run-on-last-close.
982 if (!(P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) &&
983 !(flags & PGRAB_RDONLY)) {
985 * Mark the process run-on-last-close so
986 * it runs even if we die from SIGKILL.
988 if (Psetflags(P, PR_RLC) != 0) {
989 if (errno == EAGAIN) { /* WoV */
990 (void) mutex_destroy(&P->proc_lock);
991 goto again;
993 if (errno == ENOENT) /* No complaint about zombies */
994 rc = G_ZOMB;
995 else {
996 dprintf("Pgrab: failed to set RLC\n");
997 rc = G_STRANGE;
999 goto err;
1004 * If a stop directive is pending and the process has not yet stopped,
1005 * then synchronously wait for the stop directive to take effect.
1006 * Limit the time spent waiting for the process to stop by iterating
1007 * at most 10 times. The time-out of 20 ms corresponds to the time
1008 * between sending the stop directive and the process actually stopped
1009 * as measured by DTrace on a slow, busy system. If the process doesn't
1010 * stop voluntarily, clear the PR_DSTOP flag so that the code below
1011 * forces the process to stop.
1013 if (!(flags & PGRAB_RDONLY)) {
1014 int niter = 0;
1015 while ((P->status.pr_lwp.pr_flags & (PR_STOPPED|PR_DSTOP)) ==
1016 PR_DSTOP && niter < 10 &&
1017 Pstopstatus(P, PCTWSTOP, 20) != 0) {
1018 niter++;
1019 if (flags & PGRAB_NOSTOP)
1020 break;
1022 if (niter == 10 && !(flags & PGRAB_NOSTOP)) {
1023 /* Try it harder down below */
1024 P->status.pr_lwp.pr_flags &= ~PR_DSTOP;
1029 * If the process is not already stopped or directed to stop
1030 * and PGRAB_NOSTOP was not specified, stop the process now.
1032 if (!(P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) &&
1033 !(flags & PGRAB_NOSTOP)) {
1035 * Stop the process, get its status and signal/syscall masks.
1037 if (((P->status.pr_lwp.pr_flags & PR_STOPPED) &&
1038 Pstopstatus(P, PCDSTOP, 0) != 0) ||
1039 Pstopstatus(P, PCSTOP, 2000) != 0) {
1040 #ifndef _LP64
1041 if (errno == EOVERFLOW) {
1042 rc = G_LP64;
1043 goto err;
1045 #endif
1046 if (P->state == PS_LOST) { /* WoV */
1047 (void) mutex_destroy(&P->proc_lock);
1048 goto again;
1050 if ((errno != EINTR && errno != ERESTART) ||
1051 (P->state != PS_STOP &&
1052 !(P->status.pr_flags & PR_DSTOP))) {
1053 if (P->state != PS_RUN && errno != ENOENT) {
1054 dprintf("Pgrab: failed to PCSTOP\n");
1055 rc = G_STRANGE;
1056 } else {
1057 rc = G_ZOMB;
1059 goto err;
1064 * Process should now either be stopped via /proc or there
1065 * should be an outstanding stop directive.
1067 if (!(P->status.pr_flags & (PR_ISTOP|PR_DSTOP))) {
1068 dprintf("Pgrab: process is not stopped\n");
1069 rc = G_STRANGE;
1070 goto err;
1072 #ifndef _LP64
1074 * Test this again now because the 32-bit victim process may
1075 * have exec'd a 64-bit process in the meantime.
1077 if (P->status.pr_dmodel == PR_MODEL_LP64) {
1078 rc = G_LP64;
1079 goto err;
1081 #endif
1085 * Cancel all tracing flags unless the PGRAB_RETAIN flag is set.
1087 if (!(flags & PGRAB_RETAIN)) {
1088 (void) Psysentry(P, 0, FALSE);
1089 (void) Psysexit(P, 0, FALSE);
1090 (void) Psignal(P, 0, FALSE);
1091 (void) Pfault(P, 0, FALSE);
1092 Psync(P);
1095 *perr = 0;
1096 return (P);
1098 err:
1099 Pfree(P);
1100 *perr = rc;
1101 return (NULL);
1105 * Return a printable string corresponding to a Pgrab() error return.
1107 const char *
1108 Pgrab_error(int error)
1110 const char *str;
1112 switch (error) {
1113 case G_NOPROC:
1114 str = "no such process";
1115 break;
1116 case G_NOCORE:
1117 str = "no such core file";
1118 break;
1119 case G_NOPROCORCORE:
1120 str = "no such process or core file";
1121 break;
1122 case G_NOEXEC:
1123 str = "cannot find executable file";
1124 break;
1125 case G_ZOMB:
1126 str = "zombie process";
1127 break;
1128 case G_PERM:
1129 str = "permission denied";
1130 break;
1131 case G_BUSY:
1132 str = "process is traced";
1133 break;
1134 case G_SYS:
1135 str = "system process";
1136 break;
1137 case G_SELF:
1138 str = "attempt to grab self";
1139 break;
1140 case G_INTR:
1141 str = "operation interrupted";
1142 break;
1143 case G_LP64:
1144 str = "program is _LP64, self is not";
1145 break;
1146 case G_FORMAT:
1147 str = "file is not an ELF core file";
1148 break;
1149 case G_ELF:
1150 str = "libelf error";
1151 break;
1152 case G_NOTE:
1153 str = "core file is corrupt or missing required data";
1154 break;
1155 case G_STRANGE:
1156 str = "unanticipated system error";
1157 break;
1158 case G_ISAINVAL:
1159 str = "wrong ELF machine type";
1160 break;
1161 case G_BADLWPS:
1162 str = "bad lwp specification";
1163 break;
1164 case G_NOFD:
1165 str = "too many open files";
1166 break;
1167 default:
1168 str = "unknown error";
1169 break;
1172 return (str);
1176 * Free a process control structure.
1177 * Close the file descriptors but don't do the Prelease logic.
1179 void
1180 Pfree(struct ps_prochandle *P)
1182 uint_t i;
1184 if (P->ucaddrs != NULL) {
1185 free(P->ucaddrs);
1186 P->ucaddrs = NULL;
1187 P->ucnelems = 0;
1190 (void) mutex_lock(&P->proc_lock);
1191 if (P->hashtab != NULL) {
1192 struct ps_lwphandle *L;
1193 for (i = 0; i < HASHSIZE; i++) {
1194 while ((L = P->hashtab[i]) != NULL)
1195 Lfree_internal(P, L);
1197 free(P->hashtab);
1200 while (P->num_fd > 0) {
1201 fd_info_t *fip = list_next(&P->fd_head);
1202 list_unlink(fip);
1203 free(fip);
1204 P->num_fd--;
1206 (void) mutex_unlock(&P->proc_lock);
1207 (void) mutex_destroy(&P->proc_lock);
1209 if (P->agentctlfd >= 0)
1210 (void) close(P->agentctlfd);
1211 if (P->agentstatfd >= 0)
1212 (void) close(P->agentstatfd);
1213 if (P->ctlfd >= 0)
1214 (void) close(P->ctlfd);
1215 if (P->asfd >= 0)
1216 (void) close(P->asfd);
1217 if (P->statfd >= 0)
1218 (void) close(P->statfd);
1219 Preset_maps(P);
1220 P->ops.pop_fini(P, P->data);
1222 /* clear out the structure as a precaution against reuse */
1223 (void) memset(P, 0, sizeof (*P));
1224 P->ctlfd = -1;
1225 P->asfd = -1;
1226 P->statfd = -1;
1227 P->agentctlfd = -1;
1228 P->agentstatfd = -1;
1230 free(P);
1234 * Return the state of the process, one of the PS_* values.
1237 Pstate(struct ps_prochandle *P)
1239 return (P->state);
1243 * Return the open address space file descriptor for the process.
1244 * Clients must not close this file descriptor, not use it
1245 * after the process is freed.
1248 Pasfd(struct ps_prochandle *P)
1250 return (P->asfd);
1254 * Return the open control file descriptor for the process.
1255 * Clients must not close this file descriptor, not use it
1256 * after the process is freed.
1259 Pctlfd(struct ps_prochandle *P)
1261 return (P->ctlfd);
1265 * Return a pointer to the process psinfo structure.
1266 * Clients should not hold on to this pointer indefinitely.
1267 * It will become invalid on Prelease().
1269 const psinfo_t *
1270 Ppsinfo(struct ps_prochandle *P)
1272 return (P->ops.pop_psinfo(P, &P->psinfo, P->data));
1276 * Return a pointer to the process status structure.
1277 * Clients should not hold on to this pointer indefinitely.
1278 * It will become invalid on Prelease().
1280 const pstatus_t *
1281 Pstatus(struct ps_prochandle *P)
1283 return (&P->status);
1286 static void
1287 Pread_status(struct ps_prochandle *P)
1289 P->ops.pop_status(P, &P->status, P->data);
1293 * Fill in a pointer to a process credentials structure. The ngroups parameter
1294 * is the number of supplementary group entries allocated in the caller's cred
1295 * structure. It should equal zero or one unless extra space has been
1296 * allocated for the group list by the caller.
1299 Pcred(struct ps_prochandle *P, prcred_t *pcrp, int ngroups)
1301 return (P->ops.pop_cred(P, pcrp, ngroups, P->data));
1304 /* Return an allocated prsecflags_t */
1306 Psecflags(struct ps_prochandle *P, prsecflags_t **psf)
1308 int ret;
1310 if ((ret = P->ops.pop_secflags(P, psf, P->data)) == 0) {
1311 if ((*psf)->pr_version != PRSECFLAGS_VERSION_1) {
1312 errno = EINVAL;
1313 return (-1);
1317 return (ret);
1320 void
1321 Psecflags_free(prsecflags_t *psf)
1323 free(psf);
1326 static prheader_t *
1327 Plstatus(struct ps_prochandle *P)
1329 return (P->ops.pop_lstatus(P, P->data));
1332 static prheader_t *
1333 Plpsinfo(struct ps_prochandle *P)
1335 return (P->ops.pop_lpsinfo(P, P->data));
1339 #if defined(__i386) || defined(__amd64)
1341 * Fill in a pointer to a process LDT structure.
1342 * The caller provides a buffer of size 'nldt * sizeof (struct ssd)';
1343 * If pldt == NULL or nldt == 0, we return the number of existing LDT entries.
1344 * Otherwise we return the actual number of LDT entries fetched (<= nldt).
1347 Pldt(struct ps_prochandle *P, struct ssd *pldt, int nldt)
1349 return (P->ops.pop_ldt(P, pldt, nldt, P->data));
1352 #endif /* __i386 */
1354 /* ARGSUSED */
1355 void
1356 Ppriv_free(struct ps_prochandle *P, prpriv_t *prv)
1358 free(prv);
1362 * Return a malloced process privilege structure in *pprv.
1365 Ppriv(struct ps_prochandle *P, prpriv_t **pprv)
1367 return (P->ops.pop_priv(P, pprv, P->data));
1371 Psetpriv(struct ps_prochandle *P, prpriv_t *pprv)
1373 int rc;
1374 long *ctl;
1375 size_t sz;
1377 if (P->state == PS_DEAD) {
1378 errno = EBADF;
1379 return (-1);
1382 sz = PRIV_PRPRIV_SIZE(pprv) + sizeof (long);
1384 sz = ((sz - 1) / sizeof (long) + 1) * sizeof (long);
1386 ctl = malloc(sz);
1387 if (ctl == NULL)
1388 return (-1);
1390 ctl[0] = PCSPRIV;
1392 (void) memcpy(&ctl[1], pprv, PRIV_PRPRIV_SIZE(pprv));
1394 if (write(P->ctlfd, ctl, sz) != sz)
1395 rc = -1;
1396 else
1397 rc = 0;
1399 free(ctl);
1401 return (rc);
1404 void *
1405 Pprivinfo(struct ps_prochandle *P)
1407 core_info_t *core = P->data;
1409 /* Use default from libc */
1410 if (P->state != PS_DEAD)
1411 return (NULL);
1413 return (core->core_privinfo);
1417 * Ensure that all cached state is written to the process.
1418 * The cached state is the LWP's signal mask and registers
1419 * and the process's tracing flags.
1421 void
1422 Psync(struct ps_prochandle *P)
1424 int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
1425 long cmd[6];
1426 iovec_t iov[12];
1427 int n = 0;
1429 if (P->flags & SETHOLD) {
1430 cmd[0] = PCSHOLD;
1431 iov[n].iov_base = (caddr_t)&cmd[0];
1432 iov[n++].iov_len = sizeof (long);
1433 iov[n].iov_base = (caddr_t)&P->status.pr_lwp.pr_lwphold;
1434 iov[n++].iov_len = sizeof (P->status.pr_lwp.pr_lwphold);
1436 if (P->flags & SETREGS) {
1437 cmd[1] = PCSREG;
1438 #ifdef __i386
1439 /* XX64 we should probably restore REG_GS after this */
1440 if (ctlfd == P->agentctlfd)
1441 P->status.pr_lwp.pr_reg[GS] = 0;
1442 #elif defined(__amd64)
1443 /* XX64 */
1444 #endif
1445 iov[n].iov_base = (caddr_t)&cmd[1];
1446 iov[n++].iov_len = sizeof (long);
1447 iov[n].iov_base = (caddr_t)&P->status.pr_lwp.pr_reg[0];
1448 iov[n++].iov_len = sizeof (P->status.pr_lwp.pr_reg);
1450 if (P->flags & SETSIG) {
1451 cmd[2] = PCSTRACE;
1452 iov[n].iov_base = (caddr_t)&cmd[2];
1453 iov[n++].iov_len = sizeof (long);
1454 iov[n].iov_base = (caddr_t)&P->status.pr_sigtrace;
1455 iov[n++].iov_len = sizeof (P->status.pr_sigtrace);
1457 if (P->flags & SETFAULT) {
1458 cmd[3] = PCSFAULT;
1459 iov[n].iov_base = (caddr_t)&cmd[3];
1460 iov[n++].iov_len = sizeof (long);
1461 iov[n].iov_base = (caddr_t)&P->status.pr_flttrace;
1462 iov[n++].iov_len = sizeof (P->status.pr_flttrace);
1464 if (P->flags & SETENTRY) {
1465 cmd[4] = PCSENTRY;
1466 iov[n].iov_base = (caddr_t)&cmd[4];
1467 iov[n++].iov_len = sizeof (long);
1468 iov[n].iov_base = (caddr_t)&P->status.pr_sysentry;
1469 iov[n++].iov_len = sizeof (P->status.pr_sysentry);
1471 if (P->flags & SETEXIT) {
1472 cmd[5] = PCSEXIT;
1473 iov[n].iov_base = (caddr_t)&cmd[5];
1474 iov[n++].iov_len = sizeof (long);
1475 iov[n].iov_base = (caddr_t)&P->status.pr_sysexit;
1476 iov[n++].iov_len = sizeof (P->status.pr_sysexit);
1479 if (n == 0 || writev(ctlfd, iov, n) < 0)
1480 return; /* nothing to do or write failed */
1482 P->flags &= ~(SETSIG|SETFAULT|SETENTRY|SETEXIT|SETHOLD|SETREGS);
1486 * Reopen the /proc file (after PS_LOST).
1489 Preopen(struct ps_prochandle *P)
1491 int fd;
1492 char procname[PATH_MAX];
1493 char *fname;
1495 if (P->state == PS_DEAD || P->state == PS_IDLE)
1496 return (0);
1498 if (P->agentcnt > 0) {
1499 P->agentcnt = 1;
1500 Pdestroy_agent(P);
1503 (void) snprintf(procname, sizeof (procname), "%s/%d/",
1504 procfs_path, (int)P->pid);
1505 fname = procname + strlen(procname);
1507 (void) strcpy(fname, "as");
1508 if ((fd = open(procname, O_RDWR)) < 0 ||
1509 close(P->asfd) < 0 ||
1510 (fd = dupfd(fd, P->asfd)) != P->asfd) {
1511 dprintf("Preopen: failed to open %s: %s\n",
1512 procname, strerror(errno));
1513 if (fd >= 0)
1514 (void) close(fd);
1515 return (-1);
1517 P->asfd = fd;
1519 (void) strcpy(fname, "status");
1520 if ((fd = open(procname, O_RDONLY)) < 0 ||
1521 close(P->statfd) < 0 ||
1522 (fd = dupfd(fd, P->statfd)) != P->statfd) {
1523 dprintf("Preopen: failed to open %s: %s\n",
1524 procname, strerror(errno));
1525 if (fd >= 0)
1526 (void) close(fd);
1527 return (-1);
1529 P->statfd = fd;
1531 (void) strcpy(fname, "ctl");
1532 if ((fd = open(procname, O_WRONLY)) < 0 ||
1533 close(P->ctlfd) < 0 ||
1534 (fd = dupfd(fd, P->ctlfd)) != P->ctlfd) {
1535 dprintf("Preopen: failed to open %s: %s\n",
1536 procname, strerror(errno));
1537 if (fd >= 0)
1538 (void) close(fd);
1539 return (-1);
1541 P->ctlfd = fd;
1544 * Set the state to PS_RUN and wait for the process to stop so that
1545 * we re-read the status from the new P->statfd. If this fails, Pwait
1546 * will reset the state to PS_LOST and we fail the reopen. Before
1547 * returning, we also forge a bit of P->status to allow the debugger to
1548 * see that we are PS_LOST following a successful exec.
1550 P->state = PS_RUN;
1551 if (Pwait(P, 0) == -1) {
1552 #ifdef _ILP32
1553 if (errno == EOVERFLOW)
1554 P->status.pr_dmodel = PR_MODEL_LP64;
1555 #endif
1556 P->status.pr_lwp.pr_why = PR_SYSEXIT;
1557 P->status.pr_lwp.pr_what = SYS_execve;
1558 P->status.pr_lwp.pr_errno = 0;
1559 return (-1);
1563 * The process should be stopped on exec (REQUESTED)
1564 * or else should be stopped on exit from exec() (SYSEXIT)
1566 if (P->state == PS_STOP &&
1567 (P->status.pr_lwp.pr_why == PR_REQUESTED ||
1568 (P->status.pr_lwp.pr_why == PR_SYSEXIT &&
1569 P->status.pr_lwp.pr_what == SYS_execve))) {
1570 /* fake up stop-on-exit-from-execve */
1571 if (P->status.pr_lwp.pr_why == PR_REQUESTED) {
1572 P->status.pr_lwp.pr_why = PR_SYSEXIT;
1573 P->status.pr_lwp.pr_what = SYS_execve;
1574 P->status.pr_lwp.pr_errno = 0;
1576 } else {
1577 dprintf("Preopen: expected REQUESTED or "
1578 "SYSEXIT(SYS_execve) stop\n");
1581 return (0);
1585 * Define all settable flags other than the microstate accounting flags.
1587 #define ALL_SETTABLE_FLAGS (PR_FORK|PR_RLC|PR_KLC|PR_ASYNC|PR_BPTADJ|PR_PTRACE)
1590 * Restore /proc tracing flags to their original values
1591 * in preparation for releasing the process.
1592 * Also called by Pcreate() to clear all tracing flags.
1594 static void
1595 restore_tracing_flags(struct ps_prochandle *P)
1597 long flags;
1598 long cmd[4];
1599 iovec_t iov[8];
1601 if (P->flags & CREATED) {
1602 /* we created this process; clear all tracing flags */
1603 premptyset(&P->status.pr_sigtrace);
1604 premptyset(&P->status.pr_flttrace);
1605 premptyset(&P->status.pr_sysentry);
1606 premptyset(&P->status.pr_sysexit);
1607 if ((P->status.pr_flags & ALL_SETTABLE_FLAGS) != 0)
1608 (void) Punsetflags(P, ALL_SETTABLE_FLAGS);
1609 } else {
1610 /* we grabbed the process; restore its tracing flags */
1611 P->status.pr_sigtrace = P->orig_status.pr_sigtrace;
1612 P->status.pr_flttrace = P->orig_status.pr_flttrace;
1613 P->status.pr_sysentry = P->orig_status.pr_sysentry;
1614 P->status.pr_sysexit = P->orig_status.pr_sysexit;
1615 if ((P->status.pr_flags & ALL_SETTABLE_FLAGS) !=
1616 (flags = (P->orig_status.pr_flags & ALL_SETTABLE_FLAGS))) {
1617 (void) Punsetflags(P, ALL_SETTABLE_FLAGS);
1618 if (flags)
1619 (void) Psetflags(P, flags);
1623 cmd[0] = PCSTRACE;
1624 iov[0].iov_base = (caddr_t)&cmd[0];
1625 iov[0].iov_len = sizeof (long);
1626 iov[1].iov_base = (caddr_t)&P->status.pr_sigtrace;
1627 iov[1].iov_len = sizeof (P->status.pr_sigtrace);
1629 cmd[1] = PCSFAULT;
1630 iov[2].iov_base = (caddr_t)&cmd[1];
1631 iov[2].iov_len = sizeof (long);
1632 iov[3].iov_base = (caddr_t)&P->status.pr_flttrace;
1633 iov[3].iov_len = sizeof (P->status.pr_flttrace);
1635 cmd[2] = PCSENTRY;
1636 iov[4].iov_base = (caddr_t)&cmd[2];
1637 iov[4].iov_len = sizeof (long);
1638 iov[5].iov_base = (caddr_t)&P->status.pr_sysentry;
1639 iov[5].iov_len = sizeof (P->status.pr_sysentry);
1641 cmd[3] = PCSEXIT;
1642 iov[6].iov_base = (caddr_t)&cmd[3];
1643 iov[6].iov_len = sizeof (long);
1644 iov[7].iov_base = (caddr_t)&P->status.pr_sysexit;
1645 iov[7].iov_len = sizeof (P->status.pr_sysexit);
1647 (void) writev(P->ctlfd, iov, 8);
1649 P->flags &= ~(SETSIG|SETFAULT|SETENTRY|SETEXIT);
1653 * Release the process. Frees the process control structure.
1654 * flags:
1655 * PRELEASE_CLEAR Clear all tracing flags.
1656 * PRELEASE_RETAIN Retain current tracing flags.
1657 * PRELEASE_HANG Leave the process stopped and abandoned.
1658 * PRELEASE_KILL Terminate the process with SIGKILL.
1660 void
1661 Prelease(struct ps_prochandle *P, int flags)
1663 if (P->state == PS_DEAD) {
1664 dprintf("Prelease: releasing handle %p PS_DEAD of pid %d\n",
1665 (void *)P, (int)P->pid);
1666 Pfree(P);
1667 return;
1670 if (P->state == PS_IDLE) {
1671 file_info_t *fptr = list_next(&P->file_head);
1672 dprintf("Prelease: releasing handle %p PS_IDLE of file %s\n",
1673 (void *)P, fptr->file_pname);
1674 Pfree(P);
1675 return;
1678 dprintf("Prelease: releasing handle %p pid %d\n",
1679 (void *)P, (int)P->pid);
1681 if (P->ctlfd == -1) {
1682 Pfree(P);
1683 return;
1686 if (P->agentcnt > 0) {
1687 P->agentcnt = 1;
1688 Pdestroy_agent(P);
1692 * Attempt to stop the process.
1694 P->state = PS_RUN;
1695 (void) Pstop(P, 1000);
1697 if (flags & PRELEASE_KILL) {
1698 if (P->state == PS_STOP)
1699 (void) Psetrun(P, SIGKILL, 0);
1700 (void) kill(P->pid, SIGKILL);
1701 Pfree(P);
1702 return;
1706 * If we lost control, all we can do now is close the files.
1707 * In this case, the last close sets the process running.
1709 if (P->state != PS_STOP &&
1710 (P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) == 0) {
1711 Pfree(P);
1712 return;
1716 * We didn't lose control; we do more.
1718 Psync(P);
1720 if (flags & PRELEASE_CLEAR)
1721 P->flags |= CREATED;
1723 if (!(flags & PRELEASE_RETAIN))
1724 restore_tracing_flags(P);
1726 if (flags & PRELEASE_HANG) {
1727 /* Leave the process stopped and abandoned */
1728 (void) Punsetflags(P, PR_RLC|PR_KLC);
1729 Pfree(P);
1730 return;
1734 * Set the process running if we created it or if it was
1735 * not originally stopped or directed to stop via /proc
1736 * or if we were given the PRELEASE_CLEAR flag.
1738 if ((P->flags & CREATED) ||
1739 (P->orig_status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) == 0) {
1740 (void) Psetflags(P, PR_RLC);
1742 * We do this repeatedly because the process may have
1743 * more than one LWP stopped on an event of interest.
1744 * This makes sure all of them are set running.
1746 do {
1747 if (Psetrun(P, 0, 0) == -1 && errno == EBUSY)
1748 break; /* Agent LWP may be stuck */
1749 } while (Pstopstatus(P, PCNULL, 0) == 0 &&
1750 P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP));
1752 if (P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP))
1753 dprintf("Prelease: failed to set process running\n");
1756 Pfree(P);
1759 /* debugging */
1760 void
1761 prldump(const char *caller, lwpstatus_t *lsp)
1763 char name[32];
1764 uint32_t bits;
1766 switch (lsp->pr_why) {
1767 case PR_REQUESTED:
1768 dprintf("%s: REQUESTED\n", caller);
1769 break;
1770 case PR_SIGNALLED:
1771 dprintf("%s: SIGNALLED %s\n", caller,
1772 proc_signame(lsp->pr_what, name, sizeof (name)));
1773 break;
1774 case PR_FAULTED:
1775 dprintf("%s: FAULTED %s\n", caller,
1776 proc_fltname(lsp->pr_what, name, sizeof (name)));
1777 break;
1778 case PR_SYSENTRY:
1779 dprintf("%s: SYSENTRY %s\n", caller,
1780 proc_sysname(lsp->pr_what, name, sizeof (name)));
1781 break;
1782 case PR_SYSEXIT:
1783 dprintf("%s: SYSEXIT %s\n", caller,
1784 proc_sysname(lsp->pr_what, name, sizeof (name)));
1785 break;
1786 case PR_JOBCONTROL:
1787 dprintf("%s: JOBCONTROL %s\n", caller,
1788 proc_signame(lsp->pr_what, name, sizeof (name)));
1789 break;
1790 case PR_SUSPENDED:
1791 dprintf("%s: SUSPENDED\n", caller);
1792 break;
1793 default:
1794 dprintf("%s: Unknown\n", caller);
1795 break;
1798 if (lsp->pr_cursig)
1799 dprintf("%s: p_cursig = %d\n", caller, lsp->pr_cursig);
1801 bits = *((uint32_t *)&lsp->pr_lwppend);
1802 if (bits)
1803 dprintf("%s: pr_lwppend = 0x%.8X\n", caller, bits);
1806 /* debugging */
1807 static void
1808 prdump(struct ps_prochandle *P)
1810 uint32_t bits;
1812 prldump("Pstopstatus", &P->status.pr_lwp);
1814 bits = *((uint32_t *)&P->status.pr_sigpend);
1815 if (bits)
1816 dprintf("Pstopstatus: pr_sigpend = 0x%.8X\n", bits);
1820 * Wait for the specified process to stop or terminate.
1821 * Or, just get the current status (PCNULL).
1822 * Or, direct it to stop and get the current status (PCDSTOP).
1823 * If the agent LWP exists, do these things to the agent,
1824 * else do these things to the process as a whole.
1827 Pstopstatus(struct ps_prochandle *P,
1828 long request, /* PCNULL, PCDSTOP, PCSTOP, PCWSTOP */
1829 uint_t msec) /* if non-zero, timeout in milliseconds */
1831 int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
1832 long ctl[3];
1833 ssize_t rc;
1834 int err;
1835 int old_state = P->state;
1837 switch (P->state) {
1838 case PS_RUN:
1839 break;
1840 case PS_STOP:
1841 if (request != PCNULL && request != PCDSTOP)
1842 return (0);
1843 break;
1844 case PS_LOST:
1845 if (request != PCNULL) {
1846 errno = EAGAIN;
1847 return (-1);
1849 break;
1850 case PS_UNDEAD:
1851 case PS_DEAD:
1852 case PS_IDLE:
1853 if (request != PCNULL) {
1854 errno = ENOENT;
1855 return (-1);
1857 break;
1858 default: /* corrupted state */
1859 dprintf("Pstopstatus: corrupted state: %d\n", P->state);
1860 errno = EINVAL;
1861 return (-1);
1864 ctl[0] = PCDSTOP;
1865 ctl[1] = PCTWSTOP;
1866 ctl[2] = (long)msec;
1867 rc = 0;
1868 switch (request) {
1869 case PCSTOP:
1870 rc = write(ctlfd, &ctl[0], 3*sizeof (long));
1871 break;
1872 case PCWSTOP:
1873 rc = write(ctlfd, &ctl[1], 2*sizeof (long));
1874 break;
1875 case PCDSTOP:
1876 rc = write(ctlfd, &ctl[0], 1*sizeof (long));
1877 break;
1878 case PCNULL:
1879 if (P->state == PS_DEAD || P->state == PS_IDLE)
1880 return (0);
1881 break;
1882 default: /* programming error */
1883 errno = EINVAL;
1884 return (-1);
1886 err = (rc < 0)? errno : 0;
1887 Psync(P);
1889 if (P->agentstatfd < 0) {
1890 if (pread(P->statfd, &P->status,
1891 sizeof (P->status), (off_t)0) < 0)
1892 err = errno;
1893 } else {
1894 if (pread(P->agentstatfd, &P->status.pr_lwp,
1895 sizeof (P->status.pr_lwp), (off_t)0) < 0)
1896 err = errno;
1897 P->status.pr_flags = P->status.pr_lwp.pr_flags;
1900 if (err) {
1901 switch (err) {
1902 case EINTR: /* user typed ctl-C */
1903 case ERESTART:
1904 dprintf("Pstopstatus: EINTR\n");
1905 break;
1906 case EAGAIN: /* we lost control of the the process */
1907 case EOVERFLOW:
1908 dprintf("Pstopstatus: PS_LOST, errno=%d\n", err);
1909 P->state = PS_LOST;
1910 break;
1911 default: /* check for dead process */
1912 if (_libproc_debug) {
1913 const char *errstr;
1915 switch (request) {
1916 case PCNULL:
1917 errstr = "Pstopstatus PCNULL"; break;
1918 case PCSTOP:
1919 errstr = "Pstopstatus PCSTOP"; break;
1920 case PCDSTOP:
1921 errstr = "Pstopstatus PCDSTOP"; break;
1922 case PCWSTOP:
1923 errstr = "Pstopstatus PCWSTOP"; break;
1924 default:
1925 errstr = "Pstopstatus PC???"; break;
1927 dprintf("%s: %s\n", errstr, strerror(err));
1929 deadcheck(P);
1930 break;
1932 if (err != EINTR && err != ERESTART) {
1933 errno = err;
1934 return (-1);
1938 if (!(P->status.pr_flags & PR_STOPPED)) {
1939 P->state = PS_RUN;
1940 if (request == PCNULL || request == PCDSTOP || msec != 0)
1941 return (0);
1942 dprintf("Pstopstatus: process is not stopped\n");
1943 errno = EPROTO;
1944 return (-1);
1947 P->state = PS_STOP;
1949 if (_libproc_debug) /* debugging */
1950 prdump(P);
1953 * If the process was already stopped coming into Pstopstatus(),
1954 * then don't use its PC to set P->sysaddr since it may have been
1955 * changed since the time the process originally stopped.
1957 if (old_state == PS_STOP)
1958 return (0);
1960 switch (P->status.pr_lwp.pr_why) {
1961 case PR_SYSENTRY:
1962 case PR_SYSEXIT:
1963 if (Pissyscall_prev(P, P->status.pr_lwp.pr_reg[R_PC],
1964 &P->sysaddr) == 0)
1965 P->sysaddr = P->status.pr_lwp.pr_reg[R_PC];
1966 break;
1967 case PR_REQUESTED:
1968 case PR_SIGNALLED:
1969 case PR_FAULTED:
1970 case PR_JOBCONTROL:
1971 case PR_SUSPENDED:
1972 break;
1973 default:
1974 errno = EPROTO;
1975 return (-1);
1978 return (0);
1982 * Wait for the process to stop for any reason.
1985 Pwait(struct ps_prochandle *P, uint_t msec)
1987 return (Pstopstatus(P, PCWSTOP, msec));
1991 * Direct the process to stop; wait for it to stop.
1994 Pstop(struct ps_prochandle *P, uint_t msec)
1996 return (Pstopstatus(P, PCSTOP, msec));
2000 * Direct the process to stop; don't wait.
2003 Pdstop(struct ps_prochandle *P)
2005 return (Pstopstatus(P, PCDSTOP, 0));
2008 static void
2009 deadcheck(struct ps_prochandle *P)
2011 int fd;
2012 void *buf;
2013 size_t size;
2015 if (P->statfd < 0)
2016 P->state = PS_UNDEAD;
2017 else {
2018 if (P->agentstatfd < 0) {
2019 fd = P->statfd;
2020 buf = &P->status;
2021 size = sizeof (P->status);
2022 } else {
2023 fd = P->agentstatfd;
2024 buf = &P->status.pr_lwp;
2025 size = sizeof (P->status.pr_lwp);
2027 while (pread(fd, buf, size, (off_t)0) != size) {
2028 switch (errno) {
2029 default:
2030 P->state = PS_UNDEAD;
2031 break;
2032 case EINTR:
2033 case ERESTART:
2034 continue;
2035 case EAGAIN:
2036 P->state = PS_LOST;
2037 break;
2039 break;
2041 P->status.pr_flags = P->status.pr_lwp.pr_flags;
2046 * Get the value of one register from stopped process.
2049 Pgetareg(struct ps_prochandle *P, int regno, prgreg_t *preg)
2051 if (regno < 0 || regno >= NPRGREG) {
2052 errno = EINVAL;
2053 return (-1);
2056 if (P->state == PS_IDLE) {
2057 errno = ENODATA;
2058 return (-1);
2061 if (P->state != PS_STOP && P->state != PS_DEAD) {
2062 errno = EBUSY;
2063 return (-1);
2066 *preg = P->status.pr_lwp.pr_reg[regno];
2067 return (0);
2071 * Put value of one register into stopped process.
2074 Pputareg(struct ps_prochandle *P, int regno, prgreg_t reg)
2076 if (regno < 0 || regno >= NPRGREG) {
2077 errno = EINVAL;
2078 return (-1);
2081 if (P->state != PS_STOP) {
2082 errno = EBUSY;
2083 return (-1);
2086 P->status.pr_lwp.pr_reg[regno] = reg;
2087 P->flags |= SETREGS; /* set registers before continuing */
2088 return (0);
2092 Psetrun(struct ps_prochandle *P,
2093 int sig, /* signal to pass to process */
2094 int flags) /* PRSTEP|PRSABORT|PRSTOP|PRCSIG|PRCFAULT */
2096 int ctlfd = (P->agentctlfd >= 0) ? P->agentctlfd : P->ctlfd;
2097 int sbits = (PR_DSTOP | PR_ISTOP | PR_ASLEEP);
2099 long ctl[1 + /* PCCFAULT */
2100 1 + sizeof (siginfo_t)/sizeof (long) + /* PCSSIG/PCCSIG */
2101 2 ]; /* PCRUN */
2103 long *ctlp = ctl;
2104 size_t size;
2106 if (P->state != PS_STOP && (P->status.pr_lwp.pr_flags & sbits) == 0) {
2107 errno = EBUSY;
2108 return (-1);
2111 Psync(P); /* flush tracing flags and registers */
2113 if (flags & PRCFAULT) { /* clear current fault */
2114 *ctlp++ = PCCFAULT;
2115 flags &= ~PRCFAULT;
2118 if (flags & PRCSIG) { /* clear current signal */
2119 *ctlp++ = PCCSIG;
2120 flags &= ~PRCSIG;
2121 } else if (sig && sig != P->status.pr_lwp.pr_cursig) {
2122 /* make current signal */
2123 siginfo_t *infop;
2125 *ctlp++ = PCSSIG;
2126 infop = (siginfo_t *)ctlp;
2127 (void) memset(infop, 0, sizeof (*infop));
2128 infop->si_signo = sig;
2129 ctlp += sizeof (siginfo_t) / sizeof (long);
2132 *ctlp++ = PCRUN;
2133 *ctlp++ = flags;
2134 size = (char *)ctlp - (char *)ctl;
2136 P->info_valid = 0; /* will need to update map and file info */
2139 * If we've cached ucontext-list information while we were stopped,
2140 * free it now.
2142 if (P->ucaddrs != NULL) {
2143 free(P->ucaddrs);
2144 P->ucaddrs = NULL;
2145 P->ucnelems = 0;
2148 if (write(ctlfd, ctl, size) != size) {
2149 /* If it is dead or lost, return the real status, not PS_RUN */
2150 if (errno == ENOENT || errno == EAGAIN) {
2151 (void) Pstopstatus(P, PCNULL, 0);
2152 return (0);
2154 /* If it is not in a jobcontrol stop, issue an error message */
2155 if (errno != EBUSY ||
2156 P->status.pr_lwp.pr_why != PR_JOBCONTROL) {
2157 dprintf("Psetrun: %s\n", strerror(errno));
2158 return (-1);
2160 /* Otherwise pretend that the job-stopped process is running */
2163 P->state = PS_RUN;
2164 return (0);
2167 ssize_t
2168 Pread(struct ps_prochandle *P,
2169 void *buf, /* caller's buffer */
2170 size_t nbyte, /* number of bytes to read */
2171 uintptr_t address) /* address in process */
2173 return (P->ops.pop_pread(P, buf, nbyte, address, P->data));
2176 ssize_t
2177 Pread_string(struct ps_prochandle *P,
2178 char *buf, /* caller's buffer */
2179 size_t size, /* upper limit on bytes to read */
2180 uintptr_t addr) /* address in process */
2182 enum { STRSZ = 40 };
2183 char string[STRSZ + 1];
2184 ssize_t leng = 0;
2185 int nbyte;
2187 if (size < 2) {
2188 errno = EINVAL;
2189 return (-1);
2192 size--; /* ensure trailing null fits in buffer */
2194 *buf = '\0';
2195 string[STRSZ] = '\0';
2197 for (nbyte = STRSZ; nbyte == STRSZ && leng < size; addr += STRSZ) {
2198 if ((nbyte = P->ops.pop_pread(P, string, STRSZ, addr,
2199 P->data)) <= 0) {
2200 buf[leng] = '\0';
2201 return (leng ? leng : -1);
2203 if ((nbyte = strlen(string)) > 0) {
2204 if (leng + nbyte > size)
2205 nbyte = size - leng;
2206 (void) strncpy(buf + leng, string, nbyte);
2207 leng += nbyte;
2210 buf[leng] = '\0';
2211 return (leng);
2214 ssize_t
2215 Pwrite(struct ps_prochandle *P,
2216 const void *buf, /* caller's buffer */
2217 size_t nbyte, /* number of bytes to write */
2218 uintptr_t address) /* address in process */
2220 return (P->ops.pop_pwrite(P, buf, nbyte, address, P->data));
2224 Pclearsig(struct ps_prochandle *P)
2226 int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2227 long ctl = PCCSIG;
2229 if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
2230 return (-1);
2231 P->status.pr_lwp.pr_cursig = 0;
2232 return (0);
2236 Pclearfault(struct ps_prochandle *P)
2238 int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2239 long ctl = PCCFAULT;
2241 if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
2242 return (-1);
2243 return (0);
2247 * Set a breakpoint trap, return original instruction.
2250 Psetbkpt(struct ps_prochandle *P, uintptr_t address, ulong_t *saved)
2252 long ctl[1 + sizeof (priovec_t) / sizeof (long) + /* PCREAD */
2253 1 + sizeof (priovec_t) / sizeof (long)]; /* PCWRITE */
2254 long *ctlp = ctl;
2255 size_t size;
2256 priovec_t *iovp;
2257 instr_t bpt = BPT;
2258 instr_t old;
2260 if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2261 P->state == PS_IDLE) {
2262 errno = ENOENT;
2263 return (-1);
2266 /* fetch the old instruction */
2267 *ctlp++ = PCREAD;
2268 iovp = (priovec_t *)ctlp;
2269 iovp->pio_base = &old;
2270 iovp->pio_len = sizeof (old);
2271 iovp->pio_offset = address;
2272 ctlp += sizeof (priovec_t) / sizeof (long);
2274 /* write the BPT instruction */
2275 *ctlp++ = PCWRITE;
2276 iovp = (priovec_t *)ctlp;
2277 iovp->pio_base = &bpt;
2278 iovp->pio_len = sizeof (bpt);
2279 iovp->pio_offset = address;
2280 ctlp += sizeof (priovec_t) / sizeof (long);
2282 size = (char *)ctlp - (char *)ctl;
2283 if (write(P->ctlfd, ctl, size) != size)
2284 return (-1);
2287 * Fail if there was already a breakpoint there from another debugger
2288 * or DTrace's user-level tracing on x86.
2290 if (old == BPT) {
2291 errno = EBUSY;
2292 return (-1);
2295 *saved = (ulong_t)old;
2296 return (0);
2300 * Restore original instruction where a breakpoint was set.
2303 Pdelbkpt(struct ps_prochandle *P, uintptr_t address, ulong_t saved)
2305 instr_t old = (instr_t)saved;
2306 instr_t cur;
2308 if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2309 P->state == PS_IDLE) {
2310 errno = ENOENT;
2311 return (-1);
2315 * If the breakpoint instruction we had placed has been overwritten
2316 * with a new instruction, then don't try to replace it with the
2317 * old instruction. Doing do can cause problems with self-modifying
2318 * code -- PLTs for example. If the Pread() fails, we assume that we
2319 * should proceed though most likely the Pwrite() will also fail.
2321 if (Pread(P, &cur, sizeof (cur), address) == sizeof (cur) &&
2322 cur != BPT)
2323 return (0);
2325 if (Pwrite(P, &old, sizeof (old), address) != sizeof (old))
2326 return (-1);
2328 return (0);
2332 * Common code for Pxecbkpt() and Lxecbkpt().
2333 * Develop the array of requests that will do the job, then
2334 * write them to the specified control file descriptor.
2335 * Return the non-zero errno if the write fails.
2337 static int
2338 execute_bkpt(
2339 int ctlfd, /* process or LWP control file descriptor */
2340 const fltset_t *faultset, /* current set of traced faults */
2341 const sigset_t *sigmask, /* current signal mask */
2342 uintptr_t address, /* address of breakpint */
2343 ulong_t saved) /* the saved instruction */
2345 long ctl[
2346 1 + sizeof (sigset_t) / sizeof (long) + /* PCSHOLD */
2347 1 + sizeof (fltset_t) / sizeof (long) + /* PCSFAULT */
2348 1 + sizeof (priovec_t) / sizeof (long) + /* PCWRITE */
2349 2 + /* PCRUN */
2350 1 + /* PCWSTOP */
2351 1 + /* PCCFAULT */
2352 1 + sizeof (priovec_t) / sizeof (long) + /* PCWRITE */
2353 1 + sizeof (fltset_t) / sizeof (long) + /* PCSFAULT */
2354 1 + sizeof (sigset_t) / sizeof (long)]; /* PCSHOLD */
2355 long *ctlp = ctl;
2356 sigset_t unblock;
2357 size_t size;
2358 ssize_t ssize;
2359 priovec_t *iovp;
2360 sigset_t *holdp;
2361 fltset_t *faultp;
2362 instr_t old = (instr_t)saved;
2363 instr_t bpt = BPT;
2364 int error = 0;
2366 /* block our signals for the duration */
2367 (void) sigprocmask(SIG_BLOCK, &blockable_sigs, &unblock);
2369 /* hold posted signals */
2370 *ctlp++ = PCSHOLD;
2371 holdp = (sigset_t *)ctlp;
2372 prfillset(holdp);
2373 prdelset(holdp, SIGKILL);
2374 prdelset(holdp, SIGSTOP);
2375 ctlp += sizeof (sigset_t) / sizeof (long);
2377 /* force tracing of FLTTRACE */
2378 if (!(prismember(faultset, FLTTRACE))) {
2379 *ctlp++ = PCSFAULT;
2380 faultp = (fltset_t *)ctlp;
2381 *faultp = *faultset;
2382 praddset(faultp, FLTTRACE);
2383 ctlp += sizeof (fltset_t) / sizeof (long);
2386 /* restore the old instruction */
2387 *ctlp++ = PCWRITE;
2388 iovp = (priovec_t *)ctlp;
2389 iovp->pio_base = &old;
2390 iovp->pio_len = sizeof (old);
2391 iovp->pio_offset = address;
2392 ctlp += sizeof (priovec_t) / sizeof (long);
2394 /* clear current signal and fault; set running w/ single-step */
2395 *ctlp++ = PCRUN;
2396 *ctlp++ = PRCSIG | PRCFAULT | PRSTEP;
2398 /* wait for stop, cancel the fault */
2399 *ctlp++ = PCWSTOP;
2400 *ctlp++ = PCCFAULT;
2402 /* restore the breakpoint trap */
2403 *ctlp++ = PCWRITE;
2404 iovp = (priovec_t *)ctlp;
2405 iovp->pio_base = &bpt;
2406 iovp->pio_len = sizeof (bpt);
2407 iovp->pio_offset = address;
2408 ctlp += sizeof (priovec_t) / sizeof (long);
2410 /* restore fault tracing set */
2411 if (!(prismember(faultset, FLTTRACE))) {
2412 *ctlp++ = PCSFAULT;
2413 *(fltset_t *)ctlp = *faultset;
2414 ctlp += sizeof (fltset_t) / sizeof (long);
2417 /* restore the hold mask */
2418 *ctlp++ = PCSHOLD;
2419 *(sigset_t *)ctlp = *sigmask;
2420 ctlp += sizeof (sigset_t) / sizeof (long);
2422 size = (char *)ctlp - (char *)ctl;
2423 if ((ssize = write(ctlfd, ctl, size)) != size)
2424 error = (ssize == -1)? errno : EINTR;
2425 (void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2426 return (error);
2430 * Step over a breakpoint, i.e., execute the instruction that
2431 * really belongs at the breakpoint location (the current %pc)
2432 * and leave the process stopped at the next instruction.
2435 Pxecbkpt(struct ps_prochandle *P, ulong_t saved)
2437 int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2438 int rv, error;
2440 if (P->state != PS_STOP) {
2441 errno = EBUSY;
2442 return (-1);
2445 Psync(P);
2447 error = execute_bkpt(ctlfd,
2448 &P->status.pr_flttrace, &P->status.pr_lwp.pr_lwphold,
2449 P->status.pr_lwp.pr_reg[R_PC], saved);
2450 rv = Pstopstatus(P, PCNULL, 0);
2452 if (error != 0) {
2453 if (P->status.pr_lwp.pr_why == PR_JOBCONTROL &&
2454 error == EBUSY) { /* jobcontrol stop -- back off */
2455 P->state = PS_RUN;
2456 return (0);
2458 if (error == ENOENT)
2459 return (0);
2460 errno = error;
2461 return (-1);
2464 return (rv);
2468 * Install the watchpoint described by wp.
2471 Psetwapt(struct ps_prochandle *P, const prwatch_t *wp)
2473 long ctl[1 + sizeof (prwatch_t) / sizeof (long)];
2474 prwatch_t *cwp = (prwatch_t *)&ctl[1];
2476 if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2477 P->state == PS_IDLE) {
2478 errno = ENOENT;
2479 return (-1);
2482 ctl[0] = PCWATCH;
2483 cwp->pr_vaddr = wp->pr_vaddr;
2484 cwp->pr_size = wp->pr_size;
2485 cwp->pr_wflags = wp->pr_wflags;
2487 if (write(P->ctlfd, ctl, sizeof (ctl)) != sizeof (ctl))
2488 return (-1);
2490 return (0);
2494 * Remove the watchpoint described by wp.
2497 Pdelwapt(struct ps_prochandle *P, const prwatch_t *wp)
2499 long ctl[1 + sizeof (prwatch_t) / sizeof (long)];
2500 prwatch_t *cwp = (prwatch_t *)&ctl[1];
2502 if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2503 P->state == PS_IDLE) {
2504 errno = ENOENT;
2505 return (-1);
2508 ctl[0] = PCWATCH;
2509 cwp->pr_vaddr = wp->pr_vaddr;
2510 cwp->pr_size = wp->pr_size;
2511 cwp->pr_wflags = 0;
2513 if (write(P->ctlfd, ctl, sizeof (ctl)) != sizeof (ctl))
2514 return (-1);
2516 return (0);
2520 * Common code for Pxecwapt() and Lxecwapt(). Develop the array of requests
2521 * that will do the job, then write them to the specified control file
2522 * descriptor. Return the non-zero errno if the write fails.
2524 static int
2525 execute_wapt(
2526 int ctlfd, /* process or LWP control file descriptor */
2527 const fltset_t *faultset, /* current set of traced faults */
2528 const sigset_t *sigmask, /* current signal mask */
2529 const prwatch_t *wp) /* watchpoint descriptor */
2531 long ctl[
2532 1 + sizeof (sigset_t) / sizeof (long) + /* PCSHOLD */
2533 1 + sizeof (fltset_t) / sizeof (long) + /* PCSFAULT */
2534 1 + sizeof (prwatch_t) / sizeof (long) + /* PCWATCH */
2535 2 + /* PCRUN */
2536 1 + /* PCWSTOP */
2537 1 + /* PCCFAULT */
2538 1 + sizeof (prwatch_t) / sizeof (long) + /* PCWATCH */
2539 1 + sizeof (fltset_t) / sizeof (long) + /* PCSFAULT */
2540 1 + sizeof (sigset_t) / sizeof (long)]; /* PCSHOLD */
2542 long *ctlp = ctl;
2543 int error = 0;
2545 sigset_t unblock;
2546 sigset_t *holdp;
2547 fltset_t *faultp;
2548 prwatch_t *prw;
2549 ssize_t ssize;
2550 size_t size;
2552 (void) sigprocmask(SIG_BLOCK, &blockable_sigs, &unblock);
2555 * Hold all posted signals in the victim process prior to stepping.
2557 *ctlp++ = PCSHOLD;
2558 holdp = (sigset_t *)ctlp;
2559 prfillset(holdp);
2560 prdelset(holdp, SIGKILL);
2561 prdelset(holdp, SIGSTOP);
2562 ctlp += sizeof (sigset_t) / sizeof (long);
2565 * Force tracing of FLTTRACE since we need to single step.
2567 if (!(prismember(faultset, FLTTRACE))) {
2568 *ctlp++ = PCSFAULT;
2569 faultp = (fltset_t *)ctlp;
2570 *faultp = *faultset;
2571 praddset(faultp, FLTTRACE);
2572 ctlp += sizeof (fltset_t) / sizeof (long);
2576 * Clear only the current watchpoint by setting pr_wflags to zero.
2578 *ctlp++ = PCWATCH;
2579 prw = (prwatch_t *)ctlp;
2580 prw->pr_vaddr = wp->pr_vaddr;
2581 prw->pr_size = wp->pr_size;
2582 prw->pr_wflags = 0;
2583 ctlp += sizeof (prwatch_t) / sizeof (long);
2586 * Clear the current signal and fault; set running with single-step.
2587 * Then wait for the victim to stop and cancel the FLTTRACE.
2589 *ctlp++ = PCRUN;
2590 *ctlp++ = PRCSIG | PRCFAULT | PRSTEP;
2591 *ctlp++ = PCWSTOP;
2592 *ctlp++ = PCCFAULT;
2595 * Restore the current watchpoint.
2597 *ctlp++ = PCWATCH;
2598 (void) memcpy(ctlp, wp, sizeof (prwatch_t));
2599 ctlp += sizeof (prwatch_t) / sizeof (long);
2602 * Restore fault tracing set if we modified it.
2604 if (!(prismember(faultset, FLTTRACE))) {
2605 *ctlp++ = PCSFAULT;
2606 *(fltset_t *)ctlp = *faultset;
2607 ctlp += sizeof (fltset_t) / sizeof (long);
2611 * Restore the hold mask to the current hold mask (i.e. the one
2612 * before we executed any of the previous operations).
2614 *ctlp++ = PCSHOLD;
2615 *(sigset_t *)ctlp = *sigmask;
2616 ctlp += sizeof (sigset_t) / sizeof (long);
2618 size = (char *)ctlp - (char *)ctl;
2619 if ((ssize = write(ctlfd, ctl, size)) != size)
2620 error = (ssize == -1)? errno : EINTR;
2621 (void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2622 return (error);
2626 * Step over a watchpoint, i.e., execute the instruction that was stopped by
2627 * the watchpoint, and then leave the LWP stopped at the next instruction.
2630 Pxecwapt(struct ps_prochandle *P, const prwatch_t *wp)
2632 int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2633 int rv, error;
2635 if (P->state != PS_STOP) {
2636 errno = EBUSY;
2637 return (-1);
2640 Psync(P);
2641 error = execute_wapt(ctlfd,
2642 &P->status.pr_flttrace, &P->status.pr_lwp.pr_lwphold, wp);
2643 rv = Pstopstatus(P, PCNULL, 0);
2645 if (error != 0) {
2646 if (P->status.pr_lwp.pr_why == PR_JOBCONTROL &&
2647 error == EBUSY) { /* jobcontrol stop -- back off */
2648 P->state = PS_RUN;
2649 return (0);
2651 if (error == ENOENT)
2652 return (0);
2653 errno = error;
2654 return (-1);
2657 return (rv);
2661 Psetflags(struct ps_prochandle *P, long flags)
2663 int rc;
2664 long ctl[2];
2666 ctl[0] = PCSET;
2667 ctl[1] = flags;
2669 if (write(P->ctlfd, ctl, 2*sizeof (long)) != 2*sizeof (long)) {
2670 rc = -1;
2671 } else {
2672 P->status.pr_flags |= flags;
2673 P->status.pr_lwp.pr_flags |= flags;
2674 rc = 0;
2677 return (rc);
2681 Punsetflags(struct ps_prochandle *P, long flags)
2683 int rc;
2684 long ctl[2];
2686 ctl[0] = PCUNSET;
2687 ctl[1] = flags;
2689 if (write(P->ctlfd, ctl, 2*sizeof (long)) != 2*sizeof (long)) {
2690 rc = -1;
2691 } else {
2692 P->status.pr_flags &= ~flags;
2693 P->status.pr_lwp.pr_flags &= ~flags;
2694 rc = 0;
2697 return (rc);
2701 * Common function to allow clients to manipulate the action to be taken
2702 * on receipt of a signal, receipt of machine fault, entry to a system call,
2703 * or exit from a system call. We make use of our private prset_* functions
2704 * in order to make this code be common. The 'which' parameter identifies
2705 * the code for the event of interest (0 means change the entire set), and
2706 * the 'stop' parameter is a boolean indicating whether the process should
2707 * stop when the event of interest occurs. The previous value is returned
2708 * to the caller; -1 is returned if an error occurred.
2710 static int
2711 Psetaction(struct ps_prochandle *P, void *sp, size_t size,
2712 uint_t flag, int max, int which, int stop)
2714 int oldval;
2716 if (which < 0 || which > max) {
2717 errno = EINVAL;
2718 return (-1);
2721 if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2722 P->state == PS_IDLE) {
2723 errno = ENOENT;
2724 return (-1);
2727 oldval = prset_ismember(sp, size, which) ? TRUE : FALSE;
2729 if (stop) {
2730 if (which == 0) {
2731 prset_fill(sp, size);
2732 P->flags |= flag;
2733 } else if (!oldval) {
2734 prset_add(sp, size, which);
2735 P->flags |= flag;
2737 } else {
2738 if (which == 0) {
2739 prset_empty(sp, size);
2740 P->flags |= flag;
2741 } else if (oldval) {
2742 prset_del(sp, size, which);
2743 P->flags |= flag;
2747 if (P->state == PS_RUN)
2748 Psync(P);
2750 return (oldval);
2754 * Set action on specified signal.
2757 Psignal(struct ps_prochandle *P, int which, int stop)
2759 int oldval;
2761 if (which == SIGKILL && stop != 0) {
2762 errno = EINVAL;
2763 return (-1);
2766 oldval = Psetaction(P, &P->status.pr_sigtrace, sizeof (sigset_t),
2767 SETSIG, PRMAXSIG, which, stop);
2769 if (oldval != -1 && which == 0 && stop != 0)
2770 prdelset(&P->status.pr_sigtrace, SIGKILL);
2772 return (oldval);
2776 * Set all signal tracing flags.
2778 void
2779 Psetsignal(struct ps_prochandle *P, const sigset_t *set)
2781 if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2782 P->state == PS_IDLE)
2783 return;
2785 P->status.pr_sigtrace = *set;
2786 P->flags |= SETSIG;
2788 if (P->state == PS_RUN)
2789 Psync(P);
2793 * Set action on specified fault.
2796 Pfault(struct ps_prochandle *P, int which, int stop)
2798 return (Psetaction(P, &P->status.pr_flttrace, sizeof (fltset_t),
2799 SETFAULT, PRMAXFAULT, which, stop));
2803 * Set all machine fault tracing flags.
2805 void
2806 Psetfault(struct ps_prochandle *P, const fltset_t *set)
2808 if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2809 P->state == PS_IDLE)
2810 return;
2812 P->status.pr_flttrace = *set;
2813 P->flags |= SETFAULT;
2815 if (P->state == PS_RUN)
2816 Psync(P);
2820 * Set action on specified system call entry.
2823 Psysentry(struct ps_prochandle *P, int which, int stop)
2825 return (Psetaction(P, &P->status.pr_sysentry, sizeof (sysset_t),
2826 SETENTRY, PRMAXSYS, which, stop));
2830 * Set all system call entry tracing flags.
2832 void
2833 Psetsysentry(struct ps_prochandle *P, const sysset_t *set)
2835 if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2836 P->state == PS_IDLE)
2837 return;
2839 P->status.pr_sysentry = *set;
2840 P->flags |= SETENTRY;
2842 if (P->state == PS_RUN)
2843 Psync(P);
2847 * Set action on specified system call exit.
2850 Psysexit(struct ps_prochandle *P, int which, int stop)
2852 return (Psetaction(P, &P->status.pr_sysexit, sizeof (sysset_t),
2853 SETEXIT, PRMAXSYS, which, stop));
2857 * Set all system call exit tracing flags.
2859 void
2860 Psetsysexit(struct ps_prochandle *P, const sysset_t *set)
2862 if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2863 P->state == PS_IDLE)
2864 return;
2866 P->status.pr_sysexit = *set;
2867 P->flags |= SETEXIT;
2869 if (P->state == PS_RUN)
2870 Psync(P);
2874 * Utility function to read the contents of a file that contains a
2875 * prheader_t at the start (/proc/pid/lstatus or /proc/pid/lpsinfo).
2876 * Returns a malloc()d buffer or NULL on failure.
2878 static prheader_t *
2879 read_lfile(struct ps_prochandle *P, const char *lname)
2881 prheader_t *Lhp;
2882 char lpath[PATH_MAX];
2883 struct stat64 statb;
2884 int fd;
2885 size_t size;
2886 ssize_t rval;
2888 (void) snprintf(lpath, sizeof (lpath), "%s/%d/%s", procfs_path,
2889 (int)P->status.pr_pid, lname);
2890 if ((fd = open(lpath, O_RDONLY)) < 0 || fstat64(fd, &statb) != 0) {
2891 if (fd >= 0)
2892 (void) close(fd);
2893 return (NULL);
2897 * 'size' is just the initial guess at the buffer size.
2898 * It will have to grow if the number of lwps increases
2899 * while we are looking at the process.
2900 * 'size' must be larger than the actual file size.
2902 size = statb.st_size + 32;
2904 for (;;) {
2905 if ((Lhp = malloc(size)) == NULL)
2906 break;
2907 if ((rval = pread(fd, Lhp, size, 0)) < 0 ||
2908 rval <= sizeof (prheader_t)) {
2909 free(Lhp);
2910 Lhp = NULL;
2911 break;
2913 if (rval < size)
2914 break;
2915 /* need a bigger buffer */
2916 free(Lhp);
2917 size *= 2;
2920 (void) close(fd);
2921 return (Lhp);
2925 * LWP iteration interface.
2928 Plwp_iter(struct ps_prochandle *P, proc_lwp_f *func, void *cd)
2930 prheader_t *Lhp;
2931 lwpstatus_t *Lsp;
2932 long nlwp;
2933 int rv;
2935 switch (P->state) {
2936 case PS_RUN:
2937 (void) Pstopstatus(P, PCNULL, 0);
2938 break;
2940 case PS_STOP:
2941 Psync(P);
2942 break;
2944 case PS_IDLE:
2945 errno = ENODATA;
2946 return (-1);
2950 * For either live processes or cores, the single LWP case is easy:
2951 * the pstatus_t contains the lwpstatus_t for the only LWP.
2953 if (P->status.pr_nlwp <= 1)
2954 return (func(cd, &P->status.pr_lwp));
2957 * For the core file multi-LWP case, we just iterate through the
2958 * list of LWP structs we read in from the core file.
2960 if (P->state == PS_DEAD) {
2961 core_info_t *core = P->data;
2962 lwp_info_t *lwp = list_prev(&core->core_lwp_head);
2963 uint_t i;
2965 for (i = 0; i < core->core_nlwp; i++, lwp = list_prev(lwp)) {
2966 if (lwp->lwp_psinfo.pr_sname != 'Z' &&
2967 (rv = func(cd, &lwp->lwp_status)) != 0)
2968 break;
2971 return (rv);
2975 * For the live process multi-LWP case, we have to work a little
2976 * harder: the /proc/pid/lstatus file has the array of LWP structs.
2978 if ((Lhp = Plstatus(P)) == NULL)
2979 return (-1);
2981 for (nlwp = Lhp->pr_nent, Lsp = (lwpstatus_t *)(uintptr_t)(Lhp + 1);
2982 nlwp > 0;
2983 nlwp--, Lsp = (lwpstatus_t *)((uintptr_t)Lsp + Lhp->pr_entsize)) {
2984 if ((rv = func(cd, Lsp)) != 0)
2985 break;
2988 free(Lhp);
2989 return (rv);
2993 * Extended LWP iteration interface.
2994 * Iterate over all LWPs, active and zombie.
2997 Plwp_iter_all(struct ps_prochandle *P, proc_lwp_all_f *func, void *cd)
2999 prheader_t *Lhp = NULL;
3000 lwpstatus_t *Lsp;
3001 lwpstatus_t *sp;
3002 prheader_t *Lphp = NULL;
3003 lwpsinfo_t *Lpsp;
3004 long nstat;
3005 long ninfo;
3006 int rv;
3008 retry:
3009 free(Lhp);
3010 free(Lphp);
3011 if (P->state == PS_RUN)
3012 (void) Pstopstatus(P, PCNULL, 0);
3013 (void) Ppsinfo(P);
3015 if (P->state == PS_STOP)
3016 Psync(P);
3019 * For either live processes or cores, the single LWP case is easy:
3020 * the pstatus_t contains the lwpstatus_t for the only LWP and
3021 * the psinfo_t contains the lwpsinfo_t for the only LWP.
3023 if (P->status.pr_nlwp + P->status.pr_nzomb <= 1)
3024 return (func(cd, &P->status.pr_lwp, &P->psinfo.pr_lwp));
3027 * For the core file multi-LWP case, we just iterate through the
3028 * list of LWP structs we read in from the core file.
3030 if (P->state == PS_DEAD) {
3031 core_info_t *core = P->data;
3032 lwp_info_t *lwp = list_prev(&core->core_lwp_head);
3033 uint_t i;
3035 for (i = 0; i < core->core_nlwp; i++, lwp = list_prev(lwp)) {
3036 sp = (lwp->lwp_psinfo.pr_sname == 'Z')? NULL :
3037 &lwp->lwp_status;
3038 if ((rv = func(cd, sp, &lwp->lwp_psinfo)) != 0)
3039 break;
3042 return (rv);
3046 * For all other cases retrieve the array of lwpstatus_t's and
3047 * lwpsinfo_t's.
3049 if ((Lhp = Plstatus(P)) == NULL)
3050 return (-1);
3051 if ((Lphp = Plpsinfo(P)) == NULL) {
3052 free(Lhp);
3053 return (-1);
3057 * If we are looking at a running process, or one we do not control,
3058 * the active and zombie lwps in the process may have changed since
3059 * we read the process status structure. If so, just start over.
3061 if (Lhp->pr_nent != P->status.pr_nlwp ||
3062 Lphp->pr_nent != P->status.pr_nlwp + P->status.pr_nzomb)
3063 goto retry;
3066 * To be perfectly safe, prescan the two arrays, checking consistency.
3067 * We rely on /proc giving us lwpstatus_t's and lwpsinfo_t's in the
3068 * same order (the lwp directory order) in their respective files.
3069 * We also rely on there being (possibly) more lwpsinfo_t's than
3070 * lwpstatus_t's (the extra lwpsinfo_t's are for zombie lwps).
3072 Lsp = (lwpstatus_t *)(uintptr_t)(Lhp + 1);
3073 Lpsp = (lwpsinfo_t *)(uintptr_t)(Lphp + 1);
3074 nstat = Lhp->pr_nent;
3075 for (ninfo = Lphp->pr_nent; ninfo != 0; ninfo--) {
3076 if (Lpsp->pr_sname != 'Z') {
3078 * Not a zombie lwp; check for matching lwpids.
3080 if (nstat == 0 || Lsp->pr_lwpid != Lpsp->pr_lwpid)
3081 goto retry;
3082 Lsp = (lwpstatus_t *)((uintptr_t)Lsp + Lhp->pr_entsize);
3083 nstat--;
3085 Lpsp = (lwpsinfo_t *)((uintptr_t)Lpsp + Lphp->pr_entsize);
3087 if (nstat != 0)
3088 goto retry;
3091 * Rescan, this time for real.
3093 Lsp = (lwpstatus_t *)(uintptr_t)(Lhp + 1);
3094 Lpsp = (lwpsinfo_t *)(uintptr_t)(Lphp + 1);
3095 for (ninfo = Lphp->pr_nent; ninfo != 0; ninfo--) {
3096 if (Lpsp->pr_sname != 'Z') {
3097 sp = Lsp;
3098 Lsp = (lwpstatus_t *)((uintptr_t)Lsp + Lhp->pr_entsize);
3099 } else {
3100 sp = NULL;
3102 if ((rv = func(cd, sp, Lpsp)) != 0)
3103 break;
3104 Lpsp = (lwpsinfo_t *)((uintptr_t)Lpsp + Lphp->pr_entsize);
3107 free(Lhp);
3108 free(Lphp);
3109 return (rv);
3112 core_content_t
3113 Pcontent(struct ps_prochandle *P)
3115 core_info_t *core = P->data;
3117 if (P->state == PS_DEAD)
3118 return (core->core_content);
3119 if (P->state == PS_IDLE)
3120 return (CC_CONTENT_TEXT | CC_CONTENT_DATA | CC_CONTENT_CTF);
3122 return (CC_CONTENT_ALL);
3126 * =================================================================
3127 * The remainder of the functions in this file are for the
3128 * control of individual LWPs in the controlled process.
3129 * =================================================================
3133 * Find an entry in the process hash table for the specified lwpid.
3134 * The entry will either point to an existing struct ps_lwphandle
3135 * or it will point to an empty slot for a new struct ps_lwphandle.
3137 static struct ps_lwphandle **
3138 Lfind(struct ps_prochandle *P, lwpid_t lwpid)
3140 struct ps_lwphandle **Lp;
3141 struct ps_lwphandle *L;
3143 for (Lp = &P->hashtab[lwpid % (HASHSIZE - 1)];
3144 (L = *Lp) != NULL; Lp = &L->lwp_hash)
3145 if (L->lwp_id == lwpid)
3146 break;
3147 return (Lp);
3151 * Grab an LWP contained within the controlled process.
3152 * Return an opaque pointer to its LWP control structure.
3153 * perr: pointer to error return code.
3155 struct ps_lwphandle *
3156 Lgrab(struct ps_prochandle *P, lwpid_t lwpid, int *perr)
3158 struct ps_lwphandle **Lp;
3159 struct ps_lwphandle *L;
3160 int fd;
3161 char procname[PATH_MAX];
3162 char *fname;
3163 int rc = 0;
3165 (void) mutex_lock(&P->proc_lock);
3167 if (P->state == PS_UNDEAD || P->state == PS_IDLE)
3168 rc = G_NOPROC;
3169 else if (P->hashtab == NULL &&
3170 (P->hashtab = calloc(HASHSIZE, sizeof (struct ps_lwphandle *)))
3171 == NULL)
3172 rc = G_STRANGE;
3173 else if (*(Lp = Lfind(P, lwpid)) != NULL)
3174 rc = G_BUSY;
3175 else if ((L = malloc(sizeof (struct ps_lwphandle))) == NULL)
3176 rc = G_STRANGE;
3177 if (rc) {
3178 *perr = rc;
3179 (void) mutex_unlock(&P->proc_lock);
3180 return (NULL);
3183 (void) memset(L, 0, sizeof (*L));
3184 L->lwp_ctlfd = -1;
3185 L->lwp_statfd = -1;
3186 L->lwp_proc = P;
3187 L->lwp_id = lwpid;
3188 *Lp = L; /* insert into the hash table */
3190 if (P->state == PS_DEAD) { /* core file */
3191 if (getlwpstatus(P, lwpid, &L->lwp_status) == -1) {
3192 rc = G_NOPROC;
3193 goto err;
3195 L->lwp_state = PS_DEAD;
3196 *perr = 0;
3197 (void) mutex_unlock(&P->proc_lock);
3198 return (L);
3202 * Open the /proc/<pid>/lwp/<lwpid> files
3204 (void) snprintf(procname, sizeof (procname), "%s/%d/lwp/%d/",
3205 procfs_path, (int)P->pid, (int)lwpid);
3206 fname = procname + strlen(procname);
3207 (void) set_minfd();
3209 (void) strcpy(fname, "lwpstatus");
3210 if ((fd = open(procname, O_RDONLY)) < 0 ||
3211 (fd = dupfd(fd, 0)) < 0) {
3212 switch (errno) {
3213 case ENOENT:
3214 rc = G_NOPROC;
3215 break;
3216 default:
3217 dprintf("Lgrab: failed to open %s: %s\n",
3218 procname, strerror(errno));
3219 rc = G_STRANGE;
3220 break;
3222 goto err;
3224 L->lwp_statfd = fd;
3226 if (pread(fd, &L->lwp_status, sizeof (L->lwp_status), (off_t)0) < 0) {
3227 switch (errno) {
3228 case ENOENT:
3229 rc = G_NOPROC;
3230 break;
3231 default:
3232 dprintf("Lgrab: failed to read %s: %s\n",
3233 procname, strerror(errno));
3234 rc = G_STRANGE;
3235 break;
3237 goto err;
3240 (void) strcpy(fname, "lwpctl");
3241 if ((fd = open(procname, O_WRONLY)) < 0 ||
3242 (fd = dupfd(fd, 0)) < 0) {
3243 switch (errno) {
3244 case ENOENT:
3245 rc = G_NOPROC;
3246 break;
3247 default:
3248 dprintf("Lgrab: failed to open %s: %s\n",
3249 procname, strerror(errno));
3250 rc = G_STRANGE;
3251 break;
3253 goto err;
3255 L->lwp_ctlfd = fd;
3257 L->lwp_state =
3258 ((L->lwp_status.pr_flags & (PR_STOPPED|PR_ISTOP))
3259 == (PR_STOPPED|PR_ISTOP))?
3260 PS_STOP : PS_RUN;
3262 *perr = 0;
3263 (void) mutex_unlock(&P->proc_lock);
3264 return (L);
3266 err:
3267 Lfree_internal(P, L);
3268 *perr = rc;
3269 (void) mutex_unlock(&P->proc_lock);
3270 return (NULL);
3274 * Return a printable string corresponding to an Lgrab() error return.
3276 const char *
3277 Lgrab_error(int error)
3279 const char *str;
3281 switch (error) {
3282 case G_NOPROC:
3283 str = "no such LWP";
3284 break;
3285 case G_BUSY:
3286 str = "LWP already grabbed";
3287 break;
3288 case G_STRANGE:
3289 str = "unanticipated system error";
3290 break;
3291 default:
3292 str = "unknown error";
3293 break;
3296 return (str);
3300 * Free an LWP control structure.
3302 void
3303 Lfree(struct ps_lwphandle *L)
3305 struct ps_prochandle *P = L->lwp_proc;
3307 (void) mutex_lock(&P->proc_lock);
3308 Lfree_internal(P, L);
3309 (void) mutex_unlock(&P->proc_lock);
3312 static void
3313 Lfree_internal(struct ps_prochandle *P, struct ps_lwphandle *L)
3315 *Lfind(P, L->lwp_id) = L->lwp_hash; /* delete from hash table */
3316 if (L->lwp_ctlfd >= 0)
3317 (void) close(L->lwp_ctlfd);
3318 if (L->lwp_statfd >= 0)
3319 (void) close(L->lwp_statfd);
3321 /* clear out the structure as a precaution against reuse */
3322 (void) memset(L, 0, sizeof (*L));
3323 L->lwp_ctlfd = -1;
3324 L->lwp_statfd = -1;
3326 free(L);
3330 * Return the state of the process, one of the PS_* values.
3333 Lstate(struct ps_lwphandle *L)
3335 return (L->lwp_state);
3339 * Return the open control file descriptor for the LWP.
3340 * Clients must not close this file descriptor, nor use it
3341 * after the LWP is freed.
3344 Lctlfd(struct ps_lwphandle *L)
3346 return (L->lwp_ctlfd);
3350 * Return a pointer to the LWP lwpsinfo structure.
3351 * Clients should not hold on to this pointer indefinitely.
3352 * It will become invalid on Lfree().
3354 const lwpsinfo_t *
3355 Lpsinfo(struct ps_lwphandle *L)
3357 if (Plwp_getpsinfo(L->lwp_proc, L->lwp_id, &L->lwp_psinfo) == -1)
3358 return (NULL);
3360 return (&L->lwp_psinfo);
3364 * Return a pointer to the LWP status structure.
3365 * Clients should not hold on to this pointer indefinitely.
3366 * It will become invalid on Lfree().
3368 const lwpstatus_t *
3369 Lstatus(struct ps_lwphandle *L)
3371 return (&L->lwp_status);
3375 * Given an LWP handle, return the process handle.
3377 struct ps_prochandle *
3378 Lprochandle(struct ps_lwphandle *L)
3380 return (L->lwp_proc);
3384 * Ensure that all cached state is written to the LWP.
3385 * The cached state is the LWP's signal mask and registers.
3387 void
3388 Lsync(struct ps_lwphandle *L)
3390 int ctlfd = L->lwp_ctlfd;
3391 long cmd[2];
3392 iovec_t iov[4];
3393 int n = 0;
3395 if (L->lwp_flags & SETHOLD) {
3396 cmd[0] = PCSHOLD;
3397 iov[n].iov_base = (caddr_t)&cmd[0];
3398 iov[n++].iov_len = sizeof (long);
3399 iov[n].iov_base = (caddr_t)&L->lwp_status.pr_lwphold;
3400 iov[n++].iov_len = sizeof (L->lwp_status.pr_lwphold);
3402 if (L->lwp_flags & SETREGS) {
3403 cmd[1] = PCSREG;
3404 iov[n].iov_base = (caddr_t)&cmd[1];
3405 iov[n++].iov_len = sizeof (long);
3406 iov[n].iov_base = (caddr_t)&L->lwp_status.pr_reg[0];
3407 iov[n++].iov_len = sizeof (L->lwp_status.pr_reg);
3410 if (n == 0 || writev(ctlfd, iov, n) < 0)
3411 return; /* nothing to do or write failed */
3413 L->lwp_flags &= ~(SETHOLD|SETREGS);
3417 * Wait for the specified LWP to stop or terminate.
3418 * Or, just get the current status (PCNULL).
3419 * Or, direct it to stop and get the current status (PCDSTOP).
3421 static int
3422 Lstopstatus(struct ps_lwphandle *L,
3423 long request, /* PCNULL, PCDSTOP, PCSTOP, PCWSTOP */
3424 uint_t msec) /* if non-zero, timeout in milliseconds */
3426 int ctlfd = L->lwp_ctlfd;
3427 long ctl[3];
3428 ssize_t rc;
3429 int err;
3431 switch (L->lwp_state) {
3432 case PS_RUN:
3433 break;
3434 case PS_STOP:
3435 if (request != PCNULL && request != PCDSTOP)
3436 return (0);
3437 break;
3438 case PS_LOST:
3439 if (request != PCNULL) {
3440 errno = EAGAIN;
3441 return (-1);
3443 break;
3444 case PS_UNDEAD:
3445 case PS_DEAD:
3446 if (request != PCNULL) {
3447 errno = ENOENT;
3448 return (-1);
3450 break;
3451 default: /* corrupted state */
3452 dprintf("Lstopstatus: corrupted state: %d\n", L->lwp_state);
3453 errno = EINVAL;
3454 return (-1);
3457 ctl[0] = PCDSTOP;
3458 ctl[1] = PCTWSTOP;
3459 ctl[2] = (long)msec;
3460 rc = 0;
3461 switch (request) {
3462 case PCSTOP:
3463 rc = write(ctlfd, &ctl[0], 3*sizeof (long));
3464 break;
3465 case PCWSTOP:
3466 rc = write(ctlfd, &ctl[1], 2*sizeof (long));
3467 break;
3468 case PCDSTOP:
3469 rc = write(ctlfd, &ctl[0], 1*sizeof (long));
3470 break;
3471 case PCNULL:
3472 if (L->lwp_state == PS_DEAD)
3473 return (0); /* Nothing else to do for cores */
3474 break;
3475 default: /* programming error */
3476 errno = EINVAL;
3477 return (-1);
3479 err = (rc < 0)? errno : 0;
3480 Lsync(L);
3482 if (pread(L->lwp_statfd, &L->lwp_status,
3483 sizeof (L->lwp_status), (off_t)0) < 0)
3484 err = errno;
3486 if (err) {
3487 switch (err) {
3488 case EINTR: /* user typed ctl-C */
3489 case ERESTART:
3490 dprintf("Lstopstatus: EINTR\n");
3491 break;
3492 case EAGAIN: /* we lost control of the the process */
3493 dprintf("Lstopstatus: EAGAIN\n");
3494 L->lwp_state = PS_LOST;
3495 errno = err;
3496 return (-1);
3497 default:
3498 if (_libproc_debug) {
3499 const char *errstr;
3501 switch (request) {
3502 case PCNULL:
3503 errstr = "Lstopstatus PCNULL"; break;
3504 case PCSTOP:
3505 errstr = "Lstopstatus PCSTOP"; break;
3506 case PCDSTOP:
3507 errstr = "Lstopstatus PCDSTOP"; break;
3508 case PCWSTOP:
3509 errstr = "Lstopstatus PCWSTOP"; break;
3510 default:
3511 errstr = "Lstopstatus PC???"; break;
3513 dprintf("%s: %s\n", errstr, strerror(err));
3515 L->lwp_state = PS_UNDEAD;
3516 errno = err;
3517 return (-1);
3521 if ((L->lwp_status.pr_flags & (PR_STOPPED|PR_ISTOP))
3522 != (PR_STOPPED|PR_ISTOP)) {
3523 L->lwp_state = PS_RUN;
3524 if (request == PCNULL || request == PCDSTOP || msec != 0)
3525 return (0);
3526 dprintf("Lstopstatus: LWP is not stopped\n");
3527 errno = EPROTO;
3528 return (-1);
3531 L->lwp_state = PS_STOP;
3533 if (_libproc_debug) /* debugging */
3534 prldump("Lstopstatus", &L->lwp_status);
3536 switch (L->lwp_status.pr_why) {
3537 case PR_SYSENTRY:
3538 case PR_SYSEXIT:
3539 case PR_REQUESTED:
3540 case PR_SIGNALLED:
3541 case PR_FAULTED:
3542 case PR_JOBCONTROL:
3543 case PR_SUSPENDED:
3544 break;
3545 default:
3546 errno = EPROTO;
3547 return (-1);
3550 return (0);
3554 * Wait for the LWP to stop for any reason.
3557 Lwait(struct ps_lwphandle *L, uint_t msec)
3559 return (Lstopstatus(L, PCWSTOP, msec));
3563 * Direct the LWP to stop; wait for it to stop.
3566 Lstop(struct ps_lwphandle *L, uint_t msec)
3568 return (Lstopstatus(L, PCSTOP, msec));
3572 * Direct the LWP to stop; don't wait.
3575 Ldstop(struct ps_lwphandle *L)
3577 return (Lstopstatus(L, PCDSTOP, 0));
3581 * Get the value of one register from stopped LWP.
3584 Lgetareg(struct ps_lwphandle *L, int regno, prgreg_t *preg)
3586 if (regno < 0 || regno >= NPRGREG) {
3587 errno = EINVAL;
3588 return (-1);
3591 if (L->lwp_state != PS_STOP) {
3592 errno = EBUSY;
3593 return (-1);
3596 *preg = L->lwp_status.pr_reg[regno];
3597 return (0);
3601 * Put value of one register into stopped LWP.
3604 Lputareg(struct ps_lwphandle *L, int regno, prgreg_t reg)
3606 if (regno < 0 || regno >= NPRGREG) {
3607 errno = EINVAL;
3608 return (-1);
3611 if (L->lwp_state != PS_STOP) {
3612 errno = EBUSY;
3613 return (-1);
3616 L->lwp_status.pr_reg[regno] = reg;
3617 L->lwp_flags |= SETREGS; /* set registers before continuing */
3618 return (0);
3622 Lsetrun(struct ps_lwphandle *L,
3623 int sig, /* signal to pass to LWP */
3624 int flags) /* PRSTEP|PRSABORT|PRSTOP|PRCSIG|PRCFAULT */
3626 int ctlfd = L->lwp_ctlfd;
3627 int sbits = (PR_DSTOP | PR_ISTOP | PR_ASLEEP);
3629 long ctl[1 + /* PCCFAULT */
3630 1 + sizeof (siginfo_t)/sizeof (long) + /* PCSSIG/PCCSIG */
3631 2 ]; /* PCRUN */
3633 long *ctlp = ctl;
3634 size_t size;
3636 if (L->lwp_state != PS_STOP &&
3637 (L->lwp_status.pr_flags & sbits) == 0) {
3638 errno = EBUSY;
3639 return (-1);
3642 Lsync(L); /* flush registers */
3644 if (flags & PRCFAULT) { /* clear current fault */
3645 *ctlp++ = PCCFAULT;
3646 flags &= ~PRCFAULT;
3649 if (flags & PRCSIG) { /* clear current signal */
3650 *ctlp++ = PCCSIG;
3651 flags &= ~PRCSIG;
3652 } else if (sig && sig != L->lwp_status.pr_cursig) {
3653 /* make current signal */
3654 siginfo_t *infop;
3656 *ctlp++ = PCSSIG;
3657 infop = (siginfo_t *)ctlp;
3658 (void) memset(infop, 0, sizeof (*infop));
3659 infop->si_signo = sig;
3660 ctlp += sizeof (siginfo_t) / sizeof (long);
3663 *ctlp++ = PCRUN;
3664 *ctlp++ = flags;
3665 size = (char *)ctlp - (char *)ctl;
3667 L->lwp_proc->info_valid = 0; /* will need to update map and file info */
3668 L->lwp_proc->state = PS_RUN;
3669 L->lwp_state = PS_RUN;
3671 if (write(ctlfd, ctl, size) != size) {
3672 /* Pretend that a job-stopped LWP is running */
3673 if (errno != EBUSY || L->lwp_status.pr_why != PR_JOBCONTROL)
3674 return (Lstopstatus(L, PCNULL, 0));
3677 return (0);
3681 Lclearsig(struct ps_lwphandle *L)
3683 int ctlfd = L->lwp_ctlfd;
3684 long ctl = PCCSIG;
3686 if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
3687 return (-1);
3688 L->lwp_status.pr_cursig = 0;
3689 return (0);
3693 Lclearfault(struct ps_lwphandle *L)
3695 int ctlfd = L->lwp_ctlfd;
3696 long ctl = PCCFAULT;
3698 if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
3699 return (-1);
3700 return (0);
3704 * Step over a breakpoint, i.e., execute the instruction that
3705 * really belongs at the breakpoint location (the current %pc)
3706 * and leave the LWP stopped at the next instruction.
3709 Lxecbkpt(struct ps_lwphandle *L, ulong_t saved)
3711 struct ps_prochandle *P = L->lwp_proc;
3712 int rv, error;
3714 if (L->lwp_state != PS_STOP) {
3715 errno = EBUSY;
3716 return (-1);
3719 Lsync(L);
3720 error = execute_bkpt(L->lwp_ctlfd,
3721 &P->status.pr_flttrace, &L->lwp_status.pr_lwphold,
3722 L->lwp_status.pr_reg[R_PC], saved);
3723 rv = Lstopstatus(L, PCNULL, 0);
3725 if (error != 0) {
3726 if (L->lwp_status.pr_why == PR_JOBCONTROL &&
3727 error == EBUSY) { /* jobcontrol stop -- back off */
3728 L->lwp_state = PS_RUN;
3729 return (0);
3731 if (error == ENOENT)
3732 return (0);
3733 errno = error;
3734 return (-1);
3737 return (rv);
3741 * Step over a watchpoint, i.e., execute the instruction that was stopped by
3742 * the watchpoint, and then leave the LWP stopped at the next instruction.
3745 Lxecwapt(struct ps_lwphandle *L, const prwatch_t *wp)
3747 struct ps_prochandle *P = L->lwp_proc;
3748 int rv, error;
3750 if (L->lwp_state != PS_STOP) {
3751 errno = EBUSY;
3752 return (-1);
3755 Lsync(L);
3756 error = execute_wapt(L->lwp_ctlfd,
3757 &P->status.pr_flttrace, &L->lwp_status.pr_lwphold, wp);
3758 rv = Lstopstatus(L, PCNULL, 0);
3760 if (error != 0) {
3761 if (L->lwp_status.pr_why == PR_JOBCONTROL &&
3762 error == EBUSY) { /* jobcontrol stop -- back off */
3763 L->lwp_state = PS_RUN;
3764 return (0);
3766 if (error == ENOENT)
3767 return (0);
3768 errno = error;
3769 return (-1);
3772 return (rv);
3776 Lstack(struct ps_lwphandle *L, stack_t *stkp)
3778 struct ps_prochandle *P = L->lwp_proc;
3779 uintptr_t addr = L->lwp_status.pr_ustack;
3781 if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
3782 if (Pread(P, stkp, sizeof (*stkp), addr) != sizeof (*stkp))
3783 return (-1);
3784 #ifdef _LP64
3785 } else {
3786 stack32_t stk32;
3788 if (Pread(P, &stk32, sizeof (stk32), addr) != sizeof (stk32))
3789 return (-1);
3791 stack_32_to_n(&stk32, stkp);
3792 #endif
3795 return (0);
3799 Lmain_stack(struct ps_lwphandle *L, stack_t *stkp)
3801 struct ps_prochandle *P = L->lwp_proc;
3803 if (Lstack(L, stkp) != 0)
3804 return (-1);
3807 * If the SS_ONSTACK flag is set then this LWP is operating on the
3808 * alternate signal stack. We can recover the original stack from
3809 * pr_oldcontext.
3811 if (!(stkp->ss_flags & SS_ONSTACK))
3812 return (0);
3814 if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
3815 ucontext_t *ctxp = (void *)L->lwp_status.pr_oldcontext;
3817 if (Pread(P, stkp, sizeof (*stkp),
3818 (uintptr_t)&ctxp->uc_stack) != sizeof (*stkp))
3819 return (-1);
3820 #ifdef _LP64
3821 } else {
3822 ucontext32_t *ctxp = (void *)L->lwp_status.pr_oldcontext;
3823 stack32_t stk32;
3825 if (Pread(P, &stk32, sizeof (stk32),
3826 (uintptr_t)&ctxp->uc_stack) != sizeof (stk32))
3827 return (-1);
3829 stack_32_to_n(&stk32, stkp);
3830 #endif
3833 return (0);
3837 Lalt_stack(struct ps_lwphandle *L, stack_t *stkp)
3839 if (L->lwp_status.pr_altstack.ss_flags & SS_DISABLE) {
3840 errno = ENODATA;
3841 return (-1);
3844 *stkp = L->lwp_status.pr_altstack;
3846 return (0);
3850 * Add a mapping to the given proc handle. Resizes the array as appropriate and
3851 * manages reference counts on the given file_info_t.
3853 * The 'map_relocate' member is used to tell Psort_mappings() that the
3854 * associated file_map pointer needs to be relocated after the mappings have
3855 * been sorted. It is only set for the first mapping, and has no meaning
3856 * outside these two functions.
3859 Padd_mapping(struct ps_prochandle *P, off64_t off, file_info_t *fp,
3860 prmap_t *pmap)
3862 map_info_t *mp;
3864 if (P->map_count == P->map_alloc) {
3865 size_t next = P->map_alloc ? P->map_alloc * 2 : 16;
3867 if ((P->mappings = reallocarray(P->mappings, next,
3868 sizeof (map_info_t))) == NULL)
3869 return (-1);
3871 P->map_alloc = next;
3874 mp = &P->mappings[P->map_count++];
3876 mp->map_offset = off;
3877 mp->map_pmap = *pmap;
3878 mp->map_relocate = 0;
3879 if ((mp->map_file = fp) != NULL) {
3880 if (fp->file_map == NULL) {
3881 fp->file_map = mp;
3882 mp->map_relocate = 1;
3884 fp->file_ref++;
3887 return (0);
3890 static int
3891 map_sort(const void *a, const void *b)
3893 const map_info_t *ap = a, *bp = b;
3895 if (ap->map_pmap.pr_vaddr < bp->map_pmap.pr_vaddr)
3896 return (-1);
3897 else if (ap->map_pmap.pr_vaddr > bp->map_pmap.pr_vaddr)
3898 return (1);
3899 else
3900 return (0);
3904 * Sort the current set of mappings. Should be called during target
3905 * initialization after all calls to Padd_mapping() have been made.
3907 void
3908 Psort_mappings(struct ps_prochandle *P)
3910 int i;
3911 map_info_t *mp;
3913 qsort(P->mappings, P->map_count, sizeof (map_info_t), map_sort);
3916 * Update all the file_map pointers to refer to the new locations.
3918 for (i = 0; i < P->map_count; i++) {
3919 mp = &P->mappings[i];
3920 if (mp->map_relocate)
3921 mp->map_file->file_map = mp;
3922 mp->map_relocate = 0;
3926 struct ps_prochandle *
3927 Pgrab_ops(pid_t pid, void *data, const ps_ops_t *ops, int flags)
3929 struct ps_prochandle *P;
3931 if ((P = calloc(1, sizeof (*P))) == NULL) {
3932 return (NULL);
3935 Pinit_ops(&P->ops, ops);
3936 (void) mutex_init(&P->proc_lock, USYNC_THREAD, NULL);
3937 P->pid = pid;
3938 P->state = PS_STOP;
3939 P->asfd = -1;
3940 P->ctlfd = -1;
3941 P->statfd = -1;
3942 P->agentctlfd = -1;
3943 P->agentstatfd = -1;
3944 Pinitsym(P);
3945 P->data = data;
3946 Pread_status(P);
3948 if (flags & PGRAB_INCORE) {
3949 P->flags |= INCORE;
3952 return (P);