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