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