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