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