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