xref: /titanic_50/usr/src/lib/libproc/common/Pcontrol.c (revision 0a47c91c895e274dd0990009919e30e984364a8b)
1 /*
2  * CDDL HEADER START
3  *
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.
7  *
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.
12  *
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]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Portions Copyright 2007 Chad Mynhier
27  * Copyright 2012 DEY Storage Systems, Inc.  All rights reserved.
28  */
29 
30 #include <assert.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <ctype.h>
35 #include <fcntl.h>
36 #include <string.h>
37 #include <strings.h>
38 #include <memory.h>
39 #include <errno.h>
40 #include <dirent.h>
41 #include <limits.h>
42 #include <signal.h>
43 #include <atomic.h>
44 #include <sys/types.h>
45 #include <sys/uio.h>
46 #include <sys/stat.h>
47 #include <sys/resource.h>
48 #include <sys/param.h>
49 #include <sys/stack.h>
50 #include <sys/fault.h>
51 #include <sys/syscall.h>
52 #include <sys/sysmacros.h>
53 
54 #include "libproc.h"
55 #include "Pcontrol.h"
56 #include "Putil.h"
57 #include "P32ton.h"
58 
59 int	_libproc_debug;		/* set non-zero to enable debugging printfs */
60 int	_libproc_no_qsort;	/* set non-zero to inhibit sorting */
61 				/* of symbol tables */
62 int	_libproc_incore_elf;	/* only use in-core elf data */
63 
64 sigset_t blockable_sigs;	/* signals to block when we need to be safe */
65 static	int	minfd;	/* minimum file descriptor returned by dupfd(fd, 0) */
66 char	procfs_path[PATH_MAX] = "/proc";
67 
68 /*
69  * Function prototypes for static routines in this module.
70  */
71 static	void	deadcheck(struct ps_prochandle *);
72 static	void	restore_tracing_flags(struct ps_prochandle *);
73 static	void	Lfree_internal(struct ps_prochandle *, struct ps_lwphandle *);
74 
75 /*
76  * Read/write interface for live processes: just pread/pwrite the
77  * /proc/<pid>/as file:
78  */
79 
80 static ssize_t
81 Pread_live(struct ps_prochandle *P, void *buf, size_t n, uintptr_t addr)
82 {
83 	return (pread(P->asfd, buf, n, (off_t)addr));
84 }
85 
86 static ssize_t
87 Pwrite_live(struct ps_prochandle *P, const void *buf, size_t n, uintptr_t addr)
88 {
89 	return (pwrite(P->asfd, buf, n, (off_t)addr));
90 }
91 
92 static const ps_rwops_t P_live_ops = { Pread_live, Pwrite_live };
93 
94 /*
95  * This is the library's .init handler.
96  */
97 #pragma init(_libproc_init)
98 void
99 _libproc_init(void)
100 {
101 	_libproc_debug = getenv("LIBPROC_DEBUG") != NULL;
102 	_libproc_no_qsort = getenv("LIBPROC_NO_QSORT") != NULL;
103 	_libproc_incore_elf = getenv("LIBPROC_INCORE_ELF") != NULL;
104 
105 	(void) sigfillset(&blockable_sigs);
106 	(void) sigdelset(&blockable_sigs, SIGKILL);
107 	(void) sigdelset(&blockable_sigs, SIGSTOP);
108 }
109 
110 void
111 Pset_procfs_path(const char *path)
112 {
113 	(void) snprintf(procfs_path, sizeof (procfs_path), "%s", path);
114 }
115 
116 /*
117  * Call set_minfd() once before calling dupfd() several times.
118  * We assume that the application will not reduce its current file
119  * descriptor limit lower than 512 once it has set at least that value.
120  */
121 int
122 set_minfd(void)
123 {
124 	static mutex_t minfd_lock = DEFAULTMUTEX;
125 	struct rlimit rlim;
126 	int fd;
127 
128 	if ((fd = minfd) < 256) {
129 		(void) mutex_lock(&minfd_lock);
130 		if ((fd = minfd) < 256) {
131 			if (getrlimit(RLIMIT_NOFILE, &rlim) != 0)
132 				rlim.rlim_cur = rlim.rlim_max = 0;
133 			if (rlim.rlim_cur >= 512)
134 				fd = 256;
135 			else if ((fd = rlim.rlim_cur / 2) < 3)
136 				fd = 3;
137 			membar_producer();
138 			minfd = fd;
139 		}
140 		(void) mutex_unlock(&minfd_lock);
141 	}
142 	return (fd);
143 }
144 
145 int
146 dupfd(int fd, int dfd)
147 {
148 	int mfd;
149 
150 	/*
151 	 * Make fd be greater than 255 (the 32-bit stdio limit),
152 	 * or at least make it greater than 2 so that the
153 	 * program will work when spawned by init(1m).
154 	 * Also, if dfd is non-zero, dup the fd to be dfd.
155 	 */
156 	if ((mfd = minfd) == 0)
157 		mfd = set_minfd();
158 	if (dfd > 0 || (0 <= fd && fd < mfd)) {
159 		if (dfd <= 0)
160 			dfd = mfd;
161 		dfd = fcntl(fd, F_DUPFD, dfd);
162 		(void) close(fd);
163 		fd = dfd;
164 	}
165 	/*
166 	 * Mark it close-on-exec so any created process doesn't inherit it.
167 	 */
168 	if (fd >= 0)
169 		(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
170 	return (fd);
171 }
172 
173 /*
174  * Create a new controlled process.
175  * Leave it stopped on successful exit from exec() or execve().
176  * Return an opaque pointer to its process control structure.
177  * Return NULL if process cannot be created (fork()/exec() not successful).
178  */
179 struct ps_prochandle *
180 Pxcreate(const char *file,	/* executable file name */
181 	char *const *argv,	/* argument vector */
182 	char *const *envp,	/* environment */
183 	int *perr,	/* pointer to error return code */
184 	char *path,	/* if non-null, holds exec path name on return */
185 	size_t len)	/* size of the path buffer */
186 {
187 	char execpath[PATH_MAX];
188 	char procname[PATH_MAX];
189 	struct ps_prochandle *P;
190 	pid_t pid;
191 	int fd;
192 	char *fname;
193 	int rc;
194 	int lasterrno = 0;
195 
196 	if (len == 0)	/* zero length, no path */
197 		path = NULL;
198 	if (path != NULL)
199 		*path = '\0';
200 
201 	if ((P = malloc(sizeof (struct ps_prochandle))) == NULL) {
202 		*perr = C_STRANGE;
203 		return (NULL);
204 	}
205 
206 	if ((pid = fork1()) == -1) {
207 		free(P);
208 		*perr = C_FORK;
209 		return (NULL);
210 	}
211 
212 	if (pid == 0) {			/* child process */
213 		id_t id;
214 		extern char **environ;
215 
216 		/*
217 		 * If running setuid or setgid, reset credentials to normal.
218 		 */
219 		if ((id = getgid()) != getegid())
220 			(void) setgid(id);
221 		if ((id = getuid()) != geteuid())
222 			(void) setuid(id);
223 
224 		Pcreate_callback(P);	/* execute callback (see below) */
225 		(void) pause();		/* wait for PRSABORT from parent */
226 
227 		/*
228 		 * This is ugly.  There is no execvep() function that takes a
229 		 * path and an environment.  We cheat here by replacing the
230 		 * global 'environ' variable right before we call this.
231 		 */
232 		if (envp)
233 			environ = (char **)envp;
234 
235 		(void) execvp(file, argv);  /* execute the program */
236 		_exit(127);
237 	}
238 
239 	/*
240 	 * Initialize the process structure.
241 	 */
242 	(void) memset(P, 0, sizeof (*P));
243 	(void) mutex_init(&P->proc_lock, USYNC_THREAD, NULL);
244 	P->flags |= CREATED;
245 	P->state = PS_RUN;
246 	P->pid = pid;
247 	P->asfd = -1;
248 	P->ctlfd = -1;
249 	P->statfd = -1;
250 	P->agentctlfd = -1;
251 	P->agentstatfd = -1;
252 	P->ops = &P_live_ops;
253 	Pinitsym(P);
254 
255 	/*
256 	 * Open the /proc/pid files.
257 	 */
258 	(void) snprintf(procname, sizeof (procname), "%s/%d/",
259 	    procfs_path, (int)pid);
260 	fname = procname + strlen(procname);
261 	(void) set_minfd();
262 
263 	/*
264 	 * Exclusive write open advises others not to interfere.
265 	 * There is no reason for any of these open()s to fail.
266 	 */
267 	(void) strcpy(fname, "as");
268 	if ((fd = open(procname, (O_RDWR|O_EXCL))) < 0 ||
269 	    (fd = dupfd(fd, 0)) < 0) {
270 		dprintf("Pcreate: failed to open %s: %s\n",
271 		    procname, strerror(errno));
272 		rc = C_STRANGE;
273 		goto bad;
274 	}
275 	P->asfd = fd;
276 
277 	(void) strcpy(fname, "status");
278 	if ((fd = open(procname, O_RDONLY)) < 0 ||
279 	    (fd = dupfd(fd, 0)) < 0) {
280 		dprintf("Pcreate: failed to open %s: %s\n",
281 		    procname, strerror(errno));
282 		rc = C_STRANGE;
283 		goto bad;
284 	}
285 	P->statfd = fd;
286 
287 	(void) strcpy(fname, "ctl");
288 	if ((fd = open(procname, O_WRONLY)) < 0 ||
289 	    (fd = dupfd(fd, 0)) < 0) {
290 		dprintf("Pcreate: failed to open %s: %s\n",
291 		    procname, strerror(errno));
292 		rc = C_STRANGE;
293 		goto bad;
294 	}
295 	P->ctlfd = fd;
296 
297 	(void) Pstop(P, 0);	/* stop the controlled process */
298 
299 	/*
300 	 * Wait for process to sleep in pause().
301 	 * If the process has already called pause(), then it should be
302 	 * stopped (PR_REQUESTED) while asleep in pause and we are done.
303 	 * Else we set up to catch entry/exit to pause() and set the process
304 	 * running again, expecting it to stop when it reaches pause().
305 	 * There is no reason for this to fail other than an interrupt.
306 	 */
307 	(void) Psysentry(P, SYS_pause, 1);
308 	(void) Psysexit(P, SYS_pause, 1);
309 	for (;;) {
310 		if (P->state == PS_STOP &&
311 		    P->status.pr_lwp.pr_syscall == SYS_pause &&
312 		    (P->status.pr_lwp.pr_why == PR_REQUESTED ||
313 		    P->status.pr_lwp.pr_why == PR_SYSENTRY ||
314 		    P->status.pr_lwp.pr_why == PR_SYSEXIT))
315 			break;
316 
317 		if (P->state != PS_STOP ||	/* interrupt or process died */
318 		    Psetrun(P, 0, 0) != 0) {	/* can't restart */
319 			if (errno == EINTR || errno == ERESTART)
320 				rc = C_INTR;
321 			else {
322 				dprintf("Pcreate: Psetrun failed: %s\n",
323 				    strerror(errno));
324 				rc = C_STRANGE;
325 			}
326 			goto bad;
327 		}
328 
329 		(void) Pwait(P, 0);
330 	}
331 	(void) Psysentry(P, SYS_pause, 0);
332 	(void) Psysexit(P, SYS_pause, 0);
333 
334 	/*
335 	 * Kick the process off the pause() and catch
336 	 * it again on entry to exec() or exit().
337 	 */
338 	(void) Psysentry(P, SYS_exit, 1);
339 	(void) Psysentry(P, SYS_execve, 1);
340 	if (Psetrun(P, 0, PRSABORT) == -1) {
341 		dprintf("Pcreate: Psetrun failed: %s\n", strerror(errno));
342 		rc = C_STRANGE;
343 		goto bad;
344 	}
345 	(void) Pwait(P, 0);
346 	if (P->state != PS_STOP) {
347 		dprintf("Pcreate: Pwait failed: %s\n", strerror(errno));
348 		rc = C_STRANGE;
349 		goto bad;
350 	}
351 
352 	/*
353 	 * Move the process through instances of failed exec()s
354 	 * to reach the point of stopped on successful exec().
355 	 */
356 	(void) Psysexit(P, SYS_execve, TRUE);
357 
358 	while (P->state == PS_STOP &&
359 	    P->status.pr_lwp.pr_why == PR_SYSENTRY &&
360 	    P->status.pr_lwp.pr_what == SYS_execve) {
361 		/*
362 		 * Fetch the exec path name now, before we complete
363 		 * the exec().  We may lose the process and be unable
364 		 * to get the information later.
365 		 */
366 		(void) Pread_string(P, execpath, sizeof (execpath),
367 		    (off_t)P->status.pr_lwp.pr_sysarg[0]);
368 		if (path != NULL)
369 			(void) strncpy(path, execpath, len);
370 		/*
371 		 * Set the process running and wait for
372 		 * it to stop on exit from the exec().
373 		 */
374 		(void) Psetrun(P, 0, 0);
375 		(void) Pwait(P, 0);
376 
377 		if (P->state == PS_LOST &&		/* we lost control */
378 		    Preopen(P) != 0) {		/* and we can't get it back */
379 			rc = C_PERM;
380 			goto bad;
381 		}
382 
383 		/*
384 		 * If the exec() failed, continue the loop, expecting
385 		 * there to be more attempts to exec(), based on PATH.
386 		 */
387 		if (P->state == PS_STOP &&
388 		    P->status.pr_lwp.pr_why == PR_SYSEXIT &&
389 		    P->status.pr_lwp.pr_what == SYS_execve &&
390 		    (lasterrno = P->status.pr_lwp.pr_errno) != 0) {
391 			/*
392 			 * The exec() failed.  Set the process running and
393 			 * wait for it to stop on entry to the next exec().
394 			 */
395 			(void) Psetrun(P, 0, 0);
396 			(void) Pwait(P, 0);
397 
398 			continue;
399 		}
400 		break;
401 	}
402 
403 	if (P->state == PS_STOP &&
404 	    P->status.pr_lwp.pr_why == PR_SYSEXIT &&
405 	    P->status.pr_lwp.pr_what == SYS_execve &&
406 	    P->status.pr_lwp.pr_errno == 0) {
407 		/*
408 		 * The process is stopped on successful exec() or execve().
409 		 * Turn off all tracing flags and return success.
410 		 */
411 		restore_tracing_flags(P);
412 #ifndef _LP64
413 		/* We must be a 64-bit process to deal with a 64-bit process */
414 		if (P->status.pr_dmodel == PR_MODEL_LP64) {
415 			rc = C_LP64;
416 			goto bad;
417 		}
418 #endif
419 		/*
420 		 * Set run-on-last-close so the controlled process
421 		 * runs even if we die on a signal.
422 		 */
423 		(void) Psetflags(P, PR_RLC);
424 		*perr = 0;
425 		return (P);
426 	}
427 
428 	rc = lasterrno == ENOENT ? C_NOENT : C_NOEXEC;
429 
430 bad:
431 	(void) kill(pid, SIGKILL);
432 	if (path != NULL && rc != C_PERM && rc != C_LP64)
433 		*path = '\0';
434 	Pfree(P);
435 	*perr = rc;
436 	return (NULL);
437 }
438 
439 struct ps_prochandle *
440 Pcreate(
441 	const char *file,	/* executable file name */
442 	char *const *argv,	/* argument vector */
443 	int *perr,	/* pointer to error return code */
444 	char *path,	/* if non-null, holds exec path name on return */
445 	size_t len)	/* size of the path buffer */
446 {
447 	return (Pxcreate(file, argv, NULL, perr, path, len));
448 }
449 
450 /*
451  * Return a printable string corresponding to a Pcreate() error return.
452  */
453 const char *
454 Pcreate_error(int error)
455 {
456 	const char *str;
457 
458 	switch (error) {
459 	case C_FORK:
460 		str = "cannot fork";
461 		break;
462 	case C_PERM:
463 		str = "file is set-id or unreadable";
464 		break;
465 	case C_NOEXEC:
466 		str = "cannot execute file";
467 		break;
468 	case C_INTR:
469 		str = "operation interrupted";
470 		break;
471 	case C_LP64:
472 		str = "program is _LP64, self is not";
473 		break;
474 	case C_STRANGE:
475 		str = "unanticipated system error";
476 		break;
477 	case C_NOENT:
478 		str = "cannot find executable file";
479 		break;
480 	default:
481 		str = "unknown error";
482 		break;
483 	}
484 
485 	return (str);
486 }
487 
488 /*
489  * Callback to execute in each child process created with Pcreate() after fork
490  * but before it execs the new process image.  By default, we do nothing, but
491  * by calling this function we allow the client program to define its own
492  * version of the function which will interpose on our empty default.  This
493  * may be useful for clients that need to modify signal dispositions, terminal
494  * attributes, or process group and session properties for each new victim.
495  */
496 /*ARGSUSED*/
497 void
498 Pcreate_callback(struct ps_prochandle *P)
499 {
500 	/* nothing to do here */
501 }
502 
503 /*
504  * Grab an existing process.
505  * Return an opaque pointer to its process control structure.
506  *
507  * pid:		UNIX process ID.
508  * flags:
509  *	PGRAB_RETAIN	Retain tracing flags (default clears all tracing flags).
510  *	PGRAB_FORCE	Grab regardless of whether process is already traced.
511  *	PGRAB_RDONLY	Open the address space file O_RDONLY instead of O_RDWR,
512  *                      and do not open the process control file.
513  *	PGRAB_NOSTOP	Open the process but do not force it to stop.
514  * perr:	pointer to error return code.
515  */
516 struct ps_prochandle *
517 Pgrab(pid_t pid, int flags, int *perr)
518 {
519 	struct ps_prochandle *P;
520 	int fd, omode;
521 	char procname[PATH_MAX];
522 	char *fname;
523 	int rc = 0;
524 
525 	/*
526 	 * PGRAB_RDONLY means that we do not open the /proc/<pid>/control file,
527 	 * and so it implies RETAIN and NOSTOP since both require control.
528 	 */
529 	if (flags & PGRAB_RDONLY)
530 		flags |= PGRAB_RETAIN | PGRAB_NOSTOP;
531 
532 	if ((P = malloc(sizeof (struct ps_prochandle))) == NULL) {
533 		*perr = G_STRANGE;
534 		return (NULL);
535 	}
536 
537 	P->asfd = -1;
538 	P->ctlfd = -1;
539 	P->statfd = -1;
540 
541 again:	/* Come back here if we lose it in the Window of Vulnerability */
542 	if (P->ctlfd >= 0)
543 		(void) close(P->ctlfd);
544 	if (P->asfd >= 0)
545 		(void) close(P->asfd);
546 	if (P->statfd >= 0)
547 		(void) close(P->statfd);
548 	(void) memset(P, 0, sizeof (*P));
549 	(void) mutex_init(&P->proc_lock, USYNC_THREAD, NULL);
550 	P->ctlfd = -1;
551 	P->asfd = -1;
552 	P->statfd = -1;
553 	P->agentctlfd = -1;
554 	P->agentstatfd = -1;
555 	P->ops = &P_live_ops;
556 	Pinitsym(P);
557 
558 	/*
559 	 * Open the /proc/pid files
560 	 */
561 	(void) snprintf(procname, sizeof (procname), "%s/%d/",
562 	    procfs_path, (int)pid);
563 	fname = procname + strlen(procname);
564 	(void) set_minfd();
565 
566 	/*
567 	 * Request exclusive open to avoid grabbing someone else's
568 	 * process and to prevent others from interfering afterwards.
569 	 * If this fails and the 'PGRAB_FORCE' flag is set, attempt to
570 	 * open non-exclusively.
571 	 */
572 	(void) strcpy(fname, "as");
573 	omode = (flags & PGRAB_RDONLY) ? O_RDONLY : O_RDWR;
574 
575 	if (((fd = open(procname, omode | O_EXCL)) < 0 &&
576 	    (fd = ((flags & PGRAB_FORCE)? open(procname, omode) : -1)) < 0) ||
577 	    (fd = dupfd(fd, 0)) < 0) {
578 		switch (errno) {
579 		case ENOENT:
580 			rc = G_NOPROC;
581 			break;
582 		case EACCES:
583 		case EPERM:
584 			rc = G_PERM;
585 			break;
586 		case EMFILE:
587 			rc = G_NOFD;
588 			break;
589 		case EBUSY:
590 			if (!(flags & PGRAB_FORCE) || geteuid() != 0) {
591 				rc = G_BUSY;
592 				break;
593 			}
594 			/* FALLTHROUGH */
595 		default:
596 			dprintf("Pgrab: failed to open %s: %s\n",
597 			    procname, strerror(errno));
598 			rc = G_STRANGE;
599 			break;
600 		}
601 		goto err;
602 	}
603 	P->asfd = fd;
604 
605 	(void) strcpy(fname, "status");
606 	if ((fd = open(procname, O_RDONLY)) < 0 ||
607 	    (fd = dupfd(fd, 0)) < 0) {
608 		switch (errno) {
609 		case ENOENT:
610 			rc = G_NOPROC;
611 			break;
612 		case EMFILE:
613 			rc = G_NOFD;
614 			break;
615 		default:
616 			dprintf("Pgrab: failed to open %s: %s\n",
617 			    procname, strerror(errno));
618 			rc = G_STRANGE;
619 			break;
620 		}
621 		goto err;
622 	}
623 	P->statfd = fd;
624 
625 	if (!(flags & PGRAB_RDONLY)) {
626 		(void) strcpy(fname, "ctl");
627 		if ((fd = open(procname, O_WRONLY)) < 0 ||
628 		    (fd = dupfd(fd, 0)) < 0) {
629 			switch (errno) {
630 			case ENOENT:
631 				rc = G_NOPROC;
632 				break;
633 			case EMFILE:
634 				rc = G_NOFD;
635 				break;
636 			default:
637 				dprintf("Pgrab: failed to open %s: %s\n",
638 				    procname, strerror(errno));
639 				rc = G_STRANGE;
640 				break;
641 			}
642 			goto err;
643 		}
644 		P->ctlfd = fd;
645 	}
646 
647 	P->state = PS_RUN;
648 	P->pid = pid;
649 
650 	/*
651 	 * We are now in the Window of Vulnerability (WoV).  The process may
652 	 * exec() a setuid/setgid or unreadable object file between the open()
653 	 * and the PCSTOP.  We will get EAGAIN in this case and must start over.
654 	 * As Pstopstatus will trigger the first read() from a /proc file,
655 	 * we also need to handle EOVERFLOW here when 32-bit as an indicator
656 	 * that this process is 64-bit.  Finally, if the process has become
657 	 * a zombie (PS_UNDEAD) while we were trying to grab it, just remain
658 	 * silent about this and pretend there was no process.
659 	 */
660 	if (Pstopstatus(P, PCNULL, 0) != 0) {
661 #ifndef _LP64
662 		if (errno == EOVERFLOW) {
663 			rc = G_LP64;
664 			goto err;
665 		}
666 #endif
667 		if (P->state == PS_LOST) {	/* WoV */
668 			(void) mutex_destroy(&P->proc_lock);
669 			goto again;
670 		}
671 
672 		if (P->state == PS_UNDEAD)
673 			rc = G_NOPROC;
674 		else
675 			rc = G_STRANGE;
676 
677 		goto err;
678 	}
679 
680 	/*
681 	 * If the process is a system process, we can't control it even as root
682 	 */
683 	if (P->status.pr_flags & PR_ISSYS) {
684 		rc = G_SYS;
685 		goto err;
686 	}
687 #ifndef _LP64
688 	/*
689 	 * We must be a 64-bit process to deal with a 64-bit process
690 	 */
691 	if (P->status.pr_dmodel == PR_MODEL_LP64) {
692 		rc = G_LP64;
693 		goto err;
694 	}
695 #endif
696 
697 	/*
698 	 * Remember the status for use by Prelease().
699 	 */
700 	P->orig_status = P->status;	/* structure copy */
701 
702 	/*
703 	 * Before stopping the process, make sure we are not grabbing ourselves.
704 	 * If we are, make sure we are doing it PGRAB_RDONLY.
705 	 */
706 	if (pid == getpid()) {
707 		/*
708 		 * Verify that the process is really ourself:
709 		 * Set a magic number, read it through the
710 		 * /proc file and see if the results match.
711 		 */
712 		uint32_t magic1 = 0;
713 		uint32_t magic2 = 2;
714 
715 		errno = 0;
716 
717 		if (Pread(P, &magic2, sizeof (magic2), (uintptr_t)&magic1)
718 		    == sizeof (magic2) &&
719 		    magic2 == 0 &&
720 		    (magic1 = 0xfeedbeef) &&
721 		    Pread(P, &magic2, sizeof (magic2), (uintptr_t)&magic1)
722 		    == sizeof (magic2) &&
723 		    magic2 == 0xfeedbeef &&
724 		    !(flags & PGRAB_RDONLY)) {
725 			rc = G_SELF;
726 			goto err;
727 		}
728 	}
729 
730 	/*
731 	 * If the process is already stopped or has been directed
732 	 * to stop via /proc, do not set run-on-last-close.
733 	 */
734 	if (!(P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) &&
735 	    !(flags & PGRAB_RDONLY)) {
736 		/*
737 		 * Mark the process run-on-last-close so
738 		 * it runs even if we die from SIGKILL.
739 		 */
740 		if (Psetflags(P, PR_RLC) != 0) {
741 			if (errno == EAGAIN) {	/* WoV */
742 				(void) mutex_destroy(&P->proc_lock);
743 				goto again;
744 			}
745 			if (errno == ENOENT)	/* No complaint about zombies */
746 				rc = G_ZOMB;
747 			else {
748 				dprintf("Pgrab: failed to set RLC\n");
749 				rc = G_STRANGE;
750 			}
751 			goto err;
752 		}
753 	}
754 
755 	/*
756 	 * If a stop directive is pending and the process has not yet stopped,
757 	 * then synchronously wait for the stop directive to take effect.
758 	 * Limit the time spent waiting for the process to stop by iterating
759 	 * at most 10 times. The time-out of 20 ms corresponds to the time
760 	 * between sending the stop directive and the process actually stopped
761 	 * as measured by DTrace on a slow, busy system. If the process doesn't
762 	 * stop voluntarily, clear the PR_DSTOP flag so that the code below
763 	 * forces the process to stop.
764 	 */
765 	if (!(flags & PGRAB_RDONLY)) {
766 		int niter = 0;
767 		while ((P->status.pr_lwp.pr_flags & (PR_STOPPED|PR_DSTOP)) ==
768 		    PR_DSTOP && niter < 10 &&
769 		    Pstopstatus(P, PCTWSTOP, 20) != 0) {
770 			niter++;
771 			if (flags & PGRAB_NOSTOP)
772 				break;
773 		}
774 		if (niter == 10 && !(flags & PGRAB_NOSTOP)) {
775 			/* Try it harder down below */
776 			P->status.pr_lwp.pr_flags &= ~PR_DSTOP;
777 		}
778 	}
779 
780 	/*
781 	 * If the process is not already stopped or directed to stop
782 	 * and PGRAB_NOSTOP was not specified, stop the process now.
783 	 */
784 	if (!(P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) &&
785 	    !(flags & PGRAB_NOSTOP)) {
786 		/*
787 		 * Stop the process, get its status and signal/syscall masks.
788 		 */
789 		if (((P->status.pr_lwp.pr_flags & PR_STOPPED) &&
790 		    Pstopstatus(P, PCDSTOP, 0) != 0) ||
791 		    Pstopstatus(P, PCSTOP, 2000) != 0) {
792 #ifndef _LP64
793 			if (errno == EOVERFLOW) {
794 				rc = G_LP64;
795 				goto err;
796 			}
797 #endif
798 			if (P->state == PS_LOST) {	/* WoV */
799 				(void) mutex_destroy(&P->proc_lock);
800 				goto again;
801 			}
802 			if ((errno != EINTR && errno != ERESTART) ||
803 			    (P->state != PS_STOP &&
804 			    !(P->status.pr_flags & PR_DSTOP))) {
805 				if (P->state != PS_RUN && errno != ENOENT) {
806 					dprintf("Pgrab: failed to PCSTOP\n");
807 					rc = G_STRANGE;
808 				} else {
809 					rc = G_ZOMB;
810 				}
811 				goto err;
812 			}
813 		}
814 
815 		/*
816 		 * Process should now either be stopped via /proc or there
817 		 * should be an outstanding stop directive.
818 		 */
819 		if (!(P->status.pr_flags & (PR_ISTOP|PR_DSTOP))) {
820 			dprintf("Pgrab: process is not stopped\n");
821 			rc = G_STRANGE;
822 			goto err;
823 		}
824 #ifndef _LP64
825 		/*
826 		 * Test this again now because the 32-bit victim process may
827 		 * have exec'd a 64-bit process in the meantime.
828 		 */
829 		if (P->status.pr_dmodel == PR_MODEL_LP64) {
830 			rc = G_LP64;
831 			goto err;
832 		}
833 #endif
834 	}
835 
836 	/*
837 	 * Cancel all tracing flags unless the PGRAB_RETAIN flag is set.
838 	 */
839 	if (!(flags & PGRAB_RETAIN)) {
840 		(void) Psysentry(P, 0, FALSE);
841 		(void) Psysexit(P, 0, FALSE);
842 		(void) Psignal(P, 0, FALSE);
843 		(void) Pfault(P, 0, FALSE);
844 		Psync(P);
845 	}
846 
847 	*perr = 0;
848 	return (P);
849 
850 err:
851 	Pfree(P);
852 	*perr = rc;
853 	return (NULL);
854 }
855 
856 /*
857  * Return a printable string corresponding to a Pgrab() error return.
858  */
859 const char *
860 Pgrab_error(int error)
861 {
862 	const char *str;
863 
864 	switch (error) {
865 	case G_NOPROC:
866 		str = "no such process";
867 		break;
868 	case G_NOCORE:
869 		str = "no such core file";
870 		break;
871 	case G_NOPROCORCORE:
872 		str = "no such process or core file";
873 		break;
874 	case G_NOEXEC:
875 		str = "cannot find executable file";
876 		break;
877 	case G_ZOMB:
878 		str = "zombie process";
879 		break;
880 	case G_PERM:
881 		str = "permission denied";
882 		break;
883 	case G_BUSY:
884 		str = "process is traced";
885 		break;
886 	case G_SYS:
887 		str = "system process";
888 		break;
889 	case G_SELF:
890 		str = "attempt to grab self";
891 		break;
892 	case G_INTR:
893 		str = "operation interrupted";
894 		break;
895 	case G_LP64:
896 		str = "program is _LP64, self is not";
897 		break;
898 	case G_FORMAT:
899 		str = "file is not an ELF core file";
900 		break;
901 	case G_ELF:
902 		str = "libelf error";
903 		break;
904 	case G_NOTE:
905 		str = "core file is corrupt or missing required data";
906 		break;
907 	case G_STRANGE:
908 		str = "unanticipated system error";
909 		break;
910 	case G_ISAINVAL:
911 		str = "wrong ELF machine type";
912 		break;
913 	case G_BADLWPS:
914 		str = "bad lwp specification";
915 		break;
916 	case G_NOFD:
917 		str = "too many open files";
918 		break;
919 	default:
920 		str = "unknown error";
921 		break;
922 	}
923 
924 	return (str);
925 }
926 
927 /*
928  * Free a process control structure.
929  * Close the file descriptors but don't do the Prelease logic.
930  */
931 void
932 Pfree(struct ps_prochandle *P)
933 {
934 	uint_t i;
935 
936 	if (P->core != NULL) {
937 		extern void __priv_free_info(void *);
938 		lwp_info_t *nlwp, *lwp = list_next(&P->core->core_lwp_head);
939 
940 		for (i = 0; i < P->core->core_nlwp; i++, lwp = nlwp) {
941 			nlwp = list_next(lwp);
942 #ifdef __sparc
943 			if (lwp->lwp_gwins != NULL)
944 				free(lwp->lwp_gwins);
945 			if (lwp->lwp_xregs != NULL)
946 				free(lwp->lwp_xregs);
947 			if (lwp->lwp_asrs != NULL)
948 				free(lwp->lwp_asrs);
949 #endif
950 			free(lwp);
951 		}
952 
953 		if (P->core->core_platform != NULL)
954 			free(P->core->core_platform);
955 		if (P->core->core_uts != NULL)
956 			free(P->core->core_uts);
957 		if (P->core->core_cred != NULL)
958 			free(P->core->core_cred);
959 		if (P->core->core_priv != NULL)
960 			free(P->core->core_priv);
961 		if (P->core->core_privinfo != NULL)
962 			__priv_free_info(P->core->core_privinfo);
963 		if (P->core->core_ppii != NULL)
964 			free(P->core->core_ppii);
965 		if (P->core->core_zonename != NULL)
966 			free(P->core->core_zonename);
967 #if defined(__i386) || defined(__amd64)
968 		if (P->core->core_ldt != NULL)
969 			free(P->core->core_ldt);
970 #endif
971 
972 		free(P->core);
973 	}
974 
975 	if (P->ucaddrs != NULL) {
976 		free(P->ucaddrs);
977 		P->ucaddrs = NULL;
978 		P->ucnelems = 0;
979 	}
980 
981 	(void) mutex_lock(&P->proc_lock);
982 	if (P->hashtab != NULL) {
983 		struct ps_lwphandle *L;
984 		for (i = 0; i < HASHSIZE; i++) {
985 			while ((L = P->hashtab[i]) != NULL)
986 				Lfree_internal(P, L);
987 		}
988 		free(P->hashtab);
989 	}
990 
991 	while (P->num_fd > 0) {
992 		fd_info_t *fip = list_next(&P->fd_head);
993 		list_unlink(fip);
994 		free(fip);
995 		P->num_fd--;
996 	}
997 	(void) mutex_unlock(&P->proc_lock);
998 	(void) mutex_destroy(&P->proc_lock);
999 
1000 	if (P->agentctlfd >= 0)
1001 		(void) close(P->agentctlfd);
1002 	if (P->agentstatfd >= 0)
1003 		(void) close(P->agentstatfd);
1004 	if (P->ctlfd >= 0)
1005 		(void) close(P->ctlfd);
1006 	if (P->asfd >= 0)
1007 		(void) close(P->asfd);
1008 	if (P->statfd >= 0)
1009 		(void) close(P->statfd);
1010 	Preset_maps(P);
1011 
1012 	/* clear out the structure as a precaution against reuse */
1013 	(void) memset(P, 0, sizeof (*P));
1014 	P->ctlfd = -1;
1015 	P->asfd = -1;
1016 	P->statfd = -1;
1017 	P->agentctlfd = -1;
1018 	P->agentstatfd = -1;
1019 
1020 	free(P);
1021 }
1022 
1023 /*
1024  * Return the state of the process, one of the PS_* values.
1025  */
1026 int
1027 Pstate(struct ps_prochandle *P)
1028 {
1029 	return (P->state);
1030 }
1031 
1032 /*
1033  * Return the open address space file descriptor for the process.
1034  * Clients must not close this file descriptor, not use it
1035  * after the process is freed.
1036  */
1037 int
1038 Pasfd(struct ps_prochandle *P)
1039 {
1040 	return (P->asfd);
1041 }
1042 
1043 /*
1044  * Return the open control file descriptor for the process.
1045  * Clients must not close this file descriptor, not use it
1046  * after the process is freed.
1047  */
1048 int
1049 Pctlfd(struct ps_prochandle *P)
1050 {
1051 	return (P->ctlfd);
1052 }
1053 
1054 /*
1055  * Return a pointer to the process psinfo structure.
1056  * Clients should not hold on to this pointer indefinitely.
1057  * It will become invalid on Prelease().
1058  */
1059 const psinfo_t *
1060 Ppsinfo(struct ps_prochandle *P)
1061 {
1062 	if (P->state == PS_IDLE) {
1063 		errno = ENODATA;
1064 		return (NULL);
1065 	}
1066 
1067 	if (P->state != PS_DEAD && proc_get_psinfo(P->pid, &P->psinfo) == -1)
1068 		return (NULL);
1069 
1070 	return (&P->psinfo);
1071 }
1072 
1073 /*
1074  * Return a pointer to the process status structure.
1075  * Clients should not hold on to this pointer indefinitely.
1076  * It will become invalid on Prelease().
1077  */
1078 const pstatus_t *
1079 Pstatus(struct ps_prochandle *P)
1080 {
1081 	return (&P->status);
1082 }
1083 
1084 /*
1085  * Fill in a pointer to a process credentials structure.  The ngroups parameter
1086  * is the number of supplementary group entries allocated in the caller's cred
1087  * structure.  It should equal zero or one unless extra space has been
1088  * allocated for the group list by the caller.
1089  */
1090 int
1091 Pcred(struct ps_prochandle *P, prcred_t *pcrp, int ngroups)
1092 {
1093 	if (P->state == PS_IDLE) {
1094 		errno = ENODATA;
1095 		return (-1);
1096 	}
1097 
1098 	if (P->state != PS_DEAD)
1099 		return (proc_get_cred(P->pid, pcrp, ngroups));
1100 
1101 	if (P->core->core_cred != NULL) {
1102 		/*
1103 		 * Avoid returning more supplementary group data than the
1104 		 * caller has allocated in their buffer.  We expect them to
1105 		 * check pr_ngroups afterward and potentially call us again.
1106 		 */
1107 		ngroups = MIN(ngroups, P->core->core_cred->pr_ngroups);
1108 
1109 		(void) memcpy(pcrp, P->core->core_cred,
1110 		    sizeof (prcred_t) + (ngroups - 1) * sizeof (gid_t));
1111 
1112 		return (0);
1113 	}
1114 
1115 	errno = ENODATA;
1116 	return (-1);
1117 }
1118 
1119 #if defined(__i386) || defined(__amd64)
1120 /*
1121  * Fill in a pointer to a process LDT structure.
1122  * The caller provides a buffer of size 'nldt * sizeof (struct ssd)';
1123  * If pldt == NULL or nldt == 0, we return the number of existing LDT entries.
1124  * Otherwise we return the actual number of LDT entries fetched (<= nldt).
1125  */
1126 int
1127 Pldt(struct ps_prochandle *P, struct ssd *pldt, int nldt)
1128 {
1129 	if (P->state == PS_IDLE) {
1130 		errno = ENODATA;
1131 		return (-1);
1132 	}
1133 
1134 	if (P->state != PS_DEAD)
1135 		return (proc_get_ldt(P->pid, pldt, nldt));
1136 
1137 	if (pldt == NULL || nldt == 0)
1138 		return (P->core->core_nldt);
1139 
1140 	if (P->core->core_ldt != NULL) {
1141 		nldt = MIN(nldt, P->core->core_nldt);
1142 
1143 		(void) memcpy(pldt, P->core->core_ldt,
1144 		    nldt * sizeof (struct ssd));
1145 
1146 		return (nldt);
1147 	}
1148 
1149 	errno = ENODATA;
1150 	return (-1);
1151 }
1152 #endif	/* __i386 */
1153 
1154 /*
1155  * Fill in a pointer to a process privilege structure.
1156  */
1157 ssize_t
1158 Ppriv(struct ps_prochandle *P, prpriv_t *pprv, size_t size)
1159 {
1160 	if (P->state != PS_DEAD) {
1161 		prpriv_t *pp = proc_get_priv(P->pid);
1162 		if (pp != NULL) {
1163 			size = MIN(size, PRIV_PRPRIV_SIZE(pp));
1164 			(void) memcpy(pprv, pp, size);
1165 			free(pp);
1166 			return (size);
1167 		}
1168 		return (-1);
1169 	}
1170 
1171 	if (P->core->core_priv != NULL) {
1172 		size = MIN(P->core->core_priv_size, size);
1173 		(void) memcpy(pprv, P->core->core_priv, size);
1174 		return (size);
1175 	}
1176 	errno = ENODATA;
1177 	return (-1);
1178 }
1179 
1180 int
1181 Psetpriv(struct ps_prochandle *P, prpriv_t *pprv)
1182 {
1183 	int rc;
1184 	long *ctl;
1185 	size_t sz;
1186 
1187 	if (P->state == PS_DEAD) {
1188 		errno = EBADF;
1189 		return (-1);
1190 	}
1191 
1192 	sz = PRIV_PRPRIV_SIZE(pprv) + sizeof (long);
1193 
1194 	sz = ((sz - 1) / sizeof (long) + 1) * sizeof (long);
1195 
1196 	ctl = malloc(sz);
1197 	if (ctl == NULL)
1198 		return (-1);
1199 
1200 	ctl[0] = PCSPRIV;
1201 
1202 	(void) memcpy(&ctl[1], pprv, PRIV_PRPRIV_SIZE(pprv));
1203 
1204 	if (write(P->ctlfd, ctl, sz) != sz)
1205 		rc = -1;
1206 	else
1207 		rc = 0;
1208 
1209 	free(ctl);
1210 
1211 	return (rc);
1212 }
1213 
1214 void *
1215 Pprivinfo(struct ps_prochandle *P)
1216 {
1217 	/* Use default from libc */
1218 	if (P->state != PS_DEAD)
1219 		return (NULL);
1220 
1221 	return (P->core->core_privinfo);
1222 }
1223 
1224 /*
1225  * Ensure that all cached state is written to the process.
1226  * The cached state is the LWP's signal mask and registers
1227  * and the process's tracing flags.
1228  */
1229 void
1230 Psync(struct ps_prochandle *P)
1231 {
1232 	int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
1233 	long cmd[6];
1234 	iovec_t iov[12];
1235 	int n = 0;
1236 
1237 	if (P->flags & SETHOLD) {
1238 		cmd[0] = PCSHOLD;
1239 		iov[n].iov_base = (caddr_t)&cmd[0];
1240 		iov[n++].iov_len = sizeof (long);
1241 		iov[n].iov_base = (caddr_t)&P->status.pr_lwp.pr_lwphold;
1242 		iov[n++].iov_len = sizeof (P->status.pr_lwp.pr_lwphold);
1243 	}
1244 	if (P->flags & SETREGS) {
1245 		cmd[1] = PCSREG;
1246 #ifdef __i386
1247 		/* XX64 we should probably restore REG_GS after this */
1248 		if (ctlfd == P->agentctlfd)
1249 			P->status.pr_lwp.pr_reg[GS] = 0;
1250 #elif defined(__amd64)
1251 		/* XX64 */
1252 #endif
1253 		iov[n].iov_base = (caddr_t)&cmd[1];
1254 		iov[n++].iov_len = sizeof (long);
1255 		iov[n].iov_base = (caddr_t)&P->status.pr_lwp.pr_reg[0];
1256 		iov[n++].iov_len = sizeof (P->status.pr_lwp.pr_reg);
1257 	}
1258 	if (P->flags & SETSIG) {
1259 		cmd[2] = PCSTRACE;
1260 		iov[n].iov_base = (caddr_t)&cmd[2];
1261 		iov[n++].iov_len = sizeof (long);
1262 		iov[n].iov_base = (caddr_t)&P->status.pr_sigtrace;
1263 		iov[n++].iov_len = sizeof (P->status.pr_sigtrace);
1264 	}
1265 	if (P->flags & SETFAULT) {
1266 		cmd[3] = PCSFAULT;
1267 		iov[n].iov_base = (caddr_t)&cmd[3];
1268 		iov[n++].iov_len = sizeof (long);
1269 		iov[n].iov_base = (caddr_t)&P->status.pr_flttrace;
1270 		iov[n++].iov_len = sizeof (P->status.pr_flttrace);
1271 	}
1272 	if (P->flags & SETENTRY) {
1273 		cmd[4] = PCSENTRY;
1274 		iov[n].iov_base = (caddr_t)&cmd[4];
1275 		iov[n++].iov_len = sizeof (long);
1276 		iov[n].iov_base = (caddr_t)&P->status.pr_sysentry;
1277 		iov[n++].iov_len = sizeof (P->status.pr_sysentry);
1278 	}
1279 	if (P->flags & SETEXIT) {
1280 		cmd[5] = PCSEXIT;
1281 		iov[n].iov_base = (caddr_t)&cmd[5];
1282 		iov[n++].iov_len = sizeof (long);
1283 		iov[n].iov_base = (caddr_t)&P->status.pr_sysexit;
1284 		iov[n++].iov_len = sizeof (P->status.pr_sysexit);
1285 	}
1286 
1287 	if (n == 0 || writev(ctlfd, iov, n) < 0)
1288 		return;		/* nothing to do or write failed */
1289 
1290 	P->flags &= ~(SETSIG|SETFAULT|SETENTRY|SETEXIT|SETHOLD|SETREGS);
1291 }
1292 
1293 /*
1294  * Reopen the /proc file (after PS_LOST).
1295  */
1296 int
1297 Preopen(struct ps_prochandle *P)
1298 {
1299 	int fd;
1300 	char procname[PATH_MAX];
1301 	char *fname;
1302 
1303 	if (P->state == PS_DEAD || P->state == PS_IDLE)
1304 		return (0);
1305 
1306 	if (P->agentcnt > 0) {
1307 		P->agentcnt = 1;
1308 		Pdestroy_agent(P);
1309 	}
1310 
1311 	(void) snprintf(procname, sizeof (procname), "%s/%d/",
1312 	    procfs_path, (int)P->pid);
1313 	fname = procname + strlen(procname);
1314 
1315 	(void) strcpy(fname, "as");
1316 	if ((fd = open(procname, O_RDWR)) < 0 ||
1317 	    close(P->asfd) < 0 ||
1318 	    (fd = dupfd(fd, P->asfd)) != P->asfd) {
1319 		dprintf("Preopen: failed to open %s: %s\n",
1320 		    procname, strerror(errno));
1321 		if (fd >= 0)
1322 			(void) close(fd);
1323 		return (-1);
1324 	}
1325 	P->asfd = fd;
1326 
1327 	(void) strcpy(fname, "status");
1328 	if ((fd = open(procname, O_RDONLY)) < 0 ||
1329 	    close(P->statfd) < 0 ||
1330 	    (fd = dupfd(fd, P->statfd)) != P->statfd) {
1331 		dprintf("Preopen: failed to open %s: %s\n",
1332 		    procname, strerror(errno));
1333 		if (fd >= 0)
1334 			(void) close(fd);
1335 		return (-1);
1336 	}
1337 	P->statfd = fd;
1338 
1339 	(void) strcpy(fname, "ctl");
1340 	if ((fd = open(procname, O_WRONLY)) < 0 ||
1341 	    close(P->ctlfd) < 0 ||
1342 	    (fd = dupfd(fd, P->ctlfd)) != P->ctlfd) {
1343 		dprintf("Preopen: failed to open %s: %s\n",
1344 		    procname, strerror(errno));
1345 		if (fd >= 0)
1346 			(void) close(fd);
1347 		return (-1);
1348 	}
1349 	P->ctlfd = fd;
1350 
1351 	/*
1352 	 * Set the state to PS_RUN and wait for the process to stop so that
1353 	 * we re-read the status from the new P->statfd.  If this fails, Pwait
1354 	 * will reset the state to PS_LOST and we fail the reopen.  Before
1355 	 * returning, we also forge a bit of P->status to allow the debugger to
1356 	 * see that we are PS_LOST following a successful exec.
1357 	 */
1358 	P->state = PS_RUN;
1359 	if (Pwait(P, 0) == -1) {
1360 #ifdef _ILP32
1361 		if (errno == EOVERFLOW)
1362 			P->status.pr_dmodel = PR_MODEL_LP64;
1363 #endif
1364 		P->status.pr_lwp.pr_why = PR_SYSEXIT;
1365 		P->status.pr_lwp.pr_what = SYS_execve;
1366 		P->status.pr_lwp.pr_errno = 0;
1367 		return (-1);
1368 	}
1369 
1370 	/*
1371 	 * The process should be stopped on exec (REQUESTED)
1372 	 * or else should be stopped on exit from exec() (SYSEXIT)
1373 	 */
1374 	if (P->state == PS_STOP &&
1375 	    (P->status.pr_lwp.pr_why == PR_REQUESTED ||
1376 	    (P->status.pr_lwp.pr_why == PR_SYSEXIT &&
1377 	    P->status.pr_lwp.pr_what == SYS_execve))) {
1378 		/* fake up stop-on-exit-from-execve */
1379 		if (P->status.pr_lwp.pr_why == PR_REQUESTED) {
1380 			P->status.pr_lwp.pr_why = PR_SYSEXIT;
1381 			P->status.pr_lwp.pr_what = SYS_execve;
1382 			P->status.pr_lwp.pr_errno = 0;
1383 		}
1384 	} else {
1385 		dprintf("Preopen: expected REQUESTED or "
1386 		    "SYSEXIT(SYS_execve) stop\n");
1387 	}
1388 
1389 	return (0);
1390 }
1391 
1392 /*
1393  * Define all settable flags other than the microstate accounting flags.
1394  */
1395 #define	ALL_SETTABLE_FLAGS (PR_FORK|PR_RLC|PR_KLC|PR_ASYNC|PR_BPTADJ|PR_PTRACE)
1396 
1397 /*
1398  * Restore /proc tracing flags to their original values
1399  * in preparation for releasing the process.
1400  * Also called by Pcreate() to clear all tracing flags.
1401  */
1402 static void
1403 restore_tracing_flags(struct ps_prochandle *P)
1404 {
1405 	long flags;
1406 	long cmd[4];
1407 	iovec_t iov[8];
1408 
1409 	if (P->flags & CREATED) {
1410 		/* we created this process; clear all tracing flags */
1411 		premptyset(&P->status.pr_sigtrace);
1412 		premptyset(&P->status.pr_flttrace);
1413 		premptyset(&P->status.pr_sysentry);
1414 		premptyset(&P->status.pr_sysexit);
1415 		if ((P->status.pr_flags & ALL_SETTABLE_FLAGS) != 0)
1416 			(void) Punsetflags(P, ALL_SETTABLE_FLAGS);
1417 	} else {
1418 		/* we grabbed the process; restore its tracing flags */
1419 		P->status.pr_sigtrace = P->orig_status.pr_sigtrace;
1420 		P->status.pr_flttrace = P->orig_status.pr_flttrace;
1421 		P->status.pr_sysentry = P->orig_status.pr_sysentry;
1422 		P->status.pr_sysexit  = P->orig_status.pr_sysexit;
1423 		if ((P->status.pr_flags & ALL_SETTABLE_FLAGS) !=
1424 		    (flags = (P->orig_status.pr_flags & ALL_SETTABLE_FLAGS))) {
1425 			(void) Punsetflags(P, ALL_SETTABLE_FLAGS);
1426 			if (flags)
1427 				(void) Psetflags(P, flags);
1428 		}
1429 	}
1430 
1431 	cmd[0] = PCSTRACE;
1432 	iov[0].iov_base = (caddr_t)&cmd[0];
1433 	iov[0].iov_len = sizeof (long);
1434 	iov[1].iov_base = (caddr_t)&P->status.pr_sigtrace;
1435 	iov[1].iov_len = sizeof (P->status.pr_sigtrace);
1436 
1437 	cmd[1] = PCSFAULT;
1438 	iov[2].iov_base = (caddr_t)&cmd[1];
1439 	iov[2].iov_len = sizeof (long);
1440 	iov[3].iov_base = (caddr_t)&P->status.pr_flttrace;
1441 	iov[3].iov_len = sizeof (P->status.pr_flttrace);
1442 
1443 	cmd[2] = PCSENTRY;
1444 	iov[4].iov_base = (caddr_t)&cmd[2];
1445 	iov[4].iov_len = sizeof (long);
1446 	iov[5].iov_base = (caddr_t)&P->status.pr_sysentry;
1447 	iov[5].iov_len = sizeof (P->status.pr_sysentry);
1448 
1449 	cmd[3] = PCSEXIT;
1450 	iov[6].iov_base = (caddr_t)&cmd[3];
1451 	iov[6].iov_len = sizeof (long);
1452 	iov[7].iov_base = (caddr_t)&P->status.pr_sysexit;
1453 	iov[7].iov_len = sizeof (P->status.pr_sysexit);
1454 
1455 	(void) writev(P->ctlfd, iov, 8);
1456 
1457 	P->flags &= ~(SETSIG|SETFAULT|SETENTRY|SETEXIT);
1458 }
1459 
1460 /*
1461  * Release the process.  Frees the process control structure.
1462  * flags:
1463  *	PRELEASE_CLEAR	Clear all tracing flags.
1464  *	PRELEASE_RETAIN	Retain current tracing flags.
1465  *	PRELEASE_HANG	Leave the process stopped and abandoned.
1466  *	PRELEASE_KILL	Terminate the process with SIGKILL.
1467  */
1468 void
1469 Prelease(struct ps_prochandle *P, int flags)
1470 {
1471 	if (P->state == PS_DEAD) {
1472 		dprintf("Prelease: releasing handle %p PS_DEAD of pid %d\n",
1473 		    (void *)P, (int)P->pid);
1474 		Pfree(P);
1475 		return;
1476 	}
1477 
1478 	if (P->state == PS_IDLE) {
1479 		file_info_t *fptr = list_next(&P->file_head);
1480 		dprintf("Prelease: releasing handle %p PS_IDLE of file %s\n",
1481 		    (void *)P, fptr->file_pname);
1482 		Pfree(P);
1483 		return;
1484 	}
1485 
1486 	dprintf("Prelease: releasing handle %p pid %d\n",
1487 	    (void *)P, (int)P->pid);
1488 
1489 	if (P->ctlfd == -1) {
1490 		Pfree(P);
1491 		return;
1492 	}
1493 
1494 	if (P->agentcnt > 0) {
1495 		P->agentcnt = 1;
1496 		Pdestroy_agent(P);
1497 	}
1498 
1499 	/*
1500 	 * Attempt to stop the process.
1501 	 */
1502 	P->state = PS_RUN;
1503 	(void) Pstop(P, 1000);
1504 
1505 	if (flags & PRELEASE_KILL) {
1506 		if (P->state == PS_STOP)
1507 			(void) Psetrun(P, SIGKILL, 0);
1508 		(void) kill(P->pid, SIGKILL);
1509 		Pfree(P);
1510 		return;
1511 	}
1512 
1513 	/*
1514 	 * If we lost control, all we can do now is close the files.
1515 	 * In this case, the last close sets the process running.
1516 	 */
1517 	if (P->state != PS_STOP &&
1518 	    (P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) == 0) {
1519 		Pfree(P);
1520 		return;
1521 	}
1522 
1523 	/*
1524 	 * We didn't lose control; we do more.
1525 	 */
1526 	Psync(P);
1527 
1528 	if (flags & PRELEASE_CLEAR)
1529 		P->flags |= CREATED;
1530 
1531 	if (!(flags & PRELEASE_RETAIN))
1532 		restore_tracing_flags(P);
1533 
1534 	if (flags & PRELEASE_HANG) {
1535 		/* Leave the process stopped and abandoned */
1536 		(void) Punsetflags(P, PR_RLC|PR_KLC);
1537 		Pfree(P);
1538 		return;
1539 	}
1540 
1541 	/*
1542 	 * Set the process running if we created it or if it was
1543 	 * not originally stopped or directed to stop via /proc
1544 	 * or if we were given the PRELEASE_CLEAR flag.
1545 	 */
1546 	if ((P->flags & CREATED) ||
1547 	    (P->orig_status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) == 0) {
1548 		(void) Psetflags(P, PR_RLC);
1549 		/*
1550 		 * We do this repeatedly because the process may have
1551 		 * more than one LWP stopped on an event of interest.
1552 		 * This makes sure all of them are set running.
1553 		 */
1554 		do {
1555 			if (Psetrun(P, 0, 0) == -1 && errno == EBUSY)
1556 				break; /* Agent LWP may be stuck */
1557 		} while (Pstopstatus(P, PCNULL, 0) == 0 &&
1558 		    P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP));
1559 
1560 		if (P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP))
1561 			dprintf("Prelease: failed to set process running\n");
1562 	}
1563 
1564 	Pfree(P);
1565 }
1566 
1567 /* debugging */
1568 void
1569 prldump(const char *caller, lwpstatus_t *lsp)
1570 {
1571 	char name[32];
1572 	uint32_t bits;
1573 
1574 	switch (lsp->pr_why) {
1575 	case PR_REQUESTED:
1576 		dprintf("%s: REQUESTED\n", caller);
1577 		break;
1578 	case PR_SIGNALLED:
1579 		dprintf("%s: SIGNALLED %s\n", caller,
1580 		    proc_signame(lsp->pr_what, name, sizeof (name)));
1581 		break;
1582 	case PR_FAULTED:
1583 		dprintf("%s: FAULTED %s\n", caller,
1584 		    proc_fltname(lsp->pr_what, name, sizeof (name)));
1585 		break;
1586 	case PR_SYSENTRY:
1587 		dprintf("%s: SYSENTRY %s\n", caller,
1588 		    proc_sysname(lsp->pr_what, name, sizeof (name)));
1589 		break;
1590 	case PR_SYSEXIT:
1591 		dprintf("%s: SYSEXIT %s\n", caller,
1592 		    proc_sysname(lsp->pr_what, name, sizeof (name)));
1593 		break;
1594 	case PR_JOBCONTROL:
1595 		dprintf("%s: JOBCONTROL %s\n", caller,
1596 		    proc_signame(lsp->pr_what, name, sizeof (name)));
1597 		break;
1598 	case PR_SUSPENDED:
1599 		dprintf("%s: SUSPENDED\n", caller);
1600 		break;
1601 	default:
1602 		dprintf("%s: Unknown\n", caller);
1603 		break;
1604 	}
1605 
1606 	if (lsp->pr_cursig)
1607 		dprintf("%s: p_cursig  = %d\n", caller, lsp->pr_cursig);
1608 
1609 	bits = *((uint32_t *)&lsp->pr_lwppend);
1610 	if (bits)
1611 		dprintf("%s: pr_lwppend = 0x%.8X\n", caller, bits);
1612 }
1613 
1614 /* debugging */
1615 static void
1616 prdump(struct ps_prochandle *P)
1617 {
1618 	uint32_t bits;
1619 
1620 	prldump("Pstopstatus", &P->status.pr_lwp);
1621 
1622 	bits = *((uint32_t *)&P->status.pr_sigpend);
1623 	if (bits)
1624 		dprintf("Pstopstatus: pr_sigpend = 0x%.8X\n", bits);
1625 }
1626 
1627 /*
1628  * Wait for the specified process to stop or terminate.
1629  * Or, just get the current status (PCNULL).
1630  * Or, direct it to stop and get the current status (PCDSTOP).
1631  * If the agent LWP exists, do these things to the agent,
1632  * else do these things to the process as a whole.
1633  */
1634 int
1635 Pstopstatus(struct ps_prochandle *P,
1636 	long request,		/* PCNULL, PCDSTOP, PCSTOP, PCWSTOP */
1637 	uint_t msec)		/* if non-zero, timeout in milliseconds */
1638 {
1639 	int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
1640 	long ctl[3];
1641 	ssize_t rc;
1642 	int err;
1643 	int old_state = P->state;
1644 
1645 	switch (P->state) {
1646 	case PS_RUN:
1647 		break;
1648 	case PS_STOP:
1649 		if (request != PCNULL && request != PCDSTOP)
1650 			return (0);
1651 		break;
1652 	case PS_LOST:
1653 		if (request != PCNULL) {
1654 			errno = EAGAIN;
1655 			return (-1);
1656 		}
1657 		break;
1658 	case PS_UNDEAD:
1659 	case PS_DEAD:
1660 	case PS_IDLE:
1661 		if (request != PCNULL) {
1662 			errno = ENOENT;
1663 			return (-1);
1664 		}
1665 		break;
1666 	default:	/* corrupted state */
1667 		dprintf("Pstopstatus: corrupted state: %d\n", P->state);
1668 		errno = EINVAL;
1669 		return (-1);
1670 	}
1671 
1672 	ctl[0] = PCDSTOP;
1673 	ctl[1] = PCTWSTOP;
1674 	ctl[2] = (long)msec;
1675 	rc = 0;
1676 	switch (request) {
1677 	case PCSTOP:
1678 		rc = write(ctlfd, &ctl[0], 3*sizeof (long));
1679 		break;
1680 	case PCWSTOP:
1681 		rc = write(ctlfd, &ctl[1], 2*sizeof (long));
1682 		break;
1683 	case PCDSTOP:
1684 		rc = write(ctlfd, &ctl[0], 1*sizeof (long));
1685 		break;
1686 	case PCNULL:
1687 		if (P->state == PS_DEAD || P->state == PS_IDLE)
1688 			return (0);
1689 		break;
1690 	default:	/* programming error */
1691 		errno = EINVAL;
1692 		return (-1);
1693 	}
1694 	err = (rc < 0)? errno : 0;
1695 	Psync(P);
1696 
1697 	if (P->agentstatfd < 0) {
1698 		if (pread(P->statfd, &P->status,
1699 		    sizeof (P->status), (off_t)0) < 0)
1700 			err = errno;
1701 	} else {
1702 		if (pread(P->agentstatfd, &P->status.pr_lwp,
1703 		    sizeof (P->status.pr_lwp), (off_t)0) < 0)
1704 			err = errno;
1705 		P->status.pr_flags = P->status.pr_lwp.pr_flags;
1706 	}
1707 
1708 	if (err) {
1709 		switch (err) {
1710 		case EINTR:		/* user typed ctl-C */
1711 		case ERESTART:
1712 			dprintf("Pstopstatus: EINTR\n");
1713 			break;
1714 		case EAGAIN:		/* we lost control of the the process */
1715 		case EOVERFLOW:
1716 			dprintf("Pstopstatus: PS_LOST, errno=%d\n", err);
1717 			P->state = PS_LOST;
1718 			break;
1719 		default:		/* check for dead process */
1720 			if (_libproc_debug) {
1721 				const char *errstr;
1722 
1723 				switch (request) {
1724 				case PCNULL:
1725 					errstr = "Pstopstatus PCNULL"; break;
1726 				case PCSTOP:
1727 					errstr = "Pstopstatus PCSTOP"; break;
1728 				case PCDSTOP:
1729 					errstr = "Pstopstatus PCDSTOP"; break;
1730 				case PCWSTOP:
1731 					errstr = "Pstopstatus PCWSTOP"; break;
1732 				default:
1733 					errstr = "Pstopstatus PC???"; break;
1734 				}
1735 				dprintf("%s: %s\n", errstr, strerror(err));
1736 			}
1737 			deadcheck(P);
1738 			break;
1739 		}
1740 		if (err != EINTR && err != ERESTART) {
1741 			errno = err;
1742 			return (-1);
1743 		}
1744 	}
1745 
1746 	if (!(P->status.pr_flags & PR_STOPPED)) {
1747 		P->state = PS_RUN;
1748 		if (request == PCNULL || request == PCDSTOP || msec != 0)
1749 			return (0);
1750 		dprintf("Pstopstatus: process is not stopped\n");
1751 		errno = EPROTO;
1752 		return (-1);
1753 	}
1754 
1755 	P->state = PS_STOP;
1756 
1757 	if (_libproc_debug)	/* debugging */
1758 		prdump(P);
1759 
1760 	/*
1761 	 * If the process was already stopped coming into Pstopstatus(),
1762 	 * then don't use its PC to set P->sysaddr since it may have been
1763 	 * changed since the time the process originally stopped.
1764 	 */
1765 	if (old_state == PS_STOP)
1766 		return (0);
1767 
1768 	switch (P->status.pr_lwp.pr_why) {
1769 	case PR_SYSENTRY:
1770 	case PR_SYSEXIT:
1771 		if (Pissyscall_prev(P, P->status.pr_lwp.pr_reg[R_PC],
1772 		    &P->sysaddr) == 0)
1773 			P->sysaddr = P->status.pr_lwp.pr_reg[R_PC];
1774 		break;
1775 	case PR_REQUESTED:
1776 	case PR_SIGNALLED:
1777 	case PR_FAULTED:
1778 	case PR_JOBCONTROL:
1779 	case PR_SUSPENDED:
1780 		break;
1781 	default:
1782 		errno = EPROTO;
1783 		return (-1);
1784 	}
1785 
1786 	return (0);
1787 }
1788 
1789 /*
1790  * Wait for the process to stop for any reason.
1791  */
1792 int
1793 Pwait(struct ps_prochandle *P, uint_t msec)
1794 {
1795 	return (Pstopstatus(P, PCWSTOP, msec));
1796 }
1797 
1798 /*
1799  * Direct the process to stop; wait for it to stop.
1800  */
1801 int
1802 Pstop(struct ps_prochandle *P, uint_t msec)
1803 {
1804 	return (Pstopstatus(P, PCSTOP, msec));
1805 }
1806 
1807 /*
1808  * Direct the process to stop; don't wait.
1809  */
1810 int
1811 Pdstop(struct ps_prochandle *P)
1812 {
1813 	return (Pstopstatus(P, PCDSTOP, 0));
1814 }
1815 
1816 static void
1817 deadcheck(struct ps_prochandle *P)
1818 {
1819 	int fd;
1820 	void *buf;
1821 	size_t size;
1822 
1823 	if (P->statfd < 0)
1824 		P->state = PS_UNDEAD;
1825 	else {
1826 		if (P->agentstatfd < 0) {
1827 			fd = P->statfd;
1828 			buf = &P->status;
1829 			size = sizeof (P->status);
1830 		} else {
1831 			fd = P->agentstatfd;
1832 			buf = &P->status.pr_lwp;
1833 			size = sizeof (P->status.pr_lwp);
1834 		}
1835 		while (pread(fd, buf, size, (off_t)0) != size) {
1836 			switch (errno) {
1837 			default:
1838 				P->state = PS_UNDEAD;
1839 				break;
1840 			case EINTR:
1841 			case ERESTART:
1842 				continue;
1843 			case EAGAIN:
1844 				P->state = PS_LOST;
1845 				break;
1846 			}
1847 			break;
1848 		}
1849 		P->status.pr_flags = P->status.pr_lwp.pr_flags;
1850 	}
1851 }
1852 
1853 /*
1854  * Get the value of one register from stopped process.
1855  */
1856 int
1857 Pgetareg(struct ps_prochandle *P, int regno, prgreg_t *preg)
1858 {
1859 	if (regno < 0 || regno >= NPRGREG) {
1860 		errno = EINVAL;
1861 		return (-1);
1862 	}
1863 
1864 	if (P->state == PS_IDLE) {
1865 		errno = ENODATA;
1866 		return (-1);
1867 	}
1868 
1869 	if (P->state != PS_STOP && P->state != PS_DEAD) {
1870 		errno = EBUSY;
1871 		return (-1);
1872 	}
1873 
1874 	*preg = P->status.pr_lwp.pr_reg[regno];
1875 	return (0);
1876 }
1877 
1878 /*
1879  * Put value of one register into stopped process.
1880  */
1881 int
1882 Pputareg(struct ps_prochandle *P, int regno, prgreg_t reg)
1883 {
1884 	if (regno < 0 || regno >= NPRGREG) {
1885 		errno = EINVAL;
1886 		return (-1);
1887 	}
1888 
1889 	if (P->state != PS_STOP) {
1890 		errno = EBUSY;
1891 		return (-1);
1892 	}
1893 
1894 	P->status.pr_lwp.pr_reg[regno] = reg;
1895 	P->flags |= SETREGS;	/* set registers before continuing */
1896 	return (0);
1897 }
1898 
1899 int
1900 Psetrun(struct ps_prochandle *P,
1901 	int sig,	/* signal to pass to process */
1902 	int flags)	/* PRSTEP|PRSABORT|PRSTOP|PRCSIG|PRCFAULT */
1903 {
1904 	int ctlfd = (P->agentctlfd >= 0) ? P->agentctlfd : P->ctlfd;
1905 	int sbits = (PR_DSTOP | PR_ISTOP | PR_ASLEEP);
1906 
1907 	long ctl[1 +					/* PCCFAULT	*/
1908 	    1 + sizeof (siginfo_t)/sizeof (long) +	/* PCSSIG/PCCSIG */
1909 	    2 ];					/* PCRUN	*/
1910 
1911 	long *ctlp = ctl;
1912 	size_t size;
1913 
1914 	if (P->state != PS_STOP && (P->status.pr_lwp.pr_flags & sbits) == 0) {
1915 		errno = EBUSY;
1916 		return (-1);
1917 	}
1918 
1919 	Psync(P);	/* flush tracing flags and registers */
1920 
1921 	if (flags & PRCFAULT) {		/* clear current fault */
1922 		*ctlp++ = PCCFAULT;
1923 		flags &= ~PRCFAULT;
1924 	}
1925 
1926 	if (flags & PRCSIG) {		/* clear current signal */
1927 		*ctlp++ = PCCSIG;
1928 		flags &= ~PRCSIG;
1929 	} else if (sig && sig != P->status.pr_lwp.pr_cursig) {
1930 		/* make current signal */
1931 		siginfo_t *infop;
1932 
1933 		*ctlp++ = PCSSIG;
1934 		infop = (siginfo_t *)ctlp;
1935 		(void) memset(infop, 0, sizeof (*infop));
1936 		infop->si_signo = sig;
1937 		ctlp += sizeof (siginfo_t) / sizeof (long);
1938 	}
1939 
1940 	*ctlp++ = PCRUN;
1941 	*ctlp++ = flags;
1942 	size = (char *)ctlp - (char *)ctl;
1943 
1944 	P->info_valid = 0;	/* will need to update map and file info */
1945 
1946 	/*
1947 	 * If we've cached ucontext-list information while we were stopped,
1948 	 * free it now.
1949 	 */
1950 	if (P->ucaddrs != NULL) {
1951 		free(P->ucaddrs);
1952 		P->ucaddrs = NULL;
1953 		P->ucnelems = 0;
1954 	}
1955 
1956 	if (write(ctlfd, ctl, size) != size) {
1957 		/* If it is dead or lost, return the real status, not PS_RUN */
1958 		if (errno == ENOENT || errno == EAGAIN) {
1959 			(void) Pstopstatus(P, PCNULL, 0);
1960 			return (0);
1961 		}
1962 		/* If it is not in a jobcontrol stop, issue an error message */
1963 		if (errno != EBUSY ||
1964 		    P->status.pr_lwp.pr_why != PR_JOBCONTROL) {
1965 			dprintf("Psetrun: %s\n", strerror(errno));
1966 			return (-1);
1967 		}
1968 		/* Otherwise pretend that the job-stopped process is running */
1969 	}
1970 
1971 	P->state = PS_RUN;
1972 	return (0);
1973 }
1974 
1975 ssize_t
1976 Pread(struct ps_prochandle *P,
1977 	void *buf,		/* caller's buffer */
1978 	size_t nbyte,		/* number of bytes to read */
1979 	uintptr_t address)	/* address in process */
1980 {
1981 	return (P->ops->p_pread(P, buf, nbyte, address));
1982 }
1983 
1984 ssize_t
1985 Pread_string(struct ps_prochandle *P,
1986 	char *buf, 		/* caller's buffer */
1987 	size_t size,		/* upper limit on bytes to read */
1988 	uintptr_t addr)		/* address in process */
1989 {
1990 	enum { STRSZ = 40 };
1991 	char string[STRSZ + 1];
1992 	ssize_t leng = 0;
1993 	int nbyte;
1994 
1995 	if (size < 2) {
1996 		errno = EINVAL;
1997 		return (-1);
1998 	}
1999 
2000 	size--;			/* ensure trailing null fits in buffer */
2001 
2002 	*buf = '\0';
2003 	string[STRSZ] = '\0';
2004 
2005 	for (nbyte = STRSZ; nbyte == STRSZ && leng < size; addr += STRSZ) {
2006 		if ((nbyte = P->ops->p_pread(P, string, STRSZ, addr)) <= 0) {
2007 			buf[leng] = '\0';
2008 			return (leng ? leng : -1);
2009 		}
2010 		if ((nbyte = strlen(string)) > 0) {
2011 			if (leng + nbyte > size)
2012 				nbyte = size - leng;
2013 			(void) strncpy(buf + leng, string, nbyte);
2014 			leng += nbyte;
2015 		}
2016 	}
2017 	buf[leng] = '\0';
2018 	return (leng);
2019 }
2020 
2021 ssize_t
2022 Pwrite(struct ps_prochandle *P,
2023 	const void *buf,	/* caller's buffer */
2024 	size_t nbyte,		/* number of bytes to write */
2025 	uintptr_t address)	/* address in process */
2026 {
2027 	return (P->ops->p_pwrite(P, buf, nbyte, address));
2028 }
2029 
2030 int
2031 Pclearsig(struct ps_prochandle *P)
2032 {
2033 	int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2034 	long ctl = PCCSIG;
2035 
2036 	if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
2037 		return (-1);
2038 	P->status.pr_lwp.pr_cursig = 0;
2039 	return (0);
2040 }
2041 
2042 int
2043 Pclearfault(struct ps_prochandle *P)
2044 {
2045 	int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2046 	long ctl = PCCFAULT;
2047 
2048 	if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
2049 		return (-1);
2050 	return (0);
2051 }
2052 
2053 /*
2054  * Set a breakpoint trap, return original instruction.
2055  */
2056 int
2057 Psetbkpt(struct ps_prochandle *P, uintptr_t address, ulong_t *saved)
2058 {
2059 	long ctl[1 + sizeof (priovec_t) / sizeof (long) +	/* PCREAD */
2060 	    1 + sizeof (priovec_t) / sizeof (long)];	/* PCWRITE */
2061 	long *ctlp = ctl;
2062 	size_t size;
2063 	priovec_t *iovp;
2064 	instr_t bpt = BPT;
2065 	instr_t old;
2066 
2067 	if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2068 	    P->state == PS_IDLE) {
2069 		errno = ENOENT;
2070 		return (-1);
2071 	}
2072 
2073 	/* fetch the old instruction */
2074 	*ctlp++ = PCREAD;
2075 	iovp = (priovec_t *)ctlp;
2076 	iovp->pio_base = &old;
2077 	iovp->pio_len = sizeof (old);
2078 	iovp->pio_offset = address;
2079 	ctlp += sizeof (priovec_t) / sizeof (long);
2080 
2081 	/* write the BPT instruction */
2082 	*ctlp++ = PCWRITE;
2083 	iovp = (priovec_t *)ctlp;
2084 	iovp->pio_base = &bpt;
2085 	iovp->pio_len = sizeof (bpt);
2086 	iovp->pio_offset = address;
2087 	ctlp += sizeof (priovec_t) / sizeof (long);
2088 
2089 	size = (char *)ctlp - (char *)ctl;
2090 	if (write(P->ctlfd, ctl, size) != size)
2091 		return (-1);
2092 
2093 	/*
2094 	 * Fail if there was already a breakpoint there from another debugger
2095 	 * or DTrace's user-level tracing on x86.
2096 	 */
2097 	if (old == BPT) {
2098 		errno = EBUSY;
2099 		return (-1);
2100 	}
2101 
2102 	*saved = (ulong_t)old;
2103 	return (0);
2104 }
2105 
2106 /*
2107  * Restore original instruction where a breakpoint was set.
2108  */
2109 int
2110 Pdelbkpt(struct ps_prochandle *P, uintptr_t address, ulong_t saved)
2111 {
2112 	instr_t old = (instr_t)saved;
2113 	instr_t cur;
2114 
2115 	if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2116 	    P->state == PS_IDLE) {
2117 		errno = ENOENT;
2118 		return (-1);
2119 	}
2120 
2121 	/*
2122 	 * If the breakpoint instruction we had placed has been overwritten
2123 	 * with a new instruction, then don't try to replace it with the
2124 	 * old instruction. Doing do can cause problems with self-modifying
2125 	 * code -- PLTs for example. If the Pread() fails, we assume that we
2126 	 * should proceed though most likely the Pwrite() will also fail.
2127 	 */
2128 	if (Pread(P, &cur, sizeof (cur), address) == sizeof (cur) &&
2129 	    cur != BPT)
2130 		return (0);
2131 
2132 	if (Pwrite(P, &old, sizeof (old), address) != sizeof (old))
2133 		return (-1);
2134 
2135 	return (0);
2136 }
2137 
2138 /*
2139  * Common code for Pxecbkpt() and Lxecbkpt().
2140  * Develop the array of requests that will do the job, then
2141  * write them to the specified control file descriptor.
2142  * Return the non-zero errno if the write fails.
2143  */
2144 static int
2145 execute_bkpt(
2146 	int ctlfd,		/* process or LWP control file descriptor */
2147 	const fltset_t *faultset,	/* current set of traced faults */
2148 	const sigset_t *sigmask,	/* current signal mask */
2149 	uintptr_t address,		/* address of breakpint */
2150 	ulong_t saved)			/* the saved instruction */
2151 {
2152 	long ctl[
2153 	    1 + sizeof (sigset_t) / sizeof (long) +		/* PCSHOLD */
2154 	    1 + sizeof (fltset_t) / sizeof (long) +		/* PCSFAULT */
2155 	    1 + sizeof (priovec_t) / sizeof (long) +		/* PCWRITE */
2156 	    2 +							/* PCRUN */
2157 	    1 +							/* PCWSTOP */
2158 	    1 +							/* PCCFAULT */
2159 	    1 + sizeof (priovec_t) / sizeof (long) +		/* PCWRITE */
2160 	    1 + sizeof (fltset_t) / sizeof (long) +		/* PCSFAULT */
2161 	    1 + sizeof (sigset_t) / sizeof (long)];		/* PCSHOLD */
2162 	long *ctlp = ctl;
2163 	sigset_t unblock;
2164 	size_t size;
2165 	ssize_t ssize;
2166 	priovec_t *iovp;
2167 	sigset_t *holdp;
2168 	fltset_t *faultp;
2169 	instr_t old = (instr_t)saved;
2170 	instr_t bpt = BPT;
2171 	int error = 0;
2172 
2173 	/* block our signals for the duration */
2174 	(void) sigprocmask(SIG_BLOCK, &blockable_sigs, &unblock);
2175 
2176 	/* hold posted signals */
2177 	*ctlp++ = PCSHOLD;
2178 	holdp = (sigset_t *)ctlp;
2179 	prfillset(holdp);
2180 	prdelset(holdp, SIGKILL);
2181 	prdelset(holdp, SIGSTOP);
2182 	ctlp += sizeof (sigset_t) / sizeof (long);
2183 
2184 	/* force tracing of FLTTRACE */
2185 	if (!(prismember(faultset, FLTTRACE))) {
2186 		*ctlp++ = PCSFAULT;
2187 		faultp = (fltset_t *)ctlp;
2188 		*faultp = *faultset;
2189 		praddset(faultp, FLTTRACE);
2190 		ctlp += sizeof (fltset_t) / sizeof (long);
2191 	}
2192 
2193 	/* restore the old instruction */
2194 	*ctlp++ = PCWRITE;
2195 	iovp = (priovec_t *)ctlp;
2196 	iovp->pio_base = &old;
2197 	iovp->pio_len = sizeof (old);
2198 	iovp->pio_offset = address;
2199 	ctlp += sizeof (priovec_t) / sizeof (long);
2200 
2201 	/* clear current signal and fault; set running w/ single-step */
2202 	*ctlp++ = PCRUN;
2203 	*ctlp++ = PRCSIG | PRCFAULT | PRSTEP;
2204 
2205 	/* wait for stop, cancel the fault */
2206 	*ctlp++ = PCWSTOP;
2207 	*ctlp++ = PCCFAULT;
2208 
2209 	/* restore the breakpoint trap */
2210 	*ctlp++ = PCWRITE;
2211 	iovp = (priovec_t *)ctlp;
2212 	iovp->pio_base = &bpt;
2213 	iovp->pio_len = sizeof (bpt);
2214 	iovp->pio_offset = address;
2215 	ctlp += sizeof (priovec_t) / sizeof (long);
2216 
2217 	/* restore fault tracing set */
2218 	if (!(prismember(faultset, FLTTRACE))) {
2219 		*ctlp++ = PCSFAULT;
2220 		*(fltset_t *)ctlp = *faultset;
2221 		ctlp += sizeof (fltset_t) / sizeof (long);
2222 	}
2223 
2224 	/* restore the hold mask */
2225 	*ctlp++ = PCSHOLD;
2226 	*(sigset_t *)ctlp = *sigmask;
2227 	ctlp += sizeof (sigset_t) / sizeof (long);
2228 
2229 	size = (char *)ctlp - (char *)ctl;
2230 	if ((ssize = write(ctlfd, ctl, size)) != size)
2231 		error = (ssize == -1)? errno : EINTR;
2232 	(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2233 	return (error);
2234 }
2235 
2236 /*
2237  * Step over a breakpoint, i.e., execute the instruction that
2238  * really belongs at the breakpoint location (the current %pc)
2239  * and leave the process stopped at the next instruction.
2240  */
2241 int
2242 Pxecbkpt(struct ps_prochandle *P, ulong_t saved)
2243 {
2244 	int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2245 	int rv, error;
2246 
2247 	if (P->state != PS_STOP) {
2248 		errno = EBUSY;
2249 		return (-1);
2250 	}
2251 
2252 	Psync(P);
2253 
2254 	error = execute_bkpt(ctlfd,
2255 	    &P->status.pr_flttrace, &P->status.pr_lwp.pr_lwphold,
2256 	    P->status.pr_lwp.pr_reg[R_PC], saved);
2257 	rv = Pstopstatus(P, PCNULL, 0);
2258 
2259 	if (error != 0) {
2260 		if (P->status.pr_lwp.pr_why == PR_JOBCONTROL &&
2261 		    error == EBUSY) {	/* jobcontrol stop -- back off */
2262 			P->state = PS_RUN;
2263 			return (0);
2264 		}
2265 		if (error == ENOENT)
2266 			return (0);
2267 		errno = error;
2268 		return (-1);
2269 	}
2270 
2271 	return (rv);
2272 }
2273 
2274 /*
2275  * Install the watchpoint described by wp.
2276  */
2277 int
2278 Psetwapt(struct ps_prochandle *P, const prwatch_t *wp)
2279 {
2280 	long ctl[1 + sizeof (prwatch_t) / sizeof (long)];
2281 	prwatch_t *cwp = (prwatch_t *)&ctl[1];
2282 
2283 	if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2284 	    P->state == PS_IDLE) {
2285 		errno = ENOENT;
2286 		return (-1);
2287 	}
2288 
2289 	ctl[0] = PCWATCH;
2290 	cwp->pr_vaddr = wp->pr_vaddr;
2291 	cwp->pr_size = wp->pr_size;
2292 	cwp->pr_wflags = wp->pr_wflags;
2293 
2294 	if (write(P->ctlfd, ctl, sizeof (ctl)) != sizeof (ctl))
2295 		return (-1);
2296 
2297 	return (0);
2298 }
2299 
2300 /*
2301  * Remove the watchpoint described by wp.
2302  */
2303 int
2304 Pdelwapt(struct ps_prochandle *P, const prwatch_t *wp)
2305 {
2306 	long ctl[1 + sizeof (prwatch_t) / sizeof (long)];
2307 	prwatch_t *cwp = (prwatch_t *)&ctl[1];
2308 
2309 	if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2310 	    P->state == PS_IDLE) {
2311 		errno = ENOENT;
2312 		return (-1);
2313 	}
2314 
2315 	ctl[0] = PCWATCH;
2316 	cwp->pr_vaddr = wp->pr_vaddr;
2317 	cwp->pr_size = wp->pr_size;
2318 	cwp->pr_wflags = 0;
2319 
2320 	if (write(P->ctlfd, ctl, sizeof (ctl)) != sizeof (ctl))
2321 		return (-1);
2322 
2323 	return (0);
2324 }
2325 
2326 /*
2327  * Common code for Pxecwapt() and Lxecwapt().  Develop the array of requests
2328  * that will do the job, then write them to the specified control file
2329  * descriptor.  Return the non-zero errno if the write fails.
2330  */
2331 static int
2332 execute_wapt(
2333 	int ctlfd,		/* process or LWP control file descriptor */
2334 	const fltset_t *faultset,	/* current set of traced faults */
2335 	const sigset_t *sigmask,	/* current signal mask */
2336 	const prwatch_t *wp)		/* watchpoint descriptor */
2337 {
2338 	long ctl[
2339 	    1 + sizeof (sigset_t) / sizeof (long) +		/* PCSHOLD */
2340 	    1 + sizeof (fltset_t) / sizeof (long) +		/* PCSFAULT */
2341 	    1 + sizeof (prwatch_t) / sizeof (long) +		/* PCWATCH */
2342 	    2 +							/* PCRUN */
2343 	    1 +							/* PCWSTOP */
2344 	    1 +							/* PCCFAULT */
2345 	    1 + sizeof (prwatch_t) / sizeof (long) +		/* PCWATCH */
2346 	    1 + sizeof (fltset_t) / sizeof (long) +		/* PCSFAULT */
2347 	    1 + sizeof (sigset_t) / sizeof (long)];		/* PCSHOLD */
2348 
2349 	long *ctlp = ctl;
2350 	int error = 0;
2351 
2352 	sigset_t unblock;
2353 	sigset_t *holdp;
2354 	fltset_t *faultp;
2355 	prwatch_t *prw;
2356 	ssize_t ssize;
2357 	size_t size;
2358 
2359 	(void) sigprocmask(SIG_BLOCK, &blockable_sigs, &unblock);
2360 
2361 	/*
2362 	 * Hold all posted signals in the victim process prior to stepping.
2363 	 */
2364 	*ctlp++ = PCSHOLD;
2365 	holdp = (sigset_t *)ctlp;
2366 	prfillset(holdp);
2367 	prdelset(holdp, SIGKILL);
2368 	prdelset(holdp, SIGSTOP);
2369 	ctlp += sizeof (sigset_t) / sizeof (long);
2370 
2371 	/*
2372 	 * Force tracing of FLTTRACE since we need to single step.
2373 	 */
2374 	if (!(prismember(faultset, FLTTRACE))) {
2375 		*ctlp++ = PCSFAULT;
2376 		faultp = (fltset_t *)ctlp;
2377 		*faultp = *faultset;
2378 		praddset(faultp, FLTTRACE);
2379 		ctlp += sizeof (fltset_t) / sizeof (long);
2380 	}
2381 
2382 	/*
2383 	 * Clear only the current watchpoint by setting pr_wflags to zero.
2384 	 */
2385 	*ctlp++ = PCWATCH;
2386 	prw = (prwatch_t *)ctlp;
2387 	prw->pr_vaddr = wp->pr_vaddr;
2388 	prw->pr_size = wp->pr_size;
2389 	prw->pr_wflags = 0;
2390 	ctlp += sizeof (prwatch_t) / sizeof (long);
2391 
2392 	/*
2393 	 * Clear the current signal and fault; set running with single-step.
2394 	 * Then wait for the victim to stop and cancel the FLTTRACE.
2395 	 */
2396 	*ctlp++ = PCRUN;
2397 	*ctlp++ = PRCSIG | PRCFAULT | PRSTEP;
2398 	*ctlp++ = PCWSTOP;
2399 	*ctlp++ = PCCFAULT;
2400 
2401 	/*
2402 	 * Restore the current watchpoint.
2403 	 */
2404 	*ctlp++ = PCWATCH;
2405 	(void) memcpy(ctlp, wp, sizeof (prwatch_t));
2406 	ctlp += sizeof (prwatch_t) / sizeof (long);
2407 
2408 	/*
2409 	 * Restore fault tracing set if we modified it.
2410 	 */
2411 	if (!(prismember(faultset, FLTTRACE))) {
2412 		*ctlp++ = PCSFAULT;
2413 		*(fltset_t *)ctlp = *faultset;
2414 		ctlp += sizeof (fltset_t) / sizeof (long);
2415 	}
2416 
2417 	/*
2418 	 * Restore the hold mask to the current hold mask (i.e. the one
2419 	 * before we executed any of the previous operations).
2420 	 */
2421 	*ctlp++ = PCSHOLD;
2422 	*(sigset_t *)ctlp = *sigmask;
2423 	ctlp += sizeof (sigset_t) / sizeof (long);
2424 
2425 	size = (char *)ctlp - (char *)ctl;
2426 	if ((ssize = write(ctlfd, ctl, size)) != size)
2427 		error = (ssize == -1)? errno : EINTR;
2428 	(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2429 	return (error);
2430 }
2431 
2432 /*
2433  * Step over a watchpoint, i.e., execute the instruction that was stopped by
2434  * the watchpoint, and then leave the LWP stopped at the next instruction.
2435  */
2436 int
2437 Pxecwapt(struct ps_prochandle *P, const prwatch_t *wp)
2438 {
2439 	int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2440 	int rv, error;
2441 
2442 	if (P->state != PS_STOP) {
2443 		errno = EBUSY;
2444 		return (-1);
2445 	}
2446 
2447 	Psync(P);
2448 	error = execute_wapt(ctlfd,
2449 	    &P->status.pr_flttrace, &P->status.pr_lwp.pr_lwphold, wp);
2450 	rv = Pstopstatus(P, PCNULL, 0);
2451 
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);
2457 		}
2458 		if (error == ENOENT)
2459 			return (0);
2460 		errno = error;
2461 		return (-1);
2462 	}
2463 
2464 	return (rv);
2465 }
2466 
2467 int
2468 Psetflags(struct ps_prochandle *P, long flags)
2469 {
2470 	int rc;
2471 	long ctl[2];
2472 
2473 	ctl[0] = PCSET;
2474 	ctl[1] = flags;
2475 
2476 	if (write(P->ctlfd, ctl, 2*sizeof (long)) != 2*sizeof (long)) {
2477 		rc = -1;
2478 	} else {
2479 		P->status.pr_flags |= flags;
2480 		P->status.pr_lwp.pr_flags |= flags;
2481 		rc = 0;
2482 	}
2483 
2484 	return (rc);
2485 }
2486 
2487 int
2488 Punsetflags(struct ps_prochandle *P, long flags)
2489 {
2490 	int rc;
2491 	long ctl[2];
2492 
2493 	ctl[0] = PCUNSET;
2494 	ctl[1] = flags;
2495 
2496 	if (write(P->ctlfd, ctl, 2*sizeof (long)) != 2*sizeof (long)) {
2497 		rc = -1;
2498 	} else {
2499 		P->status.pr_flags &= ~flags;
2500 		P->status.pr_lwp.pr_flags &= ~flags;
2501 		rc = 0;
2502 	}
2503 
2504 	return (rc);
2505 }
2506 
2507 /*
2508  * Common function to allow clients to manipulate the action to be taken
2509  * on receipt of a signal, receipt of machine fault, entry to a system call,
2510  * or exit from a system call.  We make use of our private prset_* functions
2511  * in order to make this code be common.  The 'which' parameter identifies
2512  * the code for the event of interest (0 means change the entire set), and
2513  * the 'stop' parameter is a boolean indicating whether the process should
2514  * stop when the event of interest occurs.  The previous value is returned
2515  * to the caller; -1 is returned if an error occurred.
2516  */
2517 static int
2518 Psetaction(struct ps_prochandle *P, void *sp, size_t size,
2519     uint_t flag, int max, int which, int stop)
2520 {
2521 	int oldval;
2522 
2523 	if (which < 0 || which > max) {
2524 		errno = EINVAL;
2525 		return (-1);
2526 	}
2527 
2528 	if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2529 	    P->state == PS_IDLE) {
2530 		errno = ENOENT;
2531 		return (-1);
2532 	}
2533 
2534 	oldval = prset_ismember(sp, size, which) ? TRUE : FALSE;
2535 
2536 	if (stop) {
2537 		if (which == 0) {
2538 			prset_fill(sp, size);
2539 			P->flags |= flag;
2540 		} else if (!oldval) {
2541 			prset_add(sp, size, which);
2542 			P->flags |= flag;
2543 		}
2544 	} else {
2545 		if (which == 0) {
2546 			prset_empty(sp, size);
2547 			P->flags |= flag;
2548 		} else if (oldval) {
2549 			prset_del(sp, size, which);
2550 			P->flags |= flag;
2551 		}
2552 	}
2553 
2554 	if (P->state == PS_RUN)
2555 		Psync(P);
2556 
2557 	return (oldval);
2558 }
2559 
2560 /*
2561  * Set action on specified signal.
2562  */
2563 int
2564 Psignal(struct ps_prochandle *P, int which, int stop)
2565 {
2566 	int oldval;
2567 
2568 	if (which == SIGKILL && stop != 0) {
2569 		errno = EINVAL;
2570 		return (-1);
2571 	}
2572 
2573 	oldval = Psetaction(P, &P->status.pr_sigtrace, sizeof (sigset_t),
2574 	    SETSIG, PRMAXSIG, which, stop);
2575 
2576 	if (oldval != -1 && which == 0 && stop != 0)
2577 		prdelset(&P->status.pr_sigtrace, SIGKILL);
2578 
2579 	return (oldval);
2580 }
2581 
2582 /*
2583  * Set all signal tracing flags.
2584  */
2585 void
2586 Psetsignal(struct ps_prochandle *P, const sigset_t *set)
2587 {
2588 	if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2589 	    P->state == PS_IDLE)
2590 		return;
2591 
2592 	P->status.pr_sigtrace = *set;
2593 	P->flags |= SETSIG;
2594 
2595 	if (P->state == PS_RUN)
2596 		Psync(P);
2597 }
2598 
2599 /*
2600  * Set action on specified fault.
2601  */
2602 int
2603 Pfault(struct ps_prochandle *P, int which, int stop)
2604 {
2605 	return (Psetaction(P, &P->status.pr_flttrace, sizeof (fltset_t),
2606 	    SETFAULT, PRMAXFAULT, which, stop));
2607 }
2608 
2609 /*
2610  * Set all machine fault tracing flags.
2611  */
2612 void
2613 Psetfault(struct ps_prochandle *P, const fltset_t *set)
2614 {
2615 	if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2616 	    P->state == PS_IDLE)
2617 		return;
2618 
2619 	P->status.pr_flttrace = *set;
2620 	P->flags |= SETFAULT;
2621 
2622 	if (P->state == PS_RUN)
2623 		Psync(P);
2624 }
2625 
2626 /*
2627  * Set action on specified system call entry.
2628  */
2629 int
2630 Psysentry(struct ps_prochandle *P, int which, int stop)
2631 {
2632 	return (Psetaction(P, &P->status.pr_sysentry, sizeof (sysset_t),
2633 	    SETENTRY, PRMAXSYS, which, stop));
2634 }
2635 
2636 /*
2637  * Set all system call entry tracing flags.
2638  */
2639 void
2640 Psetsysentry(struct ps_prochandle *P, const sysset_t *set)
2641 {
2642 	if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2643 	    P->state == PS_IDLE)
2644 		return;
2645 
2646 	P->status.pr_sysentry = *set;
2647 	P->flags |= SETENTRY;
2648 
2649 	if (P->state == PS_RUN)
2650 		Psync(P);
2651 }
2652 
2653 /*
2654  * Set action on specified system call exit.
2655  */
2656 int
2657 Psysexit(struct ps_prochandle *P, int which, int stop)
2658 {
2659 	return (Psetaction(P, &P->status.pr_sysexit, sizeof (sysset_t),
2660 	    SETEXIT, PRMAXSYS, which, stop));
2661 }
2662 
2663 /*
2664  * Set all system call exit tracing flags.
2665  */
2666 void
2667 Psetsysexit(struct ps_prochandle *P, const sysset_t *set)
2668 {
2669 	if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2670 	    P->state == PS_IDLE)
2671 		return;
2672 
2673 	P->status.pr_sysexit = *set;
2674 	P->flags |= SETEXIT;
2675 
2676 	if (P->state == PS_RUN)
2677 		Psync(P);
2678 }
2679 
2680 /*
2681  * Utility function to read the contents of a file that contains a
2682  * prheader_t at the start (/proc/pid/lstatus or /proc/pid/lpsinfo).
2683  * Returns a malloc()d buffer or NULL on failure.
2684  */
2685 static prheader_t *
2686 read_lfile(struct ps_prochandle *P, const char *lname)
2687 {
2688 	prheader_t *Lhp;
2689 	char lpath[PATH_MAX];
2690 	struct stat64 statb;
2691 	int fd;
2692 	size_t size;
2693 	ssize_t rval;
2694 
2695 	(void) snprintf(lpath, sizeof (lpath), "%s/%d/%s", procfs_path,
2696 	    (int)P->status.pr_pid, lname);
2697 	if ((fd = open(lpath, O_RDONLY)) < 0 || fstat64(fd, &statb) != 0) {
2698 		if (fd >= 0)
2699 			(void) close(fd);
2700 		return (NULL);
2701 	}
2702 
2703 	/*
2704 	 * 'size' is just the initial guess at the buffer size.
2705 	 * It will have to grow if the number of lwps increases
2706 	 * while we are looking at the process.
2707 	 * 'size' must be larger than the actual file size.
2708 	 */
2709 	size = statb.st_size + 32;
2710 
2711 	for (;;) {
2712 		if ((Lhp = malloc(size)) == NULL)
2713 			break;
2714 		if ((rval = pread(fd, Lhp, size, 0)) < 0 ||
2715 		    rval <= sizeof (prheader_t)) {
2716 			free(Lhp);
2717 			Lhp = NULL;
2718 			break;
2719 		}
2720 		if (rval < size)
2721 			break;
2722 		/* need a bigger buffer */
2723 		free(Lhp);
2724 		size *= 2;
2725 	}
2726 
2727 	(void) close(fd);
2728 	return (Lhp);
2729 }
2730 
2731 /*
2732  * LWP iteration interface.
2733  */
2734 int
2735 Plwp_iter(struct ps_prochandle *P, proc_lwp_f *func, void *cd)
2736 {
2737 	prheader_t *Lhp;
2738 	lwpstatus_t *Lsp;
2739 	long nlwp;
2740 	int rv;
2741 
2742 	switch (P->state) {
2743 	case PS_RUN:
2744 		(void) Pstopstatus(P, PCNULL, 0);
2745 		break;
2746 
2747 	case PS_STOP:
2748 		Psync(P);
2749 		break;
2750 
2751 	case PS_IDLE:
2752 		errno = ENODATA;
2753 		return (-1);
2754 	}
2755 
2756 	/*
2757 	 * For either live processes or cores, the single LWP case is easy:
2758 	 * the pstatus_t contains the lwpstatus_t for the only LWP.
2759 	 */
2760 	if (P->status.pr_nlwp <= 1)
2761 		return (func(cd, &P->status.pr_lwp));
2762 
2763 	/*
2764 	 * For the core file multi-LWP case, we just iterate through the
2765 	 * list of LWP structs we read in from the core file.
2766 	 */
2767 	if (P->state == PS_DEAD) {
2768 		lwp_info_t *lwp = list_prev(&P->core->core_lwp_head);
2769 		uint_t i;
2770 
2771 		for (i = 0; i < P->core->core_nlwp; i++, lwp = list_prev(lwp)) {
2772 			if (lwp->lwp_psinfo.pr_sname != 'Z' &&
2773 			    (rv = func(cd, &lwp->lwp_status)) != 0)
2774 				break;
2775 		}
2776 
2777 		return (rv);
2778 	}
2779 
2780 	/*
2781 	 * For the live process multi-LWP case, we have to work a little
2782 	 * harder: the /proc/pid/lstatus file has the array of LWP structs.
2783 	 */
2784 	if ((Lhp = read_lfile(P, "lstatus")) == NULL)
2785 		return (-1);
2786 
2787 	for (nlwp = Lhp->pr_nent, Lsp = (lwpstatus_t *)(uintptr_t)(Lhp + 1);
2788 	    nlwp > 0;
2789 	    nlwp--, Lsp = (lwpstatus_t *)((uintptr_t)Lsp + Lhp->pr_entsize)) {
2790 		if ((rv = func(cd, Lsp)) != 0)
2791 			break;
2792 	}
2793 
2794 	free(Lhp);
2795 	return (rv);
2796 }
2797 
2798 /*
2799  * Extended LWP iteration interface.
2800  * Iterate over all LWPs, active and zombie.
2801  */
2802 int
2803 Plwp_iter_all(struct ps_prochandle *P, proc_lwp_all_f *func, void *cd)
2804 {
2805 	prheader_t *Lhp = NULL;
2806 	lwpstatus_t *Lsp;
2807 	lwpstatus_t *sp;
2808 	prheader_t *Lphp = NULL;
2809 	lwpsinfo_t *Lpsp;
2810 	long nstat;
2811 	long ninfo;
2812 	int rv;
2813 
2814 retry:
2815 	if (Lhp != NULL)
2816 		free(Lhp);
2817 	if (Lphp != NULL)
2818 		free(Lphp);
2819 	if (P->state == PS_RUN)
2820 		(void) Pstopstatus(P, PCNULL, 0);
2821 	(void) Ppsinfo(P);
2822 
2823 	if (P->state == PS_STOP)
2824 		Psync(P);
2825 
2826 	/*
2827 	 * For either live processes or cores, the single LWP case is easy:
2828 	 * the pstatus_t contains the lwpstatus_t for the only LWP and
2829 	 * the psinfo_t contains the lwpsinfo_t for the only LWP.
2830 	 */
2831 	if (P->status.pr_nlwp + P->status.pr_nzomb <= 1)
2832 		return (func(cd, &P->status.pr_lwp, &P->psinfo.pr_lwp));
2833 
2834 	/*
2835 	 * For the core file multi-LWP case, we just iterate through the
2836 	 * list of LWP structs we read in from the core file.
2837 	 */
2838 	if (P->state == PS_DEAD) {
2839 		lwp_info_t *lwp = list_prev(&P->core->core_lwp_head);
2840 		uint_t i;
2841 
2842 		for (i = 0; i < P->core->core_nlwp; i++, lwp = list_prev(lwp)) {
2843 			sp = (lwp->lwp_psinfo.pr_sname == 'Z')? NULL :
2844 			    &lwp->lwp_status;
2845 			if ((rv = func(cd, sp, &lwp->lwp_psinfo)) != 0)
2846 				break;
2847 		}
2848 
2849 		return (rv);
2850 	}
2851 
2852 	/*
2853 	 * For the live process multi-LWP case, we have to work a little
2854 	 * harder: the /proc/pid/lstatus file has the array of lwpstatus_t's
2855 	 * and the /proc/pid/lpsinfo file has the array of lwpsinfo_t's.
2856 	 */
2857 	if ((Lhp = read_lfile(P, "lstatus")) == NULL)
2858 		return (-1);
2859 	if ((Lphp = read_lfile(P, "lpsinfo")) == NULL) {
2860 		free(Lhp);
2861 		return (-1);
2862 	}
2863 
2864 	/*
2865 	 * If we are looking at a running process, or one we do not control,
2866 	 * the active and zombie lwps in the process may have changed since
2867 	 * we read the process status structure.  If so, just start over.
2868 	 */
2869 	if (Lhp->pr_nent != P->status.pr_nlwp ||
2870 	    Lphp->pr_nent != P->status.pr_nlwp + P->status.pr_nzomb)
2871 		goto retry;
2872 
2873 	/*
2874 	 * To be perfectly safe, prescan the two arrays, checking consistency.
2875 	 * We rely on /proc giving us lwpstatus_t's and lwpsinfo_t's in the
2876 	 * same order (the lwp directory order) in their respective files.
2877 	 * We also rely on there being (possibly) more lwpsinfo_t's than
2878 	 * lwpstatus_t's (the extra lwpsinfo_t's are for zombie lwps).
2879 	 */
2880 	Lsp = (lwpstatus_t *)(uintptr_t)(Lhp + 1);
2881 	Lpsp = (lwpsinfo_t *)(uintptr_t)(Lphp + 1);
2882 	nstat = Lhp->pr_nent;
2883 	for (ninfo = Lphp->pr_nent; ninfo != 0; ninfo--) {
2884 		if (Lpsp->pr_sname != 'Z') {
2885 			/*
2886 			 * Not a zombie lwp; check for matching lwpids.
2887 			 */
2888 			if (nstat == 0 || Lsp->pr_lwpid != Lpsp->pr_lwpid)
2889 				goto retry;
2890 			Lsp = (lwpstatus_t *)((uintptr_t)Lsp + Lhp->pr_entsize);
2891 			nstat--;
2892 		}
2893 		Lpsp = (lwpsinfo_t *)((uintptr_t)Lpsp + Lphp->pr_entsize);
2894 	}
2895 	if (nstat != 0)
2896 		goto retry;
2897 
2898 	/*
2899 	 * Rescan, this time for real.
2900 	 */
2901 	Lsp = (lwpstatus_t *)(uintptr_t)(Lhp + 1);
2902 	Lpsp = (lwpsinfo_t *)(uintptr_t)(Lphp + 1);
2903 	for (ninfo = Lphp->pr_nent; ninfo != 0; ninfo--) {
2904 		if (Lpsp->pr_sname != 'Z') {
2905 			sp = Lsp;
2906 			Lsp = (lwpstatus_t *)((uintptr_t)Lsp + Lhp->pr_entsize);
2907 		} else {
2908 			sp = NULL;
2909 		}
2910 		if ((rv = func(cd, sp, Lpsp)) != 0)
2911 			break;
2912 		Lpsp = (lwpsinfo_t *)((uintptr_t)Lpsp + Lphp->pr_entsize);
2913 	}
2914 
2915 	free(Lhp);
2916 	free(Lphp);
2917 	return (rv);
2918 }
2919 
2920 core_content_t
2921 Pcontent(struct ps_prochandle *P)
2922 {
2923 	if (P->state == PS_DEAD)
2924 		return (P->core->core_content);
2925 	if (P->state == PS_IDLE)
2926 		return (CC_CONTENT_TEXT | CC_CONTENT_DATA | CC_CONTENT_CTF);
2927 
2928 	return (CC_CONTENT_ALL);
2929 }
2930 
2931 /*
2932  * =================================================================
2933  * The remainder of the functions in this file are for the
2934  * control of individual LWPs in the controlled process.
2935  * =================================================================
2936  */
2937 
2938 /*
2939  * Find an entry in the process hash table for the specified lwpid.
2940  * The entry will either point to an existing struct ps_lwphandle
2941  * or it will point to an empty slot for a new struct ps_lwphandle.
2942  */
2943 static struct ps_lwphandle **
2944 Lfind(struct ps_prochandle *P, lwpid_t lwpid)
2945 {
2946 	struct ps_lwphandle **Lp;
2947 	struct ps_lwphandle *L;
2948 
2949 	for (Lp = &P->hashtab[lwpid % (HASHSIZE - 1)];
2950 	    (L = *Lp) != NULL; Lp = &L->lwp_hash)
2951 		if (L->lwp_id == lwpid)
2952 			break;
2953 	return (Lp);
2954 }
2955 
2956 /*
2957  * Grab an LWP contained within the controlled process.
2958  * Return an opaque pointer to its LWP control structure.
2959  *	perr: pointer to error return code.
2960  */
2961 struct ps_lwphandle *
2962 Lgrab(struct ps_prochandle *P, lwpid_t lwpid, int *perr)
2963 {
2964 	struct ps_lwphandle **Lp;
2965 	struct ps_lwphandle *L;
2966 	int fd;
2967 	char procname[PATH_MAX];
2968 	char *fname;
2969 	int rc = 0;
2970 
2971 	(void) mutex_lock(&P->proc_lock);
2972 
2973 	if (P->state == PS_UNDEAD || P->state == PS_IDLE)
2974 		rc = G_NOPROC;
2975 	else if (P->hashtab == NULL &&
2976 	    (P->hashtab = calloc(HASHSIZE, sizeof (struct ps_lwphandle *)))
2977 	    == NULL)
2978 		rc = G_STRANGE;
2979 	else if (*(Lp = Lfind(P, lwpid)) != NULL)
2980 		rc = G_BUSY;
2981 	else if ((L = malloc(sizeof (struct ps_lwphandle))) == NULL)
2982 		rc = G_STRANGE;
2983 	if (rc) {
2984 		*perr = rc;
2985 		(void) mutex_unlock(&P->proc_lock);
2986 		return (NULL);
2987 	}
2988 
2989 	(void) memset(L, 0, sizeof (*L));
2990 	L->lwp_ctlfd = -1;
2991 	L->lwp_statfd = -1;
2992 	L->lwp_proc = P;
2993 	L->lwp_id = lwpid;
2994 	*Lp = L;	/* insert into the hash table */
2995 
2996 	if (P->state == PS_DEAD) {	/* core file */
2997 		if (getlwpstatus(P, lwpid, &L->lwp_status) == -1) {
2998 			rc = G_NOPROC;
2999 			goto err;
3000 		}
3001 		L->lwp_state = PS_DEAD;
3002 		*perr = 0;
3003 		(void) mutex_unlock(&P->proc_lock);
3004 		return (L);
3005 	}
3006 
3007 	/*
3008 	 * Open the /proc/<pid>/lwp/<lwpid> files
3009 	 */
3010 	(void) snprintf(procname, sizeof (procname), "%s/%d/lwp/%d/",
3011 	    procfs_path, (int)P->pid, (int)lwpid);
3012 	fname = procname + strlen(procname);
3013 	(void) set_minfd();
3014 
3015 	(void) strcpy(fname, "lwpstatus");
3016 	if ((fd = open(procname, O_RDONLY)) < 0 ||
3017 	    (fd = dupfd(fd, 0)) < 0) {
3018 		switch (errno) {
3019 		case ENOENT:
3020 			rc = G_NOPROC;
3021 			break;
3022 		default:
3023 			dprintf("Lgrab: failed to open %s: %s\n",
3024 			    procname, strerror(errno));
3025 			rc = G_STRANGE;
3026 			break;
3027 		}
3028 		goto err;
3029 	}
3030 	L->lwp_statfd = fd;
3031 
3032 	if (pread(fd, &L->lwp_status, sizeof (L->lwp_status), (off_t)0) < 0) {
3033 		switch (errno) {
3034 		case ENOENT:
3035 			rc = G_NOPROC;
3036 			break;
3037 		default:
3038 			dprintf("Lgrab: failed to read %s: %s\n",
3039 			    procname, strerror(errno));
3040 			rc = G_STRANGE;
3041 			break;
3042 		}
3043 		goto err;
3044 	}
3045 
3046 	(void) strcpy(fname, "lwpctl");
3047 	if ((fd = open(procname, O_WRONLY)) < 0 ||
3048 	    (fd = dupfd(fd, 0)) < 0) {
3049 		switch (errno) {
3050 		case ENOENT:
3051 			rc = G_NOPROC;
3052 			break;
3053 		default:
3054 			dprintf("Lgrab: failed to open %s: %s\n",
3055 			    procname, strerror(errno));
3056 			rc = G_STRANGE;
3057 			break;
3058 		}
3059 		goto err;
3060 	}
3061 	L->lwp_ctlfd = fd;
3062 
3063 	L->lwp_state =
3064 	    ((L->lwp_status.pr_flags & (PR_STOPPED|PR_ISTOP))
3065 	    == (PR_STOPPED|PR_ISTOP))?
3066 	    PS_STOP : PS_RUN;
3067 
3068 	*perr = 0;
3069 	(void) mutex_unlock(&P->proc_lock);
3070 	return (L);
3071 
3072 err:
3073 	Lfree_internal(P, L);
3074 	*perr = rc;
3075 	(void) mutex_unlock(&P->proc_lock);
3076 	return (NULL);
3077 }
3078 
3079 /*
3080  * Return a printable string corresponding to an Lgrab() error return.
3081  */
3082 const char *
3083 Lgrab_error(int error)
3084 {
3085 	const char *str;
3086 
3087 	switch (error) {
3088 	case G_NOPROC:
3089 		str = "no such LWP";
3090 		break;
3091 	case G_BUSY:
3092 		str = "LWP already grabbed";
3093 		break;
3094 	case G_STRANGE:
3095 		str = "unanticipated system error";
3096 		break;
3097 	default:
3098 		str = "unknown error";
3099 		break;
3100 	}
3101 
3102 	return (str);
3103 }
3104 
3105 /*
3106  * Free an LWP control structure.
3107  */
3108 void
3109 Lfree(struct ps_lwphandle *L)
3110 {
3111 	struct ps_prochandle *P = L->lwp_proc;
3112 
3113 	(void) mutex_lock(&P->proc_lock);
3114 	Lfree_internal(P, L);
3115 	(void) mutex_unlock(&P->proc_lock);
3116 }
3117 
3118 static void
3119 Lfree_internal(struct ps_prochandle *P, struct ps_lwphandle *L)
3120 {
3121 	*Lfind(P, L->lwp_id) = L->lwp_hash;	/* delete from hash table */
3122 	if (L->lwp_ctlfd >= 0)
3123 		(void) close(L->lwp_ctlfd);
3124 	if (L->lwp_statfd >= 0)
3125 		(void) close(L->lwp_statfd);
3126 
3127 	/* clear out the structure as a precaution against reuse */
3128 	(void) memset(L, 0, sizeof (*L));
3129 	L->lwp_ctlfd = -1;
3130 	L->lwp_statfd = -1;
3131 
3132 	free(L);
3133 }
3134 
3135 /*
3136  * Return the state of the process, one of the PS_* values.
3137  */
3138 int
3139 Lstate(struct ps_lwphandle *L)
3140 {
3141 	return (L->lwp_state);
3142 }
3143 
3144 /*
3145  * Return the open control file descriptor for the LWP.
3146  * Clients must not close this file descriptor, nor use it
3147  * after the LWP is freed.
3148  */
3149 int
3150 Lctlfd(struct ps_lwphandle *L)
3151 {
3152 	return (L->lwp_ctlfd);
3153 }
3154 
3155 /*
3156  * Return a pointer to the LWP lwpsinfo structure.
3157  * Clients should not hold on to this pointer indefinitely.
3158  * It will become invalid on Lfree().
3159  */
3160 const lwpsinfo_t *
3161 Lpsinfo(struct ps_lwphandle *L)
3162 {
3163 	if (Plwp_getpsinfo(L->lwp_proc, L->lwp_id, &L->lwp_psinfo) == -1)
3164 		return (NULL);
3165 
3166 	return (&L->lwp_psinfo);
3167 }
3168 
3169 /*
3170  * Return a pointer to the LWP status structure.
3171  * Clients should not hold on to this pointer indefinitely.
3172  * It will become invalid on Lfree().
3173  */
3174 const lwpstatus_t *
3175 Lstatus(struct ps_lwphandle *L)
3176 {
3177 	return (&L->lwp_status);
3178 }
3179 
3180 /*
3181  * Given an LWP handle, return the process handle.
3182  */
3183 struct ps_prochandle *
3184 Lprochandle(struct ps_lwphandle *L)
3185 {
3186 	return (L->lwp_proc);
3187 }
3188 
3189 /*
3190  * Ensure that all cached state is written to the LWP.
3191  * The cached state is the LWP's signal mask and registers.
3192  */
3193 void
3194 Lsync(struct ps_lwphandle *L)
3195 {
3196 	int ctlfd = L->lwp_ctlfd;
3197 	long cmd[2];
3198 	iovec_t iov[4];
3199 	int n = 0;
3200 
3201 	if (L->lwp_flags & SETHOLD) {
3202 		cmd[0] = PCSHOLD;
3203 		iov[n].iov_base = (caddr_t)&cmd[0];
3204 		iov[n++].iov_len = sizeof (long);
3205 		iov[n].iov_base = (caddr_t)&L->lwp_status.pr_lwphold;
3206 		iov[n++].iov_len = sizeof (L->lwp_status.pr_lwphold);
3207 	}
3208 	if (L->lwp_flags & SETREGS) {
3209 		cmd[1] = PCSREG;
3210 		iov[n].iov_base = (caddr_t)&cmd[1];
3211 		iov[n++].iov_len = sizeof (long);
3212 		iov[n].iov_base = (caddr_t)&L->lwp_status.pr_reg[0];
3213 		iov[n++].iov_len = sizeof (L->lwp_status.pr_reg);
3214 	}
3215 
3216 	if (n == 0 || writev(ctlfd, iov, n) < 0)
3217 		return;		/* nothing to do or write failed */
3218 
3219 	L->lwp_flags &= ~(SETHOLD|SETREGS);
3220 }
3221 
3222 /*
3223  * Wait for the specified LWP to stop or terminate.
3224  * Or, just get the current status (PCNULL).
3225  * Or, direct it to stop and get the current status (PCDSTOP).
3226  */
3227 static int
3228 Lstopstatus(struct ps_lwphandle *L,
3229 	long request,		/* PCNULL, PCDSTOP, PCSTOP, PCWSTOP */
3230 	uint_t msec)		/* if non-zero, timeout in milliseconds */
3231 {
3232 	int ctlfd = L->lwp_ctlfd;
3233 	long ctl[3];
3234 	ssize_t rc;
3235 	int err;
3236 
3237 	switch (L->lwp_state) {
3238 	case PS_RUN:
3239 		break;
3240 	case PS_STOP:
3241 		if (request != PCNULL && request != PCDSTOP)
3242 			return (0);
3243 		break;
3244 	case PS_LOST:
3245 		if (request != PCNULL) {
3246 			errno = EAGAIN;
3247 			return (-1);
3248 		}
3249 		break;
3250 	case PS_UNDEAD:
3251 	case PS_DEAD:
3252 		if (request != PCNULL) {
3253 			errno = ENOENT;
3254 			return (-1);
3255 		}
3256 		break;
3257 	default:	/* corrupted state */
3258 		dprintf("Lstopstatus: corrupted state: %d\n", L->lwp_state);
3259 		errno = EINVAL;
3260 		return (-1);
3261 	}
3262 
3263 	ctl[0] = PCDSTOP;
3264 	ctl[1] = PCTWSTOP;
3265 	ctl[2] = (long)msec;
3266 	rc = 0;
3267 	switch (request) {
3268 	case PCSTOP:
3269 		rc = write(ctlfd, &ctl[0], 3*sizeof (long));
3270 		break;
3271 	case PCWSTOP:
3272 		rc = write(ctlfd, &ctl[1], 2*sizeof (long));
3273 		break;
3274 	case PCDSTOP:
3275 		rc = write(ctlfd, &ctl[0], 1*sizeof (long));
3276 		break;
3277 	case PCNULL:
3278 		if (L->lwp_state == PS_DEAD)
3279 			return (0); /* Nothing else to do for cores */
3280 		break;
3281 	default:	/* programming error */
3282 		errno = EINVAL;
3283 		return (-1);
3284 	}
3285 	err = (rc < 0)? errno : 0;
3286 	Lsync(L);
3287 
3288 	if (pread(L->lwp_statfd, &L->lwp_status,
3289 	    sizeof (L->lwp_status), (off_t)0) < 0)
3290 		err = errno;
3291 
3292 	if (err) {
3293 		switch (err) {
3294 		case EINTR:		/* user typed ctl-C */
3295 		case ERESTART:
3296 			dprintf("Lstopstatus: EINTR\n");
3297 			break;
3298 		case EAGAIN:		/* we lost control of the the process */
3299 			dprintf("Lstopstatus: EAGAIN\n");
3300 			L->lwp_state = PS_LOST;
3301 			errno = err;
3302 			return (-1);
3303 		default:
3304 			if (_libproc_debug) {
3305 				const char *errstr;
3306 
3307 				switch (request) {
3308 				case PCNULL:
3309 					errstr = "Lstopstatus PCNULL"; break;
3310 				case PCSTOP:
3311 					errstr = "Lstopstatus PCSTOP"; break;
3312 				case PCDSTOP:
3313 					errstr = "Lstopstatus PCDSTOP"; break;
3314 				case PCWSTOP:
3315 					errstr = "Lstopstatus PCWSTOP"; break;
3316 				default:
3317 					errstr = "Lstopstatus PC???"; break;
3318 				}
3319 				dprintf("%s: %s\n", errstr, strerror(err));
3320 			}
3321 			L->lwp_state = PS_UNDEAD;
3322 			errno = err;
3323 			return (-1);
3324 		}
3325 	}
3326 
3327 	if ((L->lwp_status.pr_flags & (PR_STOPPED|PR_ISTOP))
3328 	    != (PR_STOPPED|PR_ISTOP)) {
3329 		L->lwp_state = PS_RUN;
3330 		if (request == PCNULL || request == PCDSTOP || msec != 0)
3331 			return (0);
3332 		dprintf("Lstopstatus: LWP is not stopped\n");
3333 		errno = EPROTO;
3334 		return (-1);
3335 	}
3336 
3337 	L->lwp_state = PS_STOP;
3338 
3339 	if (_libproc_debug)	/* debugging */
3340 		prldump("Lstopstatus", &L->lwp_status);
3341 
3342 	switch (L->lwp_status.pr_why) {
3343 	case PR_SYSENTRY:
3344 	case PR_SYSEXIT:
3345 	case PR_REQUESTED:
3346 	case PR_SIGNALLED:
3347 	case PR_FAULTED:
3348 	case PR_JOBCONTROL:
3349 	case PR_SUSPENDED:
3350 		break;
3351 	default:
3352 		errno = EPROTO;
3353 		return (-1);
3354 	}
3355 
3356 	return (0);
3357 }
3358 
3359 /*
3360  * Wait for the LWP to stop for any reason.
3361  */
3362 int
3363 Lwait(struct ps_lwphandle *L, uint_t msec)
3364 {
3365 	return (Lstopstatus(L, PCWSTOP, msec));
3366 }
3367 
3368 /*
3369  * Direct the LWP to stop; wait for it to stop.
3370  */
3371 int
3372 Lstop(struct ps_lwphandle *L, uint_t msec)
3373 {
3374 	return (Lstopstatus(L, PCSTOP, msec));
3375 }
3376 
3377 /*
3378  * Direct the LWP to stop; don't wait.
3379  */
3380 int
3381 Ldstop(struct ps_lwphandle *L)
3382 {
3383 	return (Lstopstatus(L, PCDSTOP, 0));
3384 }
3385 
3386 /*
3387  * Get the value of one register from stopped LWP.
3388  */
3389 int
3390 Lgetareg(struct ps_lwphandle *L, int regno, prgreg_t *preg)
3391 {
3392 	if (regno < 0 || regno >= NPRGREG) {
3393 		errno = EINVAL;
3394 		return (-1);
3395 	}
3396 
3397 	if (L->lwp_state != PS_STOP) {
3398 		errno = EBUSY;
3399 		return (-1);
3400 	}
3401 
3402 	*preg = L->lwp_status.pr_reg[regno];
3403 	return (0);
3404 }
3405 
3406 /*
3407  * Put value of one register into stopped LWP.
3408  */
3409 int
3410 Lputareg(struct ps_lwphandle *L, int regno, prgreg_t reg)
3411 {
3412 	if (regno < 0 || regno >= NPRGREG) {
3413 		errno = EINVAL;
3414 		return (-1);
3415 	}
3416 
3417 	if (L->lwp_state != PS_STOP) {
3418 		errno = EBUSY;
3419 		return (-1);
3420 	}
3421 
3422 	L->lwp_status.pr_reg[regno] = reg;
3423 	L->lwp_flags |= SETREGS;	/* set registers before continuing */
3424 	return (0);
3425 }
3426 
3427 int
3428 Lsetrun(struct ps_lwphandle *L,
3429 	int sig,	/* signal to pass to LWP */
3430 	int flags)	/* PRSTEP|PRSABORT|PRSTOP|PRCSIG|PRCFAULT */
3431 {
3432 	int ctlfd = L->lwp_ctlfd;
3433 	int sbits = (PR_DSTOP | PR_ISTOP | PR_ASLEEP);
3434 
3435 	long ctl[1 +					/* PCCFAULT	*/
3436 	    1 + sizeof (siginfo_t)/sizeof (long) +	/* PCSSIG/PCCSIG */
3437 	    2 ];					/* PCRUN	*/
3438 
3439 	long *ctlp = ctl;
3440 	size_t size;
3441 
3442 	if (L->lwp_state != PS_STOP &&
3443 	    (L->lwp_status.pr_flags & sbits) == 0) {
3444 		errno = EBUSY;
3445 		return (-1);
3446 	}
3447 
3448 	Lsync(L);	/* flush registers */
3449 
3450 	if (flags & PRCFAULT) {		/* clear current fault */
3451 		*ctlp++ = PCCFAULT;
3452 		flags &= ~PRCFAULT;
3453 	}
3454 
3455 	if (flags & PRCSIG) {		/* clear current signal */
3456 		*ctlp++ = PCCSIG;
3457 		flags &= ~PRCSIG;
3458 	} else if (sig && sig != L->lwp_status.pr_cursig) {
3459 		/* make current signal */
3460 		siginfo_t *infop;
3461 
3462 		*ctlp++ = PCSSIG;
3463 		infop = (siginfo_t *)ctlp;
3464 		(void) memset(infop, 0, sizeof (*infop));
3465 		infop->si_signo = sig;
3466 		ctlp += sizeof (siginfo_t) / sizeof (long);
3467 	}
3468 
3469 	*ctlp++ = PCRUN;
3470 	*ctlp++ = flags;
3471 	size = (char *)ctlp - (char *)ctl;
3472 
3473 	L->lwp_proc->info_valid = 0; /* will need to update map and file info */
3474 	L->lwp_proc->state = PS_RUN;
3475 	L->lwp_state = PS_RUN;
3476 
3477 	if (write(ctlfd, ctl, size) != size) {
3478 		/* Pretend that a job-stopped LWP is running */
3479 		if (errno != EBUSY || L->lwp_status.pr_why != PR_JOBCONTROL)
3480 			return (Lstopstatus(L, PCNULL, 0));
3481 	}
3482 
3483 	return (0);
3484 }
3485 
3486 int
3487 Lclearsig(struct ps_lwphandle *L)
3488 {
3489 	int ctlfd = L->lwp_ctlfd;
3490 	long ctl = PCCSIG;
3491 
3492 	if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
3493 		return (-1);
3494 	L->lwp_status.pr_cursig = 0;
3495 	return (0);
3496 }
3497 
3498 int
3499 Lclearfault(struct ps_lwphandle *L)
3500 {
3501 	int ctlfd = L->lwp_ctlfd;
3502 	long ctl = PCCFAULT;
3503 
3504 	if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
3505 		return (-1);
3506 	return (0);
3507 }
3508 
3509 /*
3510  * Step over a breakpoint, i.e., execute the instruction that
3511  * really belongs at the breakpoint location (the current %pc)
3512  * and leave the LWP stopped at the next instruction.
3513  */
3514 int
3515 Lxecbkpt(struct ps_lwphandle *L, ulong_t saved)
3516 {
3517 	struct ps_prochandle *P = L->lwp_proc;
3518 	int rv, error;
3519 
3520 	if (L->lwp_state != PS_STOP) {
3521 		errno = EBUSY;
3522 		return (-1);
3523 	}
3524 
3525 	Lsync(L);
3526 	error = execute_bkpt(L->lwp_ctlfd,
3527 	    &P->status.pr_flttrace, &L->lwp_status.pr_lwphold,
3528 	    L->lwp_status.pr_reg[R_PC], saved);
3529 	rv = Lstopstatus(L, PCNULL, 0);
3530 
3531 	if (error != 0) {
3532 		if (L->lwp_status.pr_why == PR_JOBCONTROL &&
3533 		    error == EBUSY) {	/* jobcontrol stop -- back off */
3534 			L->lwp_state = PS_RUN;
3535 			return (0);
3536 		}
3537 		if (error == ENOENT)
3538 			return (0);
3539 		errno = error;
3540 		return (-1);
3541 	}
3542 
3543 	return (rv);
3544 }
3545 
3546 /*
3547  * Step over a watchpoint, i.e., execute the instruction that was stopped by
3548  * the watchpoint, and then leave the LWP stopped at the next instruction.
3549  */
3550 int
3551 Lxecwapt(struct ps_lwphandle *L, const prwatch_t *wp)
3552 {
3553 	struct ps_prochandle *P = L->lwp_proc;
3554 	int rv, error;
3555 
3556 	if (L->lwp_state != PS_STOP) {
3557 		errno = EBUSY;
3558 		return (-1);
3559 	}
3560 
3561 	Lsync(L);
3562 	error = execute_wapt(L->lwp_ctlfd,
3563 	    &P->status.pr_flttrace, &L->lwp_status.pr_lwphold, wp);
3564 	rv = Lstopstatus(L, PCNULL, 0);
3565 
3566 	if (error != 0) {
3567 		if (L->lwp_status.pr_why == PR_JOBCONTROL &&
3568 		    error == EBUSY) {	/* jobcontrol stop -- back off */
3569 			L->lwp_state = PS_RUN;
3570 			return (0);
3571 		}
3572 		if (error == ENOENT)
3573 			return (0);
3574 		errno = error;
3575 		return (-1);
3576 	}
3577 
3578 	return (rv);
3579 }
3580 
3581 int
3582 Lstack(struct ps_lwphandle *L, stack_t *stkp)
3583 {
3584 	struct ps_prochandle *P = L->lwp_proc;
3585 	uintptr_t addr = L->lwp_status.pr_ustack;
3586 
3587 	if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
3588 		if (Pread(P, stkp, sizeof (*stkp), addr) != sizeof (*stkp))
3589 			return (-1);
3590 #ifdef _LP64
3591 	} else {
3592 		stack32_t stk32;
3593 
3594 		if (Pread(P, &stk32, sizeof (stk32), addr) != sizeof (stk32))
3595 			return (-1);
3596 
3597 		stack_32_to_n(&stk32, stkp);
3598 #endif
3599 	}
3600 
3601 	return (0);
3602 }
3603 
3604 int
3605 Lmain_stack(struct ps_lwphandle *L, stack_t *stkp)
3606 {
3607 	struct ps_prochandle *P = L->lwp_proc;
3608 
3609 	if (Lstack(L, stkp) != 0)
3610 		return (-1);
3611 
3612 	/*
3613 	 * If the SS_ONSTACK flag is set then this LWP is operating on the
3614 	 * alternate signal stack. We can recover the original stack from
3615 	 * pr_oldcontext.
3616 	 */
3617 	if (!(stkp->ss_flags & SS_ONSTACK))
3618 		return (0);
3619 
3620 	if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
3621 		ucontext_t *ctxp = (void *)L->lwp_status.pr_oldcontext;
3622 
3623 		if (Pread(P, stkp, sizeof (*stkp),
3624 		    (uintptr_t)&ctxp->uc_stack) != sizeof (*stkp))
3625 			return (-1);
3626 #ifdef _LP64
3627 	} else {
3628 		ucontext32_t *ctxp = (void *)L->lwp_status.pr_oldcontext;
3629 		stack32_t stk32;
3630 
3631 		if (Pread(P, &stk32, sizeof (stk32),
3632 		    (uintptr_t)&ctxp->uc_stack) != sizeof (stk32))
3633 			return (-1);
3634 
3635 		stack_32_to_n(&stk32, stkp);
3636 #endif
3637 	}
3638 
3639 	return (0);
3640 }
3641 
3642 int
3643 Lalt_stack(struct ps_lwphandle *L, stack_t *stkp)
3644 {
3645 	if (L->lwp_status.pr_altstack.ss_flags & SS_DISABLE) {
3646 		errno = ENODATA;
3647 		return (-1);
3648 	}
3649 
3650 	*stkp = L->lwp_status.pr_altstack;
3651 
3652 	return (0);
3653 }
3654 
3655 /*
3656  * Add a mapping to the given proc handle.  Resizes the array as appropriate and
3657  * manages reference counts on the given file_info_t.
3658  *
3659  * The 'map_relocate' member is used to tell Psort_mappings() that the
3660  * associated file_map pointer needs to be relocated after the mappings have
3661  * been sorted.  It is only set for the first mapping, and has no meaning
3662  * outside these two functions.
3663  */
3664 int
3665 Padd_mapping(struct ps_prochandle *P, off64_t off, file_info_t *fp,
3666     prmap_t *pmap)
3667 {
3668 	map_info_t *mp;
3669 
3670 	if (P->map_count == P->map_alloc) {
3671 		size_t next = P->map_alloc ? P->map_alloc * 2 : 16;
3672 
3673 		if ((P->mappings = realloc(P->mappings,
3674 		    next * sizeof (map_info_t))) == NULL)
3675 			return (-1);
3676 
3677 		P->map_alloc = next;
3678 	}
3679 
3680 	mp = &P->mappings[P->map_count++];
3681 
3682 	mp->map_offset = off;
3683 	mp->map_pmap = *pmap;
3684 	mp->map_relocate = 0;
3685 	if ((mp->map_file = fp) != NULL) {
3686 		if (fp->file_map == NULL) {
3687 			fp->file_map = mp;
3688 			mp->map_relocate = 1;
3689 		}
3690 		fp->file_ref++;
3691 	}
3692 
3693 	return (0);
3694 }
3695 
3696 static int
3697 map_sort(const void *a, const void *b)
3698 {
3699 	const map_info_t *ap = a, *bp = b;
3700 
3701 	if (ap->map_pmap.pr_vaddr < bp->map_pmap.pr_vaddr)
3702 		return (-1);
3703 	else if (ap->map_pmap.pr_vaddr > bp->map_pmap.pr_vaddr)
3704 		return (1);
3705 	else
3706 		return (0);
3707 }
3708 
3709 /*
3710  * Sort the current set of mappings.  Should be called during target
3711  * initialization after all calls to Padd_mapping() have been made.
3712  */
3713 void
3714 Psort_mappings(struct ps_prochandle *P)
3715 {
3716 	int i;
3717 	map_info_t *mp;
3718 
3719 	qsort(P->mappings, P->map_count, sizeof (map_info_t), map_sort);
3720 
3721 	/*
3722 	 * Update all the file_map pointers to refer to the new locations.
3723 	 */
3724 	for (i = 0; i < P->map_count; i++) {
3725 		mp = &P->mappings[i];
3726 		if (mp->map_relocate)
3727 			mp->map_file->file_map = mp;
3728 		mp->map_relocate = 0;
3729 	}
3730 }
3731