xref: /titanic_50/usr/src/cmd/mdb/common/mdb/mdb_proc.c (revision 8cfa78e6de0de88f6a15cd29ee5f6a8a1bfe7c20)
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 /*
27  * Copyright 2015 Joyent, Inc.
28  * Copyright (c) 2014 by Delphix. All rights reserved.
29  */
30 
31 /*
32  * User Process Target
33  *
34  * The user process target is invoked when the -u or -p command-line options
35  * are used, or when an ELF executable file or ELF core file is specified on
36  * the command-line.  This target is also selected by default when no target
37  * options are present.  In this case, it defaults the executable name to
38  * "a.out".  If no process or core file is currently attached, the target
39  * functions as a kind of virtual /dev/zero (in accordance with adb(1)
40  * semantics); reads from the virtual address space return zeroes and writes
41  * fail silently.  The proc target itself is designed as a wrapper around the
42  * services provided by libproc.so: t->t_pshandle is set to the struct
43  * ps_prochandle pointer returned as a handle by libproc.  The target also
44  * opens the executable file itself using the MDB GElf services, for
45  * interpreting the .symtab and .dynsym if no libproc handle has been
46  * initialized, and for handling i/o to and from the object file.  Currently,
47  * the only ISA-dependent portions of the proc target are the $r and ::fpregs
48  * dcmds, the callbacks for t_next() and t_step_out(), and the list of named
49  * registers; these are linked in from the proc_isadep.c file for each ISA and
50  * called from the common code in this file.
51  *
52  * The user process target implements complete user process control using the
53  * facilities provided by libproc.so.  The MDB execution control model and
54  * an overview of software event management is described in mdb_target.c.  The
55  * proc target implements breakpoints by replacing the instruction of interest
56  * with a trap instruction, and then restoring the original instruction to step
57  * over the breakpoint.  The idea of replacing program text with instructions
58  * that transfer control to the debugger dates back as far as 1951 [1].  When
59  * the target stops, we replace each breakpoint with the original instruction
60  * as part of the disarm operation.  This means that no special processing is
61  * required for t_vread() because the instrumented instructions will never be
62  * seen by the debugger once the target stops.  Some debuggers have improved
63  * start/stop performance by leaving breakpoint traps in place and then
64  * handling a read from a breakpoint address as a special case.  Although this
65  * improves efficiency for a source-level debugger, it runs somewhat contrary
66  * to the philosophy of the low-level debugger.  Since we remove the
67  * instructions, users can apply other external debugging tools to the process
68  * once it has stopped (e.g. the proc(1) tools) and not be misled by MDB
69  * instrumentation.  The tracing of faults, signals, system calls, and
70  * watchpoints and general process inspection is implemented directly using
71  * the mechanisms provided by /proc, as described originally in [2] and [3].
72  *
73  * References
74  *
75  * [1] S. Gill, "The Diagnosis Of Mistakes In Programmes on the EDSAC",
76  *     Proceedings of the Royal Society Series A Mathematical and Physical
77  *     Sciences, Cambridge University Press, 206(1087), May 1951, pp. 538-554.
78  *
79  * [2] T.J. Killian, "Processes as Files", Proceedings of the USENIX Association
80  *     Summer Conference, Salt Lake City, June 1984, pp. 203-207.
81  *
82  * [3] Roger Faulkner and Ron Gomes, "The Process File System and Process
83  *     Model in UNIX System V", Proceedings of the USENIX Association
84  *     Winter Conference, Dallas, January 1991, pp. 243-252.
85  */
86 
87 #include <mdb/mdb_proc.h>
88 #include <mdb/mdb_disasm.h>
89 #include <mdb/mdb_signal.h>
90 #include <mdb/mdb_string.h>
91 #include <mdb/mdb_module.h>
92 #include <mdb/mdb_debug.h>
93 #include <mdb/mdb_conf.h>
94 #include <mdb/mdb_err.h>
95 #include <mdb/mdb_types.h>
96 #include <mdb/mdb.h>
97 
98 #include <sys/utsname.h>
99 #include <sys/wait.h>
100 #include <sys/stat.h>
101 #include <termio.h>
102 #include <signal.h>
103 #include <stdio_ext.h>
104 #include <stdlib.h>
105 #include <string.h>
106 
107 #define	PC_FAKE		-1UL			/* illegal pc value unequal 0 */
108 #define	PANIC_BUFSIZE	1024
109 
110 static const char PT_EXEC_PATH[] = "a.out";	/* Default executable */
111 static const char PT_CORE_PATH[] = "core";	/* Default core file */
112 
113 static const pt_ptl_ops_t proc_lwp_ops;
114 static const pt_ptl_ops_t proc_tdb_ops;
115 static const mdb_se_ops_t proc_brkpt_ops;
116 static const mdb_se_ops_t proc_wapt_ops;
117 
118 static int pt_setrun(mdb_tgt_t *, mdb_tgt_status_t *, int);
119 static void pt_activate_common(mdb_tgt_t *);
120 static mdb_tgt_vespec_f pt_ignore_sig;
121 static mdb_tgt_se_f pt_fork;
122 static mdb_tgt_se_f pt_exec;
123 
124 static int pt_lookup_by_name_thr(mdb_tgt_t *, const char *,
125     const char *, GElf_Sym *, mdb_syminfo_t *, mdb_tgt_tid_t);
126 static int tlsbase(mdb_tgt_t *, mdb_tgt_tid_t, Lmid_t, const char *,
127     psaddr_t *);
128 
129 /*
130  * When debugging postmortem, we don't resolve names as we may very well not
131  * be on a system on which those names resolve.
132  */
133 #define	PT_LIBPROC_RESOLVE(P) \
134 	(!(mdb.m_flags & MDB_FL_LMRAW) && Pstate(P) != PS_DEAD)
135 
136 /*
137  * The Perror_printf() function interposes on the default, empty libproc
138  * definition.  It will be called to report additional information on complex
139  * errors, such as a corrupt core file.  We just pass the args to vwarn.
140  */
141 /*ARGSUSED*/
142 void
143 Perror_printf(struct ps_prochandle *P, const char *format, ...)
144 {
145 	va_list alist;
146 
147 	va_start(alist, format);
148 	vwarn(format, alist);
149 	va_end(alist);
150 }
151 
152 /*
153  * Open the specified i/o backend as the a.out executable file, and attempt to
154  * load its standard and dynamic symbol tables.  Note that if mdb_gelf_create
155  * succeeds, io is assigned to p_fio and is automatically held by gelf_create.
156  */
157 static mdb_gelf_file_t *
158 pt_open_aout(mdb_tgt_t *t, mdb_io_t *io)
159 {
160 	pt_data_t *pt = t->t_data;
161 	GElf_Sym s1, s2;
162 
163 	if ((pt->p_file = mdb_gelf_create(io, ET_NONE, GF_FILE)) == NULL)
164 		return (NULL);
165 
166 	pt->p_symtab = mdb_gelf_symtab_create_file(pt->p_file,
167 	    SHT_SYMTAB, MDB_TGT_SYMTAB);
168 	pt->p_dynsym = mdb_gelf_symtab_create_file(pt->p_file,
169 	    SHT_DYNSYM, MDB_TGT_DYNSYM);
170 
171 	/*
172 	 * If we've got an _start symbol with a zero size, prime the private
173 	 * symbol table with a copy of _start with its size set to the distance
174 	 * between _mcount and _start.  We do this because DevPro has shipped
175 	 * the Intel crt1.o without proper .size directives for years, which
176 	 * precludes proper identification of _start in stack traces.
177 	 */
178 	if (mdb_gelf_symtab_lookup_by_name(pt->p_dynsym, "_start", &s1,
179 	    NULL) == 0 && s1.st_size == 0 &&
180 	    GELF_ST_TYPE(s1.st_info) == STT_FUNC) {
181 		if (mdb_gelf_symtab_lookup_by_name(pt->p_dynsym, "_mcount",
182 		    &s2, NULL) == 0 && GELF_ST_TYPE(s2.st_info) == STT_FUNC) {
183 			s1.st_size = s2.st_value - s1.st_value;
184 			mdb_gelf_symtab_insert(mdb.m_prsym, "_start", &s1);
185 		}
186 	}
187 
188 	pt->p_fio = io;
189 	return (pt->p_file);
190 }
191 
192 /*
193  * Destroy the symbol tables and GElf file object associated with p_fio.  Note
194  * that we do not need to explicitly free p_fio: its reference count is
195  * automatically decremented by mdb_gelf_destroy, which will free it if needed.
196  */
197 static void
198 pt_close_aout(mdb_tgt_t *t)
199 {
200 	pt_data_t *pt = t->t_data;
201 
202 	if (pt->p_symtab != NULL) {
203 		mdb_gelf_symtab_destroy(pt->p_symtab);
204 		pt->p_symtab = NULL;
205 	}
206 
207 	if (pt->p_dynsym != NULL) {
208 		mdb_gelf_symtab_destroy(pt->p_dynsym);
209 		pt->p_dynsym = NULL;
210 	}
211 
212 	if (pt->p_file != NULL) {
213 		mdb_gelf_destroy(pt->p_file);
214 		pt->p_file = NULL;
215 	}
216 
217 	mdb_gelf_symtab_delete(mdb.m_prsym, "_start", NULL);
218 	pt->p_fio = NULL;
219 }
220 
221 typedef struct tdb_mapping {
222 	const char *tm_thr_lib;
223 	const char *tm_db_dir;
224 	const char *tm_db_name;
225 } tdb_mapping_t;
226 
227 static const tdb_mapping_t tdb_map[] = {
228 	{ "/lwp/amd64/libthread.so",	"/usr/lib/lwp/", "libthread_db.so" },
229 	{ "/lwp/sparcv9/libthread.so",	"/usr/lib/lwp/", "libthread_db.so" },
230 	{ "/lwp/libthread.so",		"/usr/lib/lwp/", "libthread_db.so" },
231 	{ "/libthread.so",		"/lib/", "libthread_db.so" },
232 	{ "/libc_hwcap",		"/lib/", "libc_db.so" },
233 	{ "/libc.so",			"/lib/", "libc_db.so" }
234 };
235 
236 /*
237  * Pobject_iter callback that we use to search for the presence of libthread in
238  * order to load the corresponding libthread_db support.  We derive the
239  * libthread_db path dynamically based on the libthread path.  If libthread is
240  * found, this function returns 1 (and thus Pobject_iter aborts and returns 1)
241  * regardless of whether it was successful in loading the libthread_db support.
242  * If we iterate over all objects and no libthread is found, 0 is returned.
243  * Since libthread_db support was then merged into libc_db, we load either
244  * libc_db or libthread_db, depending on which library we see first.
245  */
246 /*ARGSUSED*/
247 static int
248 thr_check(mdb_tgt_t *t, const prmap_t *pmp, const char *name)
249 {
250 	pt_data_t *pt = t->t_data;
251 	const mdb_tdb_ops_t *ops;
252 	char *p;
253 
254 	char path[MAXPATHLEN];
255 
256 	int libn;
257 
258 	if (name == NULL)
259 		return (0); /* no rtld_db object name; keep going */
260 
261 	for (libn = 0; libn < sizeof (tdb_map) / sizeof (tdb_map[0]); libn++) {
262 		if ((p = strstr(name, tdb_map[libn].tm_thr_lib)) != NULL)
263 			break;
264 	}
265 
266 	if (p == NULL)
267 		return (0); /* no match; keep going */
268 
269 	path[0] = '\0';
270 	(void) strlcat(path, mdb.m_root, sizeof (path));
271 	(void) strlcat(path, tdb_map[libn].tm_db_dir, sizeof (path));
272 #if !defined(_ILP32)
273 	(void) strlcat(path, "64/", sizeof (path));
274 #endif /* !_ILP32 */
275 	(void) strlcat(path, tdb_map[libn].tm_db_name, sizeof (path));
276 
277 	/* Append the trailing library version number. */
278 	(void) strlcat(path, strrchr(name, '.'), sizeof (path));
279 
280 	if ((ops = mdb_tdb_load(path)) == NULL) {
281 		if (libn != 0 || errno != ENOENT)
282 			warn("failed to load %s", path);
283 		goto err;
284 	}
285 
286 	if (ops == pt->p_tdb_ops)
287 		return (1); /* no changes needed */
288 
289 	PTL_DTOR(t);
290 	pt->p_tdb_ops = ops;
291 	pt->p_ptl_ops = &proc_tdb_ops;
292 	pt->p_ptl_hdl = NULL;
293 
294 	if (PTL_CTOR(t) == -1) {
295 		warn("failed to initialize %s", path);
296 		goto err;
297 	}
298 
299 	mdb_dprintf(MDB_DBG_TGT, "loaded %s for debugging %s\n", path, name);
300 	(void) mdb_tgt_status(t, &t->t_status);
301 	return (1);
302 err:
303 	PTL_DTOR(t);
304 	pt->p_tdb_ops = NULL;
305 	pt->p_ptl_ops = &proc_lwp_ops;
306 	pt->p_ptl_hdl = NULL;
307 
308 	if (libn != 0 || errno != ENOENT) {
309 		warn("warning: debugger will only be able to "
310 		    "examine raw LWPs\n");
311 	}
312 
313 	(void) mdb_tgt_status(t, &t->t_status);
314 	return (1);
315 }
316 
317 /*
318  * Whenever the link map is consistent following an add or delete event, we ask
319  * libproc to update its mappings, check to see if we need to load libthread_db,
320  * and then update breakpoints which have been mapped or unmapped.
321  */
322 /*ARGSUSED*/
323 static void
324 pt_rtld_event(mdb_tgt_t *t, int vid, void *private)
325 {
326 	struct ps_prochandle *P = t->t_pshandle;
327 	pt_data_t *pt = t->t_data;
328 	rd_event_msg_t rdm;
329 	int docontinue = 1;
330 
331 	if (rd_event_getmsg(pt->p_rtld, &rdm) == RD_OK) {
332 
333 		mdb_dprintf(MDB_DBG_TGT, "rtld event type 0x%x state 0x%x\n",
334 		    rdm.type, rdm.u.state);
335 
336 		if (rdm.type == RD_DLACTIVITY && rdm.u.state == RD_CONSISTENT) {
337 			mdb_sespec_t *sep, *nsep = mdb_list_next(&t->t_active);
338 			pt_brkpt_t *ptb;
339 
340 			Pupdate_maps(P);
341 
342 			if (Pobject_iter(P, (proc_map_f *)thr_check, t) == 0 &&
343 			    pt->p_ptl_ops != &proc_lwp_ops) {
344 				mdb_dprintf(MDB_DBG_TGT, "unloading thread_db "
345 				    "support after dlclose\n");
346 				PTL_DTOR(t);
347 				pt->p_tdb_ops = NULL;
348 				pt->p_ptl_ops = &proc_lwp_ops;
349 				pt->p_ptl_hdl = NULL;
350 				(void) mdb_tgt_status(t, &t->t_status);
351 			}
352 
353 			for (sep = nsep; sep != NULL; sep = nsep) {
354 				nsep = mdb_list_next(sep);
355 				ptb = sep->se_data;
356 
357 				if (sep->se_ops == &proc_brkpt_ops &&
358 				    Paddr_to_map(P, ptb->ptb_addr) == NULL)
359 					mdb_tgt_sespec_idle_one(t, sep,
360 					    EMDB_NOMAP);
361 			}
362 
363 			if (!mdb_tgt_sespec_activate_all(t) &&
364 			    (mdb.m_flags & MDB_FL_BPTNOSYMSTOP) &&
365 			    pt->p_rtld_finished) {
366 				/*
367 				 * We weren't able to activate the breakpoints.
368 				 * If so requested, we'll return without
369 				 * calling continue, thus throwing the user into
370 				 * the debugger.
371 				 */
372 				docontinue = 0;
373 			}
374 
375 			if (pt->p_rdstate == PT_RD_ADD)
376 				pt->p_rdstate = PT_RD_CONSIST;
377 		}
378 
379 		if (rdm.type == RD_PREINIT)
380 			(void) mdb_tgt_sespec_activate_all(t);
381 
382 		if (rdm.type == RD_POSTINIT) {
383 			pt->p_rtld_finished = TRUE;
384 			if (!mdb_tgt_sespec_activate_all(t) &&
385 			    (mdb.m_flags & MDB_FL_BPTNOSYMSTOP)) {
386 				/*
387 				 * Now that rtld has been initialized, we
388 				 * should be able to initialize all deferred
389 				 * breakpoints.  If we can't, don't let the
390 				 * target continue.
391 				 */
392 				docontinue = 0;
393 			}
394 		}
395 
396 		if (rdm.type == RD_DLACTIVITY && rdm.u.state == RD_ADD &&
397 		    pt->p_rtld_finished)
398 			pt->p_rdstate = MAX(pt->p_rdstate, PT_RD_ADD);
399 	}
400 
401 	if (docontinue)
402 		(void) mdb_tgt_continue(t, NULL);
403 }
404 
405 static void
406 pt_post_attach(mdb_tgt_t *t)
407 {
408 	struct ps_prochandle *P = t->t_pshandle;
409 	const lwpstatus_t *psp = &Pstatus(P)->pr_lwp;
410 	pt_data_t *pt = t->t_data;
411 	int hflag = MDB_TGT_SPEC_HIDDEN;
412 
413 	mdb_dprintf(MDB_DBG_TGT, "attach pr_flags=0x%x pr_why=%d pr_what=%d\n",
414 	    psp->pr_flags, psp->pr_why, psp->pr_what);
415 
416 	/*
417 	 * When we grab a process, the initial setting of p_rtld_finished
418 	 * should be false if the process was just created by exec; otherwise
419 	 * we permit unscoped references to resolve because we do not know how
420 	 * far the process has proceeded through linker initialization.
421 	 */
422 	if ((psp->pr_flags & PR_ISTOP) && psp->pr_why == PR_SYSEXIT &&
423 	    psp->pr_errno == 0 && psp->pr_what == SYS_execve) {
424 		if (mdb.m_target == NULL) {
425 			warn("target performed exec of %s\n",
426 			    IOP_NAME(pt->p_fio));
427 		}
428 		pt->p_rtld_finished = FALSE;
429 	} else
430 		pt->p_rtld_finished = TRUE;
431 
432 	/*
433 	 * When we grab a process, if it is stopped by job control and part of
434 	 * the same session (i.e. same controlling tty), set MDB_FL_JOBCTL so
435 	 * we will know to bring it to the foreground when we continue it.
436 	 */
437 	if (mdb.m_term != NULL && (psp->pr_flags & PR_STOPPED) &&
438 	    psp->pr_why == PR_JOBCONTROL && getsid(0) == Pstatus(P)->pr_sid)
439 		mdb.m_flags |= MDB_FL_JOBCTL;
440 
441 	/*
442 	 * When we grab control of a live process, set F_RDWR so that the
443 	 * target layer permits writes to the target's address space.
444 	 */
445 	t->t_flags |= MDB_TGT_F_RDWR;
446 
447 	(void) Pfault(P, FLTBPT, TRUE);		/* always trace breakpoints */
448 	(void) Pfault(P, FLTWATCH, TRUE);	/* always trace watchpoints */
449 	(void) Pfault(P, FLTTRACE, TRUE);	/* always trace single-step */
450 
451 	(void) Punsetflags(P, PR_ASYNC);	/* require synchronous mode */
452 	(void) Psetflags(P, PR_BPTADJ);		/* always adjust eip on x86 */
453 	(void) Psetflags(P, PR_FORK);		/* inherit tracing on fork */
454 
455 	/*
456 	 * Install event specifiers to track fork and exec activities:
457 	 */
458 	(void) mdb_tgt_add_sysexit(t, SYS_vfork, hflag, pt_fork, NULL);
459 	(void) mdb_tgt_add_sysexit(t, SYS_forksys, hflag, pt_fork, NULL);
460 	(void) mdb_tgt_add_sysexit(t, SYS_execve, hflag, pt_exec, NULL);
461 
462 	/*
463 	 * Attempt to instantiate the librtld_db agent and set breakpoints
464 	 * to track rtld activity.  We will legitimately fail to instantiate
465 	 * the rtld_db agent if the target is statically linked.
466 	 */
467 	if (pt->p_rtld == NULL && (pt->p_rtld = Prd_agent(P)) != NULL) {
468 		rd_notify_t rdn;
469 		rd_err_e err;
470 
471 		if ((err = rd_event_enable(pt->p_rtld, TRUE)) != RD_OK) {
472 			warn("failed to enable rtld_db event tracing: %s\n",
473 			    rd_errstr(err));
474 			goto out;
475 		}
476 
477 		if ((err = rd_event_addr(pt->p_rtld, RD_PREINIT,
478 		    &rdn)) == RD_OK && rdn.type == RD_NOTIFY_BPT) {
479 			(void) mdb_tgt_add_vbrkpt(t, rdn.u.bptaddr,
480 			    hflag, pt_rtld_event, NULL);
481 		} else {
482 			warn("failed to install rtld_db preinit tracing: %s\n",
483 			    rd_errstr(err));
484 		}
485 
486 		if ((err = rd_event_addr(pt->p_rtld, RD_POSTINIT,
487 		    &rdn)) == RD_OK && rdn.type == RD_NOTIFY_BPT) {
488 			(void) mdb_tgt_add_vbrkpt(t, rdn.u.bptaddr,
489 			    hflag, pt_rtld_event, NULL);
490 		} else {
491 			warn("failed to install rtld_db postinit tracing: %s\n",
492 			    rd_errstr(err));
493 		}
494 
495 		if ((err = rd_event_addr(pt->p_rtld, RD_DLACTIVITY,
496 		    &rdn)) == RD_OK && rdn.type == RD_NOTIFY_BPT) {
497 			(void) mdb_tgt_add_vbrkpt(t, rdn.u.bptaddr,
498 			    hflag, pt_rtld_event, NULL);
499 		} else {
500 			warn("failed to install rtld_db activity tracing: %s\n",
501 			    rd_errstr(err));
502 		}
503 	}
504 out:
505 	Pupdate_maps(P);
506 	Psync(P);
507 
508 	/*
509 	 * If librtld_db failed to initialize due to an error or because we are
510 	 * debugging a statically linked executable, allow unscoped references.
511 	 */
512 	if (pt->p_rtld == NULL)
513 		pt->p_rtld_finished = TRUE;
514 
515 	(void) mdb_tgt_sespec_activate_all(t);
516 }
517 
518 /*ARGSUSED*/
519 static int
520 pt_vespec_delete(mdb_tgt_t *t, void *private, int id, void *data)
521 {
522 	if (id < 0) {
523 		ASSERT(data == NULL); /* we don't use any ve_data */
524 		(void) mdb_tgt_vespec_delete(t, id);
525 	}
526 	return (0);
527 }
528 
529 static void
530 pt_pre_detach(mdb_tgt_t *t, int clear_matched)
531 {
532 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
533 	pt_data_t *pt = t->t_data;
534 	long cmd = 0;
535 
536 	/*
537 	 * If we are about to release the process and it is stopped on a traced
538 	 * SIGINT, breakpoint fault, single-step fault, or watchpoint, make
539 	 * sure to clear this event prior to releasing the process so that it
540 	 * does not subsequently reissue the fault and die from SIGTRAP.
541 	 */
542 	if (psp->pr_flags & PR_ISTOP) {
543 		if (psp->pr_why == PR_FAULTED && (psp->pr_what == FLTBPT ||
544 		    psp->pr_what == FLTTRACE || psp->pr_what == FLTWATCH))
545 			cmd = PCCFAULT;
546 		else if (psp->pr_why == PR_SIGNALLED && psp->pr_what == SIGINT)
547 			cmd = PCCSIG;
548 
549 		if (cmd != 0)
550 			(void) write(Pctlfd(t->t_pshandle), &cmd, sizeof (cmd));
551 	}
552 
553 	if (Pstate(t->t_pshandle) == PS_UNDEAD)
554 		(void) waitpid(Pstatus(t->t_pshandle)->pr_pid, NULL, WNOHANG);
555 
556 	(void) mdb_tgt_vespec_iter(t, pt_vespec_delete, NULL);
557 	mdb_tgt_sespec_idle_all(t, EMDB_NOPROC, clear_matched);
558 
559 	if (pt->p_fio != pt->p_aout_fio) {
560 		pt_close_aout(t);
561 		(void) pt_open_aout(t, pt->p_aout_fio);
562 	}
563 
564 	PTL_DTOR(t);
565 	pt->p_tdb_ops = NULL;
566 	pt->p_ptl_ops = &proc_lwp_ops;
567 	pt->p_ptl_hdl = NULL;
568 
569 	pt->p_rtld = NULL;
570 	pt->p_signal = 0;
571 	pt->p_rtld_finished = FALSE;
572 	pt->p_rdstate = PT_RD_NONE;
573 }
574 
575 static void
576 pt_release_parents(mdb_tgt_t *t)
577 {
578 	struct ps_prochandle *P = t->t_pshandle;
579 	pt_data_t *pt = t->t_data;
580 
581 	mdb_sespec_t *sep;
582 	pt_vforkp_t *vfp;
583 
584 	while ((vfp = mdb_list_next(&pt->p_vforkp)) != NULL) {
585 		mdb_dprintf(MDB_DBG_TGT, "releasing vfork parent %d\n",
586 		    (int)Pstatus(vfp->p_pshandle)->pr_pid);
587 
588 		/*
589 		 * To release vfork parents, we must also wipe out any armed
590 		 * events in the parent by switching t_pshandle and calling
591 		 * se_disarm().  Do not change states or lose the matched list.
592 		 */
593 		t->t_pshandle = vfp->p_pshandle;
594 
595 		for (sep = mdb_list_next(&t->t_active); sep != NULL;
596 		    sep = mdb_list_next(sep)) {
597 			if (sep->se_state == MDB_TGT_SPEC_ARMED)
598 				(void) sep->se_ops->se_disarm(t, sep);
599 		}
600 
601 		t->t_pshandle = P;
602 
603 		Prelease(vfp->p_pshandle, PRELEASE_CLEAR);
604 		mdb_list_delete(&pt->p_vforkp, vfp);
605 		mdb_free(vfp, sizeof (pt_vforkp_t));
606 	}
607 }
608 
609 /*ARGSUSED*/
610 static void
611 pt_fork(mdb_tgt_t *t, int vid, void *private)
612 {
613 	struct ps_prochandle *P = t->t_pshandle;
614 	const lwpstatus_t *psp = &Pstatus(P)->pr_lwp;
615 	pt_data_t *pt = t->t_data;
616 	mdb_sespec_t *sep;
617 
618 	int follow_parent = mdb.m_forkmode != MDB_FM_CHILD;
619 	int is_vfork = (psp->pr_what == SYS_vfork ||
620 	    (psp->pr_what == SYS_forksys && psp->pr_sysarg[0] == 2));
621 
622 	struct ps_prochandle *C;
623 	const lwpstatus_t *csp;
624 	char sysname[32];
625 	int gcode;
626 	char c;
627 
628 	mdb_dprintf(MDB_DBG_TGT, "parent %s: errno=%d rv1=%ld rv2=%ld\n",
629 	    proc_sysname(psp->pr_what, sysname, sizeof (sysname)),
630 	    psp->pr_errno, psp->pr_rval1, psp->pr_rval2);
631 
632 	if (psp->pr_errno != 0) {
633 		(void) mdb_tgt_continue(t, NULL);
634 		return; /* fork failed */
635 	}
636 
637 	/*
638 	 * If forkmode is ASK and stdout is a terminal, then ask the user to
639 	 * explicitly set the fork behavior for this particular fork.
640 	 */
641 	if (mdb.m_forkmode == MDB_FM_ASK && mdb.m_term != NULL) {
642 		mdb_iob_printf(mdb.m_err, "%s: %s detected: follow (p)arent "
643 		    "or (c)hild? ", mdb.m_pname, sysname);
644 		mdb_iob_flush(mdb.m_err);
645 
646 		while (IOP_READ(mdb.m_term, &c, sizeof (c)) == sizeof (c)) {
647 			if (c == 'P' || c == 'p') {
648 				mdb_iob_printf(mdb.m_err, "%c\n", c);
649 				follow_parent = TRUE;
650 				break;
651 			} else if (c == 'C' || c == 'c') {
652 				mdb_iob_printf(mdb.m_err, "%c\n", c);
653 				follow_parent = FALSE;
654 				break;
655 			}
656 		}
657 	}
658 
659 	/*
660 	 * The parent is now stopped on exit from its fork call.  We must now
661 	 * grab the child on its return from fork in order to manipulate it.
662 	 */
663 	if ((C = Pgrab(psp->pr_rval1, PGRAB_RETAIN, &gcode)) == NULL) {
664 		warn("failed to grab forked child process %ld: %s\n",
665 		    psp->pr_rval1, Pgrab_error(gcode));
666 		return; /* just stop if we failed to grab the child */
667 	}
668 
669 	/*
670 	 * We may have grabbed the child and stopped it prematurely before it
671 	 * stopped on exit from fork.  If so, wait up to 1 sec for it to settle.
672 	 */
673 	if (Pstatus(C)->pr_lwp.pr_why != PR_SYSEXIT)
674 		(void) Pwait(C, MILLISEC);
675 
676 	csp = &Pstatus(C)->pr_lwp;
677 
678 	if (csp->pr_why != PR_SYSEXIT ||
679 	    (csp->pr_what != SYS_vfork && csp->pr_what != SYS_forksys)) {
680 		warn("forked child process %ld did not stop on exit from "
681 		    "fork as expected\n", psp->pr_rval1);
682 	}
683 
684 	warn("target forked child process %ld (debugger following %s)\n",
685 	    psp->pr_rval1, follow_parent ? "parent" : "child");
686 
687 	(void) Punsetflags(C, PR_ASYNC);	/* require synchronous mode */
688 	(void) Psetflags(C, PR_BPTADJ);		/* always adjust eip on x86 */
689 	(void) Prd_agent(C);			/* initialize librtld_db */
690 
691 	/*
692 	 * At the time pt_fork() is called, the target event engine has already
693 	 * disarmed the specifiers on the active list, clearing out events in
694 	 * the parent process.  However, this means that events that change
695 	 * the address space (e.g. breakpoints) have not been effectively
696 	 * disarmed in the child since its address space reflects the state of
697 	 * the process at the time of fork when events were armed.  We must
698 	 * therefore handle this as a special case and re-invoke the disarm
699 	 * callback of each active specifier to clean out the child process.
700 	 */
701 	if (!is_vfork) {
702 		for (t->t_pshandle = C, sep = mdb_list_next(&t->t_active);
703 		    sep != NULL; sep = mdb_list_next(sep)) {
704 			if (sep->se_state == MDB_TGT_SPEC_ACTIVE)
705 				(void) sep->se_ops->se_disarm(t, sep);
706 		}
707 
708 		t->t_pshandle = P; /* restore pshandle to parent */
709 	}
710 
711 	/*
712 	 * If we're following the parent process, we need to temporarily change
713 	 * t_pshandle to refer to the child handle C so that we can clear out
714 	 * all the events in the child prior to releasing it below.  If we are
715 	 * tracing a vfork, we also need to explicitly wait for the child to
716 	 * exec, exit, or die before we can reset and continue the parent.  We
717 	 * avoid having to deal with the vfork child forking again by clearing
718 	 * PR_FORK and setting PR_RLC; if it does fork it will effectively be
719 	 * released from our control and we will continue following the parent.
720 	 */
721 	if (follow_parent) {
722 		if (is_vfork) {
723 			mdb_tgt_status_t status;
724 
725 			ASSERT(psp->pr_flags & PR_VFORKP);
726 			mdb_tgt_sespec_idle_all(t, EBUSY, FALSE);
727 			t->t_pshandle = C;
728 
729 			(void) Psysexit(C, SYS_execve, TRUE);
730 
731 			(void) Punsetflags(C, PR_FORK | PR_KLC);
732 			(void) Psetflags(C, PR_RLC);
733 
734 			do {
735 				if (pt_setrun(t, &status, 0) == -1 ||
736 				    status.st_state == MDB_TGT_UNDEAD ||
737 				    status.st_state == MDB_TGT_LOST)
738 					break; /* failure or process died */
739 
740 			} while (csp->pr_why != PR_SYSEXIT ||
741 			    csp->pr_errno != 0 || csp->pr_what != SYS_execve);
742 		} else
743 			t->t_pshandle = C;
744 	}
745 
746 	/*
747 	 * If we are following the child, destroy any active libthread_db
748 	 * handle before we release the parent process.
749 	 */
750 	if (!follow_parent) {
751 		PTL_DTOR(t);
752 		pt->p_tdb_ops = NULL;
753 		pt->p_ptl_ops = &proc_lwp_ops;
754 		pt->p_ptl_hdl = NULL;
755 	}
756 
757 	/*
758 	 * Idle all events to make sure the address space and tracing flags are
759 	 * restored, and then release the process we are not tracing.  If we
760 	 * are following the child of a vfork, we push the parent's pshandle
761 	 * on to a list of vfork parents to be released when we exec or exit.
762 	 */
763 	if (is_vfork && !follow_parent) {
764 		pt_vforkp_t *vfp = mdb_alloc(sizeof (pt_vforkp_t), UM_SLEEP);
765 
766 		ASSERT(psp->pr_flags & PR_VFORKP);
767 		vfp->p_pshandle = P;
768 		mdb_list_append(&pt->p_vforkp, vfp);
769 		mdb_tgt_sespec_idle_all(t, EBUSY, FALSE);
770 
771 	} else {
772 		mdb_tgt_sespec_idle_all(t, EBUSY, FALSE);
773 		Prelease(t->t_pshandle, PRELEASE_CLEAR);
774 		if (!follow_parent)
775 			pt_release_parents(t);
776 	}
777 
778 	/*
779 	 * Now that all the hard stuff is done, switch t_pshandle back to the
780 	 * process we are following and reset our events to the ACTIVE state.
781 	 * If we are following the child, reset the libthread_db handle as well
782 	 * as the rtld agent.
783 	 */
784 	if (follow_parent)
785 		t->t_pshandle = P;
786 	else {
787 		t->t_pshandle = C;
788 		pt->p_rtld = Prd_agent(C);
789 		(void) Pobject_iter(t->t_pshandle, (proc_map_f *)thr_check, t);
790 	}
791 
792 	(void) mdb_tgt_sespec_activate_all(t);
793 	(void) mdb_tgt_continue(t, NULL);
794 }
795 
796 /*ARGSUSED*/
797 static void
798 pt_exec(mdb_tgt_t *t, int vid, void *private)
799 {
800 	struct ps_prochandle *P = t->t_pshandle;
801 	const pstatus_t *psp = Pstatus(P);
802 	pt_data_t *pt = t->t_data;
803 	int follow_exec = mdb.m_execmode == MDB_EM_FOLLOW;
804 	pid_t pid = psp->pr_pid;
805 
806 	char execname[MAXPATHLEN];
807 	mdb_sespec_t *sep, *nsep;
808 	mdb_io_t *io;
809 	char c;
810 
811 	mdb_dprintf(MDB_DBG_TGT, "exit from %s: errno=%d\n", proc_sysname(
812 	    psp->pr_lwp.pr_what, execname, sizeof (execname)),
813 	    psp->pr_lwp.pr_errno);
814 
815 	if (psp->pr_lwp.pr_errno != 0) {
816 		(void) mdb_tgt_continue(t, NULL);
817 		return; /* exec failed */
818 	}
819 
820 	/*
821 	 * If execmode is ASK and stdout is a terminal, then ask the user to
822 	 * explicitly set the exec behavior for this particular exec.  If
823 	 * Pstate() still shows PS_LOST, we are being called from pt_setrun()
824 	 * directly and therefore we must resume the terminal since it is still
825 	 * in the suspended state as far as tgt_continue() is concerned.
826 	 */
827 	if (mdb.m_execmode == MDB_EM_ASK && mdb.m_term != NULL) {
828 		if (Pstate(P) == PS_LOST)
829 			IOP_RESUME(mdb.m_term);
830 
831 		mdb_iob_printf(mdb.m_err, "%s: %s detected: (f)ollow new "
832 		    "program or (s)top? ", mdb.m_pname, execname);
833 		mdb_iob_flush(mdb.m_err);
834 
835 		while (IOP_READ(mdb.m_term, &c, sizeof (c)) == sizeof (c)) {
836 			if (c == 'F' || c == 'f') {
837 				mdb_iob_printf(mdb.m_err, "%c\n", c);
838 				follow_exec = TRUE;
839 				break;
840 			} else if (c == 'S' || c == 's') {
841 				mdb_iob_printf(mdb.m_err, "%c\n", c);
842 				follow_exec = FALSE;
843 				break;
844 			}
845 		}
846 
847 		if (Pstate(P) == PS_LOST)
848 			IOP_SUSPEND(mdb.m_term);
849 	}
850 
851 	pt_release_parents(t);	/* release any waiting vfork parents */
852 	pt_pre_detach(t, FALSE); /* remove our breakpoints and idle events */
853 	Preset_maps(P);		/* libproc must delete mappings and symtabs */
854 	pt_close_aout(t);	/* free pt symbol tables and GElf file data */
855 
856 	/*
857 	 * If we lost control of the process across the exec and are not able
858 	 * to reopen it, we have no choice but to clear the matched event list
859 	 * and wait for the user to quit or otherwise release the process.
860 	 */
861 	if (Pstate(P) == PS_LOST && Preopen(P) == -1) {
862 		int error = errno;
863 
864 		warn("lost control of PID %d due to exec of %s executable\n",
865 		    (int)pid, error == EOVERFLOW ? "64-bit" : "set-id");
866 
867 		for (sep = t->t_matched; sep != T_SE_END; sep = nsep) {
868 			nsep = sep->se_matched;
869 			sep->se_matched = NULL;
870 			mdb_tgt_sespec_rele(t, sep);
871 		}
872 
873 		if (error != EOVERFLOW)
874 			return; /* just stop if we exec'd a set-id executable */
875 	}
876 
877 	if (Pstate(P) != PS_LOST) {
878 		if (Pexecname(P, execname, sizeof (execname)) == NULL) {
879 			(void) mdb_iob_snprintf(execname, sizeof (execname),
880 			    "/proc/%d/object/a.out", (int)pid);
881 		}
882 
883 		if (follow_exec == FALSE || psp->pr_dmodel == PR_MODEL_NATIVE)
884 			warn("target performed exec of %s\n", execname);
885 
886 		io = mdb_fdio_create_path(NULL, execname, pt->p_oflags, 0);
887 		if (io == NULL) {
888 			warn("failed to open %s", execname);
889 			warn("a.out symbol tables will not be available\n");
890 		} else if (pt_open_aout(t, io) == NULL) {
891 			(void) mdb_dis_select(pt_disasm(NULL));
892 			mdb_io_destroy(io);
893 		} else
894 			(void) mdb_dis_select(pt_disasm(&pt->p_file->gf_ehdr));
895 	}
896 
897 	/*
898 	 * We reset our libthread_db state here, but deliberately do NOT call
899 	 * PTL_DTOR because we do not want to call libthread_db's td_ta_delete.
900 	 * This interface is hopelessly broken in that it writes to the process
901 	 * address space (which we do not want it to do after an exec) and it
902 	 * doesn't bother deallocating any of its storage anyway.
903 	 */
904 	pt->p_tdb_ops = NULL;
905 	pt->p_ptl_ops = &proc_lwp_ops;
906 	pt->p_ptl_hdl = NULL;
907 
908 	if (follow_exec && psp->pr_dmodel != PR_MODEL_NATIVE) {
909 		const char *argv[3];
910 		char *state, *env;
911 		char pidarg[16];
912 		size_t envlen;
913 
914 		if (realpath(getexecname(), execname) == NULL) {
915 			warn("cannot follow PID %d -- failed to resolve "
916 			    "debugger pathname for re-exec", (int)pid);
917 			return;
918 		}
919 
920 		warn("restarting debugger to follow PID %d ...\n", (int)pid);
921 		mdb_dprintf(MDB_DBG_TGT, "re-exec'ing %s\n", execname);
922 
923 		(void) mdb_snprintf(pidarg, sizeof (pidarg), "-p%d", (int)pid);
924 
925 		state = mdb_get_config();
926 		envlen = strlen(MDB_CONFIG_ENV_VAR) + 1 + strlen(state) + 1;
927 		env = mdb_alloc(envlen, UM_SLEEP);
928 		(void) snprintf(env, envlen,
929 		    "%s=%s", MDB_CONFIG_ENV_VAR, state);
930 
931 		(void) putenv(env);
932 
933 		argv[0] = mdb.m_pname;
934 		argv[1] = pidarg;
935 		argv[2] = NULL;
936 
937 		if (mdb.m_term != NULL)
938 			IOP_SUSPEND(mdb.m_term);
939 
940 		Prelease(P, PRELEASE_CLEAR | PRELEASE_HANG);
941 		(void) execv(execname, (char *const *)argv);
942 		warn("failed to re-exec debugger");
943 
944 		if (mdb.m_term != NULL)
945 			IOP_RESUME(mdb.m_term);
946 
947 		t->t_pshandle = pt->p_idlehandle;
948 		return;
949 	}
950 
951 	pt_post_attach(t);	/* install tracing flags and activate events */
952 	pt_activate_common(t);	/* initialize librtld_db and libthread_db */
953 
954 	if (psp->pr_dmodel != PR_MODEL_NATIVE && mdb.m_term != NULL) {
955 		warn("loadable dcmds will not operate on non-native %d-bit "
956 		    "data model\n", psp->pr_dmodel == PR_MODEL_ILP32 ? 32 : 64);
957 		warn("use ::release -a and then run mdb -p %d to restart "
958 		    "debugger\n", (int)pid);
959 	}
960 
961 	if (follow_exec)
962 		(void) mdb_tgt_continue(t, NULL);
963 }
964 
965 static int
966 pt_setflags(mdb_tgt_t *t, int flags)
967 {
968 	pt_data_t *pt = t->t_data;
969 
970 	if ((flags ^ t->t_flags) & MDB_TGT_F_RDWR) {
971 		int mode = (flags & MDB_TGT_F_RDWR) ? O_RDWR : O_RDONLY;
972 		mdb_io_t *io;
973 
974 		if (pt->p_fio == NULL)
975 			return (set_errno(EMDB_NOEXEC));
976 
977 		io = mdb_fdio_create_path(NULL, IOP_NAME(pt->p_fio), mode, 0);
978 
979 		if (io == NULL)
980 			return (-1); /* errno is set for us */
981 
982 		t->t_flags = (t->t_flags & ~MDB_TGT_F_RDWR) |
983 		    (flags & MDB_TGT_F_RDWR);
984 
985 		pt->p_fio = mdb_io_hold(io);
986 		mdb_io_rele(pt->p_file->gf_io);
987 		pt->p_file->gf_io = pt->p_fio;
988 	}
989 
990 	if (flags & MDB_TGT_F_FORCE) {
991 		t->t_flags |= MDB_TGT_F_FORCE;
992 		pt->p_gflags |= PGRAB_FORCE;
993 	}
994 
995 	return (0);
996 }
997 
998 /*ARGSUSED*/
999 static int
1000 pt_frame(void *arglim, uintptr_t pc, uint_t argc, const long *argv,
1001     const mdb_tgt_gregset_t *gregs)
1002 {
1003 	argc = MIN(argc, (uint_t)(uintptr_t)arglim);
1004 	mdb_printf("%a(", pc);
1005 
1006 	if (argc != 0) {
1007 		mdb_printf("%lr", *argv++);
1008 		for (argc--; argc != 0; argc--)
1009 			mdb_printf(", %lr", *argv++);
1010 	}
1011 
1012 	mdb_printf(")\n");
1013 	return (0);
1014 }
1015 
1016 static int
1017 pt_framev(void *arglim, uintptr_t pc, uint_t argc, const long *argv,
1018     const mdb_tgt_gregset_t *gregs)
1019 {
1020 	argc = MIN(argc, (uint_t)(uintptr_t)arglim);
1021 #if defined(__i386) || defined(__amd64)
1022 	mdb_printf("%0?lr %a(", gregs->gregs[R_FP], pc);
1023 #else
1024 	mdb_printf("%0?lr %a(", gregs->gregs[R_SP], pc);
1025 #endif
1026 	if (argc != 0) {
1027 		mdb_printf("%lr", *argv++);
1028 		for (argc--; argc != 0; argc--)
1029 			mdb_printf(", %lr", *argv++);
1030 	}
1031 
1032 	mdb_printf(")\n");
1033 	return (0);
1034 }
1035 
1036 static int
1037 pt_framer(void *arglim, uintptr_t pc, uint_t argc, const long *argv,
1038     const mdb_tgt_gregset_t *gregs)
1039 {
1040 	if (pt_frameregs(arglim, pc, argc, argv, gregs, pc == PC_FAKE) == -1) {
1041 		/*
1042 		 * Use verbose format if register format is not supported.
1043 		 */
1044 		return (pt_framev(arglim, pc, argc, argv, gregs));
1045 	}
1046 
1047 	return (0);
1048 }
1049 
1050 /*ARGSUSED*/
1051 static int
1052 pt_stack_common(uintptr_t addr, uint_t flags, int argc,
1053     const mdb_arg_t *argv, mdb_tgt_stack_f *func, prgreg_t saved_pc)
1054 {
1055 	void *arg = (void *)(uintptr_t)mdb.m_nargs;
1056 	mdb_tgt_t *t = mdb.m_target;
1057 	mdb_tgt_gregset_t gregs;
1058 
1059 	if (argc != 0) {
1060 		if (argv->a_type == MDB_TYPE_CHAR || argc > 1)
1061 			return (DCMD_USAGE);
1062 
1063 		if (argv->a_type == MDB_TYPE_STRING)
1064 			arg = (void *)(uintptr_t)mdb_strtoull(argv->a_un.a_str);
1065 		else
1066 			arg = (void *)(uintptr_t)argv->a_un.a_val;
1067 	}
1068 
1069 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) == PS_IDLE) {
1070 		mdb_warn("no process active\n");
1071 		return (DCMD_ERR);
1072 	}
1073 
1074 	/*
1075 	 * In the universe of sparcv7, sparcv9, ia32, and amd64 this code can be
1076 	 * common: <sys/procfs_isa.h> conveniently #defines R_FP to be the
1077 	 * appropriate register we need to set in order to perform a stack
1078 	 * traceback from a given frame address.
1079 	 */
1080 	if (flags & DCMD_ADDRSPEC) {
1081 		bzero(&gregs, sizeof (gregs));
1082 		gregs.gregs[R_FP] = addr;
1083 #ifdef __sparc
1084 		gregs.gregs[R_I7] = saved_pc;
1085 #endif /* __sparc */
1086 	} else if (PTL_GETREGS(t, PTL_TID(t), gregs.gregs) != 0) {
1087 		mdb_warn("failed to get current register set");
1088 		return (DCMD_ERR);
1089 	}
1090 
1091 	(void) mdb_tgt_stack_iter(t, &gregs, func, arg);
1092 	return (DCMD_OK);
1093 }
1094 
1095 static int
1096 pt_stack(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1097 {
1098 	return (pt_stack_common(addr, flags, argc, argv, pt_frame, 0));
1099 }
1100 
1101 static int
1102 pt_stackv(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1103 {
1104 	return (pt_stack_common(addr, flags, argc, argv, pt_framev, 0));
1105 }
1106 
1107 static int
1108 pt_stackr(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1109 {
1110 	/*
1111 	 * Force printing of first register window, by setting  the
1112 	 * saved pc (%i7) to PC_FAKE.
1113 	 */
1114 	return (pt_stack_common(addr, flags, argc, argv, pt_framer, PC_FAKE));
1115 }
1116 
1117 /*ARGSUSED*/
1118 static int
1119 pt_ignored(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1120 {
1121 	struct ps_prochandle *P = mdb.m_target->t_pshandle;
1122 	char buf[PRSIGBUFSZ];
1123 
1124 	if ((flags & DCMD_ADDRSPEC) || argc != 0)
1125 		return (DCMD_USAGE);
1126 
1127 	if (P == NULL) {
1128 		mdb_warn("no process is currently active\n");
1129 		return (DCMD_ERR);
1130 	}
1131 
1132 	mdb_printf("%s\n", proc_sigset2str(&Pstatus(P)->pr_sigtrace, " ",
1133 	    FALSE, buf, sizeof (buf)));
1134 
1135 	return (DCMD_OK);
1136 }
1137 
1138 /*ARGSUSED*/
1139 static int
1140 pt_lwpid(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1141 {
1142 	struct ps_prochandle *P = mdb.m_target->t_pshandle;
1143 
1144 	if ((flags & DCMD_ADDRSPEC) || argc != 0)
1145 		return (DCMD_USAGE);
1146 
1147 	if (P == NULL) {
1148 		mdb_warn("no process is currently active\n");
1149 		return (DCMD_ERR);
1150 	}
1151 
1152 	mdb_printf("%d\n", Pstatus(P)->pr_lwp.pr_lwpid);
1153 	return (DCMD_OK);
1154 }
1155 
1156 static int
1157 pt_print_lwpid(int *n, const lwpstatus_t *psp)
1158 {
1159 	struct ps_prochandle *P = mdb.m_target->t_pshandle;
1160 	int nlwp = Pstatus(P)->pr_nlwp;
1161 
1162 	if (*n == nlwp - 2)
1163 		mdb_printf("%d and ", (int)psp->pr_lwpid);
1164 	else if (*n == nlwp - 1)
1165 		mdb_printf("%d are", (int)psp->pr_lwpid);
1166 	else
1167 		mdb_printf("%d, ", (int)psp->pr_lwpid);
1168 
1169 	(*n)++;
1170 	return (0);
1171 }
1172 
1173 /*ARGSUSED*/
1174 static int
1175 pt_lwpids(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1176 {
1177 	struct ps_prochandle *P = mdb.m_target->t_pshandle;
1178 	int n = 0;
1179 
1180 	if (P == NULL) {
1181 		mdb_warn("no process is currently active\n");
1182 		return (DCMD_ERR);
1183 	}
1184 
1185 	switch (Pstatus(P)->pr_nlwp) {
1186 	case 0:
1187 		mdb_printf("no lwps are");
1188 		break;
1189 	case 1:
1190 		mdb_printf("lwpid %d is the only lwp",
1191 		    Pstatus(P)->pr_lwp.pr_lwpid);
1192 		break;
1193 	default:
1194 		mdb_printf("lwpids ");
1195 		(void) Plwp_iter(P, (proc_lwp_f *)pt_print_lwpid, &n);
1196 	}
1197 
1198 	switch (Pstate(P)) {
1199 	case PS_DEAD:
1200 		mdb_printf(" in core of process %d.\n", Pstatus(P)->pr_pid);
1201 		break;
1202 	case PS_IDLE:
1203 		mdb_printf(" in idle target.\n");
1204 		break;
1205 	default:
1206 		mdb_printf(" in process %d.\n", (int)Pstatus(P)->pr_pid);
1207 		break;
1208 	}
1209 
1210 	return (DCMD_OK);
1211 }
1212 
1213 /*ARGSUSED*/
1214 static int
1215 pt_ignore(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1216 {
1217 	pt_data_t *pt = mdb.m_target->t_data;
1218 
1219 	if (!(flags & DCMD_ADDRSPEC) || argc != 0)
1220 		return (DCMD_USAGE);
1221 
1222 	if (addr < 1 || addr > pt->p_maxsig) {
1223 		mdb_warn("invalid signal number -- 0t%lu\n", addr);
1224 		return (DCMD_ERR);
1225 	}
1226 
1227 	(void) mdb_tgt_vespec_iter(mdb.m_target, pt_ignore_sig, (void *)addr);
1228 	return (DCMD_OK);
1229 }
1230 
1231 /*ARGSUSED*/
1232 static int
1233 pt_attach(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1234 {
1235 	mdb_tgt_t *t = mdb.m_target;
1236 	pt_data_t *pt = t->t_data;
1237 	int state, perr;
1238 
1239 	if (!(flags & DCMD_ADDRSPEC) && argc == 0)
1240 		return (DCMD_USAGE);
1241 
1242 	if (((flags & DCMD_ADDRSPEC) && argc != 0) || argc > 1 ||
1243 	    (argc != 0 && argv->a_type != MDB_TYPE_STRING))
1244 		return (DCMD_USAGE);
1245 
1246 	if (t->t_pshandle != NULL && Pstate(t->t_pshandle) != PS_IDLE) {
1247 		mdb_warn("debugger is already attached to a %s\n",
1248 		    (Pstate(t->t_pshandle) == PS_DEAD) ? "core" : "process");
1249 		return (DCMD_ERR);
1250 	}
1251 
1252 	if (pt->p_fio == NULL) {
1253 		mdb_warn("attach requires executable to be specified on "
1254 		    "command-line (or use -p)\n");
1255 		return (DCMD_ERR);
1256 	}
1257 
1258 	if (flags & DCMD_ADDRSPEC)
1259 		t->t_pshandle = Pgrab((pid_t)addr, pt->p_gflags, &perr);
1260 	else
1261 		t->t_pshandle = proc_arg_grab(argv->a_un.a_str,
1262 		    PR_ARG_ANY, pt->p_gflags, &perr);
1263 
1264 	if (t->t_pshandle == NULL) {
1265 		t->t_pshandle = pt->p_idlehandle;
1266 		mdb_warn("cannot attach: %s\n", Pgrab_error(perr));
1267 		return (DCMD_ERR);
1268 	}
1269 
1270 	state = Pstate(t->t_pshandle);
1271 	if (state != PS_DEAD && state != PS_IDLE) {
1272 		(void) Punsetflags(t->t_pshandle, PR_KLC);
1273 		(void) Psetflags(t->t_pshandle, PR_RLC);
1274 		pt_post_attach(t);
1275 		pt_activate_common(t);
1276 	}
1277 
1278 	(void) mdb_tgt_status(t, &t->t_status);
1279 	mdb_module_load_all(0);
1280 	return (DCMD_OK);
1281 }
1282 
1283 static int
1284 pt_regstatus(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1285 {
1286 	mdb_tgt_t *t = mdb.m_target;
1287 
1288 	if (t->t_pshandle != NULL) {
1289 		const pstatus_t *psp = Pstatus(t->t_pshandle);
1290 		int cursig = psp->pr_lwp.pr_cursig;
1291 		char signame[SIG2STR_MAX];
1292 		int state = Pstate(t->t_pshandle);
1293 
1294 		if (state != PS_DEAD && state != PS_IDLE)
1295 			mdb_printf("process id = %d\n", psp->pr_pid);
1296 		else
1297 			mdb_printf("no process\n");
1298 
1299 		if (cursig != 0 && sig2str(cursig, signame) == 0)
1300 			mdb_printf("SIG%s: %s\n", signame, strsignal(cursig));
1301 	}
1302 
1303 	return (pt_regs(addr, flags, argc, argv));
1304 }
1305 
1306 static int
1307 pt_findstack(uintptr_t tid, uint_t flags, int argc, const mdb_arg_t *argv)
1308 {
1309 	mdb_tgt_t *t = mdb.m_target;
1310 	mdb_tgt_gregset_t gregs;
1311 	int showargs = 0;
1312 	int count;
1313 	uintptr_t pc, sp;
1314 
1315 	if (!(flags & DCMD_ADDRSPEC))
1316 		return (DCMD_USAGE);
1317 
1318 	count = mdb_getopts(argc, argv, 'v', MDB_OPT_SETBITS, TRUE, &showargs,
1319 	    NULL);
1320 	argc -= count;
1321 	argv += count;
1322 
1323 	if (argc > 1 || (argc == 1 && argv->a_type != MDB_TYPE_STRING))
1324 		return (DCMD_USAGE);
1325 
1326 	if (PTL_GETREGS(t, tid, gregs.gregs) != 0) {
1327 		mdb_warn("failed to get register set for thread %p", tid);
1328 		return (DCMD_ERR);
1329 	}
1330 
1331 	pc = gregs.gregs[R_PC];
1332 #if defined(__i386) || defined(__amd64)
1333 	sp = gregs.gregs[R_FP];
1334 #else
1335 	sp = gregs.gregs[R_SP];
1336 #endif
1337 	mdb_printf("stack pointer for thread %p: %p\n", tid, sp);
1338 	if (pc != 0)
1339 		mdb_printf("[ %0?lr %a() ]\n", sp, pc);
1340 
1341 	(void) mdb_inc_indent(2);
1342 	mdb_set_dot(sp);
1343 
1344 	if (argc == 1)
1345 		(void) mdb_eval(argv->a_un.a_str);
1346 	else if (showargs)
1347 		(void) mdb_eval("<.$C");
1348 	else
1349 		(void) mdb_eval("<.$C0");
1350 
1351 	(void) mdb_dec_indent(2);
1352 	return (DCMD_OK);
1353 }
1354 
1355 /*ARGSUSED*/
1356 static int
1357 pt_gcore(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1358 {
1359 	mdb_tgt_t *t = mdb.m_target;
1360 	char *prefix = "core";
1361 	char *content_str = NULL;
1362 	core_content_t content = CC_CONTENT_DEFAULT;
1363 	size_t size;
1364 	char *fname;
1365 	pid_t pid;
1366 
1367 	if (flags & DCMD_ADDRSPEC)
1368 		return (DCMD_USAGE);
1369 
1370 	if (mdb_getopts(argc, argv,
1371 	    'o', MDB_OPT_STR, &prefix,
1372 	    'c', MDB_OPT_STR, &content_str, NULL) != argc)
1373 		return (DCMD_USAGE);
1374 
1375 	if (content_str != NULL &&
1376 	    (proc_str2content(content_str, &content) != 0 ||
1377 	    content == CC_CONTENT_INVALID)) {
1378 		mdb_warn("invalid content string '%s'\n", content_str);
1379 		return (DCMD_ERR);
1380 	}
1381 
1382 	if (t->t_pshandle == NULL) {
1383 		mdb_warn("no process active\n");
1384 		return (DCMD_ERR);
1385 	}
1386 
1387 	pid = Pstatus(t->t_pshandle)->pr_pid;
1388 	size = 1 + mdb_snprintf(NULL, 0, "%s.%d", prefix, (int)pid);
1389 	fname = mdb_alloc(size, UM_SLEEP | UM_GC);
1390 	(void) mdb_snprintf(fname, size, "%s.%d", prefix, (int)pid);
1391 
1392 	if (Pgcore(t->t_pshandle, fname, content) != 0) {
1393 		/*
1394 		 * Short writes during dumping are specifically described by
1395 		 * EBADE, just as ZFS uses this otherwise-unused code for
1396 		 * checksum errors.  Translate to and mdb errno.
1397 		 */
1398 		if (errno == EBADE)
1399 			(void) set_errno(EMDB_SHORTWRITE);
1400 		mdb_warn("couldn't dump core");
1401 		return (DCMD_ERR);
1402 	}
1403 
1404 	mdb_warn("%s dumped\n", fname);
1405 
1406 	return (DCMD_OK);
1407 }
1408 
1409 /*ARGSUSED*/
1410 static int
1411 pt_kill(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1412 {
1413 	mdb_tgt_t *t = mdb.m_target;
1414 	pt_data_t *pt = t->t_data;
1415 	int state;
1416 
1417 	if ((flags & DCMD_ADDRSPEC) || argc != 0)
1418 		return (DCMD_USAGE);
1419 
1420 	if (t->t_pshandle != NULL &&
1421 	    (state = Pstate(t->t_pshandle)) != PS_DEAD && state != PS_IDLE) {
1422 		mdb_warn("victim process PID %d forcibly terminated\n",
1423 		    (int)Pstatus(t->t_pshandle)->pr_pid);
1424 		pt_pre_detach(t, TRUE);
1425 		pt_release_parents(t);
1426 		Prelease(t->t_pshandle, PRELEASE_KILL);
1427 		t->t_pshandle = pt->p_idlehandle;
1428 		(void) mdb_tgt_status(t, &t->t_status);
1429 		mdb.m_flags &= ~(MDB_FL_VCREATE | MDB_FL_JOBCTL);
1430 	} else
1431 		mdb_warn("no victim process is currently under control\n");
1432 
1433 	return (DCMD_OK);
1434 }
1435 
1436 /*ARGSUSED*/
1437 static int
1438 pt_detach(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1439 {
1440 	mdb_tgt_t *t = mdb.m_target;
1441 	pt_data_t *pt = t->t_data;
1442 	int rflags = pt->p_rflags;
1443 
1444 	if (argc != 0 && argv->a_type == MDB_TYPE_STRING &&
1445 	    strcmp(argv->a_un.a_str, "-a") == 0) {
1446 		rflags = PRELEASE_HANG | PRELEASE_CLEAR;
1447 		argv++;
1448 		argc--;
1449 	}
1450 
1451 	if ((flags & DCMD_ADDRSPEC) || argc != 0)
1452 		return (DCMD_USAGE);
1453 
1454 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) == PS_IDLE) {
1455 		mdb_warn("debugger is not currently attached to a process "
1456 		    "or core file\n");
1457 		return (DCMD_ERR);
1458 	}
1459 
1460 	pt_pre_detach(t, TRUE);
1461 	pt_release_parents(t);
1462 	Prelease(t->t_pshandle, rflags);
1463 	t->t_pshandle = pt->p_idlehandle;
1464 	(void) mdb_tgt_status(t, &t->t_status);
1465 	mdb.m_flags &= ~(MDB_FL_VCREATE | MDB_FL_JOBCTL);
1466 
1467 	return (DCMD_OK);
1468 }
1469 
1470 static uintmax_t
1471 reg_disc_get(const mdb_var_t *v)
1472 {
1473 	mdb_tgt_t *t = MDB_NV_COOKIE(v);
1474 	mdb_tgt_tid_t tid = PTL_TID(t);
1475 	mdb_tgt_reg_t r = 0;
1476 
1477 	if (tid != (mdb_tgt_tid_t)-1L)
1478 		(void) mdb_tgt_getareg(t, tid, mdb_nv_get_name(v), &r);
1479 
1480 	return (r);
1481 }
1482 
1483 static void
1484 reg_disc_set(mdb_var_t *v, uintmax_t r)
1485 {
1486 	mdb_tgt_t *t = MDB_NV_COOKIE(v);
1487 	mdb_tgt_tid_t tid = PTL_TID(t);
1488 
1489 	if (tid != (mdb_tgt_tid_t)-1L && mdb_tgt_putareg(t, tid,
1490 	    mdb_nv_get_name(v), r) == -1)
1491 		mdb_warn("failed to modify %%%s register", mdb_nv_get_name(v));
1492 }
1493 
1494 static void
1495 pt_print_reason(const lwpstatus_t *psp)
1496 {
1497 	char name[SIG2STR_MAX + 4]; /* enough for SIG+name+\0, syscall or flt */
1498 	const char *desc;
1499 
1500 	switch (psp->pr_why) {
1501 	case PR_REQUESTED:
1502 		mdb_printf("stopped by debugger");
1503 		break;
1504 	case PR_SIGNALLED:
1505 		mdb_printf("stopped on %s (%s)", proc_signame(psp->pr_what,
1506 		    name, sizeof (name)), strsignal(psp->pr_what));
1507 		break;
1508 	case PR_SYSENTRY:
1509 		mdb_printf("stopped on entry to %s system call",
1510 		    proc_sysname(psp->pr_what, name, sizeof (name)));
1511 		break;
1512 	case PR_SYSEXIT:
1513 		mdb_printf("stopped on exit from %s system call",
1514 		    proc_sysname(psp->pr_what, name, sizeof (name)));
1515 		break;
1516 	case PR_JOBCONTROL:
1517 		mdb_printf("stopped by job control");
1518 		break;
1519 	case PR_FAULTED:
1520 		if (psp->pr_what == FLTBPT) {
1521 			mdb_printf("stopped on a breakpoint");
1522 		} else if (psp->pr_what == FLTWATCH) {
1523 			switch (psp->pr_info.si_code) {
1524 			case TRAP_RWATCH:
1525 				desc = "read";
1526 				break;
1527 			case TRAP_WWATCH:
1528 				desc = "write";
1529 				break;
1530 			case TRAP_XWATCH:
1531 				desc = "execute";
1532 				break;
1533 			default:
1534 				desc = "unknown";
1535 			}
1536 			mdb_printf("stopped %s a watchpoint (%s access to %p)",
1537 			    psp->pr_info.si_trapafter ? "after" : "on",
1538 			    desc, psp->pr_info.si_addr);
1539 		} else if (psp->pr_what == FLTTRACE) {
1540 			mdb_printf("stopped after a single-step");
1541 		} else {
1542 			mdb_printf("stopped on a %s fault",
1543 			    proc_fltname(psp->pr_what, name, sizeof (name)));
1544 		}
1545 		break;
1546 	case PR_SUSPENDED:
1547 	case PR_CHECKPOINT:
1548 		mdb_printf("suspended by the kernel");
1549 		break;
1550 	default:
1551 		mdb_printf("stopped for unknown reason (%d/%d)",
1552 		    psp->pr_why, psp->pr_what);
1553 	}
1554 }
1555 
1556 /*ARGSUSED*/
1557 static int
1558 pt_status_dcmd(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1559 {
1560 	mdb_tgt_t *t = mdb.m_target;
1561 	struct ps_prochandle *P = t->t_pshandle;
1562 	pt_data_t *pt = t->t_data;
1563 
1564 	if (P != NULL) {
1565 		const psinfo_t *pip = Ppsinfo(P);
1566 		const pstatus_t *psp = Pstatus(P);
1567 		int cursig = 0, bits = 0, coredump = 0;
1568 		int state;
1569 		GElf_Sym sym;
1570 		uintptr_t panicstr;
1571 		char *panicbuf = mdb_alloc(PANIC_BUFSIZE, UM_SLEEP);
1572 		const siginfo_t *sip = &(psp->pr_lwp.pr_info);
1573 
1574 		char execname[MAXPATHLEN], buf[BUFSIZ];
1575 		char signame[SIG2STR_MAX + 4]; /* enough for SIG+name+\0 */
1576 
1577 		mdb_tgt_spec_desc_t desc;
1578 		mdb_sespec_t *sep;
1579 
1580 		struct utsname uts;
1581 		prcred_t cred;
1582 		psinfo_t pi;
1583 
1584 		(void) strcpy(uts.nodename, "unknown machine");
1585 		(void) Puname(P, &uts);
1586 
1587 		if (pip != NULL) {
1588 			bcopy(pip, &pi, sizeof (psinfo_t));
1589 			proc_unctrl_psinfo(&pi);
1590 		} else
1591 			bzero(&pi, sizeof (psinfo_t));
1592 
1593 		bits = pi.pr_dmodel == PR_MODEL_ILP32 ? 32 : 64;
1594 
1595 		state = Pstate(P);
1596 		if (psp != NULL && state != PS_UNDEAD && state != PS_IDLE)
1597 			cursig = psp->pr_lwp.pr_cursig;
1598 
1599 		if (state == PS_DEAD && pip != NULL) {
1600 			mdb_printf("debugging core file of %s (%d-bit) "
1601 			    "from %s\n", pi.pr_fname, bits, uts.nodename);
1602 
1603 		} else if (state == PS_DEAD) {
1604 			mdb_printf("debugging core file\n");
1605 
1606 		} else if (state == PS_IDLE) {
1607 			const GElf_Ehdr *ehp = &pt->p_file->gf_ehdr;
1608 
1609 			mdb_printf("debugging %s file (%d-bit)\n",
1610 			    ehp->e_type == ET_EXEC ? "executable" : "object",
1611 			    ehp->e_ident[EI_CLASS] == ELFCLASS32 ? 32 : 64);
1612 
1613 		} else if (state == PS_UNDEAD && pi.pr_pid == 0) {
1614 			mdb_printf("debugging defunct process\n");
1615 
1616 		} else {
1617 			mdb_printf("debugging PID %d (%d-bit)\n",
1618 			    pi.pr_pid, bits);
1619 		}
1620 
1621 		if (Pexecname(P, execname, sizeof (execname)) != NULL)
1622 			mdb_printf("file: %s\n", execname);
1623 
1624 		if (pip != NULL && state == PS_DEAD)
1625 			mdb_printf("initial argv: %s\n", pi.pr_psargs);
1626 
1627 		if (state != PS_UNDEAD && state != PS_IDLE) {
1628 			mdb_printf("threading model: ");
1629 			if (pt->p_ptl_ops == &proc_lwp_ops)
1630 				mdb_printf("raw lwps\n");
1631 			else
1632 				mdb_printf("native threads\n");
1633 		}
1634 
1635 		mdb_printf("status: ");
1636 		switch (state) {
1637 		case PS_RUN:
1638 			ASSERT(!(psp->pr_flags & PR_STOPPED));
1639 			mdb_printf("process is running");
1640 			if (psp->pr_flags & PR_DSTOP)
1641 				mdb_printf(", debugger stop directive pending");
1642 			mdb_printf("\n");
1643 			break;
1644 
1645 		case PS_STOP:
1646 			ASSERT(psp->pr_flags & PR_STOPPED);
1647 			pt_print_reason(&psp->pr_lwp);
1648 
1649 			if (psp->pr_flags & PR_DSTOP)
1650 				mdb_printf(", debugger stop directive pending");
1651 			if (psp->pr_flags & PR_ASLEEP)
1652 				mdb_printf(", sleeping in %s system call",
1653 				    proc_sysname(psp->pr_lwp.pr_syscall,
1654 				    signame, sizeof (signame)));
1655 
1656 			mdb_printf("\n");
1657 
1658 			for (sep = t->t_matched; sep != T_SE_END;
1659 			    sep = sep->se_matched) {
1660 				mdb_printf("event: %s\n", sep->se_ops->se_info(
1661 				    t, sep, mdb_list_next(&sep->se_velist),
1662 				    &desc, buf, sizeof (buf)));
1663 			}
1664 			break;
1665 
1666 		case PS_LOST:
1667 			mdb_printf("debugger lost control of process\n");
1668 			break;
1669 
1670 		case PS_UNDEAD:
1671 			coredump = WIFSIGNALED(pi.pr_wstat) &&
1672 			    WCOREDUMP(pi.pr_wstat);
1673 			/*FALLTHRU*/
1674 
1675 		case PS_DEAD:
1676 			if (cursig == 0 && WIFSIGNALED(pi.pr_wstat))
1677 				cursig = WTERMSIG(pi.pr_wstat);
1678 			/*
1679 			 * We can only use pr_wstat == 0 as a test for gcore if
1680 			 * an NT_PRCRED note is present; these features were
1681 			 * added at the same time in Solaris 8.
1682 			 */
1683 			if (pi.pr_wstat == 0 && Pstate(P) == PS_DEAD &&
1684 			    Pcred(P, &cred, 1) == 0) {
1685 				mdb_printf("process core file generated "
1686 				    "with gcore(1)\n");
1687 			} else if (cursig != 0) {
1688 				mdb_printf("process terminated by %s (%s)",
1689 				    proc_signame(cursig, signame,
1690 				    sizeof (signame)), strsignal(cursig));
1691 
1692 				if (sip->si_signo != 0 && SI_FROMUSER(sip) &&
1693 				    sip->si_pid != 0) {
1694 					mdb_printf(", pid=%d uid=%u",
1695 					    (int)sip->si_pid, sip->si_uid);
1696 					if (sip->si_code != 0) {
1697 						mdb_printf(" code=%d",
1698 						    sip->si_code);
1699 					}
1700 				} else {
1701 					switch (sip->si_signo) {
1702 					case SIGILL:
1703 					case SIGTRAP:
1704 					case SIGFPE:
1705 					case SIGSEGV:
1706 					case SIGBUS:
1707 					case SIGEMT:
1708 						mdb_printf(", addr=%p",
1709 						    sip->si_addr);
1710 					default:
1711 						break;
1712 					}
1713 				}
1714 
1715 				if (coredump)
1716 					mdb_printf(" - core file dumped");
1717 				mdb_printf("\n");
1718 			} else {
1719 				mdb_printf("process terminated with exit "
1720 				    "status %d\n", WEXITSTATUS(pi.pr_wstat));
1721 			}
1722 
1723 			if (Plookup_by_name(t->t_pshandle, "libc.so",
1724 			    "panicstr", &sym) == 0 &&
1725 			    Pread(t->t_pshandle, &panicstr, sizeof (panicstr),
1726 			    sym.st_value) == sizeof (panicstr) &&
1727 			    Pread_string(t->t_pshandle, panicbuf,
1728 			    PANIC_BUFSIZE, panicstr) > 0) {
1729 				mdb_printf("panic message: %s",
1730 				    panicbuf);
1731 			}
1732 
1733 
1734 			break;
1735 
1736 		case PS_IDLE:
1737 			mdb_printf("idle\n");
1738 			break;
1739 
1740 		default:
1741 			mdb_printf("unknown libproc Pstate: %d\n", Pstate(P));
1742 		}
1743 		mdb_free(panicbuf, PANIC_BUFSIZE);
1744 
1745 	} else if (pt->p_file != NULL) {
1746 		const GElf_Ehdr *ehp = &pt->p_file->gf_ehdr;
1747 
1748 		mdb_printf("debugging %s file (%d-bit)\n",
1749 		    ehp->e_type == ET_EXEC ? "executable" : "object",
1750 		    ehp->e_ident[EI_CLASS] == ELFCLASS32 ? 32 : 64);
1751 		mdb_printf("executable file: %s\n", IOP_NAME(pt->p_fio));
1752 		mdb_printf("status: idle\n");
1753 	}
1754 
1755 	return (DCMD_OK);
1756 }
1757 
1758 static int
1759 pt_tls(uintptr_t tid, uint_t flags, int argc, const mdb_arg_t *argv)
1760 {
1761 	const char *name;
1762 	const char *object;
1763 	GElf_Sym sym;
1764 	mdb_syminfo_t si;
1765 	mdb_tgt_t *t = mdb.m_target;
1766 
1767 	if (!(flags & DCMD_ADDRSPEC) || argc > 1)
1768 		return (DCMD_USAGE);
1769 
1770 	if (argc == 0) {
1771 		psaddr_t b;
1772 
1773 		if (tlsbase(t, tid, PR_LMID_EVERY, MDB_TGT_OBJ_EXEC, &b) != 0) {
1774 			mdb_warn("failed to lookup tlsbase for %r", tid);
1775 			return (DCMD_ERR);
1776 		}
1777 
1778 		mdb_printf("%lr\n", b);
1779 		mdb_set_dot(b);
1780 
1781 		return (DCMD_OK);
1782 	}
1783 
1784 	name = argv[0].a_un.a_str;
1785 	object = MDB_TGT_OBJ_EVERY;
1786 
1787 	if (pt_lookup_by_name_thr(t, object, name, &sym, &si, tid) != 0) {
1788 		mdb_warn("failed to lookup %s", name);
1789 		return (DCMD_ABORT); /* avoid repeated failure */
1790 	}
1791 
1792 	if (GELF_ST_TYPE(sym.st_info) != STT_TLS && DCMD_HDRSPEC(flags))
1793 		mdb_warn("%s does not refer to thread local storage\n", name);
1794 
1795 	mdb_printf("%llr\n", sym.st_value);
1796 	mdb_set_dot(sym.st_value);
1797 
1798 	return (DCMD_OK);
1799 }
1800 
1801 /*ARGSUSED*/
1802 static int
1803 pt_tmodel(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1804 {
1805 	mdb_tgt_t *t = mdb.m_target;
1806 	pt_data_t *pt = t->t_data;
1807 	const pt_ptl_ops_t *ptl_ops;
1808 
1809 	if (argc != 1 || argv->a_type != MDB_TYPE_STRING)
1810 		return (DCMD_USAGE);
1811 
1812 	if (strcmp(argv->a_un.a_str, "thread") == 0)
1813 		ptl_ops = &proc_tdb_ops;
1814 	else if (strcmp(argv->a_un.a_str, "lwp") == 0)
1815 		ptl_ops = &proc_lwp_ops;
1816 	else
1817 		return (DCMD_USAGE);
1818 
1819 	if (t->t_pshandle != NULL && pt->p_ptl_ops != ptl_ops) {
1820 		PTL_DTOR(t);
1821 		pt->p_tdb_ops = NULL;
1822 		pt->p_ptl_ops = &proc_lwp_ops;
1823 		pt->p_ptl_hdl = NULL;
1824 
1825 		if (ptl_ops == &proc_tdb_ops) {
1826 			(void) Pobject_iter(t->t_pshandle, (proc_map_f *)
1827 			    thr_check, t);
1828 		}
1829 	}
1830 
1831 	(void) mdb_tgt_status(t, &t->t_status);
1832 	return (DCMD_OK);
1833 }
1834 
1835 static const char *
1836 env_match(const char *cmp, const char *nameval)
1837 {
1838 	const char *loc;
1839 	size_t cmplen = strlen(cmp);
1840 
1841 	loc = strchr(nameval, '=');
1842 	if (loc != NULL && (loc - nameval) == cmplen &&
1843 	    strncmp(nameval, cmp, cmplen) == 0) {
1844 		return (loc + 1);
1845 	}
1846 
1847 	return (NULL);
1848 }
1849 
1850 /*ARGSUSED*/
1851 static int
1852 print_env(void *data, struct ps_prochandle *P, uintptr_t addr,
1853     const char *nameval)
1854 {
1855 	const char *value;
1856 
1857 	if (nameval == NULL) {
1858 		mdb_printf("<0x%p>\n", addr);
1859 	} else {
1860 		if (data == NULL)
1861 			mdb_printf("%s\n", nameval);
1862 		else if ((value = env_match(data, nameval)) != NULL)
1863 			mdb_printf("%s\n", value);
1864 	}
1865 
1866 	return (0);
1867 }
1868 
1869 /*ARGSUSED*/
1870 static int
1871 pt_getenv(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
1872 {
1873 	mdb_tgt_t *t = mdb.m_target;
1874 	pt_data_t *pt = t->t_data;
1875 	int i;
1876 	uint_t opt_t = 0;
1877 	mdb_var_t *v;
1878 
1879 	i = mdb_getopts(argc, argv,
1880 	    't', MDB_OPT_SETBITS, TRUE, &opt_t, NULL);
1881 
1882 	argc -= i;
1883 	argv += i;
1884 
1885 	if ((flags & DCMD_ADDRSPEC) || argc > 1)
1886 		return (DCMD_USAGE);
1887 
1888 	if (argc == 1 && argv->a_type != MDB_TYPE_STRING)
1889 		return (DCMD_USAGE);
1890 
1891 	if (opt_t && t->t_pshandle == NULL) {
1892 		mdb_warn("no process active\n");
1893 		return (DCMD_ERR);
1894 	}
1895 
1896 	if (opt_t && (Pstate(t->t_pshandle) == PS_IDLE ||
1897 	    Pstate(t->t_pshandle) == PS_UNDEAD)) {
1898 		mdb_warn("-t option requires target to be running\n");
1899 		return (DCMD_ERR);
1900 	}
1901 
1902 	if (opt_t != 0) {
1903 		if (Penv_iter(t->t_pshandle, print_env,
1904 		    argc == 0 ? NULL : (void *)argv->a_un.a_str) != 0)
1905 			return (DCMD_ERR);
1906 	} else if (argc == 1) {
1907 		if ((v = mdb_nv_lookup(&pt->p_env, argv->a_un.a_str)) == NULL)
1908 			return (DCMD_ERR);
1909 
1910 		ASSERT(strchr(mdb_nv_get_cookie(v), '=') != NULL);
1911 		mdb_printf("%s\n", strchr(mdb_nv_get_cookie(v), '=') + 1);
1912 	} else {
1913 
1914 		mdb_nv_rewind(&pt->p_env);
1915 		while ((v = mdb_nv_advance(&pt->p_env)) != NULL)
1916 			mdb_printf("%s\n", mdb_nv_get_cookie(v));
1917 	}
1918 
1919 	return (DCMD_OK);
1920 }
1921 
1922 /*
1923  * Function to set a variable in the internal environment, which is used when
1924  * creating new processes.  Note that it is possible that 'nameval' can refer to
1925  * read-only memory, if mdb calls putenv() on an existing value before calling
1926  * this function.  While we should avoid this situation, this function is
1927  * designed to be robust in the face of such changes.
1928  */
1929 static void
1930 pt_env_set(pt_data_t *pt, const char *nameval)
1931 {
1932 	mdb_var_t *v;
1933 	char *equals, *val;
1934 	const char *name;
1935 	size_t len;
1936 
1937 	if ((equals = strchr(nameval, '=')) != NULL) {
1938 		val = strdup(nameval);
1939 		equals = val + (equals - nameval);
1940 	} else {
1941 		/*
1942 		 * nameval doesn't contain an equals character.  Convert this to
1943 		 * be 'nameval='.
1944 		 */
1945 		len = strlen(nameval);
1946 		val = mdb_alloc(len + 2, UM_SLEEP);
1947 		(void) mdb_snprintf(val, len + 2, "%s=", nameval);
1948 		equals = val + len;
1949 	}
1950 
1951 	/* temporary truncate the string for lookup/insert */
1952 	*equals = '\0';
1953 	v = mdb_nv_lookup(&pt->p_env, val);
1954 
1955 	if (v != NULL) {
1956 		char *old = mdb_nv_get_cookie(v);
1957 		mdb_free(old, strlen(old) + 1);
1958 		name = mdb_nv_get_name(v);
1959 	} else {
1960 		/*
1961 		 * The environment is created using MDB_NV_EXTNAME, so we must
1962 		 * provide external storage for the variable names.
1963 		 */
1964 		name = strdup(val);
1965 	}
1966 
1967 	*equals = '=';
1968 
1969 	(void) mdb_nv_insert(&pt->p_env, name, NULL, (uintptr_t)val,
1970 	    MDB_NV_EXTNAME);
1971 
1972 	if (equals)
1973 		*equals = '=';
1974 }
1975 
1976 /*
1977  * Clears the internal environment.
1978  */
1979 static void
1980 pt_env_clear(pt_data_t *pt)
1981 {
1982 	mdb_var_t *v;
1983 	char *val, *name;
1984 
1985 	mdb_nv_rewind(&pt->p_env);
1986 	while ((v = mdb_nv_advance(&pt->p_env)) != NULL) {
1987 
1988 		name = (char *)mdb_nv_get_name(v);
1989 		val = mdb_nv_get_cookie(v);
1990 
1991 		mdb_nv_remove(&pt->p_env, v);
1992 
1993 		mdb_free(name, strlen(name) + 1);
1994 		mdb_free(val, strlen(val) + 1);
1995 	}
1996 }
1997 
1998 /*ARGSUSED*/
1999 static int
2000 pt_setenv(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2001 {
2002 	mdb_tgt_t *t = mdb.m_target;
2003 	pt_data_t *pt = t->t_data;
2004 	char *nameval;
2005 	size_t len;
2006 	int alloc;
2007 
2008 	if ((flags & DCMD_ADDRSPEC) || argc == 0 || argc > 2)
2009 		return (DCMD_USAGE);
2010 
2011 	if ((argc > 0 && argv[0].a_type != MDB_TYPE_STRING) ||
2012 	    (argc > 1 && argv[1].a_type != MDB_TYPE_STRING))
2013 		return (DCMD_USAGE);
2014 
2015 	if (t->t_pshandle == NULL) {
2016 		mdb_warn("no process active\n");
2017 		return (DCMD_ERR);
2018 	}
2019 
2020 	/*
2021 	 * If the process is in some sort of running state, warn the user that
2022 	 * changes won't immediately take effect.
2023 	 */
2024 	if (Pstate(t->t_pshandle) == PS_RUN ||
2025 	    Pstate(t->t_pshandle) == PS_STOP) {
2026 		mdb_warn("warning: changes will not take effect until process"
2027 		    " is restarted\n");
2028 	}
2029 
2030 	/*
2031 	 * We allow two forms of operation.  The first is the usual "name=value"
2032 	 * parameter.  We also allow the user to specify two arguments, where
2033 	 * the first is the name of the variable, and the second is the value.
2034 	 */
2035 	alloc = 0;
2036 	if (argc == 1) {
2037 		nameval = (char *)argv->a_un.a_str;
2038 	} else {
2039 		len = strlen(argv[0].a_un.a_str) +
2040 		    strlen(argv[1].a_un.a_str) + 2;
2041 		nameval = mdb_alloc(len, UM_SLEEP);
2042 		(void) mdb_snprintf(nameval, len, "%s=%s", argv[0].a_un.a_str,
2043 		    argv[1].a_un.a_str);
2044 		alloc = 1;
2045 	}
2046 
2047 	pt_env_set(pt, nameval);
2048 
2049 	if (alloc)
2050 		mdb_free(nameval, strlen(nameval) + 1);
2051 
2052 	return (DCMD_OK);
2053 }
2054 
2055 /*ARGSUSED*/
2056 static int
2057 pt_unsetenv(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2058 {
2059 	mdb_tgt_t *t = mdb.m_target;
2060 	pt_data_t *pt = t->t_data;
2061 	mdb_var_t *v;
2062 	char *value, *name;
2063 
2064 	if ((flags & DCMD_ADDRSPEC) || argc > 1)
2065 		return (DCMD_USAGE);
2066 
2067 	if (argc == 1 && argv->a_type != MDB_TYPE_STRING)
2068 		return (DCMD_USAGE);
2069 
2070 	if (t->t_pshandle == NULL) {
2071 		mdb_warn("no process active\n");
2072 		return (DCMD_ERR);
2073 	}
2074 
2075 	/*
2076 	 * If the process is in some sort of running state, warn the user that
2077 	 * changes won't immediately take effect.
2078 	 */
2079 	if (Pstate(t->t_pshandle) == PS_RUN ||
2080 	    Pstate(t->t_pshandle) == PS_STOP) {
2081 		mdb_warn("warning: changes will not take effect until process"
2082 		    " is restarted\n");
2083 	}
2084 
2085 	if (argc == 0) {
2086 		pt_env_clear(pt);
2087 	} else {
2088 		if ((v = mdb_nv_lookup(&pt->p_env, argv->a_un.a_str)) != NULL) {
2089 			name = (char *)mdb_nv_get_name(v);
2090 			value = mdb_nv_get_cookie(v);
2091 
2092 			mdb_nv_remove(&pt->p_env, v);
2093 
2094 			mdb_free(name, strlen(name) + 1);
2095 			mdb_free(value, strlen(value) + 1);
2096 		}
2097 	}
2098 
2099 	return (DCMD_OK);
2100 }
2101 
2102 void
2103 getenv_help(void)
2104 {
2105 	mdb_printf("-t  show current process environment"
2106 	    " instead of initial environment.\n");
2107 }
2108 
2109 static const mdb_dcmd_t pt_dcmds[] = {
2110 	{ "$c", "?[cnt]", "print stack backtrace", pt_stack },
2111 	{ "$C", "?[cnt]", "print stack backtrace", pt_stackv },
2112 	{ "$i", NULL, "print signals that are ignored", pt_ignored },
2113 	{ "$l", NULL, "print the representative thread's lwp id", pt_lwpid },
2114 	{ "$L", NULL, "print list of the active lwp ids", pt_lwpids },
2115 	{ "$r", "?[-u]", "print general-purpose registers", pt_regs },
2116 	{ "$x", "?", "print floating point registers", pt_fpregs },
2117 	{ "$X", "?", "print floating point registers", pt_fpregs },
2118 	{ "$y", "?", "print floating point registers", pt_fpregs },
2119 	{ "$Y", "?", "print floating point registers", pt_fpregs },
2120 	{ "$?", "?", "print status and registers", pt_regstatus },
2121 	{ ":A", "?[core|pid]", "attach to process or core file", pt_attach },
2122 	{ ":i", ":", "ignore signal (delete all matching events)", pt_ignore },
2123 	{ ":k", NULL, "forcibly kill and release target", pt_kill },
2124 	{ ":R", "[-a]", "release the previously attached process", pt_detach },
2125 	{ "attach", "?[core|pid]",
2126 	    "attach to process or core file", pt_attach },
2127 	{ "findstack", ":[-v]", "find user thread stack", pt_findstack },
2128 	{ "gcore", "[-o prefix] [-c content]",
2129 	    "produce a core file for the attached process", pt_gcore },
2130 	{ "getenv", "[-t] [name]", "display an environment variable",
2131 		pt_getenv, getenv_help },
2132 	{ "kill", NULL, "forcibly kill and release target", pt_kill },
2133 	{ "release", "[-a]",
2134 	    "release the previously attached process", pt_detach },
2135 	{ "regs", "?[-u]", "print general-purpose registers", pt_regs },
2136 	{ "fpregs", "?[-dqs]", "print floating point registers", pt_fpregs },
2137 	{ "setenv", "name=value", "set an environment variable", pt_setenv },
2138 	{ "stack", "?[cnt]", "print stack backtrace", pt_stack },
2139 	{ "stackregs", "?", "print stack backtrace and registers", pt_stackr },
2140 	{ "status", NULL, "print summary of current target", pt_status_dcmd },
2141 	{ "tls", ":symbol",
2142 	    "lookup TLS data in the context of a given thread", pt_tls },
2143 	{ "tmodel", "{thread|lwp}", NULL, pt_tmodel },
2144 	{ "unsetenv", "[name]", "clear an environment variable", pt_unsetenv },
2145 	{ NULL }
2146 };
2147 
2148 static void
2149 pt_thr_walk_fini(mdb_walk_state_t *wsp)
2150 {
2151 	mdb_addrvec_destroy(wsp->walk_data);
2152 	mdb_free(wsp->walk_data, sizeof (mdb_addrvec_t));
2153 }
2154 
2155 static int
2156 pt_thr_walk_init(mdb_walk_state_t *wsp)
2157 {
2158 	wsp->walk_data = mdb_zalloc(sizeof (mdb_addrvec_t), UM_SLEEP);
2159 	mdb_addrvec_create(wsp->walk_data);
2160 
2161 	if (PTL_ITER(mdb.m_target, wsp->walk_data) == -1) {
2162 		mdb_warn("failed to iterate over threads");
2163 		pt_thr_walk_fini(wsp);
2164 		return (WALK_ERR);
2165 	}
2166 
2167 	return (WALK_NEXT);
2168 }
2169 
2170 static int
2171 pt_thr_walk_step(mdb_walk_state_t *wsp)
2172 {
2173 	if (mdb_addrvec_length(wsp->walk_data) != 0) {
2174 		return (wsp->walk_callback(mdb_addrvec_shift(wsp->walk_data),
2175 		    NULL, wsp->walk_cbdata));
2176 	}
2177 	return (WALK_DONE);
2178 }
2179 
2180 static const mdb_walker_t pt_walkers[] = {
2181 	{ "thread", "walk list of valid thread identifiers",
2182 	    pt_thr_walk_init, pt_thr_walk_step, pt_thr_walk_fini },
2183 	{ NULL }
2184 };
2185 
2186 static int
2187 pt_agent_check(boolean_t *agent, const lwpstatus_t *psp)
2188 {
2189 	if (psp->pr_flags & PR_AGENT)
2190 		*agent = B_TRUE;
2191 
2192 	return (0);
2193 }
2194 
2195 static void
2196 pt_activate_common(mdb_tgt_t *t)
2197 {
2198 	pt_data_t *pt = t->t_data;
2199 	boolean_t hasagent = B_FALSE;
2200 	GElf_Sym sym;
2201 
2202 	/*
2203 	 * If we have a libproc handle and AT_BASE is set, the process or core
2204 	 * is dynamically linked.  We call Prd_agent() to force libproc to
2205 	 * try to initialize librtld_db, and issue a warning if that fails.
2206 	 */
2207 	if (t->t_pshandle != NULL && Pgetauxval(t->t_pshandle,
2208 	    AT_BASE) != -1L && Prd_agent(t->t_pshandle) == NULL) {
2209 		mdb_warn("warning: librtld_db failed to initialize; shared "
2210 		    "library information will not be available\n");
2211 	}
2212 
2213 	if (t->t_pshandle != NULL) {
2214 		(void) Plwp_iter(t->t_pshandle,
2215 		    (proc_lwp_f *)pt_agent_check, &hasagent);
2216 	}
2217 
2218 	if (hasagent) {
2219 		mdb_warn("agent lwp detected; forcing "
2220 		    "lwp thread model (use ::tmodel to change)\n");
2221 	} else if (t->t_pshandle != NULL && Pstate(t->t_pshandle) != PS_IDLE) {
2222 		/*
2223 		 * If we have a libproc handle and we do not have an agent LWP,
2224 		 * look for the correct thread debugging library.  (If we have
2225 		 * an agent LWP, we leave the model as the raw LWP model to
2226 		 * allow the agent LWP to be visible to the debugger.)
2227 		 */
2228 		(void) Pobject_iter(t->t_pshandle, (proc_map_f *)thr_check, t);
2229 	}
2230 
2231 	/*
2232 	 * If there's a global object named '_mdb_abort_info', assuming we're
2233 	 * debugging mdb itself and load the developer support module.
2234 	 */
2235 	if (mdb_gelf_symtab_lookup_by_name(pt->p_symtab, "_mdb_abort_info",
2236 	    &sym, NULL) == 0 && GELF_ST_TYPE(sym.st_info) == STT_OBJECT) {
2237 		if (mdb_module_load("mdb_ds", MDB_MOD_SILENT) < 0)
2238 			mdb_warn("warning: failed to load developer support\n");
2239 	}
2240 
2241 	mdb_tgt_elf_export(pt->p_file);
2242 }
2243 
2244 static void
2245 pt_activate(mdb_tgt_t *t)
2246 {
2247 	static const mdb_nv_disc_t reg_disc = { reg_disc_set, reg_disc_get };
2248 
2249 	pt_data_t *pt = t->t_data;
2250 	struct utsname u1, u2;
2251 	mdb_var_t *v;
2252 	core_content_t content;
2253 
2254 	if (t->t_pshandle) {
2255 		mdb_prop_postmortem = (Pstate(t->t_pshandle) == PS_DEAD);
2256 		mdb_prop_kernel = FALSE;
2257 	} else
2258 		mdb_prop_kernel = mdb_prop_postmortem = FALSE;
2259 
2260 	mdb_prop_datamodel = MDB_TGT_MODEL_NATIVE;
2261 
2262 	/*
2263 	 * If we're examining a core file that doesn't contain program text,
2264 	 * and uname(2) doesn't match the NT_UTSNAME note recorded in the
2265 	 * core file, issue a warning.
2266 	 */
2267 	if (mdb_prop_postmortem == TRUE &&
2268 	    ((content = Pcontent(t->t_pshandle)) == CC_CONTENT_INVALID ||
2269 	    !(content & CC_CONTENT_TEXT)) &&
2270 	    uname(&u1) >= 0 && Puname(t->t_pshandle, &u2) == 0 &&
2271 	    (strcmp(u1.release, u2.release) != 0 ||
2272 	    strcmp(u1.version, u2.version) != 0)) {
2273 		mdb_warn("warning: core file is from %s %s %s; shared text "
2274 		    "mappings may not match installed libraries\n",
2275 		    u2.sysname, u2.release, u2.version);
2276 	}
2277 
2278 	/*
2279 	 * Perform the common initialization tasks -- these are shared with
2280 	 * the pt_exec() and pt_run() subroutines.
2281 	 */
2282 	pt_activate_common(t);
2283 
2284 	(void) mdb_tgt_register_dcmds(t, &pt_dcmds[0], MDB_MOD_FORCE);
2285 	(void) mdb_tgt_register_walkers(t, &pt_walkers[0], MDB_MOD_FORCE);
2286 
2287 	/*
2288 	 * Iterate through our register description list and export
2289 	 * each register as a named variable.
2290 	 */
2291 	mdb_nv_rewind(&pt->p_regs);
2292 	while ((v = mdb_nv_advance(&pt->p_regs)) != NULL) {
2293 		ushort_t rd_flags = MDB_TGT_R_FLAGS(mdb_nv_get_value(v));
2294 
2295 		if (!(rd_flags & MDB_TGT_R_EXPORT))
2296 			continue; /* Don't export register as a variable */
2297 
2298 		(void) mdb_nv_insert(&mdb.m_nv, mdb_nv_get_name(v), &reg_disc,
2299 		    (uintptr_t)t, MDB_NV_PERSIST);
2300 	}
2301 }
2302 
2303 static void
2304 pt_deactivate(mdb_tgt_t *t)
2305 {
2306 	pt_data_t *pt = t->t_data;
2307 	const mdb_dcmd_t *dcp;
2308 	const mdb_walker_t *wp;
2309 	mdb_var_t *v, *w;
2310 
2311 	mdb_nv_rewind(&pt->p_regs);
2312 	while ((v = mdb_nv_advance(&pt->p_regs)) != NULL) {
2313 		ushort_t rd_flags = MDB_TGT_R_FLAGS(mdb_nv_get_value(v));
2314 
2315 		if (!(rd_flags & MDB_TGT_R_EXPORT))
2316 			continue; /* Didn't export register as a variable */
2317 
2318 		if (w = mdb_nv_lookup(&mdb.m_nv, mdb_nv_get_name(v))) {
2319 			w->v_flags &= ~MDB_NV_PERSIST;
2320 			mdb_nv_remove(&mdb.m_nv, w);
2321 		}
2322 	}
2323 
2324 	for (wp = &pt_walkers[0]; wp->walk_name != NULL; wp++) {
2325 		if (mdb_module_remove_walker(t->t_module, wp->walk_name) == -1)
2326 			warn("failed to remove walk %s", wp->walk_name);
2327 	}
2328 
2329 	for (dcp = &pt_dcmds[0]; dcp->dc_name != NULL; dcp++) {
2330 		if (mdb_module_remove_dcmd(t->t_module, dcp->dc_name) == -1)
2331 			warn("failed to remove dcmd %s", dcp->dc_name);
2332 	}
2333 
2334 	mdb_prop_postmortem = FALSE;
2335 	mdb_prop_kernel = FALSE;
2336 	mdb_prop_datamodel = MDB_TGT_MODEL_UNKNOWN;
2337 }
2338 
2339 static void
2340 pt_periodic(mdb_tgt_t *t)
2341 {
2342 	pt_data_t *pt = t->t_data;
2343 
2344 	if (pt->p_rdstate == PT_RD_CONSIST) {
2345 		if (t->t_pshandle != NULL && Pstate(t->t_pshandle) < PS_LOST &&
2346 		    !(mdb.m_flags & MDB_FL_NOMODS)) {
2347 			mdb_printf("%s: You've got symbols!\n", mdb.m_pname);
2348 			mdb_module_load_all(0);
2349 		}
2350 		pt->p_rdstate = PT_RD_NONE;
2351 	}
2352 }
2353 
2354 static void
2355 pt_destroy(mdb_tgt_t *t)
2356 {
2357 	pt_data_t *pt = t->t_data;
2358 
2359 	if (pt->p_idlehandle != NULL && pt->p_idlehandle != t->t_pshandle)
2360 		Prelease(pt->p_idlehandle, 0);
2361 
2362 	if (t->t_pshandle != NULL) {
2363 		PTL_DTOR(t);
2364 		pt_release_parents(t);
2365 		pt_pre_detach(t, TRUE);
2366 		Prelease(t->t_pshandle, pt->p_rflags);
2367 	}
2368 
2369 	mdb.m_flags &= ~(MDB_FL_VCREATE | MDB_FL_JOBCTL);
2370 	pt_close_aout(t);
2371 
2372 	if (pt->p_aout_fio != NULL)
2373 		mdb_io_rele(pt->p_aout_fio);
2374 
2375 	pt_env_clear(pt);
2376 	mdb_nv_destroy(&pt->p_env);
2377 
2378 	mdb_nv_destroy(&pt->p_regs);
2379 	mdb_free(pt, sizeof (pt_data_t));
2380 }
2381 
2382 /*ARGSUSED*/
2383 static const char *
2384 pt_name(mdb_tgt_t *t)
2385 {
2386 	return ("proc");
2387 }
2388 
2389 static const char *
2390 pt_platform(mdb_tgt_t *t)
2391 {
2392 	pt_data_t *pt = t->t_data;
2393 
2394 	if (t->t_pshandle != NULL &&
2395 	    Pplatform(t->t_pshandle, pt->p_platform, MAXNAMELEN) != NULL)
2396 		return (pt->p_platform);
2397 
2398 	return (mdb_conf_platform());
2399 }
2400 
2401 static int
2402 pt_uname(mdb_tgt_t *t, struct utsname *utsp)
2403 {
2404 	if (t->t_pshandle != NULL)
2405 		return (Puname(t->t_pshandle, utsp));
2406 
2407 	return (uname(utsp) >= 0 ? 0 : -1);
2408 }
2409 
2410 static int
2411 pt_dmodel(mdb_tgt_t *t)
2412 {
2413 	if (t->t_pshandle == NULL)
2414 		return (MDB_TGT_MODEL_NATIVE);
2415 
2416 	switch (Pstatus(t->t_pshandle)->pr_dmodel) {
2417 	case PR_MODEL_ILP32:
2418 		return (MDB_TGT_MODEL_ILP32);
2419 	case PR_MODEL_LP64:
2420 		return (MDB_TGT_MODEL_LP64);
2421 	}
2422 
2423 	return (MDB_TGT_MODEL_UNKNOWN);
2424 }
2425 
2426 static ssize_t
2427 pt_vread(mdb_tgt_t *t, void *buf, size_t nbytes, uintptr_t addr)
2428 {
2429 	ssize_t n;
2430 
2431 	/*
2432 	 * If no handle is open yet, reads from virtual addresses are
2433 	 * allowed to succeed but return zero-filled memory.
2434 	 */
2435 	if (t->t_pshandle == NULL) {
2436 		bzero(buf, nbytes);
2437 		return (nbytes);
2438 	}
2439 
2440 	if ((n = Pread(t->t_pshandle, buf, nbytes, addr)) <= 0)
2441 		return (set_errno(EMDB_NOMAP));
2442 
2443 	return (n);
2444 }
2445 
2446 static ssize_t
2447 pt_vwrite(mdb_tgt_t *t, const void *buf, size_t nbytes, uintptr_t addr)
2448 {
2449 	ssize_t n;
2450 
2451 	/*
2452 	 * If no handle is open yet, writes to virtual addresses are
2453 	 * allowed to succeed but do not actually modify anything.
2454 	 */
2455 	if (t->t_pshandle == NULL)
2456 		return (nbytes);
2457 
2458 	n = Pwrite(t->t_pshandle, buf, nbytes, addr);
2459 
2460 	if (n == -1 && errno == EIO)
2461 		return (set_errno(EMDB_NOMAP));
2462 
2463 	return (n);
2464 }
2465 
2466 static ssize_t
2467 pt_fread(mdb_tgt_t *t, void *buf, size_t nbytes, uintptr_t addr)
2468 {
2469 	pt_data_t *pt = t->t_data;
2470 
2471 	if (pt->p_file != NULL) {
2472 		return (mdb_gelf_rw(pt->p_file, buf, nbytes, addr,
2473 		    IOPF_READ(pt->p_fio), GIO_READ));
2474 	}
2475 
2476 	bzero(buf, nbytes);
2477 	return (nbytes);
2478 }
2479 
2480 static ssize_t
2481 pt_fwrite(mdb_tgt_t *t, const void *buf, size_t nbytes, uintptr_t addr)
2482 {
2483 	pt_data_t *pt = t->t_data;
2484 
2485 	if (pt->p_file != NULL) {
2486 		return (mdb_gelf_rw(pt->p_file, (void *)buf, nbytes, addr,
2487 		    IOPF_WRITE(pt->p_fio), GIO_WRITE));
2488 	}
2489 
2490 	return (nbytes);
2491 }
2492 
2493 static const char *
2494 pt_resolve_lmid(const char *object, Lmid_t *lmidp)
2495 {
2496 	Lmid_t lmid = PR_LMID_EVERY;
2497 	const char *p;
2498 
2499 	if (object == MDB_TGT_OBJ_EVERY || object == MDB_TGT_OBJ_EXEC)
2500 		lmid = LM_ID_BASE; /* restrict scope to a.out's link map */
2501 	else if (object != MDB_TGT_OBJ_RTLD && strncmp(object, "LM", 2) == 0 &&
2502 	    (p = strchr(object, '`')) != NULL) {
2503 		object += 2;	/* skip past initial "LM" prefix */
2504 		lmid = strntoul(object, (size_t)(p - object), mdb.m_radix);
2505 		object = p + 1;	/* skip past link map specifier */
2506 	}
2507 
2508 	*lmidp = lmid;
2509 	return (object);
2510 }
2511 
2512 static int
2513 tlsbase(mdb_tgt_t *t, mdb_tgt_tid_t tid, Lmid_t lmid, const char *object,
2514     psaddr_t *basep)
2515 {
2516 	pt_data_t *pt = t->t_data;
2517 	const rd_loadobj_t *loadobjp;
2518 	td_thrhandle_t th;
2519 	td_err_e err;
2520 
2521 	if (object == MDB_TGT_OBJ_EVERY)
2522 		return (set_errno(EINVAL));
2523 
2524 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) == PS_IDLE)
2525 		return (set_errno(EMDB_NOPROC));
2526 
2527 	if (pt->p_tdb_ops == NULL)
2528 		return (set_errno(EMDB_TDB));
2529 
2530 	err = pt->p_tdb_ops->td_ta_map_id2thr(pt->p_ptl_hdl, tid, &th);
2531 	if (err != TD_OK)
2532 		return (set_errno(tdb_to_errno(err)));
2533 
2534 	/*
2535 	 * If this fails, rtld_db has failed to initialize properly.
2536 	 */
2537 	if ((loadobjp = Plmid_to_loadobj(t->t_pshandle, lmid, object)) == NULL)
2538 		return (set_errno(EMDB_NORTLD));
2539 
2540 	/*
2541 	 * This will fail if the TLS block has not been allocated for the
2542 	 * object that contains the TLS symbol in question.
2543 	 */
2544 	err = pt->p_tdb_ops->td_thr_tlsbase(&th, loadobjp->rl_tlsmodid, basep);
2545 	if (err != TD_OK)
2546 		return (set_errno(tdb_to_errno(err)));
2547 
2548 	return (0);
2549 }
2550 
2551 typedef struct {
2552 	mdb_tgt_t	*pl_tgt;
2553 	const char	*pl_name;
2554 	Lmid_t		pl_lmid;
2555 	GElf_Sym	*pl_symp;
2556 	mdb_syminfo_t	*pl_sip;
2557 	mdb_tgt_tid_t	pl_tid;
2558 	mdb_bool_t	pl_found;
2559 } pt_lookup_t;
2560 
2561 /*ARGSUSED*/
2562 static int
2563 pt_lookup_cb(void *data, const prmap_t *pmp, const char *object)
2564 {
2565 	pt_lookup_t *plp = data;
2566 	struct ps_prochandle *P = plp->pl_tgt->t_pshandle;
2567 	prsyminfo_t si;
2568 	GElf_Sym sym;
2569 
2570 	if (Pxlookup_by_name(P, plp->pl_lmid, object, plp->pl_name, &sym,
2571 	    &si) != 0)
2572 		return (0);
2573 
2574 	/*
2575 	 * If we encounter a match with SHN_UNDEF, keep looking for a
2576 	 * better match. Return the first match with SHN_UNDEF set if no
2577 	 * better match is found.
2578 	 */
2579 	if (sym.st_shndx == SHN_UNDEF) {
2580 		if (!plp->pl_found) {
2581 			plp->pl_found = TRUE;
2582 			*plp->pl_symp = sym;
2583 			plp->pl_sip->sym_table = si.prs_table;
2584 			plp->pl_sip->sym_id = si.prs_id;
2585 		}
2586 
2587 		return (0);
2588 	}
2589 
2590 	/*
2591 	 * Note that if the symbol's st_shndx is SHN_UNDEF we don't have the
2592 	 * TLS offset anyway, so adding in the tlsbase would be worthless.
2593 	 */
2594 	if (GELF_ST_TYPE(sym.st_info) == STT_TLS &&
2595 	    plp->pl_tid != (mdb_tgt_tid_t)-1) {
2596 		psaddr_t base;
2597 
2598 		if (tlsbase(plp->pl_tgt, plp->pl_tid, plp->pl_lmid, object,
2599 		    &base) != 0)
2600 			return (-1); /* errno is set for us */
2601 
2602 		sym.st_value += base;
2603 	}
2604 
2605 	plp->pl_found = TRUE;
2606 	*plp->pl_symp = sym;
2607 	plp->pl_sip->sym_table = si.prs_table;
2608 	plp->pl_sip->sym_id = si.prs_id;
2609 
2610 	return (1);
2611 }
2612 
2613 /*
2614  * Lookup the symbol with a thread context so that we can adjust TLS symbols
2615  * to get the values as they would appear in the context of the given thread.
2616  */
2617 static int
2618 pt_lookup_by_name_thr(mdb_tgt_t *t, const char *object,
2619     const char *name, GElf_Sym *symp, mdb_syminfo_t *sip, mdb_tgt_tid_t tid)
2620 {
2621 	struct ps_prochandle *P = t->t_pshandle;
2622 	pt_data_t *pt = t->t_data;
2623 	Lmid_t lmid;
2624 	uint_t i;
2625 	const rd_loadobj_t *aout_lop;
2626 
2627 	object = pt_resolve_lmid(object, &lmid);
2628 
2629 	if (P != NULL) {
2630 		pt_lookup_t pl;
2631 
2632 		pl.pl_tgt = t;
2633 		pl.pl_name = name;
2634 		pl.pl_lmid = lmid;
2635 		pl.pl_symp = symp;
2636 		pl.pl_sip = sip;
2637 		pl.pl_tid = tid;
2638 		pl.pl_found = FALSE;
2639 
2640 		if (object == MDB_TGT_OBJ_EVERY) {
2641 			if (Pobject_iter_resolved(P, pt_lookup_cb, &pl) == -1)
2642 				return (-1); /* errno is set for us */
2643 			if ((!pl.pl_found) &&
2644 			    (Pobject_iter(P, pt_lookup_cb, &pl) == -1))
2645 				return (-1); /* errno is set for us */
2646 		} else {
2647 			const prmap_t *pmp;
2648 
2649 			/*
2650 			 * This can fail either due to an invalid lmid or
2651 			 * an invalid object. To determine which is
2652 			 * faulty, we test the lmid against known valid
2653 			 * lmids and then see if using a wild-card lmid
2654 			 * improves ths situation.
2655 			 */
2656 			if ((pmp = Plmid_to_map(P, lmid, object)) == NULL) {
2657 				if (lmid != PR_LMID_EVERY &&
2658 				    lmid != LM_ID_BASE &&
2659 				    lmid != LM_ID_LDSO &&
2660 				    Plmid_to_map(P, PR_LMID_EVERY, object)
2661 				    != NULL)
2662 					return (set_errno(EMDB_NOLMID));
2663 				else
2664 					return (set_errno(EMDB_NOOBJ));
2665 			}
2666 
2667 			if (pt_lookup_cb(&pl, pmp, object) == -1)
2668 				return (-1); /* errno is set for us */
2669 		}
2670 
2671 		if (pl.pl_found)
2672 			return (0);
2673 	}
2674 
2675 	/*
2676 	 * If libproc doesn't have the symbols for rtld, we're cooked --
2677 	 * mdb doesn't have those symbols either.
2678 	 */
2679 	if (object == MDB_TGT_OBJ_RTLD)
2680 		return (set_errno(EMDB_NOSYM));
2681 
2682 	if (object != MDB_TGT_OBJ_EXEC && object != MDB_TGT_OBJ_EVERY) {
2683 		int status = mdb_gelf_symtab_lookup_by_file(pt->p_symtab,
2684 		    object, name, symp, &sip->sym_id);
2685 
2686 		if (status != 0) {
2687 			if (P != NULL &&
2688 			    Plmid_to_map(P, PR_LMID_EVERY, object) != NULL)
2689 				return (set_errno(EMDB_NOSYM));
2690 			else
2691 				return (-1); /* errno set from lookup_by_file */
2692 		}
2693 
2694 		goto found;
2695 	}
2696 
2697 	if (mdb_gelf_symtab_lookup_by_name(pt->p_symtab, name, symp, &i) == 0) {
2698 		sip->sym_table = MDB_TGT_SYMTAB;
2699 		sip->sym_id = i;
2700 		goto local_found;
2701 	}
2702 
2703 	if (mdb_gelf_symtab_lookup_by_name(pt->p_dynsym, name, symp, &i) == 0) {
2704 		sip->sym_table = MDB_TGT_DYNSYM;
2705 		sip->sym_id = i;
2706 		goto local_found;
2707 	}
2708 
2709 	return (set_errno(EMDB_NOSYM));
2710 
2711 local_found:
2712 	if (pt->p_file != NULL &&
2713 	    pt->p_file->gf_ehdr.e_type == ET_DYN &&
2714 	    P != NULL &&
2715 	    (aout_lop = Pname_to_loadobj(P, PR_OBJ_EXEC)) != NULL)
2716 		symp->st_value += aout_lop->rl_base;
2717 
2718 found:
2719 	/*
2720 	 * If the symbol has type TLS, libproc should have found the symbol
2721 	 * if it exists and has been allocated.
2722 	 */
2723 	if (GELF_ST_TYPE(symp->st_info) == STT_TLS)
2724 		return (set_errno(EMDB_TLS));
2725 
2726 	return (0);
2727 }
2728 
2729 static int
2730 pt_lookup_by_name(mdb_tgt_t *t, const char *object,
2731     const char *name, GElf_Sym *symp, mdb_syminfo_t *sip)
2732 {
2733 	return (pt_lookup_by_name_thr(t, object, name, symp, sip, PTL_TID(t)));
2734 }
2735 
2736 static int
2737 pt_lookup_by_addr(mdb_tgt_t *t, uintptr_t addr, uint_t flags,
2738     char *buf, size_t nbytes, GElf_Sym *symp, mdb_syminfo_t *sip)
2739 {
2740 	struct ps_prochandle *P = t->t_pshandle;
2741 	pt_data_t *pt = t->t_data;
2742 	rd_plt_info_t rpi = { 0 };
2743 
2744 	const char *pltsym;
2745 	int rv, match, i;
2746 
2747 	mdb_gelf_symtab_t *gsts[3];	/* mdb.m_prsym, .symtab, .dynsym */
2748 	int gstc = 0;			/* number of valid gsts[] entries */
2749 
2750 	mdb_gelf_symtab_t *gst = NULL;	/* set if 'sym' is from a gst */
2751 	const prmap_t *pmp = NULL;	/* set if 'sym' is from libproc */
2752 	GElf_Sym sym;			/* best symbol found so far if !exact */
2753 	prsyminfo_t si;
2754 
2755 	/*
2756 	 * Fill in our array of symbol table pointers with the private symbol
2757 	 * table, static symbol table, and dynamic symbol table if applicable.
2758 	 * These are done in order of precedence so that if we match and
2759 	 * MDB_TGT_SYM_EXACT is set, we need not look any further.
2760 	 */
2761 	if (mdb.m_prsym != NULL)
2762 		gsts[gstc++] = mdb.m_prsym;
2763 	if (P == NULL && pt->p_symtab != NULL)
2764 		gsts[gstc++] = pt->p_symtab;
2765 	if (P == NULL && pt->p_dynsym != NULL)
2766 		gsts[gstc++] = pt->p_dynsym;
2767 
2768 	/*
2769 	 * Loop through our array attempting to match the address.  If we match
2770 	 * and we're in exact mode, we're done.  Otherwise save the symbol in
2771 	 * the local sym variable if it is closer than our previous match.
2772 	 * We explicitly watch for zero-valued symbols since DevPro insists
2773 	 * on storing __fsr_init_value's value as the symbol value instead
2774 	 * of storing it in a constant integer.
2775 	 */
2776 	for (i = 0; i < gstc; i++) {
2777 		if (mdb_gelf_symtab_lookup_by_addr(gsts[i], addr, flags, buf,
2778 		    nbytes, symp, &sip->sym_id) != 0 || symp->st_value == 0)
2779 			continue;
2780 
2781 		if (flags & MDB_TGT_SYM_EXACT) {
2782 			gst = gsts[i];
2783 			goto found;
2784 		}
2785 
2786 		if (gst == NULL || mdb_gelf_sym_closer(symp, &sym, addr)) {
2787 			gst = gsts[i];
2788 			sym = *symp;
2789 		}
2790 	}
2791 
2792 	/*
2793 	 * If we have no libproc handle active, we're done: fail if gst is
2794 	 * NULL; otherwise copy out our best symbol and skip to the end.
2795 	 * We also skip to found if gst is the private symbol table: we
2796 	 * want this to always take precedence over PLT re-vectoring.
2797 	 */
2798 	if (P == NULL || (gst != NULL && gst == mdb.m_prsym)) {
2799 		if (gst == NULL)
2800 			return (set_errno(EMDB_NOSYMADDR));
2801 		*symp = sym;
2802 		goto found;
2803 	}
2804 
2805 	/*
2806 	 * Check to see if the address is in a PLT: if it is, use librtld_db to
2807 	 * attempt to resolve the PLT entry.  If the entry is bound, reset addr
2808 	 * to the bound address, add a special prefix to the caller's buf,
2809 	 * forget our previous guess, and then continue using the new addr.
2810 	 * If the entry is not bound, copy the corresponding symbol name into
2811 	 * buf and return a fake symbol for the given address.
2812 	 */
2813 	if ((pltsym = Ppltdest(P, addr)) != NULL) {
2814 		const rd_loadobj_t *rlp;
2815 		rd_agent_t *rap;
2816 
2817 		if ((rap = Prd_agent(P)) != NULL &&
2818 		    (rlp = Paddr_to_loadobj(P, addr)) != NULL &&
2819 		    rd_plt_resolution(rap, addr, Pstatus(P)->pr_lwp.pr_lwpid,
2820 		    rlp->rl_plt_base, &rpi) == RD_OK &&
2821 		    (rpi.pi_flags & RD_FLG_PI_PLTBOUND)) {
2822 			size_t n;
2823 			n = mdb_iob_snprintf(buf, nbytes, "PLT=");
2824 			addr = rpi.pi_baddr;
2825 			if (n > nbytes) {
2826 				buf += nbytes;
2827 				nbytes = 0;
2828 			} else {
2829 				buf += n;
2830 				nbytes -= n;
2831 			}
2832 			gst = NULL;
2833 		} else {
2834 			(void) mdb_iob_snprintf(buf, nbytes, "PLT:%s", pltsym);
2835 			bzero(symp, sizeof (GElf_Sym));
2836 			symp->st_value = addr;
2837 			symp->st_info = GELF_ST_INFO(STB_GLOBAL, STT_FUNC);
2838 			return (0);
2839 		}
2840 	}
2841 
2842 	/*
2843 	 * Ask libproc to convert the address to the closest symbol for us.
2844 	 * Once we get the closest symbol, we perform the EXACT match or
2845 	 * smart-mode or absolute distance check ourself:
2846 	 */
2847 	if (PT_LIBPROC_RESOLVE(P)) {
2848 		rv = Pxlookup_by_addr_resolved(P, addr, buf, nbytes,
2849 		    symp, &si);
2850 	} else {
2851 		rv = Pxlookup_by_addr(P, addr, buf, nbytes,
2852 		    symp, &si);
2853 	}
2854 	if ((rv == 0) && (symp->st_value != 0) &&
2855 	    (gst == NULL || mdb_gelf_sym_closer(symp, &sym, addr))) {
2856 
2857 		if (flags & MDB_TGT_SYM_EXACT)
2858 			match = (addr == symp->st_value);
2859 		else if (mdb.m_symdist == 0)
2860 			match = (addr >= symp->st_value &&
2861 			    addr < symp->st_value + symp->st_size);
2862 		else
2863 			match = (addr >= symp->st_value &&
2864 			    addr < symp->st_value + mdb.m_symdist);
2865 
2866 		if (match) {
2867 			pmp = Paddr_to_map(P, addr);
2868 			gst = NULL;
2869 			sip->sym_table = si.prs_table;
2870 			sip->sym_id = si.prs_id;
2871 			goto found;
2872 		}
2873 	}
2874 
2875 	/*
2876 	 * If we get here, Plookup_by_addr has failed us.  If we have no
2877 	 * previous best symbol (gst == NULL), we've failed completely.
2878 	 * Otherwise we copy out that symbol and continue on to 'found'.
2879 	 */
2880 	if (gst == NULL)
2881 		return (set_errno(EMDB_NOSYMADDR));
2882 	*symp = sym;
2883 found:
2884 	/*
2885 	 * Once we've found something, copy the final name into the caller's
2886 	 * buffer and prefix it with the mapping name if appropriate.
2887 	 */
2888 	if (pmp != NULL && pmp != Pname_to_map(P, PR_OBJ_EXEC)) {
2889 		const char *prefix = pmp->pr_mapname;
2890 		Lmid_t lmid;
2891 
2892 		if (PT_LIBPROC_RESOLVE(P)) {
2893 			if (Pobjname_resolved(P, addr, pt->p_objname,
2894 			    MDB_TGT_MAPSZ))
2895 				prefix = pt->p_objname;
2896 		} else {
2897 			if (Pobjname(P, addr, pt->p_objname, MDB_TGT_MAPSZ))
2898 				prefix = pt->p_objname;
2899 		}
2900 
2901 		if (buf != NULL && nbytes > 1) {
2902 			(void) strncpy(pt->p_symname, buf, MDB_TGT_SYM_NAMLEN);
2903 			pt->p_symname[MDB_TGT_SYM_NAMLEN - 1] = '\0';
2904 		} else {
2905 			pt->p_symname[0] = '\0';
2906 		}
2907 
2908 		if (prefix == pt->p_objname && Plmid(P, addr, &lmid) == 0 && (
2909 		    (lmid != LM_ID_BASE && lmid != LM_ID_LDSO) ||
2910 		    (mdb.m_flags & MDB_FL_SHOWLMID))) {
2911 			(void) mdb_iob_snprintf(buf, nbytes, "LM%lr`%s`%s",
2912 			    lmid, strbasename(prefix), pt->p_symname);
2913 		} else {
2914 			(void) mdb_iob_snprintf(buf, nbytes, "%s`%s",
2915 			    strbasename(prefix), pt->p_symname);
2916 		}
2917 
2918 	} else if (gst != NULL && buf != NULL && nbytes > 0) {
2919 		(void) strncpy(buf, mdb_gelf_sym_name(gst, symp), nbytes);
2920 		buf[nbytes - 1] = '\0';
2921 	}
2922 
2923 	return (0);
2924 }
2925 
2926 
2927 static int
2928 pt_symbol_iter_cb(void *arg, const GElf_Sym *sym, const char *name,
2929     const prsyminfo_t *sip)
2930 {
2931 	pt_symarg_t *psp = arg;
2932 
2933 	psp->psym_info.sym_id = sip->prs_id;
2934 
2935 	return (psp->psym_func(psp->psym_private, sym, name, &psp->psym_info,
2936 	    psp->psym_obj));
2937 }
2938 
2939 static int
2940 pt_objsym_iter(void *arg, const prmap_t *pmp, const char *object)
2941 {
2942 	Lmid_t lmid = PR_LMID_EVERY;
2943 	pt_symarg_t *psp = arg;
2944 
2945 	psp->psym_obj = object;
2946 
2947 	(void) Plmid(psp->psym_targ->t_pshandle, pmp->pr_vaddr, &lmid);
2948 	(void) Pxsymbol_iter(psp->psym_targ->t_pshandle, lmid, object,
2949 	    psp->psym_which, psp->psym_type, pt_symbol_iter_cb, arg);
2950 
2951 	return (0);
2952 }
2953 
2954 static int
2955 pt_symbol_filt(void *arg, const GElf_Sym *sym, const char *name, uint_t id)
2956 {
2957 	pt_symarg_t *psp = arg;
2958 
2959 	if (mdb_tgt_sym_match(sym, psp->psym_type)) {
2960 		psp->psym_info.sym_id = id;
2961 		return (psp->psym_func(psp->psym_private, sym, name,
2962 		    &psp->psym_info, psp->psym_obj));
2963 	}
2964 
2965 	return (0);
2966 }
2967 
2968 static int
2969 pt_symbol_iter(mdb_tgt_t *t, const char *object, uint_t which,
2970     uint_t type, mdb_tgt_sym_f *func, void *private)
2971 {
2972 	pt_data_t *pt = t->t_data;
2973 	mdb_gelf_symtab_t *gst;
2974 	pt_symarg_t ps;
2975 	Lmid_t lmid;
2976 
2977 	object = pt_resolve_lmid(object, &lmid);
2978 
2979 	ps.psym_targ = t;
2980 	ps.psym_which = which;
2981 	ps.psym_type = type;
2982 	ps.psym_func = func;
2983 	ps.psym_private = private;
2984 	ps.psym_obj = object;
2985 
2986 	if (t->t_pshandle != NULL) {
2987 		if (object != MDB_TGT_OBJ_EVERY) {
2988 			if (Plmid_to_map(t->t_pshandle, lmid, object) == NULL)
2989 				return (set_errno(EMDB_NOOBJ));
2990 			(void) Pxsymbol_iter(t->t_pshandle, lmid, object,
2991 			    which, type, pt_symbol_iter_cb, &ps);
2992 			return (0);
2993 		} else if (Prd_agent(t->t_pshandle) != NULL) {
2994 			if (PT_LIBPROC_RESOLVE(t->t_pshandle)) {
2995 				(void) Pobject_iter_resolved(t->t_pshandle,
2996 				    pt_objsym_iter, &ps);
2997 			} else {
2998 				(void) Pobject_iter(t->t_pshandle,
2999 				    pt_objsym_iter, &ps);
3000 			}
3001 			return (0);
3002 		}
3003 	}
3004 
3005 	if (lmid != LM_ID_BASE && lmid != PR_LMID_EVERY)
3006 		return (set_errno(EMDB_NOLMID));
3007 
3008 	if (object != MDB_TGT_OBJ_EXEC && object != MDB_TGT_OBJ_EVERY &&
3009 	    pt->p_fio != NULL &&
3010 	    strcmp(object, IOP_NAME(pt->p_fio)) != 0)
3011 		return (set_errno(EMDB_NOOBJ));
3012 
3013 	if (which == MDB_TGT_SYMTAB)
3014 		gst = pt->p_symtab;
3015 	else
3016 		gst = pt->p_dynsym;
3017 
3018 	if (gst != NULL) {
3019 		ps.psym_info.sym_table = gst->gst_tabid;
3020 		mdb_gelf_symtab_iter(gst, pt_symbol_filt, &ps);
3021 	}
3022 
3023 	return (0);
3024 }
3025 
3026 static const mdb_map_t *
3027 pt_prmap_to_mdbmap(mdb_tgt_t *t, const prmap_t *prp, mdb_map_t *mp)
3028 {
3029 	struct ps_prochandle *P = t->t_pshandle;
3030 	char *rv, name[MAXPATHLEN];
3031 	Lmid_t lmid;
3032 
3033 	if (PT_LIBPROC_RESOLVE(P)) {
3034 		rv = Pobjname_resolved(P, prp->pr_vaddr, name, sizeof (name));
3035 	} else {
3036 		rv = Pobjname(P, prp->pr_vaddr, name, sizeof (name));
3037 	}
3038 
3039 	if (rv != NULL) {
3040 		if (Plmid(P, prp->pr_vaddr, &lmid) == 0 && (
3041 		    (lmid != LM_ID_BASE && lmid != LM_ID_LDSO) ||
3042 		    (mdb.m_flags & MDB_FL_SHOWLMID))) {
3043 			(void) mdb_iob_snprintf(mp->map_name, MDB_TGT_MAPSZ,
3044 			    "LM%lr`%s", lmid, name);
3045 		} else {
3046 			(void) strncpy(mp->map_name, name, MDB_TGT_MAPSZ - 1);
3047 			mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
3048 		}
3049 	} else {
3050 		(void) strncpy(mp->map_name, prp->pr_mapname,
3051 		    MDB_TGT_MAPSZ - 1);
3052 		mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
3053 	}
3054 
3055 	mp->map_base = prp->pr_vaddr;
3056 	mp->map_size = prp->pr_size;
3057 	mp->map_flags = 0;
3058 
3059 	if (prp->pr_mflags & MA_READ)
3060 		mp->map_flags |= MDB_TGT_MAP_R;
3061 	if (prp->pr_mflags & MA_WRITE)
3062 		mp->map_flags |= MDB_TGT_MAP_W;
3063 	if (prp->pr_mflags & MA_EXEC)
3064 		mp->map_flags |= MDB_TGT_MAP_X;
3065 
3066 	if (prp->pr_mflags & MA_SHM)
3067 		mp->map_flags |= MDB_TGT_MAP_SHMEM;
3068 	if (prp->pr_mflags & MA_BREAK)
3069 		mp->map_flags |= MDB_TGT_MAP_HEAP;
3070 	if (prp->pr_mflags & MA_STACK)
3071 		mp->map_flags |= MDB_TGT_MAP_STACK;
3072 	if (prp->pr_mflags & MA_ANON)
3073 		mp->map_flags |= MDB_TGT_MAP_ANON;
3074 
3075 	return (mp);
3076 }
3077 
3078 /*ARGSUSED*/
3079 static int
3080 pt_map_apply(void *arg, const prmap_t *prp, const char *name)
3081 {
3082 	pt_maparg_t *pmp = arg;
3083 	mdb_map_t map;
3084 
3085 	return (pmp->pmap_func(pmp->pmap_private,
3086 	    pt_prmap_to_mdbmap(pmp->pmap_targ, prp, &map), map.map_name));
3087 }
3088 
3089 static int
3090 pt_mapping_iter(mdb_tgt_t *t, mdb_tgt_map_f *func, void *private)
3091 {
3092 	if (t->t_pshandle != NULL) {
3093 		pt_maparg_t pm;
3094 
3095 		pm.pmap_targ = t;
3096 		pm.pmap_func = func;
3097 		pm.pmap_private = private;
3098 
3099 		if (PT_LIBPROC_RESOLVE(t->t_pshandle)) {
3100 			(void) Pmapping_iter_resolved(t->t_pshandle,
3101 			    pt_map_apply, &pm);
3102 		} else {
3103 			(void) Pmapping_iter(t->t_pshandle,
3104 			    pt_map_apply, &pm);
3105 		}
3106 		return (0);
3107 	}
3108 
3109 	return (set_errno(EMDB_NOPROC));
3110 }
3111 
3112 static int
3113 pt_object_iter(mdb_tgt_t *t, mdb_tgt_map_f *func, void *private)
3114 {
3115 	pt_data_t *pt = t->t_data;
3116 
3117 	/*
3118 	 * If we have a libproc handle, we can just call Pobject_iter to
3119 	 * iterate over its list of load object information.
3120 	 */
3121 	if (t->t_pshandle != NULL) {
3122 		pt_maparg_t pm;
3123 
3124 		pm.pmap_targ = t;
3125 		pm.pmap_func = func;
3126 		pm.pmap_private = private;
3127 
3128 		if (PT_LIBPROC_RESOLVE(t->t_pshandle)) {
3129 			(void) Pobject_iter_resolved(t->t_pshandle,
3130 			    pt_map_apply, &pm);
3131 		} else {
3132 			(void) Pobject_iter(t->t_pshandle,
3133 			    pt_map_apply, &pm);
3134 		}
3135 		return (0);
3136 	}
3137 
3138 	/*
3139 	 * If we're examining an executable or other ELF file but we have no
3140 	 * libproc handle, fake up some information based on DT_NEEDED entries.
3141 	 */
3142 	if (pt->p_dynsym != NULL && pt->p_file->gf_dyns != NULL &&
3143 	    pt->p_fio != NULL) {
3144 		mdb_gelf_sect_t *gsp = pt->p_dynsym->gst_ssect;
3145 		GElf_Dyn *dynp = pt->p_file->gf_dyns;
3146 		mdb_map_t *mp = &pt->p_map;
3147 		const char *s = IOP_NAME(pt->p_fio);
3148 		size_t i;
3149 
3150 		(void) strncpy(mp->map_name, s, MDB_TGT_MAPSZ);
3151 		mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
3152 		mp->map_flags = MDB_TGT_MAP_R | MDB_TGT_MAP_X;
3153 		mp->map_base = NULL;
3154 		mp->map_size = 0;
3155 
3156 		if (func(private, mp, s) != 0)
3157 			return (0);
3158 
3159 		for (i = 0; i < pt->p_file->gf_ndyns; i++, dynp++) {
3160 			if (dynp->d_tag == DT_NEEDED) {
3161 				s = (char *)gsp->gs_data + dynp->d_un.d_val;
3162 				(void) strncpy(mp->map_name, s, MDB_TGT_MAPSZ);
3163 				mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
3164 				if (func(private, mp, s) != 0)
3165 					return (0);
3166 			}
3167 		}
3168 
3169 		return (0);
3170 	}
3171 
3172 	return (set_errno(EMDB_NOPROC));
3173 }
3174 
3175 static const mdb_map_t *
3176 pt_addr_to_map(mdb_tgt_t *t, uintptr_t addr)
3177 {
3178 	pt_data_t *pt = t->t_data;
3179 	const prmap_t *pmp;
3180 
3181 	if (t->t_pshandle == NULL) {
3182 		(void) set_errno(EMDB_NOPROC);
3183 		return (NULL);
3184 	}
3185 
3186 	if ((pmp = Paddr_to_map(t->t_pshandle, addr)) == NULL) {
3187 		(void) set_errno(EMDB_NOMAP);
3188 		return (NULL);
3189 	}
3190 
3191 	return (pt_prmap_to_mdbmap(t, pmp, &pt->p_map));
3192 }
3193 
3194 static const mdb_map_t *
3195 pt_name_to_map(mdb_tgt_t *t, const char *object)
3196 {
3197 	pt_data_t *pt = t->t_data;
3198 	const prmap_t *pmp;
3199 	Lmid_t lmid;
3200 
3201 	if (t->t_pshandle == NULL) {
3202 		(void) set_errno(EMDB_NOPROC);
3203 		return (NULL);
3204 	}
3205 
3206 	object = pt_resolve_lmid(object, &lmid);
3207 
3208 	if ((pmp = Plmid_to_map(t->t_pshandle, lmid, object)) == NULL) {
3209 		(void) set_errno(EMDB_NOOBJ);
3210 		return (NULL);
3211 	}
3212 
3213 	return (pt_prmap_to_mdbmap(t, pmp, &pt->p_map));
3214 }
3215 
3216 static ctf_file_t *
3217 pt_addr_to_ctf(mdb_tgt_t *t, uintptr_t addr)
3218 {
3219 	ctf_file_t *ret;
3220 
3221 	if (t->t_pshandle == NULL) {
3222 		(void) set_errno(EMDB_NOPROC);
3223 		return (NULL);
3224 	}
3225 
3226 	if ((ret = Paddr_to_ctf(t->t_pshandle, addr)) == NULL) {
3227 		(void) set_errno(EMDB_NOOBJ);
3228 		return (NULL);
3229 	}
3230 
3231 	return (ret);
3232 }
3233 
3234 static ctf_file_t *
3235 pt_name_to_ctf(mdb_tgt_t *t, const char *name)
3236 {
3237 	ctf_file_t *ret;
3238 
3239 	if (t->t_pshandle == NULL) {
3240 		(void) set_errno(EMDB_NOPROC);
3241 		return (NULL);
3242 	}
3243 
3244 	if ((ret = Pname_to_ctf(t->t_pshandle, name)) == NULL) {
3245 		(void) set_errno(EMDB_NOOBJ);
3246 		return (NULL);
3247 	}
3248 
3249 	return (ret);
3250 }
3251 
3252 static int
3253 pt_status(mdb_tgt_t *t, mdb_tgt_status_t *tsp)
3254 {
3255 	const pstatus_t *psp;
3256 	prgregset_t gregs;
3257 	int state;
3258 
3259 	bzero(tsp, sizeof (mdb_tgt_status_t));
3260 
3261 	if (t->t_pshandle == NULL) {
3262 		tsp->st_state = MDB_TGT_IDLE;
3263 		return (0);
3264 	}
3265 
3266 	switch (state = Pstate(t->t_pshandle)) {
3267 	case PS_RUN:
3268 		tsp->st_state = MDB_TGT_RUNNING;
3269 		break;
3270 
3271 	case PS_STOP:
3272 		tsp->st_state = MDB_TGT_STOPPED;
3273 		psp = Pstatus(t->t_pshandle);
3274 
3275 		tsp->st_tid = PTL_TID(t);
3276 		if (PTL_GETREGS(t, tsp->st_tid, gregs) == 0)
3277 			tsp->st_pc = gregs[R_PC];
3278 
3279 		if (psp->pr_flags & PR_ISTOP)
3280 			tsp->st_flags |= MDB_TGT_ISTOP;
3281 		if (psp->pr_flags & PR_DSTOP)
3282 			tsp->st_flags |= MDB_TGT_DSTOP;
3283 
3284 		break;
3285 
3286 	case PS_LOST:
3287 		tsp->st_state = MDB_TGT_LOST;
3288 		break;
3289 	case PS_UNDEAD:
3290 		tsp->st_state = MDB_TGT_UNDEAD;
3291 		break;
3292 	case PS_DEAD:
3293 		tsp->st_state = MDB_TGT_DEAD;
3294 		break;
3295 	case PS_IDLE:
3296 		tsp->st_state = MDB_TGT_IDLE;
3297 		break;
3298 	default:
3299 		fail("unknown libproc state (%d)\n", state);
3300 	}
3301 
3302 	if (t->t_flags & MDB_TGT_F_BUSY)
3303 		tsp->st_flags |= MDB_TGT_BUSY;
3304 
3305 	return (0);
3306 }
3307 
3308 static void
3309 pt_dupfd(const char *file, int oflags, mode_t mode, int dfd)
3310 {
3311 	int fd;
3312 
3313 	if ((fd = open(file, oflags, mode)) >= 0) {
3314 		(void) fcntl(fd, F_DUP2FD, dfd);
3315 		(void) close(fd);
3316 	} else
3317 		warn("failed to open %s as descriptor %d", file, dfd);
3318 }
3319 
3320 /*
3321  * The Pcreate_callback() function interposes on the default, empty libproc
3322  * definition.  It will be called following a fork of a new child process by
3323  * Pcreate() below, but before the exec of the new process image.  We use this
3324  * callback to optionally redirect stdin and stdout and reset the dispositions
3325  * of SIGPIPE and SIGQUIT from SIG_IGN back to SIG_DFL.
3326  */
3327 /*ARGSUSED*/
3328 void
3329 Pcreate_callback(struct ps_prochandle *P)
3330 {
3331 	pt_data_t *pt = mdb.m_target->t_data;
3332 
3333 	if (pt->p_stdin != NULL)
3334 		pt_dupfd(pt->p_stdin, O_RDWR, 0, STDIN_FILENO);
3335 	if (pt->p_stdout != NULL)
3336 		pt_dupfd(pt->p_stdout, O_CREAT | O_WRONLY, 0666, STDOUT_FILENO);
3337 
3338 	(void) mdb_signal_sethandler(SIGPIPE, SIG_DFL, NULL);
3339 	(void) mdb_signal_sethandler(SIGQUIT, SIG_DFL, NULL);
3340 }
3341 
3342 static int
3343 pt_run(mdb_tgt_t *t, int argc, const mdb_arg_t *argv)
3344 {
3345 	pt_data_t *pt = t->t_data;
3346 	struct ps_prochandle *P;
3347 	char execname[MAXPATHLEN];
3348 	const char **pargv;
3349 	int pargc = 0;
3350 	int i, perr;
3351 	char **penv;
3352 	mdb_var_t *v;
3353 
3354 	if (pt->p_aout_fio == NULL) {
3355 		warn("run requires executable to be specified on "
3356 		    "command-line\n");
3357 		return (set_errno(EMDB_TGT));
3358 	}
3359 
3360 	pargv = mdb_alloc(sizeof (char *) * (argc + 2), UM_SLEEP);
3361 	pargv[pargc++] = strbasename(IOP_NAME(pt->p_aout_fio));
3362 
3363 	for (i = 0; i < argc; i++) {
3364 		if (argv[i].a_type != MDB_TYPE_STRING) {
3365 			mdb_free(pargv, sizeof (char *) * (argc + 2));
3366 			return (set_errno(EINVAL));
3367 		}
3368 		if (argv[i].a_un.a_str[0] == '<')
3369 			pt->p_stdin = argv[i].a_un.a_str + 1;
3370 		else if (argv[i].a_un.a_str[0] == '>')
3371 			pt->p_stdout = argv[i].a_un.a_str + 1;
3372 		else
3373 			pargv[pargc++] = argv[i].a_un.a_str;
3374 	}
3375 	pargv[pargc] = NULL;
3376 
3377 	/*
3378 	 * Since Pcreate() uses execvp() and "." may not be present in $PATH,
3379 	 * we must manually prepend "./" when the executable is a simple name.
3380 	 */
3381 	if (strchr(IOP_NAME(pt->p_aout_fio), '/') == NULL) {
3382 		(void) snprintf(execname, sizeof (execname), "./%s",
3383 		    IOP_NAME(pt->p_aout_fio));
3384 	} else {
3385 		(void) snprintf(execname, sizeof (execname), "%s",
3386 		    IOP_NAME(pt->p_aout_fio));
3387 	}
3388 
3389 	penv = mdb_alloc((mdb_nv_size(&pt->p_env)+ 1) * sizeof (char *),
3390 	    UM_SLEEP);
3391 	for (mdb_nv_rewind(&pt->p_env), i = 0;
3392 	    (v = mdb_nv_advance(&pt->p_env)) != NULL; i++)
3393 		penv[i] = mdb_nv_get_cookie(v);
3394 	penv[i] = NULL;
3395 
3396 	P = Pxcreate(execname, (char **)pargv, penv, &perr, NULL, 0);
3397 	mdb_free(pargv, sizeof (char *) * (argc + 2));
3398 	pt->p_stdin = pt->p_stdout = NULL;
3399 
3400 	mdb_free(penv, i * sizeof (char *));
3401 
3402 	if (P == NULL) {
3403 		warn("failed to create process: %s\n", Pcreate_error(perr));
3404 		return (set_errno(EMDB_TGT));
3405 	}
3406 
3407 	if (t->t_pshandle != NULL) {
3408 		pt_pre_detach(t, TRUE);
3409 		if (t->t_pshandle != pt->p_idlehandle)
3410 			Prelease(t->t_pshandle, pt->p_rflags);
3411 	}
3412 
3413 	(void) Punsetflags(P, PR_RLC);	/* make sure run-on-last-close is off */
3414 	(void) Psetflags(P, PR_KLC);	/* kill on last close by debugger */
3415 	pt->p_rflags = PRELEASE_KILL;	/* kill on debugger Prelease */
3416 	t->t_pshandle = P;
3417 
3418 	pt_post_attach(t);
3419 	pt_activate_common(t);
3420 	(void) mdb_tgt_status(t, &t->t_status);
3421 	mdb.m_flags |= MDB_FL_VCREATE;
3422 
3423 	return (0);
3424 }
3425 
3426 /*
3427  * Forward a signal to the victim process in order to force it to stop or die.
3428  * Refer to the comments above pt_setrun(), below, for more info.
3429  */
3430 /*ARGSUSED*/
3431 static void
3432 pt_sigfwd(int sig, siginfo_t *sip, ucontext_t *ucp, mdb_tgt_t *t)
3433 {
3434 	struct ps_prochandle *P = t->t_pshandle;
3435 	const lwpstatus_t *psp = &Pstatus(P)->pr_lwp;
3436 	pid_t pid = Pstatus(P)->pr_pid;
3437 	long ctl[2];
3438 
3439 	if (getpgid(pid) != mdb.m_pgid) {
3440 		mdb_dprintf(MDB_DBG_TGT, "fwd SIG#%d to %d\n", sig, (int)pid);
3441 		(void) kill(pid, sig);
3442 	}
3443 
3444 	if (Pwait(P, 1) == 0 && (psp->pr_flags & PR_STOPPED) &&
3445 	    psp->pr_why == PR_JOBCONTROL && Pdstop(P) == 0) {
3446 		/*
3447 		 * If we're job control stopped and our DSTOP is pending, the
3448 		 * victim will never see our signal, so undo the kill() and
3449 		 * then send SIGCONT the victim to kick it out of the job
3450 		 * control stop and force our DSTOP to take effect.
3451 		 */
3452 		if ((psp->pr_flags & PR_DSTOP) &&
3453 		    prismember(&Pstatus(P)->pr_sigpend, sig)) {
3454 			ctl[0] = PCUNKILL;
3455 			ctl[1] = sig;
3456 			(void) write(Pctlfd(P), ctl, sizeof (ctl));
3457 		}
3458 
3459 		mdb_dprintf(MDB_DBG_TGT, "fwd SIGCONT to %d\n", (int)pid);
3460 		(void) kill(pid, SIGCONT);
3461 	}
3462 }
3463 
3464 /*
3465  * Common code for step and continue: if no victim process has been created,
3466  * call pt_run() to create one.  Then set the victim running, clearing any
3467  * pending fault.  One special case is that if the victim was previously
3468  * stopped on reception of SIGINT, we know that SIGINT was traced and the user
3469  * requested the victim to stop, so clear this signal before continuing.
3470  * For all other traced signals, the signal will be delivered on continue.
3471  *
3472  * Once the victim process is running, we wait for it to stop on an event of
3473  * interest.  Although libproc provides the basic primitive to wait for the
3474  * victim, we must be careful in our handling of signals.  We want to allow the
3475  * user to issue a SIGINT or SIGQUIT using the designated terminal control
3476  * character (typically ^C and ^\), and have these signals stop the target and
3477  * return control to the debugger if the signals are traced.  There are three
3478  * cases to be considered in our implementation:
3479  *
3480  * (1) If the debugger and victim are in the same process group, both receive
3481  * the signal from the terminal driver.  The debugger returns from Pwait() with
3482  * errno = EINTR, so we want to loop back and continue waiting until the victim
3483  * stops on receipt of its SIGINT or SIGQUIT.
3484  *
3485  * (2) If the debugger and victim are in different process groups, and the
3486  * victim is a member of the foreground process group, it will receive the
3487  * signal from the terminal driver and the debugger will not.  As such, we
3488  * will remain blocked in Pwait() until the victim stops on its signal.
3489  *
3490  * (3) If the debugger and victim are in different process groups, and the
3491  * debugger is a member of the foreground process group, it will receive the
3492  * signal from the terminal driver, and the victim will not.  The debugger
3493  * returns from Pwait() with errno = EINTR, so we need to forward the signal
3494  * to the victim process directly and then Pwait() again for it to stop.
3495  *
3496  * We can observe that all three cases are handled by simply calling Pwait()
3497  * repeatedly if it fails with EINTR, and forwarding SIGINT and SIGQUIT to
3498  * the victim if it is in a different process group, using pt_sigfwd() above.
3499  *
3500  * An additional complication is that the process may not be able to field
3501  * the signal if it is currently stopped by job control.  In this case, we
3502  * also DSTOP the process, and then send it a SIGCONT to wake it up from
3503  * job control and force it to re-enter stop() under the control of /proc.
3504  *
3505  * Finally, we would like to allow the user to suspend the process using the
3506  * terminal suspend character (typically ^Z) if both are in the same session.
3507  * We again employ pt_sigfwd() to forward SIGTSTP to the victim, wait for it to
3508  * stop from job control, and then capture it using /proc.  Once the process
3509  * has stopped, normal SIGTSTP processing is restored and the user can issue
3510  * another ^Z in order to suspend the debugger and return to the parent shell.
3511  */
3512 static int
3513 pt_setrun(mdb_tgt_t *t, mdb_tgt_status_t *tsp, int flags)
3514 {
3515 	struct ps_prochandle *P = t->t_pshandle;
3516 	pt_data_t *pt = t->t_data;
3517 	pid_t old_pgid = -1;
3518 
3519 	mdb_signal_f *intf, *quitf, *tstpf;
3520 	const lwpstatus_t *psp;
3521 	void *intd, *quitd, *tstpd;
3522 
3523 	int sig = pt->p_signal;
3524 	int error = 0;
3525 	int pgid = -1;
3526 
3527 	pt->p_signal = 0; /* clear pending signal */
3528 
3529 	if (P == NULL && pt_run(t, 0, NULL) == -1)
3530 		return (-1); /* errno is set for us */
3531 
3532 	P = t->t_pshandle;
3533 	psp = &Pstatus(P)->pr_lwp;
3534 
3535 	if (sig == 0 && psp->pr_why == PR_SIGNALLED && psp->pr_what == SIGINT)
3536 		flags |= PRCSIG; /* clear pending SIGINT */
3537 	else
3538 		flags |= PRCFAULT; /* clear any pending fault (e.g. BPT) */
3539 
3540 	intf = mdb_signal_gethandler(SIGINT, &intd);
3541 	quitf = mdb_signal_gethandler(SIGQUIT, &quitd);
3542 	tstpf = mdb_signal_gethandler(SIGTSTP, &tstpd);
3543 
3544 	(void) mdb_signal_sethandler(SIGINT, (mdb_signal_f *)pt_sigfwd, t);
3545 	(void) mdb_signal_sethandler(SIGQUIT, (mdb_signal_f *)pt_sigfwd, t);
3546 	(void) mdb_signal_sethandler(SIGTSTP, (mdb_signal_f *)pt_sigfwd, t);
3547 
3548 	if (sig != 0 && Pstate(P) == PS_RUN &&
3549 	    kill(Pstatus(P)->pr_pid, sig) == -1) {
3550 		error = errno;
3551 		goto out;
3552 	}
3553 
3554 	/*
3555 	 * If we attached to a job stopped background process in the same
3556 	 * session, make its pgid the foreground process group before running
3557 	 * it.  Ignore SIGTTOU while doing this to avoid being suspended.
3558 	 */
3559 	if (mdb.m_flags & MDB_FL_JOBCTL) {
3560 		(void) mdb_signal_sethandler(SIGTTOU, SIG_IGN, NULL);
3561 		(void) IOP_CTL(mdb.m_term, TIOCGPGRP, &old_pgid);
3562 		(void) IOP_CTL(mdb.m_term, TIOCSPGRP,
3563 		    (void *)&Pstatus(P)->pr_pgid);
3564 		(void) mdb_signal_sethandler(SIGTTOU, SIG_DFL, NULL);
3565 	}
3566 
3567 	if (Pstate(P) != PS_RUN && Psetrun(P, sig, flags) == -1) {
3568 		error = errno;
3569 		goto out;
3570 	}
3571 
3572 	/*
3573 	 * If the process is stopped on job control, resume its process group
3574 	 * by sending it a SIGCONT if we are in the same session.  Otherwise
3575 	 * we have no choice but to wait for someone else to foreground it.
3576 	 */
3577 	if (psp->pr_why == PR_JOBCONTROL) {
3578 		if (mdb.m_flags & MDB_FL_JOBCTL)
3579 			(void) kill(-Pstatus(P)->pr_pgid, SIGCONT);
3580 		else if (mdb.m_term != NULL)
3581 			warn("process is still suspended by job control ...\n");
3582 	}
3583 
3584 	/*
3585 	 * Wait for the process to stop.  As described above, we loop around if
3586 	 * we are interrupted (EINTR).  If we lose control, attempt to re-open
3587 	 * the process, or call pt_exec() if that fails to handle a re-exec.
3588 	 * If the process dies (ENOENT) or Pwait() fails, break out of the loop.
3589 	 */
3590 	while (Pwait(P, 0) == -1) {
3591 		if (errno != EINTR) {
3592 			if (Pstate(P) == PS_LOST) {
3593 				if (Preopen(P) == 0)
3594 					continue; /* Pwait() again */
3595 				else
3596 					pt_exec(t, 0, NULL);
3597 			} else if (errno != ENOENT)
3598 				warn("failed to wait for event");
3599 			break;
3600 		}
3601 	}
3602 
3603 	/*
3604 	 * If we changed the foreground process group, restore the old pgid
3605 	 * while ignoring SIGTTOU so we are not accidentally suspended.
3606 	 */
3607 	if (old_pgid != -1) {
3608 		(void) mdb_signal_sethandler(SIGTTOU, SIG_IGN, NULL);
3609 		(void) IOP_CTL(mdb.m_term, TIOCSPGRP, &pgid);
3610 		(void) mdb_signal_sethandler(SIGTTOU, SIG_DFL, NULL);
3611 	}
3612 
3613 	/*
3614 	 * If we're now stopped on exit from a successful exec, release any
3615 	 * vfork parents and clean out their address space before returning
3616 	 * to tgt_continue() and perturbing the list of armed event specs.
3617 	 * If we're stopped for any other reason, just update the mappings.
3618 	 */
3619 	switch (Pstate(P)) {
3620 	case PS_STOP:
3621 		if (psp->pr_why == PR_SYSEXIT && psp->pr_errno == 0 &&
3622 		    psp->pr_what == SYS_execve)
3623 			pt_release_parents(t);
3624 		else
3625 			Pupdate_maps(P);
3626 		break;
3627 
3628 	case PS_UNDEAD:
3629 	case PS_LOST:
3630 		pt_release_parents(t);
3631 		break;
3632 	}
3633 
3634 out:
3635 	(void) mdb_signal_sethandler(SIGINT, intf, intd);
3636 	(void) mdb_signal_sethandler(SIGQUIT, quitf, quitd);
3637 	(void) mdb_signal_sethandler(SIGTSTP, tstpf, tstpd);
3638 	(void) pt_status(t, tsp);
3639 
3640 	return (error ? set_errno(error) : 0);
3641 }
3642 
3643 static int
3644 pt_step(mdb_tgt_t *t, mdb_tgt_status_t *tsp)
3645 {
3646 	return (pt_setrun(t, tsp, PRSTEP));
3647 }
3648 
3649 static int
3650 pt_continue(mdb_tgt_t *t, mdb_tgt_status_t *tsp)
3651 {
3652 	return (pt_setrun(t, tsp, 0));
3653 }
3654 
3655 static int
3656 pt_signal(mdb_tgt_t *t, int sig)
3657 {
3658 	pt_data_t *pt = t->t_data;
3659 
3660 	if (sig > 0 && sig <= pt->p_maxsig) {
3661 		pt->p_signal = sig; /* pending until next pt_setrun */
3662 		return (0);
3663 	}
3664 
3665 	return (set_errno(EMDB_BADSIGNUM));
3666 }
3667 
3668 static int
3669 pt_sysenter_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3670 {
3671 	struct ps_prochandle *P = t->t_pshandle;
3672 
3673 	if (P != NULL && Pstate(P) < PS_LOST) {
3674 		sep->se_data = args; /* data is raw system call number */
3675 		return (Psysentry(P, (intptr_t)args, TRUE) < 0 ? -1 : 0);
3676 	}
3677 
3678 	return (set_errno(EMDB_NOPROC));
3679 }
3680 
3681 static void
3682 pt_sysenter_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3683 {
3684 	(void) Psysentry(t->t_pshandle, (intptr_t)sep->se_data, FALSE);
3685 }
3686 
3687 /*ARGSUSED*/
3688 static char *
3689 pt_sysenter_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3690     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3691 {
3692 	char name[32];
3693 	int sysnum;
3694 
3695 	if (vep != NULL)
3696 		sysnum = (intptr_t)vep->ve_args;
3697 	else
3698 		sysnum = (intptr_t)sep->se_data;
3699 
3700 	(void) proc_sysname(sysnum, name, sizeof (name));
3701 	(void) mdb_iob_snprintf(buf, nbytes, "stop on entry to %s", name);
3702 
3703 	return (buf);
3704 }
3705 
3706 /*ARGSUSED*/
3707 static int
3708 pt_sysenter_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
3709 {
3710 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3711 	int sysnum = (intptr_t)sep->se_data;
3712 
3713 	return (psp->pr_why == PR_SYSENTRY && psp->pr_what == sysnum);
3714 }
3715 
3716 static const mdb_se_ops_t proc_sysenter_ops = {
3717 	pt_sysenter_ctor,	/* se_ctor */
3718 	pt_sysenter_dtor,	/* se_dtor */
3719 	pt_sysenter_info,	/* se_info */
3720 	no_se_secmp,		/* se_secmp */
3721 	no_se_vecmp,		/* se_vecmp */
3722 	no_se_arm,		/* se_arm */
3723 	no_se_disarm,		/* se_disarm */
3724 	no_se_cont,		/* se_cont */
3725 	pt_sysenter_match	/* se_match */
3726 };
3727 
3728 static int
3729 pt_sysexit_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3730 {
3731 	struct ps_prochandle *P = t->t_pshandle;
3732 
3733 	if (P != NULL && Pstate(P) < PS_LOST) {
3734 		sep->se_data = args; /* data is raw system call number */
3735 		return (Psysexit(P, (intptr_t)args, TRUE) < 0 ? -1 : 0);
3736 	}
3737 
3738 	return (set_errno(EMDB_NOPROC));
3739 }
3740 
3741 static void
3742 pt_sysexit_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3743 {
3744 	(void) Psysexit(t->t_pshandle, (intptr_t)sep->se_data, FALSE);
3745 }
3746 
3747 /*ARGSUSED*/
3748 static char *
3749 pt_sysexit_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3750     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3751 {
3752 	char name[32];
3753 	int sysnum;
3754 
3755 	if (vep != NULL)
3756 		sysnum = (intptr_t)vep->ve_args;
3757 	else
3758 		sysnum = (intptr_t)sep->se_data;
3759 
3760 	(void) proc_sysname(sysnum, name, sizeof (name));
3761 	(void) mdb_iob_snprintf(buf, nbytes, "stop on exit from %s", name);
3762 
3763 	return (buf);
3764 }
3765 
3766 /*ARGSUSED*/
3767 static int
3768 pt_sysexit_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
3769 {
3770 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3771 	int sysnum = (intptr_t)sep->se_data;
3772 
3773 	return (psp->pr_why == PR_SYSEXIT && psp->pr_what == sysnum);
3774 }
3775 
3776 static const mdb_se_ops_t proc_sysexit_ops = {
3777 	pt_sysexit_ctor,	/* se_ctor */
3778 	pt_sysexit_dtor,	/* se_dtor */
3779 	pt_sysexit_info,	/* se_info */
3780 	no_se_secmp,		/* se_secmp */
3781 	no_se_vecmp,		/* se_vecmp */
3782 	no_se_arm,		/* se_arm */
3783 	no_se_disarm,		/* se_disarm */
3784 	no_se_cont,		/* se_cont */
3785 	pt_sysexit_match	/* se_match */
3786 };
3787 
3788 static int
3789 pt_signal_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3790 {
3791 	struct ps_prochandle *P = t->t_pshandle;
3792 
3793 	if (P != NULL && Pstate(P) < PS_LOST) {
3794 		sep->se_data = args; /* data is raw signal number */
3795 		return (Psignal(P, (intptr_t)args, TRUE) < 0 ? -1 : 0);
3796 	}
3797 
3798 	return (set_errno(EMDB_NOPROC));
3799 }
3800 
3801 static void
3802 pt_signal_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3803 {
3804 	(void) Psignal(t->t_pshandle, (intptr_t)sep->se_data, FALSE);
3805 }
3806 
3807 /*ARGSUSED*/
3808 static char *
3809 pt_signal_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3810     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3811 {
3812 	char name[SIG2STR_MAX];
3813 	int signum;
3814 
3815 	if (vep != NULL)
3816 		signum = (intptr_t)vep->ve_args;
3817 	else
3818 		signum = (intptr_t)sep->se_data;
3819 
3820 	(void) proc_signame(signum, name, sizeof (name));
3821 	(void) mdb_iob_snprintf(buf, nbytes, "stop on %s", name);
3822 
3823 	return (buf);
3824 }
3825 
3826 /*ARGSUSED*/
3827 static int
3828 pt_signal_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
3829 {
3830 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3831 	int signum = (intptr_t)sep->se_data;
3832 
3833 	return (psp->pr_why == PR_SIGNALLED && psp->pr_what == signum);
3834 }
3835 
3836 static const mdb_se_ops_t proc_signal_ops = {
3837 	pt_signal_ctor,		/* se_ctor */
3838 	pt_signal_dtor,		/* se_dtor */
3839 	pt_signal_info,		/* se_info */
3840 	no_se_secmp,		/* se_secmp */
3841 	no_se_vecmp,		/* se_vecmp */
3842 	no_se_arm,		/* se_arm */
3843 	no_se_disarm,		/* se_disarm */
3844 	no_se_cont,		/* se_cont */
3845 	pt_signal_match		/* se_match */
3846 };
3847 
3848 static int
3849 pt_fault_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3850 {
3851 	struct ps_prochandle *P = t->t_pshandle;
3852 
3853 	if (P != NULL && Pstate(P) < PS_LOST) {
3854 		sep->se_data = args; /* data is raw fault number */
3855 		return (Pfault(P, (intptr_t)args, TRUE) < 0 ? -1 : 0);
3856 	}
3857 
3858 	return (set_errno(EMDB_NOPROC));
3859 }
3860 
3861 static void
3862 pt_fault_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3863 {
3864 	int fault = (intptr_t)sep->se_data;
3865 
3866 	if (fault != FLTBPT && fault != FLTTRACE && fault != FLTWATCH)
3867 		(void) Pfault(t->t_pshandle, fault, FALSE);
3868 }
3869 
3870 /*ARGSUSED*/
3871 static char *
3872 pt_fault_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3873     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3874 {
3875 	char name[32];
3876 	int fltnum;
3877 
3878 	if (vep != NULL)
3879 		fltnum = (intptr_t)vep->ve_args;
3880 	else
3881 		fltnum = (intptr_t)sep->se_data;
3882 
3883 	(void) proc_fltname(fltnum, name, sizeof (name));
3884 	(void) mdb_iob_snprintf(buf, nbytes, "stop on %s", name);
3885 
3886 	return (buf);
3887 }
3888 
3889 /*ARGSUSED*/
3890 static int
3891 pt_fault_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
3892 {
3893 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3894 	int fltnum = (intptr_t)sep->se_data;
3895 
3896 	return (psp->pr_why == PR_FAULTED && psp->pr_what == fltnum);
3897 }
3898 
3899 static const mdb_se_ops_t proc_fault_ops = {
3900 	pt_fault_ctor,		/* se_ctor */
3901 	pt_fault_dtor,		/* se_dtor */
3902 	pt_fault_info,		/* se_info */
3903 	no_se_secmp,		/* se_secmp */
3904 	no_se_vecmp,		/* se_vecmp */
3905 	no_se_arm,		/* se_arm */
3906 	no_se_disarm,		/* se_disarm */
3907 	no_se_cont,		/* se_cont */
3908 	pt_fault_match		/* se_match */
3909 };
3910 
3911 /*
3912  * Callback for pt_ignore() dcmd above: for each VID, determine if it
3913  * corresponds to a vespec that traces the specified signal, and delete it.
3914  */
3915 /*ARGSUSED*/
3916 static int
3917 pt_ignore_sig(mdb_tgt_t *t, void *sig, int vid, void *data)
3918 {
3919 	mdb_vespec_t *vep = mdb_tgt_vespec_lookup(t, vid);
3920 
3921 	if (vep->ve_se->se_ops == &proc_signal_ops && vep->ve_args == sig)
3922 		(void) mdb_tgt_vespec_delete(t, vid);
3923 
3924 	return (0);
3925 }
3926 
3927 static int
3928 pt_brkpt_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3929 {
3930 	pt_data_t *pt = t->t_data;
3931 	pt_bparg_t *pta = args;
3932 	pt_brkpt_t *ptb;
3933 	GElf_Sym s;
3934 
3935 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) >= PS_LOST)
3936 		return (set_errno(EMDB_NOPROC));
3937 
3938 	if (pta->pta_symbol != NULL) {
3939 		if (!pt->p_rtld_finished &&
3940 		    strchr(pta->pta_symbol, '`') == NULL)
3941 			return (set_errno(EMDB_NOSYM));
3942 		if (mdb_tgt_lookup_by_scope(t, pta->pta_symbol, &s,
3943 		    NULL) == -1) {
3944 			if (errno != EMDB_NOOBJ && !(errno == EMDB_NOSYM &&
3945 			    (!(mdb.m_flags & MDB_FL_BPTNOSYMSTOP) ||
3946 			    !pt->p_rtld_finished))) {
3947 				warn("breakpoint %s activation failed",
3948 				    pta->pta_symbol);
3949 			}
3950 			return (-1); /* errno is set for us */
3951 		}
3952 
3953 		pta->pta_addr = (uintptr_t)s.st_value;
3954 	}
3955 
3956 #ifdef __sparc
3957 	if (pta->pta_addr & 3)
3958 		return (set_errno(EMDB_BPALIGN));
3959 #endif
3960 
3961 	if (Paddr_to_map(t->t_pshandle, pta->pta_addr) == NULL)
3962 		return (set_errno(EMDB_NOMAP));
3963 
3964 	ptb = mdb_alloc(sizeof (pt_brkpt_t), UM_SLEEP);
3965 	ptb->ptb_addr = pta->pta_addr;
3966 	ptb->ptb_instr = NULL;
3967 	sep->se_data = ptb;
3968 
3969 	return (0);
3970 }
3971 
3972 /*ARGSUSED*/
3973 static void
3974 pt_brkpt_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3975 {
3976 	mdb_free(sep->se_data, sizeof (pt_brkpt_t));
3977 }
3978 
3979 /*ARGSUSED*/
3980 static char *
3981 pt_brkpt_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3982     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3983 {
3984 	uintptr_t addr = NULL;
3985 
3986 	if (vep != NULL) {
3987 		pt_bparg_t *pta = vep->ve_args;
3988 
3989 		if (pta->pta_symbol != NULL) {
3990 			(void) mdb_iob_snprintf(buf, nbytes, "stop at %s",
3991 			    pta->pta_symbol);
3992 		} else {
3993 			(void) mdb_iob_snprintf(buf, nbytes, "stop at %a",
3994 			    pta->pta_addr);
3995 			addr = pta->pta_addr;
3996 		}
3997 
3998 	} else {
3999 		addr = ((pt_brkpt_t *)sep->se_data)->ptb_addr;
4000 		(void) mdb_iob_snprintf(buf, nbytes, "stop at %a", addr);
4001 	}
4002 
4003 	sp->spec_base = addr;
4004 	sp->spec_size = sizeof (instr_t);
4005 
4006 	return (buf);
4007 }
4008 
4009 static int
4010 pt_brkpt_secmp(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
4011 {
4012 	pt_brkpt_t *ptb = sep->se_data;
4013 	pt_bparg_t *pta = args;
4014 	GElf_Sym sym;
4015 
4016 	if (pta->pta_symbol != NULL) {
4017 		return (mdb_tgt_lookup_by_scope(t, pta->pta_symbol,
4018 		    &sym, NULL) == 0 && sym.st_value == ptb->ptb_addr);
4019 	}
4020 
4021 	return (pta->pta_addr == ptb->ptb_addr);
4022 }
4023 
4024 /*ARGSUSED*/
4025 static int
4026 pt_brkpt_vecmp(mdb_tgt_t *t, mdb_vespec_t *vep, void *args)
4027 {
4028 	pt_bparg_t *pta1 = vep->ve_args;
4029 	pt_bparg_t *pta2 = args;
4030 
4031 	if (pta1->pta_symbol != NULL && pta2->pta_symbol != NULL)
4032 		return (strcmp(pta1->pta_symbol, pta2->pta_symbol) == 0);
4033 
4034 	if (pta1->pta_symbol == NULL && pta2->pta_symbol == NULL)
4035 		return (pta1->pta_addr == pta2->pta_addr);
4036 
4037 	return (0); /* fail if one is symbolic, other is an explicit address */
4038 }
4039 
4040 static int
4041 pt_brkpt_arm(mdb_tgt_t *t, mdb_sespec_t *sep)
4042 {
4043 	pt_brkpt_t *ptb = sep->se_data;
4044 	return (Psetbkpt(t->t_pshandle, ptb->ptb_addr, &ptb->ptb_instr));
4045 }
4046 
4047 /*
4048  * In order to disarm a breakpoint, we replace the trap instruction at ptb_addr
4049  * with the saved instruction.  However, if we have stopped after a successful
4050  * exec(2), we do not want to restore ptb_instr because the address space has
4051  * now been replaced with the text of a different executable, and so restoring
4052  * the saved instruction would be incorrect.  The exec itself has effectively
4053  * removed all breakpoint trap instructions for us, so we can just return.
4054  */
4055 static int
4056 pt_brkpt_disarm(mdb_tgt_t *t, mdb_sespec_t *sep)
4057 {
4058 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
4059 	pt_brkpt_t *ptb = sep->se_data;
4060 
4061 	if (psp->pr_why == PR_SYSEXIT && psp->pr_errno == 0 &&
4062 	    psp->pr_what == SYS_execve)
4063 		return (0); /* do not restore saved instruction */
4064 
4065 	return (Pdelbkpt(t->t_pshandle, ptb->ptb_addr, ptb->ptb_instr));
4066 }
4067 
4068 /*
4069  * Determine whether the specified sespec is an armed watchpoint that overlaps
4070  * with the given breakpoint and has the given flags set.  We use this to find
4071  * conflicts with breakpoints, below.
4072  */
4073 static int
4074 pt_wp_overlap(mdb_sespec_t *sep, pt_brkpt_t *ptb, int flags)
4075 {
4076 	const prwatch_t *wp = sep->se_data;
4077 
4078 	return (sep->se_state == MDB_TGT_SPEC_ARMED &&
4079 	    sep->se_ops == &proc_wapt_ops && (wp->pr_wflags & flags) &&
4080 	    ptb->ptb_addr - wp->pr_vaddr < wp->pr_size);
4081 }
4082 
4083 /*
4084  * We step over breakpoints using Pxecbkpt() in libproc.  If a conflicting
4085  * watchpoint is present, we must temporarily remove it before stepping over
4086  * the breakpoint so we do not immediately re-trigger the watchpoint.  We know
4087  * the watchpoint has already triggered on our trap instruction as part of
4088  * fetching it.  Before we return, we must re-install any disabled watchpoints.
4089  */
4090 static int
4091 pt_brkpt_cont(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
4092 {
4093 	pt_brkpt_t *ptb = sep->se_data;
4094 	int status = -1;
4095 	int error;
4096 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
4097 
4098 	/*
4099 	 * If the PC no longer matches our original address, then the user has
4100 	 * changed it while we have been stopped. In this case, it no longer
4101 	 * makes any sense to continue over this breakpoint.  We return as if we
4102 	 * continued normally.
4103 	 */
4104 	if ((uintptr_t)psp->pr_info.si_addr != psp->pr_reg[R_PC])
4105 		return (pt_status(t, tsp));
4106 
4107 	for (sep = mdb_list_next(&t->t_active); sep; sep = mdb_list_next(sep)) {
4108 		if (pt_wp_overlap(sep, ptb, WA_EXEC))
4109 			(void) Pdelwapt(t->t_pshandle, sep->se_data);
4110 	}
4111 
4112 	if (Pxecbkpt(t->t_pshandle, ptb->ptb_instr) == 0 &&
4113 	    Pdelbkpt(t->t_pshandle, ptb->ptb_addr, ptb->ptb_instr) == 0)
4114 		status = pt_status(t, tsp);
4115 
4116 	error = errno; /* save errno from Pxecbkpt, Pdelbkpt, or pt_status */
4117 
4118 	for (sep = mdb_list_next(&t->t_active); sep; sep = mdb_list_next(sep)) {
4119 		if (pt_wp_overlap(sep, ptb, WA_EXEC) &&
4120 		    Psetwapt(t->t_pshandle, sep->se_data) == -1) {
4121 			sep->se_state = MDB_TGT_SPEC_ERROR;
4122 			sep->se_errno = errno;
4123 		}
4124 	}
4125 
4126 	(void) set_errno(error);
4127 	return (status);
4128 }
4129 
4130 /*ARGSUSED*/
4131 static int
4132 pt_brkpt_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
4133 {
4134 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
4135 	pt_brkpt_t *ptb = sep->se_data;
4136 
4137 	return (psp->pr_why == PR_FAULTED && psp->pr_what == FLTBPT &&
4138 	    psp->pr_reg[R_PC] == ptb->ptb_addr);
4139 }
4140 
4141 static const mdb_se_ops_t proc_brkpt_ops = {
4142 	pt_brkpt_ctor,		/* se_ctor */
4143 	pt_brkpt_dtor,		/* se_dtor */
4144 	pt_brkpt_info,		/* se_info */
4145 	pt_brkpt_secmp,		/* se_secmp */
4146 	pt_brkpt_vecmp,		/* se_vecmp */
4147 	pt_brkpt_arm,		/* se_arm */
4148 	pt_brkpt_disarm,	/* se_disarm */
4149 	pt_brkpt_cont,		/* se_cont */
4150 	pt_brkpt_match		/* se_match */
4151 };
4152 
4153 static int
4154 pt_wapt_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
4155 {
4156 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) >= PS_LOST)
4157 		return (set_errno(EMDB_NOPROC));
4158 
4159 	sep->se_data = mdb_alloc(sizeof (prwatch_t), UM_SLEEP);
4160 	bcopy(args, sep->se_data, sizeof (prwatch_t));
4161 	return (0);
4162 }
4163 
4164 /*ARGSUSED*/
4165 static void
4166 pt_wapt_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
4167 {
4168 	mdb_free(sep->se_data, sizeof (prwatch_t));
4169 }
4170 
4171 /*ARGSUSED*/
4172 static char *
4173 pt_wapt_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
4174     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
4175 {
4176 	prwatch_t *wp = vep != NULL ? vep->ve_args : sep->se_data;
4177 	char desc[24];
4178 
4179 	ASSERT(wp->pr_wflags != 0);
4180 	desc[0] = '\0';
4181 
4182 	switch (wp->pr_wflags) {
4183 	case WA_READ:
4184 		(void) strcat(desc, "/read");
4185 		break;
4186 	case WA_WRITE:
4187 		(void) strcat(desc, "/write");
4188 		break;
4189 	case WA_EXEC:
4190 		(void) strcat(desc, "/exec");
4191 		break;
4192 	default:
4193 		if (wp->pr_wflags & WA_READ)
4194 			(void) strcat(desc, "/r");
4195 		if (wp->pr_wflags & WA_WRITE)
4196 			(void) strcat(desc, "/w");
4197 		if (wp->pr_wflags & WA_EXEC)
4198 			(void) strcat(desc, "/x");
4199 	}
4200 
4201 	(void) mdb_iob_snprintf(buf, nbytes, "stop on %s of [%la, %la)",
4202 	    desc + 1, wp->pr_vaddr, wp->pr_vaddr + wp->pr_size);
4203 
4204 	sp->spec_base = wp->pr_vaddr;
4205 	sp->spec_size = wp->pr_size;
4206 
4207 	return (buf);
4208 }
4209 
4210 /*ARGSUSED*/
4211 static int
4212 pt_wapt_secmp(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
4213 {
4214 	prwatch_t *wp1 = sep->se_data;
4215 	prwatch_t *wp2 = args;
4216 
4217 	return (wp1->pr_vaddr == wp2->pr_vaddr &&
4218 	    wp1->pr_size == wp2->pr_size && wp1->pr_wflags == wp2->pr_wflags);
4219 }
4220 
4221 /*ARGSUSED*/
4222 static int
4223 pt_wapt_vecmp(mdb_tgt_t *t, mdb_vespec_t *vep, void *args)
4224 {
4225 	prwatch_t *wp1 = vep->ve_args;
4226 	prwatch_t *wp2 = args;
4227 
4228 	return (wp1->pr_vaddr == wp2->pr_vaddr &&
4229 	    wp1->pr_size == wp2->pr_size && wp1->pr_wflags == wp2->pr_wflags);
4230 }
4231 
4232 static int
4233 pt_wapt_arm(mdb_tgt_t *t, mdb_sespec_t *sep)
4234 {
4235 	return (Psetwapt(t->t_pshandle, sep->se_data));
4236 }
4237 
4238 static int
4239 pt_wapt_disarm(mdb_tgt_t *t, mdb_sespec_t *sep)
4240 {
4241 	return (Pdelwapt(t->t_pshandle, sep->se_data));
4242 }
4243 
4244 /*
4245  * Determine whether the specified sespec is an armed breakpoint at the
4246  * given %pc.  We use this to find conflicts with watchpoints below.
4247  */
4248 static int
4249 pt_bp_overlap(mdb_sespec_t *sep, uintptr_t pc)
4250 {
4251 	pt_brkpt_t *ptb = sep->se_data;
4252 
4253 	return (sep->se_state == MDB_TGT_SPEC_ARMED &&
4254 	    sep->se_ops == &proc_brkpt_ops && ptb->ptb_addr == pc);
4255 }
4256 
4257 /*
4258  * We step over watchpoints using Pxecwapt() in libproc.  If a conflicting
4259  * breakpoint is present, we must temporarily disarm it before stepping
4260  * over the watchpoint so we do not immediately re-trigger the breakpoint.
4261  * This is similar to the case handled in pt_brkpt_cont(), above.
4262  */
4263 static int
4264 pt_wapt_cont(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
4265 {
4266 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
4267 	mdb_sespec_t *bep = NULL;
4268 	int status = -1;
4269 	int error;
4270 
4271 	/*
4272 	 * If the PC no longer matches our original address, then the user has
4273 	 * changed it while we have been stopped. In this case, it no longer
4274 	 * makes any sense to continue over this instruction.  We return as if
4275 	 * we continued normally.
4276 	 */
4277 	if ((uintptr_t)psp->pr_info.si_pc != psp->pr_reg[R_PC])
4278 		return (pt_status(t, tsp));
4279 
4280 	if (psp->pr_info.si_code != TRAP_XWATCH) {
4281 		for (bep = mdb_list_next(&t->t_active); bep != NULL;
4282 		    bep = mdb_list_next(bep)) {
4283 			if (pt_bp_overlap(bep, psp->pr_reg[R_PC])) {
4284 				(void) bep->se_ops->se_disarm(t, bep);
4285 				bep->se_state = MDB_TGT_SPEC_ACTIVE;
4286 				break;
4287 			}
4288 		}
4289 	}
4290 
4291 	if (Pxecwapt(t->t_pshandle, sep->se_data) == 0)
4292 		status = pt_status(t, tsp);
4293 
4294 	error = errno; /* save errno from Pxecwapt or pt_status */
4295 
4296 	if (bep != NULL)
4297 		mdb_tgt_sespec_arm_one(t, bep);
4298 
4299 	(void) set_errno(error);
4300 	return (status);
4301 }
4302 
4303 /*ARGSUSED*/
4304 static int
4305 pt_wapt_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
4306 {
4307 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
4308 	prwatch_t *wp = sep->se_data;
4309 
4310 	return (psp->pr_why == PR_FAULTED && psp->pr_what == FLTWATCH &&
4311 	    (uintptr_t)psp->pr_info.si_addr - wp->pr_vaddr < wp->pr_size);
4312 }
4313 
4314 static const mdb_se_ops_t proc_wapt_ops = {
4315 	pt_wapt_ctor,		/* se_ctor */
4316 	pt_wapt_dtor,		/* se_dtor */
4317 	pt_wapt_info,		/* se_info */
4318 	pt_wapt_secmp,		/* se_secmp */
4319 	pt_wapt_vecmp,		/* se_vecmp */
4320 	pt_wapt_arm,		/* se_arm */
4321 	pt_wapt_disarm,		/* se_disarm */
4322 	pt_wapt_cont,		/* se_cont */
4323 	pt_wapt_match		/* se_match */
4324 };
4325 
4326 static void
4327 pt_bparg_dtor(mdb_vespec_t *vep)
4328 {
4329 	pt_bparg_t *pta = vep->ve_args;
4330 
4331 	if (pta->pta_symbol != NULL)
4332 		strfree(pta->pta_symbol);
4333 
4334 	mdb_free(pta, sizeof (pt_bparg_t));
4335 }
4336 
4337 static int
4338 pt_add_vbrkpt(mdb_tgt_t *t, uintptr_t addr,
4339     int spec_flags, mdb_tgt_se_f *func, void *data)
4340 {
4341 	pt_bparg_t *pta = mdb_alloc(sizeof (pt_bparg_t), UM_SLEEP);
4342 
4343 	pta->pta_symbol = NULL;
4344 	pta->pta_addr = addr;
4345 
4346 	return (mdb_tgt_vespec_insert(t, &proc_brkpt_ops, spec_flags,
4347 	    func, data, pta, pt_bparg_dtor));
4348 }
4349 
4350 static int
4351 pt_add_sbrkpt(mdb_tgt_t *t, const char *sym,
4352     int spec_flags, mdb_tgt_se_f *func, void *data)
4353 {
4354 	pt_bparg_t *pta;
4355 
4356 	if (sym[0] == '`') {
4357 		(void) set_errno(EMDB_NOOBJ);
4358 		return (0);
4359 	}
4360 
4361 	if (sym[strlen(sym) - 1] == '`') {
4362 		(void) set_errno(EMDB_NOSYM);
4363 		return (0);
4364 	}
4365 
4366 	pta = mdb_alloc(sizeof (pt_bparg_t), UM_SLEEP);
4367 	pta->pta_symbol = strdup(sym);
4368 	pta->pta_addr = NULL;
4369 
4370 	return (mdb_tgt_vespec_insert(t, &proc_brkpt_ops, spec_flags,
4371 	    func, data, pta, pt_bparg_dtor));
4372 }
4373 
4374 static int
4375 pt_wparg_overlap(const prwatch_t *wp1, const prwatch_t *wp2)
4376 {
4377 	if (wp2->pr_vaddr + wp2->pr_size <= wp1->pr_vaddr)
4378 		return (0); /* no range overlap */
4379 
4380 	if (wp1->pr_vaddr + wp1->pr_size <= wp2->pr_vaddr)
4381 		return (0); /* no range overlap */
4382 
4383 	return (wp1->pr_vaddr != wp2->pr_vaddr ||
4384 	    wp1->pr_size != wp2->pr_size || wp1->pr_wflags != wp2->pr_wflags);
4385 }
4386 
4387 static void
4388 pt_wparg_dtor(mdb_vespec_t *vep)
4389 {
4390 	mdb_free(vep->ve_args, sizeof (prwatch_t));
4391 }
4392 
4393 static int
4394 pt_add_vwapt(mdb_tgt_t *t, uintptr_t addr, size_t len, uint_t wflags,
4395     int spec_flags, mdb_tgt_se_f *func, void *data)
4396 {
4397 	prwatch_t *wp = mdb_alloc(sizeof (prwatch_t), UM_SLEEP);
4398 	mdb_sespec_t *sep;
4399 
4400 	wp->pr_vaddr = addr;
4401 	wp->pr_size = len;
4402 	wp->pr_wflags = 0;
4403 
4404 	if (wflags & MDB_TGT_WA_R)
4405 		wp->pr_wflags |= WA_READ;
4406 	if (wflags & MDB_TGT_WA_W)
4407 		wp->pr_wflags |= WA_WRITE;
4408 	if (wflags & MDB_TGT_WA_X)
4409 		wp->pr_wflags |= WA_EXEC;
4410 
4411 	for (sep = mdb_list_next(&t->t_active); sep; sep = mdb_list_next(sep)) {
4412 		if (sep->se_ops == &proc_wapt_ops &&
4413 		    mdb_list_next(&sep->se_velist) != NULL &&
4414 		    pt_wparg_overlap(wp, sep->se_data))
4415 			goto dup;
4416 	}
4417 
4418 	for (sep = mdb_list_next(&t->t_idle); sep; sep = mdb_list_next(sep)) {
4419 		if (sep->se_ops == &proc_wapt_ops && pt_wparg_overlap(wp,
4420 		    ((mdb_vespec_t *)mdb_list_next(&sep->se_velist))->ve_args))
4421 			goto dup;
4422 	}
4423 
4424 	return (mdb_tgt_vespec_insert(t, &proc_wapt_ops, spec_flags,
4425 	    func, data, wp, pt_wparg_dtor));
4426 
4427 dup:
4428 	mdb_free(wp, sizeof (prwatch_t));
4429 	(void) set_errno(EMDB_WPDUP);
4430 	return (0);
4431 }
4432 
4433 static int
4434 pt_add_sysenter(mdb_tgt_t *t, int sysnum,
4435     int spec_flags, mdb_tgt_se_f *func, void *data)
4436 {
4437 	if (sysnum <= 0 || sysnum > PRMAXSYS) {
4438 		(void) set_errno(EMDB_BADSYSNUM);
4439 		return (0);
4440 	}
4441 
4442 	return (mdb_tgt_vespec_insert(t, &proc_sysenter_ops, spec_flags,
4443 	    func, data, (void *)(uintptr_t)sysnum, no_ve_dtor));
4444 }
4445 
4446 static int
4447 pt_add_sysexit(mdb_tgt_t *t, int sysnum,
4448     int spec_flags, mdb_tgt_se_f *func, void *data)
4449 {
4450 	if (sysnum <= 0 || sysnum > PRMAXSYS) {
4451 		(void) set_errno(EMDB_BADSYSNUM);
4452 		return (0);
4453 	}
4454 
4455 	return (mdb_tgt_vespec_insert(t, &proc_sysexit_ops, spec_flags,
4456 	    func, data, (void *)(uintptr_t)sysnum, no_ve_dtor));
4457 }
4458 
4459 static int
4460 pt_add_signal(mdb_tgt_t *t, int signum,
4461     int spec_flags, mdb_tgt_se_f *func, void *data)
4462 {
4463 	pt_data_t *pt = t->t_data;
4464 
4465 	if (signum <= 0 || signum > pt->p_maxsig) {
4466 		(void) set_errno(EMDB_BADSIGNUM);
4467 		return (0);
4468 	}
4469 
4470 	return (mdb_tgt_vespec_insert(t, &proc_signal_ops, spec_flags,
4471 	    func, data, (void *)(uintptr_t)signum, no_ve_dtor));
4472 }
4473 
4474 static int
4475 pt_add_fault(mdb_tgt_t *t, int fltnum,
4476     int spec_flags, mdb_tgt_se_f *func, void *data)
4477 {
4478 	if (fltnum <= 0 || fltnum > PRMAXFAULT) {
4479 		(void) set_errno(EMDB_BADFLTNUM);
4480 		return (0);
4481 	}
4482 
4483 	return (mdb_tgt_vespec_insert(t, &proc_fault_ops, spec_flags,
4484 	    func, data, (void *)(uintptr_t)fltnum, no_ve_dtor));
4485 }
4486 
4487 static int
4488 pt_getareg(mdb_tgt_t *t, mdb_tgt_tid_t tid,
4489     const char *rname, mdb_tgt_reg_t *rp)
4490 {
4491 	pt_data_t *pt = t->t_data;
4492 	prgregset_t grs;
4493 	mdb_var_t *v;
4494 
4495 	if (t->t_pshandle == NULL)
4496 		return (set_errno(EMDB_NOPROC));
4497 
4498 	if ((v = mdb_nv_lookup(&pt->p_regs, rname)) != NULL) {
4499 		uintmax_t rd_nval = mdb_nv_get_value(v);
4500 		ushort_t rd_num = MDB_TGT_R_NUM(rd_nval);
4501 		ushort_t rd_flags = MDB_TGT_R_FLAGS(rd_nval);
4502 
4503 		if (!MDB_TGT_R_IS_FP(rd_flags)) {
4504 			mdb_tgt_reg_t r = 0;
4505 
4506 #if defined(__sparc) && defined(_ILP32)
4507 			/*
4508 			 * If we are debugging on 32-bit SPARC, the globals and
4509 			 * outs can have 32 upper bits hiding in the xregs.
4510 			 */
4511 			/* gcc doesn't like >= R_G0 because R_G0 == 0 */
4512 			int is_g = (rd_num == R_G0 ||
4513 			    rd_num >= R_G1 && rd_num <= R_G7);
4514 			int is_o = (rd_num >= R_O0 && rd_num <= R_O7);
4515 			prxregset_t xrs;
4516 
4517 			if (is_g && PTL_GETXREGS(t, tid, &xrs) == 0 &&
4518 			    xrs.pr_type == XR_TYPE_V8P) {
4519 				r |= (uint64_t)xrs.pr_un.pr_v8p.pr_xg[
4520 				    rd_num - R_G0 + XR_G0] << 32;
4521 			}
4522 
4523 			if (is_o && PTL_GETXREGS(t, tid, &xrs) == 0 &&
4524 			    xrs.pr_type == XR_TYPE_V8P) {
4525 				r |= (uint64_t)xrs.pr_un.pr_v8p.pr_xo[
4526 				    rd_num - R_O0 + XR_O0] << 32;
4527 			}
4528 #endif	/* __sparc && _ILP32 */
4529 
4530 			/*
4531 			 * Avoid sign-extension by casting: recall that procfs
4532 			 * defines prgreg_t as a long or int and our native
4533 			 * register handling uses uint64_t's.
4534 			 */
4535 			if (PTL_GETREGS(t, tid, grs) == 0) {
4536 				*rp = r | (ulong_t)grs[rd_num];
4537 				if (rd_flags & MDB_TGT_R_32)
4538 					*rp &= 0xffffffffULL;
4539 				else if (rd_flags & MDB_TGT_R_16)
4540 					*rp &= 0xffffULL;
4541 				else if (rd_flags & MDB_TGT_R_8H)
4542 					*rp = (*rp & 0xff00ULL) >> 8;
4543 				else if (rd_flags & MDB_TGT_R_8L)
4544 					*rp &= 0xffULL;
4545 				return (0);
4546 			}
4547 			return (-1);
4548 		} else
4549 			return (pt_getfpreg(t, tid, rd_num, rd_flags, rp));
4550 	}
4551 
4552 	return (set_errno(EMDB_BADREG));
4553 }
4554 
4555 static int
4556 pt_putareg(mdb_tgt_t *t, mdb_tgt_tid_t tid, const char *rname, mdb_tgt_reg_t r)
4557 {
4558 	pt_data_t *pt = t->t_data;
4559 	prgregset_t grs;
4560 	mdb_var_t *v;
4561 
4562 	if (t->t_pshandle == NULL)
4563 		return (set_errno(EMDB_NOPROC));
4564 
4565 	if ((v = mdb_nv_lookup(&pt->p_regs, rname)) != NULL) {
4566 		uintmax_t rd_nval = mdb_nv_get_value(v);
4567 		ushort_t rd_num = MDB_TGT_R_NUM(rd_nval);
4568 		ushort_t rd_flags = MDB_TGT_R_FLAGS(rd_nval);
4569 
4570 		if (!MDB_TGT_R_IS_FP(rd_flags)) {
4571 
4572 			if (rd_flags & MDB_TGT_R_32)
4573 				r &= 0xffffffffULL;
4574 			else if (rd_flags & MDB_TGT_R_16)
4575 				r &= 0xffffULL;
4576 			else if (rd_flags & MDB_TGT_R_8H)
4577 				r = (r & 0xffULL) << 8;
4578 			else if (rd_flags & MDB_TGT_R_8L)
4579 				r &= 0xffULL;
4580 
4581 #if defined(__sparc) && defined(_ILP32)
4582 			/*
4583 			 * If we are debugging on 32-bit SPARC, the globals and
4584 			 * outs can have 32 upper bits stored in the xregs.
4585 			 */
4586 			int is_g = (rd_num == R_G0 ||
4587 			    rd_num >= R_G1 && rd_num <= R_G7);
4588 			int is_o = (rd_num >= R_O0 && rd_num <= R_O7);
4589 			prxregset_t xrs;
4590 
4591 			if ((is_g || is_o) && PTL_GETXREGS(t, tid, &xrs) == 0 &&
4592 			    xrs.pr_type == XR_TYPE_V8P) {
4593 				if (is_g) {
4594 					xrs.pr_un.pr_v8p.pr_xg[rd_num -
4595 					    R_G0 + XR_G0] = (uint32_t)(r >> 32);
4596 				} else if (is_o) {
4597 					xrs.pr_un.pr_v8p.pr_xo[rd_num -
4598 					    R_O0 + XR_O0] = (uint32_t)(r >> 32);
4599 				}
4600 
4601 				if (PTL_SETXREGS(t, tid, &xrs) == -1)
4602 					return (-1);
4603 			}
4604 #endif	/* __sparc && _ILP32 */
4605 
4606 			if (PTL_GETREGS(t, tid, grs) == 0) {
4607 				grs[rd_num] = (prgreg_t)r;
4608 				return (PTL_SETREGS(t, tid, grs));
4609 			}
4610 			return (-1);
4611 		} else
4612 			return (pt_putfpreg(t, tid, rd_num, rd_flags, r));
4613 	}
4614 
4615 	return (set_errno(EMDB_BADREG));
4616 }
4617 
4618 static int
4619 pt_stack_call(pt_stkarg_t *psp, const prgregset_t grs, uint_t argc, long *argv)
4620 {
4621 	psp->pstk_gotpc |= (grs[R_PC] != 0);
4622 
4623 	if (!psp->pstk_gotpc)
4624 		return (0); /* skip initial zeroed frames */
4625 
4626 	return (psp->pstk_func(psp->pstk_private, grs[R_PC],
4627 	    argc, argv, (const struct mdb_tgt_gregset *)grs));
4628 }
4629 
4630 static int
4631 pt_stack_iter(mdb_tgt_t *t, const mdb_tgt_gregset_t *gsp,
4632     mdb_tgt_stack_f *func, void *arg)
4633 {
4634 	if (t->t_pshandle != NULL) {
4635 		pt_stkarg_t pstk;
4636 
4637 		pstk.pstk_func = func;
4638 		pstk.pstk_private = arg;
4639 		pstk.pstk_gotpc = FALSE;
4640 
4641 		(void) Pstack_iter(t->t_pshandle, gsp->gregs,
4642 		    (proc_stack_f *)pt_stack_call, &pstk);
4643 
4644 		return (0);
4645 	}
4646 
4647 	return (set_errno(EMDB_NOPROC));
4648 }
4649 
4650 static int
4651 pt_auxv(mdb_tgt_t *t, const auxv_t **auxvp)
4652 {
4653 	if (t->t_pshandle != NULL) {
4654 		*auxvp = Pgetauxvec(t->t_pshandle);
4655 		return (0);
4656 	}
4657 
4658 	return (set_errno(EMDB_NOPROC));
4659 }
4660 
4661 
4662 static const mdb_tgt_ops_t proc_ops = {
4663 	pt_setflags,				/* t_setflags */
4664 	(int (*)()) mdb_tgt_notsup,		/* t_setcontext */
4665 	pt_activate,				/* t_activate */
4666 	pt_deactivate,				/* t_deactivate */
4667 	pt_periodic,				/* t_periodic */
4668 	pt_destroy,				/* t_destroy */
4669 	pt_name,				/* t_name */
4670 	(const char *(*)()) mdb_conf_isa,	/* t_isa */
4671 	pt_platform,				/* t_platform */
4672 	pt_uname,				/* t_uname */
4673 	pt_dmodel,				/* t_dmodel */
4674 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_aread */
4675 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_awrite */
4676 	pt_vread,				/* t_vread */
4677 	pt_vwrite,				/* t_vwrite */
4678 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_pread */
4679 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_pwrite */
4680 	pt_fread,				/* t_fread */
4681 	pt_fwrite,				/* t_fwrite */
4682 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_ioread */
4683 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_iowrite */
4684 	(int (*)()) mdb_tgt_notsup,		/* t_vtop */
4685 	pt_lookup_by_name,			/* t_lookup_by_name */
4686 	pt_lookup_by_addr,			/* t_lookup_by_addr */
4687 	pt_symbol_iter,				/* t_symbol_iter */
4688 	pt_mapping_iter,			/* t_mapping_iter */
4689 	pt_object_iter,				/* t_object_iter */
4690 	pt_addr_to_map,				/* t_addr_to_map */
4691 	pt_name_to_map,				/* t_name_to_map */
4692 	pt_addr_to_ctf,				/* t_addr_to_ctf */
4693 	pt_name_to_ctf,				/* t_name_to_ctf */
4694 	pt_status,				/* t_status */
4695 	pt_run,					/* t_run */
4696 	pt_step,				/* t_step */
4697 	pt_step_out,				/* t_step_out */
4698 	(int (*)()) mdb_tgt_notsup,		/* t_step_branch */
4699 	pt_next,				/* t_next */
4700 	pt_continue,				/* t_cont */
4701 	pt_signal,				/* t_signal */
4702 	pt_add_vbrkpt,				/* t_add_vbrkpt */
4703 	pt_add_sbrkpt,				/* t_add_sbrkpt */
4704 	(int (*)()) mdb_tgt_null,		/* t_add_pwapt */
4705 	pt_add_vwapt,				/* t_add_vwapt */
4706 	(int (*)()) mdb_tgt_null,		/* t_add_iowapt */
4707 	pt_add_sysenter,			/* t_add_sysenter */
4708 	pt_add_sysexit,				/* t_add_sysexit */
4709 	pt_add_signal,				/* t_add_signal */
4710 	pt_add_fault,				/* t_add_fault */
4711 	pt_getareg,				/* t_getareg */
4712 	pt_putareg,				/* t_putareg */
4713 	pt_stack_iter,				/* t_stack_iter */
4714 	pt_auxv					/* t_auxv */
4715 };
4716 
4717 /*
4718  * Utility function for converting libproc errno values to mdb error values
4719  * for the ptl calls below.  Currently, we only need to convert ENOENT to
4720  * EMDB_NOTHREAD to produce a more useful error message for the user.
4721  */
4722 static int
4723 ptl_err(int error)
4724 {
4725 	if (error != 0 && errno == ENOENT)
4726 		return (set_errno(EMDB_NOTHREAD));
4727 
4728 	return (error);
4729 }
4730 
4731 /*ARGSUSED*/
4732 static mdb_tgt_tid_t
4733 pt_lwp_tid(mdb_tgt_t *t, void *tap)
4734 {
4735 	if (t->t_pshandle != NULL)
4736 		return (Pstatus(t->t_pshandle)->pr_lwp.pr_lwpid);
4737 
4738 	return (set_errno(EMDB_NOPROC));
4739 }
4740 
4741 static int
4742 pt_lwp_add(mdb_addrvec_t *ap, const lwpstatus_t *psp)
4743 {
4744 	mdb_addrvec_unshift(ap, psp->pr_lwpid);
4745 	return (0);
4746 }
4747 
4748 /*ARGSUSED*/
4749 static int
4750 pt_lwp_iter(mdb_tgt_t *t, void *tap, mdb_addrvec_t *ap)
4751 {
4752 	if (t->t_pshandle != NULL)
4753 		return (Plwp_iter(t->t_pshandle, (proc_lwp_f *)pt_lwp_add, ap));
4754 
4755 	return (set_errno(EMDB_NOPROC));
4756 }
4757 
4758 /*ARGSUSED*/
4759 static int
4760 pt_lwp_getregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prgregset_t gregs)
4761 {
4762 	if (t->t_pshandle != NULL) {
4763 		return (ptl_err(Plwp_getregs(t->t_pshandle,
4764 		    (lwpid_t)tid, gregs)));
4765 	}
4766 	return (set_errno(EMDB_NOPROC));
4767 }
4768 
4769 /*ARGSUSED*/
4770 static int
4771 pt_lwp_setregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prgregset_t gregs)
4772 {
4773 	if (t->t_pshandle != NULL) {
4774 		return (ptl_err(Plwp_setregs(t->t_pshandle,
4775 		    (lwpid_t)tid, gregs)));
4776 	}
4777 	return (set_errno(EMDB_NOPROC));
4778 }
4779 
4780 #ifdef	__sparc
4781 
4782 /*ARGSUSED*/
4783 static int
4784 pt_lwp_getxregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prxregset_t *xregs)
4785 {
4786 	if (t->t_pshandle != NULL) {
4787 		return (ptl_err(Plwp_getxregs(t->t_pshandle,
4788 		    (lwpid_t)tid, xregs)));
4789 	}
4790 	return (set_errno(EMDB_NOPROC));
4791 }
4792 
4793 /*ARGSUSED*/
4794 static int
4795 pt_lwp_setxregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4796     const prxregset_t *xregs)
4797 {
4798 	if (t->t_pshandle != NULL) {
4799 		return (ptl_err(Plwp_setxregs(t->t_pshandle,
4800 		    (lwpid_t)tid, xregs)));
4801 	}
4802 	return (set_errno(EMDB_NOPROC));
4803 }
4804 
4805 #endif	/* __sparc */
4806 
4807 /*ARGSUSED*/
4808 static int
4809 pt_lwp_getfpregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4810     prfpregset_t *fpregs)
4811 {
4812 	if (t->t_pshandle != NULL) {
4813 		return (ptl_err(Plwp_getfpregs(t->t_pshandle,
4814 		    (lwpid_t)tid, fpregs)));
4815 	}
4816 	return (set_errno(EMDB_NOPROC));
4817 }
4818 
4819 /*ARGSUSED*/
4820 static int
4821 pt_lwp_setfpregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4822     const prfpregset_t *fpregs)
4823 {
4824 	if (t->t_pshandle != NULL) {
4825 		return (ptl_err(Plwp_setfpregs(t->t_pshandle,
4826 		    (lwpid_t)tid, fpregs)));
4827 	}
4828 	return (set_errno(EMDB_NOPROC));
4829 }
4830 
4831 static const pt_ptl_ops_t proc_lwp_ops = {
4832 	(int (*)()) mdb_tgt_nop,
4833 	(void (*)()) mdb_tgt_nop,
4834 	pt_lwp_tid,
4835 	pt_lwp_iter,
4836 	pt_lwp_getregs,
4837 	pt_lwp_setregs,
4838 #ifdef __sparc
4839 	pt_lwp_getxregs,
4840 	pt_lwp_setxregs,
4841 #endif
4842 	pt_lwp_getfpregs,
4843 	pt_lwp_setfpregs
4844 };
4845 
4846 static int
4847 pt_tdb_ctor(mdb_tgt_t *t)
4848 {
4849 	pt_data_t *pt = t->t_data;
4850 	td_thragent_t *tap;
4851 	td_err_e err;
4852 
4853 	if ((err = pt->p_tdb_ops->td_ta_new(t->t_pshandle, &tap)) != TD_OK)
4854 		return (set_errno(tdb_to_errno(err)));
4855 
4856 	pt->p_ptl_hdl = tap;
4857 	return (0);
4858 }
4859 
4860 static void
4861 pt_tdb_dtor(mdb_tgt_t *t, void *tap)
4862 {
4863 	pt_data_t *pt = t->t_data;
4864 
4865 	ASSERT(tap == pt->p_ptl_hdl);
4866 	(void) pt->p_tdb_ops->td_ta_delete(tap);
4867 	pt->p_ptl_hdl = NULL;
4868 }
4869 
4870 static mdb_tgt_tid_t
4871 pt_tdb_tid(mdb_tgt_t *t, void *tap)
4872 {
4873 	pt_data_t *pt = t->t_data;
4874 
4875 	td_thrhandle_t th;
4876 	td_thrinfo_t ti;
4877 	td_err_e err;
4878 
4879 	if (t->t_pshandle == NULL)
4880 		return (set_errno(EMDB_NOPROC));
4881 
4882 	if ((err = pt->p_tdb_ops->td_ta_map_lwp2thr(tap,
4883 	    Pstatus(t->t_pshandle)->pr_lwp.pr_lwpid, &th)) != TD_OK)
4884 		return (set_errno(tdb_to_errno(err)));
4885 
4886 	if ((err = pt->p_tdb_ops->td_thr_get_info(&th, &ti)) != TD_OK)
4887 		return (set_errno(tdb_to_errno(err)));
4888 
4889 	return (ti.ti_tid);
4890 }
4891 
4892 static int
4893 pt_tdb_add(const td_thrhandle_t *thp, pt_addarg_t *pap)
4894 {
4895 	td_thrinfo_t ti;
4896 
4897 	if (pap->pa_pt->p_tdb_ops->td_thr_get_info(thp, &ti) == TD_OK &&
4898 	    ti.ti_state != TD_THR_ZOMBIE)
4899 		mdb_addrvec_unshift(pap->pa_ap, ti.ti_tid);
4900 
4901 	return (0);
4902 }
4903 
4904 static int
4905 pt_tdb_iter(mdb_tgt_t *t, void *tap, mdb_addrvec_t *ap)
4906 {
4907 	pt_data_t *pt = t->t_data;
4908 	pt_addarg_t arg;
4909 	int err;
4910 
4911 	if (t->t_pshandle == NULL)
4912 		return (set_errno(EMDB_NOPROC));
4913 
4914 	arg.pa_pt = pt;
4915 	arg.pa_ap = ap;
4916 
4917 	if ((err = pt->p_tdb_ops->td_ta_thr_iter(tap, (td_thr_iter_f *)
4918 	    pt_tdb_add, &arg, TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
4919 	    TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS)) != TD_OK)
4920 		return (set_errno(tdb_to_errno(err)));
4921 
4922 	return (0);
4923 }
4924 
4925 static int
4926 pt_tdb_getregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prgregset_t gregs)
4927 {
4928 	pt_data_t *pt = t->t_data;
4929 
4930 	td_thrhandle_t th;
4931 	td_err_e err;
4932 
4933 	if (t->t_pshandle == NULL)
4934 		return (set_errno(EMDB_NOPROC));
4935 
4936 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
4937 		return (set_errno(tdb_to_errno(err)));
4938 
4939 	err = pt->p_tdb_ops->td_thr_getgregs(&th, gregs);
4940 	if (err != TD_OK && err != TD_PARTIALREG)
4941 		return (set_errno(tdb_to_errno(err)));
4942 
4943 	return (0);
4944 }
4945 
4946 static int
4947 pt_tdb_setregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prgregset_t gregs)
4948 {
4949 	pt_data_t *pt = t->t_data;
4950 
4951 	td_thrhandle_t th;
4952 	td_err_e err;
4953 
4954 	if (t->t_pshandle == NULL)
4955 		return (set_errno(EMDB_NOPROC));
4956 
4957 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
4958 		return (set_errno(tdb_to_errno(err)));
4959 
4960 	err = pt->p_tdb_ops->td_thr_setgregs(&th, gregs);
4961 	if (err != TD_OK && err != TD_PARTIALREG)
4962 		return (set_errno(tdb_to_errno(err)));
4963 
4964 	return (0);
4965 }
4966 
4967 #ifdef __sparc
4968 
4969 static int
4970 pt_tdb_getxregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prxregset_t *xregs)
4971 {
4972 	pt_data_t *pt = t->t_data;
4973 
4974 	td_thrhandle_t th;
4975 	td_err_e err;
4976 
4977 	if (t->t_pshandle == NULL)
4978 		return (set_errno(EMDB_NOPROC));
4979 
4980 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
4981 		return (set_errno(tdb_to_errno(err)));
4982 
4983 	err = pt->p_tdb_ops->td_thr_getxregs(&th, xregs);
4984 	if (err != TD_OK && err != TD_PARTIALREG)
4985 		return (set_errno(tdb_to_errno(err)));
4986 
4987 	return (0);
4988 }
4989 
4990 static int
4991 pt_tdb_setxregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4992     const prxregset_t *xregs)
4993 {
4994 	pt_data_t *pt = t->t_data;
4995 
4996 	td_thrhandle_t th;
4997 	td_err_e err;
4998 
4999 	if (t->t_pshandle == NULL)
5000 		return (set_errno(EMDB_NOPROC));
5001 
5002 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
5003 		return (set_errno(tdb_to_errno(err)));
5004 
5005 	err = pt->p_tdb_ops->td_thr_setxregs(&th, xregs);
5006 	if (err != TD_OK && err != TD_PARTIALREG)
5007 		return (set_errno(tdb_to_errno(err)));
5008 
5009 	return (0);
5010 }
5011 
5012 #endif	/* __sparc */
5013 
5014 static int
5015 pt_tdb_getfpregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
5016     prfpregset_t *fpregs)
5017 {
5018 	pt_data_t *pt = t->t_data;
5019 
5020 	td_thrhandle_t th;
5021 	td_err_e err;
5022 
5023 	if (t->t_pshandle == NULL)
5024 		return (set_errno(EMDB_NOPROC));
5025 
5026 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
5027 		return (set_errno(tdb_to_errno(err)));
5028 
5029 	err = pt->p_tdb_ops->td_thr_getfpregs(&th, fpregs);
5030 	if (err != TD_OK && err != TD_PARTIALREG)
5031 		return (set_errno(tdb_to_errno(err)));
5032 
5033 	return (0);
5034 }
5035 
5036 static int
5037 pt_tdb_setfpregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
5038     const prfpregset_t *fpregs)
5039 {
5040 	pt_data_t *pt = t->t_data;
5041 
5042 	td_thrhandle_t th;
5043 	td_err_e err;
5044 
5045 	if (t->t_pshandle == NULL)
5046 		return (set_errno(EMDB_NOPROC));
5047 
5048 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
5049 		return (set_errno(tdb_to_errno(err)));
5050 
5051 	err = pt->p_tdb_ops->td_thr_setfpregs(&th, fpregs);
5052 	if (err != TD_OK && err != TD_PARTIALREG)
5053 		return (set_errno(tdb_to_errno(err)));
5054 
5055 	return (0);
5056 }
5057 
5058 static const pt_ptl_ops_t proc_tdb_ops = {
5059 	pt_tdb_ctor,
5060 	pt_tdb_dtor,
5061 	pt_tdb_tid,
5062 	pt_tdb_iter,
5063 	pt_tdb_getregs,
5064 	pt_tdb_setregs,
5065 #ifdef __sparc
5066 	pt_tdb_getxregs,
5067 	pt_tdb_setxregs,
5068 #endif
5069 	pt_tdb_getfpregs,
5070 	pt_tdb_setfpregs
5071 };
5072 
5073 static ssize_t
5074 pt_xd_auxv(mdb_tgt_t *t, void *buf, size_t nbytes)
5075 {
5076 	struct ps_prochandle *P = t->t_pshandle;
5077 	const auxv_t *auxp, *auxv = NULL;
5078 	int auxn = 0;
5079 
5080 	if (P != NULL && (auxv = Pgetauxvec(P)) != NULL &&
5081 	    auxv->a_type != AT_NULL) {
5082 		for (auxp = auxv, auxn = 1; auxp->a_type != NULL; auxp++)
5083 			auxn++;
5084 	}
5085 
5086 	if (buf == NULL && nbytes == 0)
5087 		return (sizeof (auxv_t) * auxn);
5088 
5089 	if (auxn == 0)
5090 		return (set_errno(ENODATA));
5091 
5092 	nbytes = MIN(nbytes, sizeof (auxv_t) * auxn);
5093 	bcopy(auxv, buf, nbytes);
5094 	return (nbytes);
5095 }
5096 
5097 static ssize_t
5098 pt_xd_cred(mdb_tgt_t *t, void *buf, size_t nbytes)
5099 {
5100 	prcred_t cr, *crp;
5101 	size_t cbytes = 0;
5102 
5103 	if (t->t_pshandle != NULL && Pcred(t->t_pshandle, &cr, 1) == 0) {
5104 		cbytes = (cr.pr_ngroups <= 1) ? sizeof (prcred_t) :
5105 		    (sizeof (prcred_t) + (cr.pr_ngroups - 1) * sizeof (gid_t));
5106 	}
5107 
5108 	if (buf == NULL && nbytes == 0)
5109 		return (cbytes);
5110 
5111 	if (cbytes == 0)
5112 		return (set_errno(ENODATA));
5113 
5114 	crp = mdb_alloc(cbytes, UM_SLEEP);
5115 
5116 	if (Pcred(t->t_pshandle, crp, cr.pr_ngroups) == -1)
5117 		return (set_errno(ENODATA));
5118 
5119 	nbytes = MIN(nbytes, cbytes);
5120 	bcopy(crp, buf, nbytes);
5121 	mdb_free(crp, cbytes);
5122 	return (nbytes);
5123 }
5124 
5125 static ssize_t
5126 pt_xd_ehdr(mdb_tgt_t *t, void *buf, size_t nbytes)
5127 {
5128 	pt_data_t *pt = t->t_data;
5129 
5130 	if (buf == NULL && nbytes == 0)
5131 		return (sizeof (GElf_Ehdr));
5132 
5133 	if (pt->p_file == NULL)
5134 		return (set_errno(ENODATA));
5135 
5136 	nbytes = MIN(nbytes, sizeof (GElf_Ehdr));
5137 	bcopy(&pt->p_file->gf_ehdr, buf, nbytes);
5138 	return (nbytes);
5139 }
5140 
5141 static int
5142 pt_copy_lwp(lwpstatus_t **lspp, const lwpstatus_t *lsp)
5143 {
5144 	bcopy(lsp, *lspp, sizeof (lwpstatus_t));
5145 	(*lspp)++;
5146 	return (0);
5147 }
5148 
5149 static ssize_t
5150 pt_xd_lwpstatus(mdb_tgt_t *t, void *buf, size_t nbytes)
5151 {
5152 	lwpstatus_t *lsp, *lbuf;
5153 	const pstatus_t *psp;
5154 	int nlwp = 0;
5155 
5156 	if (t->t_pshandle != NULL && (psp = Pstatus(t->t_pshandle)) != NULL)
5157 		nlwp = psp->pr_nlwp;
5158 
5159 	if (buf == NULL && nbytes == 0)
5160 		return (sizeof (lwpstatus_t) * nlwp);
5161 
5162 	if (nlwp == 0)
5163 		return (set_errno(ENODATA));
5164 
5165 	lsp = lbuf = mdb_alloc(sizeof (lwpstatus_t) * nlwp, UM_SLEEP);
5166 	nbytes = MIN(nbytes, sizeof (lwpstatus_t) * nlwp);
5167 
5168 	(void) Plwp_iter(t->t_pshandle, (proc_lwp_f *)pt_copy_lwp, &lsp);
5169 	bcopy(lbuf, buf, nbytes);
5170 
5171 	mdb_free(lbuf, sizeof (lwpstatus_t) * nlwp);
5172 	return (nbytes);
5173 }
5174 
5175 static ssize_t
5176 pt_xd_pshandle(mdb_tgt_t *t, void *buf, size_t nbytes)
5177 {
5178 	if (buf == NULL && nbytes == 0)
5179 		return (sizeof (struct ps_prochandle *));
5180 
5181 	if (t->t_pshandle == NULL || nbytes != sizeof (struct ps_prochandle *))
5182 		return (set_errno(ENODATA));
5183 
5184 	bcopy(&t->t_pshandle, buf, nbytes);
5185 	return (nbytes);
5186 }
5187 
5188 static ssize_t
5189 pt_xd_psinfo(mdb_tgt_t *t, void *buf, size_t nbytes)
5190 {
5191 	const psinfo_t *psp;
5192 
5193 	if (buf == NULL && nbytes == 0)
5194 		return (sizeof (psinfo_t));
5195 
5196 	if (t->t_pshandle == NULL || (psp = Ppsinfo(t->t_pshandle)) == NULL)
5197 		return (set_errno(ENODATA));
5198 
5199 	nbytes = MIN(nbytes, sizeof (psinfo_t));
5200 	bcopy(psp, buf, nbytes);
5201 	return (nbytes);
5202 }
5203 
5204 static ssize_t
5205 pt_xd_pstatus(mdb_tgt_t *t, void *buf, size_t nbytes)
5206 {
5207 	const pstatus_t *psp;
5208 
5209 	if (buf == NULL && nbytes == 0)
5210 		return (sizeof (pstatus_t));
5211 
5212 	if (t->t_pshandle == NULL || (psp = Pstatus(t->t_pshandle)) == NULL)
5213 		return (set_errno(ENODATA));
5214 
5215 	nbytes = MIN(nbytes, sizeof (pstatus_t));
5216 	bcopy(psp, buf, nbytes);
5217 	return (nbytes);
5218 }
5219 
5220 static ssize_t
5221 pt_xd_utsname(mdb_tgt_t *t, void *buf, size_t nbytes)
5222 {
5223 	struct utsname uts;
5224 
5225 	if (buf == NULL && nbytes == 0)
5226 		return (sizeof (struct utsname));
5227 
5228 	if (t->t_pshandle == NULL || Puname(t->t_pshandle, &uts) != 0)
5229 		return (set_errno(ENODATA));
5230 
5231 	nbytes = MIN(nbytes, sizeof (struct utsname));
5232 	bcopy(&uts, buf, nbytes);
5233 	return (nbytes);
5234 }
5235 
5236 int
5237 mdb_proc_tgt_create(mdb_tgt_t *t, int argc, const char *argv[])
5238 {
5239 	pt_data_t *pt = mdb_zalloc(sizeof (pt_data_t), UM_SLEEP);
5240 
5241 	const char *aout_path = argc > 0 ? argv[0] : PT_EXEC_PATH;
5242 	const char *core_path = argc > 1 ? argv[1] : NULL;
5243 
5244 	const mdb_tgt_regdesc_t *rdp;
5245 	char execname[MAXPATHLEN];
5246 	struct stat64 st;
5247 	int perr;
5248 	int state;
5249 	struct rlimit rlim;
5250 	int i;
5251 
5252 	if (argc > 2) {
5253 		mdb_free(pt, sizeof (pt_data_t));
5254 		return (set_errno(EINVAL));
5255 	}
5256 
5257 	if (t->t_flags & MDB_TGT_F_RDWR)
5258 		pt->p_oflags = O_RDWR;
5259 	else
5260 		pt->p_oflags = O_RDONLY;
5261 
5262 	if (t->t_flags & MDB_TGT_F_FORCE)
5263 		pt->p_gflags |= PGRAB_FORCE;
5264 	if (t->t_flags & MDB_TGT_F_NOSTOP)
5265 		pt->p_gflags |= PGRAB_NOSTOP;
5266 
5267 	pt->p_ptl_ops = &proc_lwp_ops;
5268 	pt->p_maxsig = sysconf(_SC_SIGRT_MAX);
5269 
5270 	(void) mdb_nv_create(&pt->p_regs, UM_SLEEP);
5271 	(void) mdb_nv_create(&pt->p_env, UM_SLEEP);
5272 
5273 	t->t_ops = &proc_ops;
5274 	t->t_data = pt;
5275 
5276 	/*
5277 	 * If no core file name was specified, but the file ./core is present,
5278 	 * infer that we want to debug it.  I find this behavior confusing,
5279 	 * so we only do this when precise adb(1) compatibility is required.
5280 	 */
5281 	if (core_path == NULL && (mdb.m_flags & MDB_FL_ADB) &&
5282 	    access(PT_CORE_PATH, F_OK) == 0)
5283 		core_path = PT_CORE_PATH;
5284 
5285 	/*
5286 	 * For compatibility with adb(1), the special name "-" may be used
5287 	 * to suppress the loading of the executable or core file.
5288 	 */
5289 	if (aout_path != NULL && strcmp(aout_path, "-") == 0)
5290 		aout_path = NULL;
5291 	if (core_path != NULL && strcmp(core_path, "-") == 0)
5292 		core_path = NULL;
5293 
5294 	/*
5295 	 * If a core file or pid was specified, attempt to grab it now using
5296 	 * proc_arg_grab(); otherwise we'll create a fresh process later.
5297 	 */
5298 	if (core_path != NULL && (t->t_pshandle = proc_arg_xgrab(core_path,
5299 	    aout_path == PT_EXEC_PATH ? NULL : aout_path, PR_ARG_ANY,
5300 	    pt->p_gflags, &perr, NULL)) == NULL) {
5301 		mdb_warn("cannot debug %s: %s\n", core_path, Pgrab_error(perr));
5302 		goto err;
5303 	}
5304 
5305 	if (aout_path != NULL &&
5306 	    (pt->p_idlehandle = Pgrab_file(aout_path, &perr)) != NULL &&
5307 	    t->t_pshandle == NULL)
5308 		t->t_pshandle = pt->p_idlehandle;
5309 
5310 	if (t->t_pshandle != NULL)
5311 		state = Pstate(t->t_pshandle);
5312 
5313 	/*
5314 	 * Make sure we'll have enough file descriptors to handle a target
5315 	 * has many many mappings.
5316 	 */
5317 	if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
5318 		rlim.rlim_cur = rlim.rlim_max;
5319 		(void) setrlimit(RLIMIT_NOFILE, &rlim);
5320 		(void) enable_extended_FILE_stdio(-1, -1);
5321 	}
5322 
5323 	/*
5324 	 * If we don't have an executable path or the executable path is the
5325 	 * /proc/<pid>/object/a.out path, but we now have a libproc handle,
5326 	 * attempt to derive the executable path using Pexecname().  We need
5327 	 * to do this in the /proc case in order to open the executable for
5328 	 * writing because /proc/object/<file> permission are masked with 0555.
5329 	 * If Pexecname() fails us, fall back to /proc/<pid>/object/a.out.
5330 	 */
5331 	if (t->t_pshandle != NULL && (aout_path == NULL || (stat64(aout_path,
5332 	    &st) == 0 && strcmp(st.st_fstype, "proc") == 0))) {
5333 		GElf_Sym s;
5334 		aout_path = Pexecname(t->t_pshandle, execname, MAXPATHLEN);
5335 		if (aout_path == NULL && state != PS_DEAD && state != PS_IDLE) {
5336 			(void) mdb_iob_snprintf(execname, sizeof (execname),
5337 			    "/proc/%d/object/a.out",
5338 			    (int)Pstatus(t->t_pshandle)->pr_pid);
5339 			aout_path = execname;
5340 		}
5341 		if (aout_path == NULL &&
5342 		    Plookup_by_name(t->t_pshandle, "a.out", "_start", &s) != 0)
5343 			mdb_warn("warning: failed to infer pathname to "
5344 			    "executable; symbol table will not be available\n");
5345 
5346 		mdb_dprintf(MDB_DBG_TGT, "a.out is %s\n", aout_path);
5347 	}
5348 
5349 	/*
5350 	 * Attempt to open the executable file.  We only want this operation
5351 	 * to actually cause the constructor to abort if the executable file
5352 	 * name was given explicitly.  If we defaulted to PT_EXEC_PATH or
5353 	 * derived the executable using Pexecname, then we want to continue
5354 	 * along with p_fio and p_file set to NULL.
5355 	 */
5356 	if (aout_path != NULL && (pt->p_aout_fio = mdb_fdio_create_path(NULL,
5357 	    aout_path, pt->p_oflags, 0)) == NULL && argc > 0) {
5358 		mdb_warn("failed to open %s", aout_path);
5359 		goto err;
5360 	}
5361 
5362 	/*
5363 	 * Now create an ELF file from the input file, if we have one.  Again,
5364 	 * only abort the constructor if the name was given explicitly.
5365 	 */
5366 	if (pt->p_aout_fio != NULL && pt_open_aout(t,
5367 	    mdb_io_hold(pt->p_aout_fio)) == NULL && argc > 0)
5368 		goto err;
5369 
5370 	/*
5371 	 * If we've successfully opened an ELF file, select the appropriate
5372 	 * disassembler based on the ELF header.
5373 	 */
5374 	if (pt->p_file != NULL)
5375 		(void) mdb_dis_select(pt_disasm(&pt->p_file->gf_ehdr));
5376 	else
5377 		(void) mdb_dis_select(pt_disasm(NULL));
5378 
5379 	/*
5380 	 * Add each register described in the target ISA register description
5381 	 * list to our hash table of register descriptions and then add any
5382 	 * appropriate ISA-specific floating-point register descriptions.
5383 	 */
5384 	for (rdp = pt_regdesc; rdp->rd_name != NULL; rdp++) {
5385 		(void) mdb_nv_insert(&pt->p_regs, rdp->rd_name, NULL,
5386 		    MDB_TGT_R_NVAL(rdp->rd_num, rdp->rd_flags), MDB_NV_RDONLY);
5387 	}
5388 	pt_addfpregs(t);
5389 
5390 	/*
5391 	 * Certain important /proc structures may be of interest to mdb
5392 	 * modules and their dcmds.  Export these using the xdata interface:
5393 	 */
5394 	(void) mdb_tgt_xdata_insert(t, "auxv",
5395 	    "procfs auxv_t array", pt_xd_auxv);
5396 	(void) mdb_tgt_xdata_insert(t, "cred",
5397 	    "procfs prcred_t structure", pt_xd_cred);
5398 	(void) mdb_tgt_xdata_insert(t, "ehdr",
5399 	    "executable file GElf_Ehdr structure", pt_xd_ehdr);
5400 	(void) mdb_tgt_xdata_insert(t, "lwpstatus",
5401 	    "procfs lwpstatus_t array", pt_xd_lwpstatus);
5402 	(void) mdb_tgt_xdata_insert(t, "pshandle",
5403 	    "libproc proc service API handle", pt_xd_pshandle);
5404 	(void) mdb_tgt_xdata_insert(t, "psinfo",
5405 	    "procfs psinfo_t structure", pt_xd_psinfo);
5406 	(void) mdb_tgt_xdata_insert(t, "pstatus",
5407 	    "procfs pstatus_t structure", pt_xd_pstatus);
5408 	(void) mdb_tgt_xdata_insert(t, "utsname",
5409 	    "utsname structure", pt_xd_utsname);
5410 
5411 	/*
5412 	 * Force a status update now so that we fill in t_status with the
5413 	 * latest information based on any successful grab.
5414 	 */
5415 	(void) mdb_tgt_status(t, &t->t_status);
5416 
5417 	/*
5418 	 * If we're not examining a core file, trace SIGINT and all signals
5419 	 * that cause the process to dump core as part of our initialization.
5420 	 */
5421 	if ((t->t_pshandle != NULL && state != PS_DEAD && state != PS_IDLE) ||
5422 	    (pt->p_file != NULL && pt->p_file->gf_ehdr.e_type == ET_EXEC)) {
5423 
5424 		int tflag = MDB_TGT_SPEC_STICKY; /* default sigs are sticky */
5425 
5426 		(void) mdb_tgt_add_signal(t, SIGINT, tflag, no_se_f, NULL);
5427 		(void) mdb_tgt_add_signal(t, SIGQUIT, tflag, no_se_f, NULL);
5428 		(void) mdb_tgt_add_signal(t, SIGILL, tflag, no_se_f, NULL);
5429 		(void) mdb_tgt_add_signal(t, SIGTRAP, tflag, no_se_f, NULL);
5430 		(void) mdb_tgt_add_signal(t, SIGABRT, tflag, no_se_f, NULL);
5431 		(void) mdb_tgt_add_signal(t, SIGEMT, tflag, no_se_f, NULL);
5432 		(void) mdb_tgt_add_signal(t, SIGFPE, tflag, no_se_f, NULL);
5433 		(void) mdb_tgt_add_signal(t, SIGBUS, tflag, no_se_f, NULL);
5434 		(void) mdb_tgt_add_signal(t, SIGSEGV, tflag, no_se_f, NULL);
5435 		(void) mdb_tgt_add_signal(t, SIGSYS, tflag, no_se_f, NULL);
5436 		(void) mdb_tgt_add_signal(t, SIGXCPU, tflag, no_se_f, NULL);
5437 		(void) mdb_tgt_add_signal(t, SIGXFSZ, tflag, no_se_f, NULL);
5438 	}
5439 
5440 	/*
5441 	 * If we've grabbed a live process, establish our initial breakpoints
5442 	 * and librtld_db agent so we can track rtld activity.  If FL_VCREATE
5443 	 * is set, this process was created by a previous instantiation of
5444 	 * the debugger, so reset pr_flags to kill it; otherwise we attached
5445 	 * to an already running process.  Pgrab() has already set the PR_RLC
5446 	 * flag appropriately based on whether the process was stopped when we
5447 	 * attached.
5448 	 */
5449 	if (t->t_pshandle != NULL && state != PS_DEAD && state != PS_IDLE) {
5450 		if (mdb.m_flags & MDB_FL_VCREATE) {
5451 			(void) Punsetflags(t->t_pshandle, PR_RLC);
5452 			(void) Psetflags(t->t_pshandle, PR_KLC);
5453 			pt->p_rflags = PRELEASE_KILL;
5454 		} else {
5455 			(void) Punsetflags(t->t_pshandle, PR_KLC);
5456 		}
5457 		pt_post_attach(t);
5458 	}
5459 
5460 	/*
5461 	 * Initialize a local copy of the environment, which can be modified
5462 	 * before running the program.
5463 	 */
5464 	for (i = 0; mdb.m_env[i] != NULL; i++)
5465 		pt_env_set(pt, mdb.m_env[i]);
5466 
5467 	/*
5468 	 * If adb(1) compatibility mode is on, then print the appropriate
5469 	 * greeting message if we have grabbed a core file.
5470 	 */
5471 	if ((mdb.m_flags & MDB_FL_ADB) && t->t_pshandle != NULL &&
5472 	    state == PS_DEAD) {
5473 		const pstatus_t *psp = Pstatus(t->t_pshandle);
5474 		int cursig = psp->pr_lwp.pr_cursig;
5475 		char signame[SIG2STR_MAX];
5476 
5477 		mdb_printf("core file = %s -- program ``%s'' on platform %s\n",
5478 		    core_path, aout_path ? aout_path : "?", pt_platform(t));
5479 
5480 		if (cursig != 0 && sig2str(cursig, signame) == 0)
5481 			mdb_printf("SIG%s: %s\n", signame, strsignal(cursig));
5482 	}
5483 
5484 	return (0);
5485 
5486 err:
5487 	pt_destroy(t);
5488 	return (-1);
5489 }
5490