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