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