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