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