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