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