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