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