xref: /titanic_50/usr/src/cmd/mdb/common/mdb/mdb_proc.c (revision b54157c1b1bf9673e4da8b526477d59202cd08a6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #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 void
2063 getenv_help(void)
2064 {
2065 	mdb_printf("-t  show current process environment"
2066 	    " instead of initial environment.\n");
2067 }
2068 
2069 static const mdb_dcmd_t pt_dcmds[] = {
2070 	{ "$c", "?[cnt]", "print stack backtrace", pt_stack },
2071 	{ "$C", "?[cnt]", "print stack backtrace", pt_stackv },
2072 	{ "$i", NULL, "print signals that are ignored", pt_ignored },
2073 	{ "$l", NULL, "print the representative thread's lwp id", pt_lwpid },
2074 	{ "$L", NULL, "print list of the active lwp ids", pt_lwpids },
2075 	{ "$r", "?", "print general-purpose registers", pt_regs },
2076 	{ "$x", "?", "print floating point registers", pt_fpregs },
2077 	{ "$X", "?", "print floating point registers", pt_fpregs },
2078 	{ "$y", "?", "print floating point registers", pt_fpregs },
2079 	{ "$Y", "?", "print floating point registers", pt_fpregs },
2080 	{ "$?", "?", "print status and registers", pt_regstatus },
2081 	{ ":A", "?[core|pid]", "attach to process or core file", pt_attach },
2082 	{ ":i", ":", "ignore signal (delete all matching events)", pt_ignore },
2083 	{ ":k", NULL, "forcibly kill and release target", pt_kill },
2084 	{ ":R", "[-a]", "release the previously attached process", pt_detach },
2085 	{ "attach", "?[core|pid]",
2086 	    "attach to process or core file", pt_attach },
2087 	{ "findstack", ":[-v]", "find user thread stack", pt_findstack },
2088 	{ "gcore", "[-o prefix] [-c content]",
2089 	    "produce a core file for the attached process", pt_gcore },
2090 	{ "getenv", "[-t] [name]", "display an environment variable",
2091 		pt_getenv, getenv_help },
2092 	{ "kill", NULL, "forcibly kill and release target", pt_kill },
2093 	{ "release", "[-a]",
2094 	    "release the previously attached process", pt_detach },
2095 	{ "regs", "?", "print general-purpose registers", pt_regs },
2096 	{ "fpregs", "?[-dqs]", "print floating point registers", pt_fpregs },
2097 	{ "setenv", "name=value", "set an environment variable", pt_setenv },
2098 	{ "stack", "?[cnt]", "print stack backtrace", pt_stack },
2099 	{ "stackregs", "?", "print stack backtrace and registers", pt_stackr },
2100 	{ "status", NULL, "print summary of current target", pt_status_dcmd },
2101 	{ "tls", ":symbol",
2102 	    "lookup TLS data in the context of a given thread", pt_tls },
2103 	{ "tmodel", "{thread|lwp}", NULL, pt_tmodel },
2104 	{ "unsetenv", "[name]", "clear an environment variable", pt_unsetenv },
2105 	{ NULL }
2106 };
2107 
2108 static void
2109 pt_thr_walk_fini(mdb_walk_state_t *wsp)
2110 {
2111 	mdb_addrvec_destroy(wsp->walk_data);
2112 	mdb_free(wsp->walk_data, sizeof (mdb_addrvec_t));
2113 }
2114 
2115 static int
2116 pt_thr_walk_init(mdb_walk_state_t *wsp)
2117 {
2118 	wsp->walk_data = mdb_zalloc(sizeof (mdb_addrvec_t), UM_SLEEP);
2119 	mdb_addrvec_create(wsp->walk_data);
2120 
2121 	if (PTL_ITER(mdb.m_target, wsp->walk_data) == -1) {
2122 		mdb_warn("failed to iterate over threads");
2123 		pt_thr_walk_fini(wsp);
2124 		return (WALK_ERR);
2125 	}
2126 
2127 	return (WALK_NEXT);
2128 }
2129 
2130 static int
2131 pt_thr_walk_step(mdb_walk_state_t *wsp)
2132 {
2133 	if (mdb_addrvec_length(wsp->walk_data) != 0) {
2134 		return (wsp->walk_callback(mdb_addrvec_shift(wsp->walk_data),
2135 		    NULL, wsp->walk_cbdata));
2136 	}
2137 	return (WALK_DONE);
2138 }
2139 
2140 static const mdb_walker_t pt_walkers[] = {
2141 	{ "thread", "walk list of valid thread identifiers",
2142 	    pt_thr_walk_init, pt_thr_walk_step, pt_thr_walk_fini },
2143 	{ NULL }
2144 };
2145 
2146 
2147 static void
2148 pt_activate_common(mdb_tgt_t *t)
2149 {
2150 	pt_data_t *pt = t->t_data;
2151 	GElf_Sym sym;
2152 
2153 	/*
2154 	 * If we have a libproc handle and AT_BASE is set, the process or core
2155 	 * is dynamically linked.  We call Prd_agent() to force libproc to
2156 	 * try to initialize librtld_db, and issue a warning if that fails.
2157 	 */
2158 	if (t->t_pshandle != NULL && Pgetauxval(t->t_pshandle,
2159 	    AT_BASE) != -1L && Prd_agent(t->t_pshandle) == NULL) {
2160 		mdb_warn("warning: librtld_db failed to initialize; shared "
2161 		    "library information will not be available\n");
2162 	}
2163 
2164 	/*
2165 	 * If we have a libproc handle and libthread is loaded, attempt to load
2166 	 * and initialize the corresponding libthread_db.  If this fails, fall
2167 	 * back to our native LWP implementation and issue a warning.
2168 	 */
2169 	if (t->t_pshandle != NULL && Pstate(t->t_pshandle) != PS_IDLE)
2170 		(void) Pobject_iter(t->t_pshandle, (proc_map_f *)thr_check, t);
2171 
2172 	/*
2173 	 * If there's a global object named '_mdb_abort_info', assuming we're
2174 	 * debugging mdb itself and load the developer support module.
2175 	 */
2176 	if (mdb_gelf_symtab_lookup_by_name(pt->p_symtab, "_mdb_abort_info",
2177 	    &sym, NULL) == 0 && GELF_ST_TYPE(sym.st_info) == STT_OBJECT) {
2178 		if (mdb_module_load("mdb_ds", MDB_MOD_SILENT) < 0)
2179 			mdb_warn("warning: failed to load developer support\n");
2180 	}
2181 
2182 	mdb_tgt_elf_export(pt->p_file);
2183 }
2184 
2185 static void
2186 pt_activate(mdb_tgt_t *t)
2187 {
2188 	static const mdb_nv_disc_t reg_disc = { reg_disc_set, reg_disc_get };
2189 
2190 	pt_data_t *pt = t->t_data;
2191 	struct utsname u1, u2;
2192 	mdb_var_t *v;
2193 	core_content_t content;
2194 
2195 	if (t->t_pshandle) {
2196 		mdb_prop_postmortem = (Pstate(t->t_pshandle) == PS_DEAD);
2197 		mdb_prop_kernel = FALSE;
2198 	} else
2199 		mdb_prop_kernel = mdb_prop_postmortem = FALSE;
2200 
2201 	mdb_prop_datamodel = MDB_TGT_MODEL_NATIVE;
2202 
2203 	/*
2204 	 * If we're examining a core file that doesn't contain program text,
2205 	 * and uname(2) doesn't match the NT_UTSNAME note recorded in the
2206 	 * core file, issue a warning.
2207 	 */
2208 	if (mdb_prop_postmortem == TRUE &&
2209 	    ((content = Pcontent(t->t_pshandle)) == CC_CONTENT_INVALID ||
2210 	    !(content & CC_CONTENT_TEXT)) &&
2211 	    uname(&u1) >= 0 && Puname(t->t_pshandle, &u2) == 0 &&
2212 	    (strcmp(u1.release, u2.release) != 0 ||
2213 	    strcmp(u1.version, u2.version) != 0)) {
2214 		mdb_warn("warning: core file is from %s %s %s; shared text "
2215 		    "mappings may not match installed libraries\n",
2216 		    u2.sysname, u2.release, u2.version);
2217 	}
2218 
2219 	/*
2220 	 * Perform the common initialization tasks -- these are shared with
2221 	 * the pt_exec() and pt_run() subroutines.
2222 	 */
2223 	pt_activate_common(t);
2224 
2225 	(void) mdb_tgt_register_dcmds(t, &pt_dcmds[0], MDB_MOD_FORCE);
2226 	(void) mdb_tgt_register_walkers(t, &pt_walkers[0], MDB_MOD_FORCE);
2227 
2228 	/*
2229 	 * Iterate through our register description list and export
2230 	 * each register as a named variable.
2231 	 */
2232 	mdb_nv_rewind(&pt->p_regs);
2233 	while ((v = mdb_nv_advance(&pt->p_regs)) != NULL) {
2234 		ushort_t rd_flags = MDB_TGT_R_FLAGS(mdb_nv_get_value(v));
2235 
2236 		if (!(rd_flags & MDB_TGT_R_EXPORT))
2237 			continue; /* Don't export register as a variable */
2238 
2239 		(void) mdb_nv_insert(&mdb.m_nv, mdb_nv_get_name(v), &reg_disc,
2240 		    (uintptr_t)t, MDB_NV_PERSIST);
2241 	}
2242 }
2243 
2244 static void
2245 pt_deactivate(mdb_tgt_t *t)
2246 {
2247 	pt_data_t *pt = t->t_data;
2248 	const mdb_dcmd_t *dcp;
2249 	const mdb_walker_t *wp;
2250 	mdb_var_t *v, *w;
2251 
2252 	mdb_nv_rewind(&pt->p_regs);
2253 	while ((v = mdb_nv_advance(&pt->p_regs)) != NULL) {
2254 		ushort_t rd_flags = MDB_TGT_R_FLAGS(mdb_nv_get_value(v));
2255 
2256 		if (!(rd_flags & MDB_TGT_R_EXPORT))
2257 			continue; /* Didn't export register as a variable */
2258 
2259 		if (w = mdb_nv_lookup(&mdb.m_nv, mdb_nv_get_name(v))) {
2260 			w->v_flags &= ~MDB_NV_PERSIST;
2261 			mdb_nv_remove(&mdb.m_nv, w);
2262 		}
2263 	}
2264 
2265 	for (wp = &pt_walkers[0]; wp->walk_name != NULL; wp++) {
2266 		if (mdb_module_remove_walker(t->t_module, wp->walk_name) == -1)
2267 			warn("failed to remove walk %s", wp->walk_name);
2268 	}
2269 
2270 	for (dcp = &pt_dcmds[0]; dcp->dc_name != NULL; dcp++) {
2271 		if (mdb_module_remove_dcmd(t->t_module, dcp->dc_name) == -1)
2272 			warn("failed to remove dcmd %s", dcp->dc_name);
2273 	}
2274 
2275 	mdb_prop_postmortem = FALSE;
2276 	mdb_prop_kernel = FALSE;
2277 	mdb_prop_datamodel = MDB_TGT_MODEL_UNKNOWN;
2278 }
2279 
2280 static void
2281 pt_periodic(mdb_tgt_t *t)
2282 {
2283 	pt_data_t *pt = t->t_data;
2284 
2285 	if (pt->p_rdstate == PT_RD_CONSIST) {
2286 		if (t->t_pshandle != NULL && Pstate(t->t_pshandle) < PS_LOST &&
2287 		    !(mdb.m_flags & MDB_FL_NOMODS)) {
2288 			mdb_printf("%s: You've got symbols!\n", mdb.m_pname);
2289 			mdb_module_load_all(0);
2290 		}
2291 		pt->p_rdstate = PT_RD_NONE;
2292 	}
2293 }
2294 
2295 static void
2296 pt_destroy(mdb_tgt_t *t)
2297 {
2298 	pt_data_t *pt = t->t_data;
2299 
2300 	if (pt->p_idlehandle != NULL && pt->p_idlehandle != t->t_pshandle)
2301 		Prelease(pt->p_idlehandle, 0);
2302 
2303 	if (t->t_pshandle != NULL) {
2304 		PTL_DTOR(t);
2305 		pt_release_parents(t);
2306 		pt_pre_detach(t, TRUE);
2307 		Prelease(t->t_pshandle, pt->p_rflags);
2308 	}
2309 
2310 	mdb.m_flags &= ~(MDB_FL_VCREATE | MDB_FL_JOBCTL);
2311 	pt_close_aout(t);
2312 
2313 	if (pt->p_aout_fio != NULL)
2314 		mdb_io_rele(pt->p_aout_fio);
2315 
2316 	pt_env_clear(pt);
2317 	mdb_nv_destroy(&pt->p_env);
2318 
2319 	mdb_nv_destroy(&pt->p_regs);
2320 	mdb_free(pt, sizeof (pt_data_t));
2321 }
2322 
2323 /*ARGSUSED*/
2324 static const char *
2325 pt_name(mdb_tgt_t *t)
2326 {
2327 	return ("proc");
2328 }
2329 
2330 static const char *
2331 pt_platform(mdb_tgt_t *t)
2332 {
2333 	pt_data_t *pt = t->t_data;
2334 
2335 	if (t->t_pshandle != NULL &&
2336 	    Pplatform(t->t_pshandle, pt->p_platform, MAXNAMELEN) != NULL)
2337 		return (pt->p_platform);
2338 
2339 	return (mdb_conf_platform());
2340 }
2341 
2342 static int
2343 pt_uname(mdb_tgt_t *t, struct utsname *utsp)
2344 {
2345 	if (t->t_pshandle != NULL)
2346 		return (Puname(t->t_pshandle, utsp));
2347 
2348 	return (uname(utsp) >= 0 ? 0 : -1);
2349 }
2350 
2351 static int
2352 pt_dmodel(mdb_tgt_t *t)
2353 {
2354 	if (t->t_pshandle == NULL)
2355 		return (MDB_TGT_MODEL_NATIVE);
2356 
2357 	switch (Pstatus(t->t_pshandle)->pr_dmodel) {
2358 	case PR_MODEL_ILP32:
2359 		return (MDB_TGT_MODEL_ILP32);
2360 	case PR_MODEL_LP64:
2361 		return (MDB_TGT_MODEL_LP64);
2362 	}
2363 
2364 	return (MDB_TGT_MODEL_UNKNOWN);
2365 }
2366 
2367 static ssize_t
2368 pt_vread(mdb_tgt_t *t, void *buf, size_t nbytes, uintptr_t addr)
2369 {
2370 	ssize_t n;
2371 
2372 	/*
2373 	 * If no handle is open yet, reads from virtual addresses are
2374 	 * allowed to succeed but return zero-filled memory.
2375 	 */
2376 	if (t->t_pshandle == NULL) {
2377 		bzero(buf, nbytes);
2378 		return (nbytes);
2379 	}
2380 
2381 	if ((n = Pread(t->t_pshandle, buf, nbytes, addr)) <= 0)
2382 		return (set_errno(EMDB_NOMAP));
2383 
2384 	return (n);
2385 }
2386 
2387 static ssize_t
2388 pt_vwrite(mdb_tgt_t *t, const void *buf, size_t nbytes, uintptr_t addr)
2389 {
2390 	ssize_t n;
2391 
2392 	/*
2393 	 * If no handle is open yet, writes to virtual addresses are
2394 	 * allowed to succeed but do not actually modify anything.
2395 	 */
2396 	if (t->t_pshandle == NULL)
2397 		return (nbytes);
2398 
2399 	n = Pwrite(t->t_pshandle, buf, nbytes, addr);
2400 
2401 	if (n == -1 && errno == EIO)
2402 		return (set_errno(EMDB_NOMAP));
2403 
2404 	return (n);
2405 }
2406 
2407 static ssize_t
2408 pt_fread(mdb_tgt_t *t, void *buf, size_t nbytes, uintptr_t addr)
2409 {
2410 	pt_data_t *pt = t->t_data;
2411 
2412 	if (pt->p_file != NULL) {
2413 		return (mdb_gelf_rw(pt->p_file, buf, nbytes, addr,
2414 		    IOPF_READ(pt->p_fio), GIO_READ));
2415 	}
2416 
2417 	bzero(buf, nbytes);
2418 	return (nbytes);
2419 }
2420 
2421 static ssize_t
2422 pt_fwrite(mdb_tgt_t *t, const void *buf, size_t nbytes, uintptr_t addr)
2423 {
2424 	pt_data_t *pt = t->t_data;
2425 
2426 	if (pt->p_file != NULL) {
2427 		return (mdb_gelf_rw(pt->p_file, (void *)buf, nbytes, addr,
2428 		    IOPF_WRITE(pt->p_fio), GIO_WRITE));
2429 	}
2430 
2431 	return (nbytes);
2432 }
2433 
2434 static const char *
2435 pt_resolve_lmid(const char *object, Lmid_t *lmidp)
2436 {
2437 	Lmid_t lmid = PR_LMID_EVERY;
2438 	const char *p;
2439 
2440 	if (object == MDB_TGT_OBJ_EVERY || object == MDB_TGT_OBJ_EXEC)
2441 		lmid = LM_ID_BASE; /* restrict scope to a.out's link map */
2442 	else if (object != MDB_TGT_OBJ_RTLD && strncmp(object, "LM", 2) == 0 &&
2443 	    (p = strchr(object, '`')) != NULL) {
2444 		object += 2;	/* skip past initial "LM" prefix */
2445 		lmid = strntoul(object, (size_t)(p - object), mdb.m_radix);
2446 		object = p + 1;	/* skip past link map specifier */
2447 	}
2448 
2449 	*lmidp = lmid;
2450 	return (object);
2451 }
2452 
2453 static int
2454 tlsbase(mdb_tgt_t *t, mdb_tgt_tid_t tid, Lmid_t lmid, const char *object,
2455     psaddr_t *basep)
2456 {
2457 	pt_data_t *pt = t->t_data;
2458 	const rd_loadobj_t *loadobjp;
2459 	td_thrhandle_t th;
2460 	td_err_e err;
2461 
2462 	if (object == MDB_TGT_OBJ_EVERY)
2463 		return (set_errno(EINVAL));
2464 
2465 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) == PS_IDLE)
2466 		return (set_errno(EMDB_NOPROC));
2467 
2468 	if (pt->p_tdb_ops == NULL)
2469 		return (set_errno(EMDB_TDB));
2470 
2471 	err = pt->p_tdb_ops->td_ta_map_id2thr(pt->p_ptl_hdl, tid, &th);
2472 	if (err != TD_OK)
2473 		return (set_errno(tdb_to_errno(err)));
2474 
2475 	/*
2476 	 * If this fails, rtld_db has failed to initialize properly.
2477 	 */
2478 	if ((loadobjp = Plmid_to_loadobj(t->t_pshandle, lmid, object)) == NULL)
2479 		return (set_errno(EMDB_NORTLD));
2480 
2481 	/*
2482 	 * This will fail if the TLS block has not been allocated for the
2483 	 * object that contains the TLS symbol in question.
2484 	 */
2485 	err = pt->p_tdb_ops->td_thr_tlsbase(&th, loadobjp->rl_tlsmodid, basep);
2486 	if (err != TD_OK)
2487 		return (set_errno(tdb_to_errno(err)));
2488 
2489 	return (0);
2490 }
2491 
2492 typedef struct {
2493 	mdb_tgt_t	*pl_tgt;
2494 	const char	*pl_name;
2495 	Lmid_t		pl_lmid;
2496 	GElf_Sym	*pl_symp;
2497 	mdb_syminfo_t	*pl_sip;
2498 	mdb_tgt_tid_t	pl_tid;
2499 	mdb_bool_t	pl_found;
2500 } pt_lookup_t;
2501 
2502 /*ARGSUSED*/
2503 static int
2504 pt_lookup_cb(void *data, const prmap_t *pmp, const char *object)
2505 {
2506 	pt_lookup_t *plp = data;
2507 	struct ps_prochandle *P = plp->pl_tgt->t_pshandle;
2508 	prsyminfo_t si;
2509 	GElf_Sym sym;
2510 
2511 	if (Pxlookup_by_name(P, plp->pl_lmid, object, plp->pl_name, &sym,
2512 	    &si) != 0)
2513 		return (0);
2514 
2515 	/*
2516 	 * If we encounter a match with SHN_UNDEF, keep looking for a
2517 	 * better match. Return the first match with SHN_UNDEF set if no
2518 	 * better match is found.
2519 	 */
2520 	if (sym.st_shndx == SHN_UNDEF) {
2521 		if (!plp->pl_found) {
2522 			plp->pl_found = TRUE;
2523 			*plp->pl_symp = sym;
2524 			plp->pl_sip->sym_table = si.prs_table;
2525 			plp->pl_sip->sym_id = si.prs_id;
2526 		}
2527 
2528 		return (0);
2529 	}
2530 
2531 	/*
2532 	 * Note that if the symbol's st_shndx is SHN_UNDEF we don't have the
2533 	 * TLS offset anyway, so adding in the tlsbase would be worthless.
2534 	 */
2535 	if (GELF_ST_TYPE(sym.st_info) == STT_TLS &&
2536 	    plp->pl_tid != (mdb_tgt_tid_t)-1) {
2537 		psaddr_t base;
2538 
2539 		if (tlsbase(plp->pl_tgt, plp->pl_tid, plp->pl_lmid, object,
2540 		    &base) != 0)
2541 			return (-1); /* errno is set for us */
2542 
2543 		sym.st_value += base;
2544 	}
2545 
2546 	plp->pl_found = TRUE;
2547 	*plp->pl_symp = sym;
2548 	plp->pl_sip->sym_table = si.prs_table;
2549 	plp->pl_sip->sym_id = si.prs_id;
2550 
2551 	return (1);
2552 }
2553 
2554 /*
2555  * Lookup the symbol with a thread context so that we can adjust TLS symbols
2556  * to get the values as they would appear in the context of the given thread.
2557  */
2558 static int
2559 pt_lookup_by_name_thr(mdb_tgt_t *t, const char *object,
2560     const char *name, GElf_Sym *symp, mdb_syminfo_t *sip, mdb_tgt_tid_t tid)
2561 {
2562 	struct ps_prochandle *P = t->t_pshandle;
2563 	pt_data_t *pt = t->t_data;
2564 	Lmid_t lmid;
2565 	uint_t i;
2566 	const rd_loadobj_t *aout_lop;
2567 
2568 	object = pt_resolve_lmid(object, &lmid);
2569 
2570 	if (P != NULL) {
2571 		pt_lookup_t pl;
2572 
2573 		pl.pl_tgt = t;
2574 		pl.pl_name = name;
2575 		pl.pl_lmid = lmid;
2576 		pl.pl_symp = symp;
2577 		pl.pl_sip = sip;
2578 		pl.pl_tid = tid;
2579 		pl.pl_found = FALSE;
2580 
2581 		if (object == MDB_TGT_OBJ_EVERY) {
2582 			if (Pobject_iter(P, pt_lookup_cb, &pl) == -1)
2583 				return (-1); /* errno is set for us */
2584 		} else {
2585 			const prmap_t *pmp;
2586 
2587 			/*
2588 			 * This can fail either due to an invalid lmid or
2589 			 * an invalid object. To determine which is
2590 			 * faulty, we test the lmid against known valid
2591 			 * lmids and then see if using a wild-card lmid
2592 			 * improves ths situation.
2593 			 */
2594 			if ((pmp = Plmid_to_map(P, lmid, object)) == NULL) {
2595 				if (lmid != PR_LMID_EVERY &&
2596 				    lmid != LM_ID_BASE &&
2597 				    lmid != LM_ID_LDSO &&
2598 				    Plmid_to_map(P, PR_LMID_EVERY, object)
2599 				    != NULL)
2600 					return (set_errno(EMDB_NOLMID));
2601 				else
2602 					return (set_errno(EMDB_NOOBJ));
2603 			}
2604 
2605 			if (pt_lookup_cb(&pl, pmp, object) == -1)
2606 				return (-1); /* errno is set for us */
2607 		}
2608 
2609 		if (pl.pl_found)
2610 			return (0);
2611 	}
2612 
2613 	/*
2614 	 * If libproc doesn't have the symbols for rtld, we're cooked --
2615 	 * mdb doesn't have those symbols either.
2616 	 */
2617 	if (object == MDB_TGT_OBJ_RTLD)
2618 		return (set_errno(EMDB_NOSYM));
2619 
2620 	if (object != MDB_TGT_OBJ_EXEC && object != MDB_TGT_OBJ_EVERY) {
2621 		int status = mdb_gelf_symtab_lookup_by_file(pt->p_symtab,
2622 		    object, name, symp, &sip->sym_id);
2623 
2624 		if (status != 0) {
2625 			if (P != NULL &&
2626 			    Plmid_to_map(P, PR_LMID_EVERY, object) != NULL)
2627 				return (set_errno(EMDB_NOSYM));
2628 			else
2629 				return (-1); /* errno set from lookup_by_file */
2630 		}
2631 
2632 		goto found;
2633 	}
2634 
2635 	if (mdb_gelf_symtab_lookup_by_name(pt->p_symtab, name, symp, &i) == 0) {
2636 		sip->sym_table = MDB_TGT_SYMTAB;
2637 		sip->sym_id = i;
2638 		goto local_found;
2639 	}
2640 
2641 	if (mdb_gelf_symtab_lookup_by_name(pt->p_dynsym, name, symp, &i) == 0) {
2642 		sip->sym_table = MDB_TGT_DYNSYM;
2643 		sip->sym_id = i;
2644 		goto local_found;
2645 	}
2646 
2647 	return (set_errno(EMDB_NOSYM));
2648 
2649 local_found:
2650 	if (pt->p_file != NULL &&
2651 	    pt->p_file->gf_ehdr.e_type == ET_DYN &&
2652 	    P != NULL &&
2653 	    (aout_lop = Pname_to_loadobj(P, PR_OBJ_EXEC)) != NULL)
2654 		symp->st_value += aout_lop->rl_base;
2655 
2656 found:
2657 	/*
2658 	 * If the symbol has type TLS, libproc should have found the symbol
2659 	 * if it exists and has been allocated.
2660 	 */
2661 	if (GELF_ST_TYPE(symp->st_info) == STT_TLS)
2662 		return (set_errno(EMDB_TLS));
2663 
2664 	return (0);
2665 }
2666 
2667 static int
2668 pt_lookup_by_name(mdb_tgt_t *t, const char *object,
2669     const char *name, GElf_Sym *symp, mdb_syminfo_t *sip)
2670 {
2671 	return (pt_lookup_by_name_thr(t, object, name, symp, sip, PTL_TID(t)));
2672 }
2673 
2674 static int
2675 pt_lookup_by_addr(mdb_tgt_t *t, uintptr_t addr, uint_t flags,
2676     char *buf, size_t nbytes, GElf_Sym *symp, mdb_syminfo_t *sip)
2677 {
2678 	struct ps_prochandle *P = t->t_pshandle;
2679 	pt_data_t *pt = t->t_data;
2680 
2681 	rd_plt_info_t rpi = { 0 };
2682 	const char *pltsym;
2683 	int match, i;
2684 
2685 	mdb_gelf_symtab_t *gsts[3];	/* mdb.m_prsym, .symtab, .dynsym */
2686 	int gstc = 0;			/* number of valid gsts[] entries */
2687 
2688 	mdb_gelf_symtab_t *gst = NULL;	/* set if 'sym' is from a gst */
2689 	const prmap_t *pmp = NULL;	/* set if 'sym' is from libproc */
2690 	GElf_Sym sym;			/* best symbol found so far if !exact */
2691 	prsyminfo_t si;
2692 
2693 	/*
2694 	 * Fill in our array of symbol table pointers with the private symbol
2695 	 * table, static symbol table, and dynamic symbol table if applicable.
2696 	 * These are done in order of precedence so that if we match and
2697 	 * MDB_TGT_SYM_EXACT is set, we need not look any further.
2698 	 */
2699 	if (mdb.m_prsym != NULL)
2700 		gsts[gstc++] = mdb.m_prsym;
2701 	if (P == NULL && pt->p_symtab != NULL)
2702 		gsts[gstc++] = pt->p_symtab;
2703 	if (P == NULL && pt->p_dynsym != NULL)
2704 		gsts[gstc++] = pt->p_dynsym;
2705 
2706 	/*
2707 	 * Loop through our array attempting to match the address.  If we match
2708 	 * and we're in exact mode, we're done.  Otherwise save the symbol in
2709 	 * the local sym variable if it is closer than our previous match.
2710 	 * We explicitly watch for zero-valued symbols since DevPro insists
2711 	 * on storing __fsr_init_value's value as the symbol value instead
2712 	 * of storing it in a constant integer.
2713 	 */
2714 	for (i = 0; i < gstc; i++) {
2715 		if (mdb_gelf_symtab_lookup_by_addr(gsts[i], addr, flags, buf,
2716 		    nbytes, symp, &sip->sym_id) != 0 || symp->st_value == 0)
2717 			continue;
2718 
2719 		if (flags & MDB_TGT_SYM_EXACT) {
2720 			gst = gsts[i];
2721 			goto found;
2722 		}
2723 
2724 		if (gst == NULL || mdb_gelf_sym_closer(symp, &sym, addr)) {
2725 			gst = gsts[i];
2726 			sym = *symp;
2727 		}
2728 	}
2729 
2730 	/*
2731 	 * If we have no libproc handle active, we're done: fail if gst is
2732 	 * NULL; otherwise copy out our best symbol and skip to the end.
2733 	 * We also skip to found if gst is the private symbol table: we
2734 	 * want this to always take precedence over PLT re-vectoring.
2735 	 */
2736 	if (P == NULL || (gst != NULL && gst == mdb.m_prsym)) {
2737 		if (gst == NULL)
2738 			return (set_errno(EMDB_NOSYMADDR));
2739 		*symp = sym;
2740 		goto found;
2741 	}
2742 
2743 	/*
2744 	 * Check to see if the address is in a PLT: if it is, use librtld_db to
2745 	 * attempt to resolve the PLT entry.  If the entry is bound, reset addr
2746 	 * to the bound address, add a special prefix to the caller's buf,
2747 	 * forget our previous guess, and then continue using the new addr.
2748 	 * If the entry is not bound, copy the corresponding symbol name into
2749 	 * buf and return a fake symbol for the given address.
2750 	 */
2751 	if ((pltsym = Ppltdest(P, addr)) != NULL) {
2752 		const rd_loadobj_t *rlp;
2753 		rd_agent_t *rap;
2754 
2755 		if ((rap = Prd_agent(P)) != NULL &&
2756 		    (rlp = Paddr_to_loadobj(P, addr)) != NULL &&
2757 		    rd_plt_resolution(rap, addr, Pstatus(P)->pr_lwp.pr_lwpid,
2758 		    rlp->rl_plt_base, &rpi) == RD_OK &&
2759 		    (rpi.pi_flags & RD_FLG_PI_PLTBOUND)) {
2760 			size_t n;
2761 			n = mdb_iob_snprintf(buf, nbytes, "PLT=");
2762 			addr = rpi.pi_baddr;
2763 			if (n > nbytes) {
2764 				buf += nbytes;
2765 				nbytes = 0;
2766 			} else {
2767 				buf += n;
2768 				nbytes -= n;
2769 			}
2770 			gst = NULL;
2771 		} else {
2772 			(void) mdb_iob_snprintf(buf, nbytes, "PLT:%s", pltsym);
2773 			bzero(symp, sizeof (GElf_Sym));
2774 			symp->st_value = addr;
2775 			symp->st_info = GELF_ST_INFO(STB_GLOBAL, STT_FUNC);
2776 			return (0);
2777 		}
2778 	}
2779 
2780 	/*
2781 	 * Ask libproc to convert the address to the closest symbol for us.
2782 	 * Once we get the closest symbol, we perform the EXACT match or
2783 	 * smart-mode or absolute distance check ourself:
2784 	 */
2785 	if (Pxlookup_by_addr(P, addr, buf, nbytes, symp, &si) == 0 &&
2786 	    symp->st_value != 0 && (gst == NULL ||
2787 	    mdb_gelf_sym_closer(symp, &sym, addr))) {
2788 
2789 		if (flags & MDB_TGT_SYM_EXACT)
2790 			match = (addr == symp->st_value);
2791 		else if (mdb.m_symdist == 0)
2792 			match = (addr >= symp->st_value &&
2793 			    addr < symp->st_value + symp->st_size);
2794 		else
2795 			match = (addr >= symp->st_value &&
2796 			    addr < symp->st_value + mdb.m_symdist);
2797 
2798 		if (match) {
2799 			pmp = Paddr_to_map(P, addr);
2800 			gst = NULL;
2801 			sip->sym_table = si.prs_table;
2802 			sip->sym_id = si.prs_id;
2803 			goto found;
2804 		}
2805 	}
2806 
2807 	/*
2808 	 * If we get here, Plookup_by_addr has failed us.  If we have no
2809 	 * previous best symbol (gst == NULL), we've failed completely.
2810 	 * Otherwise we copy out that symbol and continue on to 'found'.
2811 	 */
2812 	if (gst == NULL)
2813 		return (set_errno(EMDB_NOSYMADDR));
2814 	*symp = sym;
2815 found:
2816 	/*
2817 	 * Once we've found something, copy the final name into the caller's
2818 	 * buffer and prefix it with the mapping name if appropriate.
2819 	 */
2820 	if (pmp != NULL && pmp != Pname_to_map(P, PR_OBJ_EXEC)) {
2821 		const char *prefix = pmp->pr_mapname;
2822 		Lmid_t lmid;
2823 
2824 		if (Pobjname(P, addr, pt->p_objname, MDB_TGT_MAPSZ))
2825 			prefix = pt->p_objname;
2826 
2827 		if (buf != NULL && nbytes > 1) {
2828 			(void) strncpy(pt->p_symname, buf, MDB_TGT_SYM_NAMLEN);
2829 			pt->p_symname[MDB_TGT_SYM_NAMLEN - 1] = '\0';
2830 		} else {
2831 			pt->p_symname[0] = '\0';
2832 		}
2833 
2834 		if (prefix == pt->p_objname && Plmid(P, addr, &lmid) == 0 && (
2835 		    (lmid != LM_ID_BASE && lmid != LM_ID_LDSO) ||
2836 		    (mdb.m_flags & MDB_FL_SHOWLMID))) {
2837 			(void) mdb_iob_snprintf(buf, nbytes, "LM%lr`%s`%s",
2838 			    lmid, strbasename(prefix), pt->p_symname);
2839 		} else {
2840 			(void) mdb_iob_snprintf(buf, nbytes, "%s`%s",
2841 			    strbasename(prefix), pt->p_symname);
2842 		}
2843 
2844 	} else if (gst != NULL && buf != NULL && nbytes > 0) {
2845 		(void) strncpy(buf, mdb_gelf_sym_name(gst, symp), nbytes);
2846 		buf[nbytes - 1] = '\0';
2847 	}
2848 
2849 	return (0);
2850 }
2851 
2852 
2853 static int
2854 pt_symbol_iter_cb(void *arg, const GElf_Sym *sym, const char *name,
2855     const prsyminfo_t *sip)
2856 {
2857 	pt_symarg_t *psp = arg;
2858 
2859 	psp->psym_info.sym_id = sip->prs_id;
2860 
2861 	return (psp->psym_func(psp->psym_private, sym, name, &psp->psym_info,
2862 	    psp->psym_obj));
2863 }
2864 
2865 static int
2866 pt_objsym_iter(void *arg, const prmap_t *pmp, const char *object)
2867 {
2868 	Lmid_t lmid = PR_LMID_EVERY;
2869 	pt_symarg_t *psp = arg;
2870 
2871 	psp->psym_obj = object;
2872 
2873 	(void) Plmid(psp->psym_targ->t_pshandle, pmp->pr_vaddr, &lmid);
2874 	(void) Pxsymbol_iter(psp->psym_targ->t_pshandle, lmid, object,
2875 	    psp->psym_which, psp->psym_type, pt_symbol_iter_cb, arg);
2876 
2877 	return (0);
2878 }
2879 
2880 static int
2881 pt_symbol_filt(void *arg, const GElf_Sym *sym, const char *name, uint_t id)
2882 {
2883 	pt_symarg_t *psp = arg;
2884 
2885 	if (mdb_tgt_sym_match(sym, psp->psym_type)) {
2886 		psp->psym_info.sym_id = id;
2887 		return (psp->psym_func(psp->psym_private, sym, name,
2888 		    &psp->psym_info, psp->psym_obj));
2889 	}
2890 
2891 	return (0);
2892 }
2893 
2894 static int
2895 pt_symbol_iter(mdb_tgt_t *t, const char *object, uint_t which,
2896     uint_t type, mdb_tgt_sym_f *func, void *private)
2897 {
2898 	pt_data_t *pt = t->t_data;
2899 	mdb_gelf_symtab_t *gst;
2900 	pt_symarg_t ps;
2901 	Lmid_t lmid;
2902 
2903 	object = pt_resolve_lmid(object, &lmid);
2904 
2905 	ps.psym_targ = t;
2906 	ps.psym_which = which;
2907 	ps.psym_type = type;
2908 	ps.psym_func = func;
2909 	ps.psym_private = private;
2910 	ps.psym_obj = object;
2911 
2912 	if (t->t_pshandle != NULL) {
2913 		if (object != MDB_TGT_OBJ_EVERY) {
2914 			if (Plmid_to_map(t->t_pshandle, lmid, object) == NULL)
2915 				return (set_errno(EMDB_NOOBJ));
2916 			(void) Pxsymbol_iter(t->t_pshandle, lmid, object,
2917 			    which, type, pt_symbol_iter_cb, &ps);
2918 			return (0);
2919 		} else if (Prd_agent(t->t_pshandle) != NULL) {
2920 			(void) Pobject_iter(t->t_pshandle, pt_objsym_iter, &ps);
2921 			return (0);
2922 		}
2923 	}
2924 
2925 	if (lmid != LM_ID_BASE && lmid != PR_LMID_EVERY)
2926 		return (set_errno(EMDB_NOLMID));
2927 
2928 	if (object != MDB_TGT_OBJ_EXEC && object != MDB_TGT_OBJ_EVERY &&
2929 	    pt->p_fio != NULL &&
2930 	    strcmp(object, IOP_NAME(pt->p_fio)) != 0)
2931 		return (set_errno(EMDB_NOOBJ));
2932 
2933 	if (which == MDB_TGT_SYMTAB)
2934 		gst = pt->p_symtab;
2935 	else
2936 		gst = pt->p_dynsym;
2937 
2938 	if (gst != NULL) {
2939 		ps.psym_info.sym_table = gst->gst_tabid;
2940 		mdb_gelf_symtab_iter(gst, pt_symbol_filt, &ps);
2941 	}
2942 
2943 	return (0);
2944 }
2945 
2946 static const mdb_map_t *
2947 pt_prmap_to_mdbmap(mdb_tgt_t *t, const prmap_t *prp, mdb_map_t *mp)
2948 {
2949 	struct ps_prochandle *P = t->t_pshandle;
2950 	char name[MAXPATHLEN];
2951 	Lmid_t lmid;
2952 
2953 	if (Pobjname(P, prp->pr_vaddr, name, sizeof (name)) != NULL) {
2954 		if (Plmid(P, prp->pr_vaddr, &lmid) == 0 && (
2955 		    (lmid != LM_ID_BASE && lmid != LM_ID_LDSO) ||
2956 		    (mdb.m_flags & MDB_FL_SHOWLMID))) {
2957 			(void) mdb_iob_snprintf(mp->map_name, MDB_TGT_MAPSZ,
2958 			    "LM%lr`%s", lmid, name);
2959 		} else {
2960 			(void) strncpy(mp->map_name, name, MDB_TGT_MAPSZ - 1);
2961 			mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
2962 		}
2963 	} else {
2964 		(void) strncpy(mp->map_name, prp->pr_mapname,
2965 		    MDB_TGT_MAPSZ - 1);
2966 		mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
2967 	}
2968 
2969 	mp->map_base = prp->pr_vaddr;
2970 	mp->map_size = prp->pr_size;
2971 	mp->map_flags = 0;
2972 
2973 	if (prp->pr_mflags & MA_READ)
2974 		mp->map_flags |= MDB_TGT_MAP_R;
2975 	if (prp->pr_mflags & MA_WRITE)
2976 		mp->map_flags |= MDB_TGT_MAP_W;
2977 	if (prp->pr_mflags & MA_EXEC)
2978 		mp->map_flags |= MDB_TGT_MAP_X;
2979 
2980 	if (prp->pr_mflags & MA_SHM)
2981 		mp->map_flags |= MDB_TGT_MAP_SHMEM;
2982 	if (prp->pr_mflags & MA_BREAK)
2983 		mp->map_flags |= MDB_TGT_MAP_HEAP;
2984 	if (prp->pr_mflags & MA_STACK)
2985 		mp->map_flags |= MDB_TGT_MAP_STACK;
2986 	if (prp->pr_mflags & MA_ANON)
2987 		mp->map_flags |= MDB_TGT_MAP_ANON;
2988 
2989 	return (mp);
2990 }
2991 
2992 /*ARGSUSED*/
2993 static int
2994 pt_map_apply(void *arg, const prmap_t *prp, const char *name)
2995 {
2996 	pt_maparg_t *pmp = arg;
2997 	mdb_map_t map;
2998 
2999 	return (pmp->pmap_func(pmp->pmap_private,
3000 	    pt_prmap_to_mdbmap(pmp->pmap_targ, prp, &map), map.map_name));
3001 }
3002 
3003 static int
3004 pt_mapping_iter(mdb_tgt_t *t, mdb_tgt_map_f *func, void *private)
3005 {
3006 	if (t->t_pshandle != NULL) {
3007 		pt_maparg_t pm;
3008 
3009 		pm.pmap_targ = t;
3010 		pm.pmap_func = func;
3011 		pm.pmap_private = private;
3012 
3013 		(void) Pmapping_iter(t->t_pshandle, pt_map_apply, &pm);
3014 		return (0);
3015 	}
3016 
3017 	return (set_errno(EMDB_NOPROC));
3018 }
3019 
3020 static int
3021 pt_object_iter(mdb_tgt_t *t, mdb_tgt_map_f *func, void *private)
3022 {
3023 	pt_data_t *pt = t->t_data;
3024 
3025 	/*
3026 	 * If we have a libproc handle, we can just call Pobject_iter to
3027 	 * iterate over its list of load object information.
3028 	 */
3029 	if (t->t_pshandle != NULL) {
3030 		pt_maparg_t pm;
3031 
3032 		pm.pmap_targ = t;
3033 		pm.pmap_func = func;
3034 		pm.pmap_private = private;
3035 
3036 		(void) Pobject_iter(t->t_pshandle, pt_map_apply, &pm);
3037 		return (0);
3038 	}
3039 
3040 	/*
3041 	 * If we're examining an executable or other ELF file but we have no
3042 	 * libproc handle, fake up some information based on DT_NEEDED entries.
3043 	 */
3044 	if (pt->p_dynsym != NULL && pt->p_file->gf_dyns != NULL &&
3045 	    pt->p_fio != NULL) {
3046 		mdb_gelf_sect_t *gsp = pt->p_dynsym->gst_ssect;
3047 		GElf_Dyn *dynp = pt->p_file->gf_dyns;
3048 		mdb_map_t *mp = &pt->p_map;
3049 		const char *s = IOP_NAME(pt->p_fio);
3050 		size_t i;
3051 
3052 		(void) strncpy(mp->map_name, s, MDB_TGT_MAPSZ);
3053 		mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
3054 		mp->map_flags = MDB_TGT_MAP_R | MDB_TGT_MAP_X;
3055 		mp->map_base = NULL;
3056 		mp->map_size = 0;
3057 
3058 		if (func(private, mp, s) != 0)
3059 			return (0);
3060 
3061 		for (i = 0; i < pt->p_file->gf_ndyns; i++, dynp++) {
3062 			if (dynp->d_tag == DT_NEEDED) {
3063 				s = (char *)gsp->gs_data + dynp->d_un.d_val;
3064 				(void) strncpy(mp->map_name, s, MDB_TGT_MAPSZ);
3065 				mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
3066 				if (func(private, mp, s) != 0)
3067 					return (0);
3068 			}
3069 		}
3070 
3071 		return (0);
3072 	}
3073 
3074 	return (set_errno(EMDB_NOPROC));
3075 }
3076 
3077 static const mdb_map_t *
3078 pt_addr_to_map(mdb_tgt_t *t, uintptr_t addr)
3079 {
3080 	pt_data_t *pt = t->t_data;
3081 	const prmap_t *pmp;
3082 
3083 	if (t->t_pshandle == NULL) {
3084 		(void) set_errno(EMDB_NOPROC);
3085 		return (NULL);
3086 	}
3087 
3088 	if ((pmp = Paddr_to_map(t->t_pshandle, addr)) == NULL) {
3089 		(void) set_errno(EMDB_NOMAP);
3090 		return (NULL);
3091 	}
3092 
3093 	return (pt_prmap_to_mdbmap(t, pmp, &pt->p_map));
3094 }
3095 
3096 static const mdb_map_t *
3097 pt_name_to_map(mdb_tgt_t *t, const char *object)
3098 {
3099 	pt_data_t *pt = t->t_data;
3100 	const prmap_t *pmp;
3101 	Lmid_t lmid;
3102 
3103 	if (t->t_pshandle == NULL) {
3104 		(void) set_errno(EMDB_NOPROC);
3105 		return (NULL);
3106 	}
3107 
3108 	object = pt_resolve_lmid(object, &lmid);
3109 
3110 	if ((pmp = Plmid_to_map(t->t_pshandle, lmid, object)) == NULL) {
3111 		(void) set_errno(EMDB_NOOBJ);
3112 		return (NULL);
3113 	}
3114 
3115 	return (pt_prmap_to_mdbmap(t, pmp, &pt->p_map));
3116 }
3117 
3118 static ctf_file_t *
3119 pt_addr_to_ctf(mdb_tgt_t *t, uintptr_t addr)
3120 {
3121 	ctf_file_t *ret;
3122 
3123 	if (t->t_pshandle == NULL) {
3124 		(void) set_errno(EMDB_NOPROC);
3125 		return (NULL);
3126 	}
3127 
3128 	if ((ret = Paddr_to_ctf(t->t_pshandle, addr)) == NULL) {
3129 		(void) set_errno(EMDB_NOOBJ);
3130 		return (NULL);
3131 	}
3132 
3133 	return (ret);
3134 }
3135 
3136 static ctf_file_t *
3137 pt_name_to_ctf(mdb_tgt_t *t, const char *name)
3138 {
3139 	ctf_file_t *ret;
3140 
3141 	if (t->t_pshandle == NULL) {
3142 		(void) set_errno(EMDB_NOPROC);
3143 		return (NULL);
3144 	}
3145 
3146 	if ((ret = Pname_to_ctf(t->t_pshandle, name)) == NULL) {
3147 		(void) set_errno(EMDB_NOOBJ);
3148 		return (NULL);
3149 	}
3150 
3151 	return (ret);
3152 }
3153 
3154 static int
3155 pt_status(mdb_tgt_t *t, mdb_tgt_status_t *tsp)
3156 {
3157 	const pstatus_t *psp;
3158 	prgregset_t gregs;
3159 	int state;
3160 
3161 	bzero(tsp, sizeof (mdb_tgt_status_t));
3162 
3163 	if (t->t_pshandle == NULL) {
3164 		tsp->st_state = MDB_TGT_IDLE;
3165 		return (0);
3166 	}
3167 
3168 	switch (state = Pstate(t->t_pshandle)) {
3169 	case PS_RUN:
3170 		tsp->st_state = MDB_TGT_RUNNING;
3171 		break;
3172 
3173 	case PS_STOP:
3174 		tsp->st_state = MDB_TGT_STOPPED;
3175 		psp = Pstatus(t->t_pshandle);
3176 
3177 		tsp->st_tid = PTL_TID(t);
3178 		if (PTL_GETREGS(t, tsp->st_tid, gregs) == 0)
3179 			tsp->st_pc = gregs[R_PC];
3180 
3181 		if (psp->pr_flags & PR_ISTOP)
3182 			tsp->st_flags |= MDB_TGT_ISTOP;
3183 		if (psp->pr_flags & PR_DSTOP)
3184 			tsp->st_flags |= MDB_TGT_DSTOP;
3185 
3186 		break;
3187 
3188 	case PS_LOST:
3189 		tsp->st_state = MDB_TGT_LOST;
3190 		break;
3191 	case PS_UNDEAD:
3192 		tsp->st_state = MDB_TGT_UNDEAD;
3193 		break;
3194 	case PS_DEAD:
3195 		tsp->st_state = MDB_TGT_DEAD;
3196 		break;
3197 	case PS_IDLE:
3198 		tsp->st_state = MDB_TGT_IDLE;
3199 		break;
3200 	default:
3201 		fail("unknown libproc state (%d)\n", state);
3202 	}
3203 
3204 	if (t->t_flags & MDB_TGT_F_BUSY)
3205 		tsp->st_flags |= MDB_TGT_BUSY;
3206 
3207 	return (0);
3208 }
3209 
3210 static void
3211 pt_dupfd(const char *file, int oflags, mode_t mode, int dfd)
3212 {
3213 	int fd;
3214 
3215 	if ((fd = open(file, oflags, mode)) >= 0) {
3216 		(void) fcntl(fd, F_DUP2FD, dfd);
3217 		(void) close(fd);
3218 	} else
3219 		warn("failed to open %s as descriptor %d", file, dfd);
3220 }
3221 
3222 /*
3223  * The Pcreate_callback() function interposes on the default, empty libproc
3224  * definition.  It will be called following a fork of a new child process by
3225  * Pcreate() below, but before the exec of the new process image.  We use this
3226  * callback to optionally redirect stdin and stdout and reset the dispositions
3227  * of SIGPIPE and SIGQUIT from SIG_IGN back to SIG_DFL.
3228  */
3229 /*ARGSUSED*/
3230 void
3231 Pcreate_callback(struct ps_prochandle *P)
3232 {
3233 	pt_data_t *pt = mdb.m_target->t_data;
3234 
3235 	if (pt->p_stdin != NULL)
3236 		pt_dupfd(pt->p_stdin, O_RDWR, 0, STDIN_FILENO);
3237 	if (pt->p_stdout != NULL)
3238 		pt_dupfd(pt->p_stdout, O_CREAT | O_WRONLY, 0666, STDOUT_FILENO);
3239 
3240 	(void) mdb_signal_sethandler(SIGPIPE, SIG_DFL, NULL);
3241 	(void) mdb_signal_sethandler(SIGQUIT, SIG_DFL, NULL);
3242 }
3243 
3244 static int
3245 pt_run(mdb_tgt_t *t, int argc, const mdb_arg_t *argv)
3246 {
3247 	pt_data_t *pt = t->t_data;
3248 	struct ps_prochandle *P;
3249 	char execname[MAXPATHLEN];
3250 	const char **pargv;
3251 	int pargc = 0;
3252 	int i, perr;
3253 	char **penv;
3254 	mdb_var_t *v;
3255 
3256 	if (pt->p_aout_fio == NULL) {
3257 		warn("run requires executable to be specified on "
3258 		    "command-line\n");
3259 		return (set_errno(EMDB_TGT));
3260 	}
3261 
3262 	pargv = mdb_alloc(sizeof (char *) * (argc + 2), UM_SLEEP);
3263 	pargv[pargc++] = strbasename(IOP_NAME(pt->p_aout_fio));
3264 
3265 	for (i = 0; i < argc; i++) {
3266 		if (argv[i].a_type != MDB_TYPE_STRING) {
3267 			mdb_free(pargv, sizeof (char *) * (argc + 2));
3268 			return (set_errno(EINVAL));
3269 		}
3270 		if (argv[i].a_un.a_str[0] == '<')
3271 			pt->p_stdin = argv[i].a_un.a_str + 1;
3272 		else if (argv[i].a_un.a_str[0] == '>')
3273 			pt->p_stdout = argv[i].a_un.a_str + 1;
3274 		else
3275 			pargv[pargc++] = argv[i].a_un.a_str;
3276 	}
3277 	pargv[pargc] = NULL;
3278 
3279 	/*
3280 	 * Since Pcreate() uses execvp() and "." may not be present in $PATH,
3281 	 * we must manually prepend "./" when the executable is a simple name.
3282 	 */
3283 	if (strchr(IOP_NAME(pt->p_aout_fio), '/') == NULL) {
3284 		(void) snprintf(execname, sizeof (execname), "./%s",
3285 		    IOP_NAME(pt->p_aout_fio));
3286 	} else {
3287 		(void) snprintf(execname, sizeof (execname), "%s",
3288 		    IOP_NAME(pt->p_aout_fio));
3289 	}
3290 
3291 	penv = mdb_alloc((mdb_nv_size(&pt->p_env)+ 1) * sizeof (char *),
3292 	    UM_SLEEP);
3293 	for (mdb_nv_rewind(&pt->p_env), i = 0;
3294 	    (v = mdb_nv_advance(&pt->p_env)) != NULL; i++)
3295 		penv[i] = mdb_nv_get_cookie(v);
3296 	penv[i] = NULL;
3297 
3298 	P = Pxcreate(execname, (char **)pargv, penv, &perr, NULL, 0);
3299 	mdb_free(pargv, sizeof (char *) * (argc + 2));
3300 	pt->p_stdin = pt->p_stdout = NULL;
3301 
3302 	mdb_free(penv, i * sizeof (char *));
3303 
3304 	if (P == NULL) {
3305 		warn("failed to create process: %s\n", Pcreate_error(perr));
3306 		return (set_errno(EMDB_TGT));
3307 	}
3308 
3309 	if (t->t_pshandle != NULL) {
3310 		pt_pre_detach(t, TRUE);
3311 		if (t->t_pshandle != pt->p_idlehandle)
3312 			Prelease(t->t_pshandle, pt->p_rflags);
3313 	}
3314 
3315 	(void) Punsetflags(P, PR_RLC);	/* make sure run-on-last-close is off */
3316 	(void) Psetflags(P, PR_KLC);	/* kill on last close by debugger */
3317 	pt->p_rflags = PRELEASE_KILL;	/* kill on debugger Prelease */
3318 	t->t_pshandle = P;
3319 
3320 	pt_post_attach(t);
3321 	pt_activate_common(t);
3322 	(void) mdb_tgt_status(t, &t->t_status);
3323 	mdb.m_flags |= MDB_FL_VCREATE;
3324 
3325 	return (0);
3326 }
3327 
3328 /*
3329  * Forward a signal to the victim process in order to force it to stop or die.
3330  * Refer to the comments above pt_setrun(), below, for more info.
3331  */
3332 /*ARGSUSED*/
3333 static void
3334 pt_sigfwd(int sig, siginfo_t *sip, ucontext_t *ucp, mdb_tgt_t *t)
3335 {
3336 	struct ps_prochandle *P = t->t_pshandle;
3337 	const lwpstatus_t *psp = &Pstatus(P)->pr_lwp;
3338 	pid_t pid = Pstatus(P)->pr_pid;
3339 	long ctl[2];
3340 
3341 	if (getpgid(pid) != mdb.m_pgid) {
3342 		mdb_dprintf(MDB_DBG_TGT, "fwd SIG#%d to %d\n", sig, (int)pid);
3343 		(void) kill(pid, sig);
3344 	}
3345 
3346 	if (Pwait(P, 1) == 0 && (psp->pr_flags & PR_STOPPED) &&
3347 	    psp->pr_why == PR_JOBCONTROL && Pdstop(P) == 0) {
3348 		/*
3349 		 * If we're job control stopped and our DSTOP is pending, the
3350 		 * victim will never see our signal, so undo the kill() and
3351 		 * then send SIGCONT the victim to kick it out of the job
3352 		 * control stop and force our DSTOP to take effect.
3353 		 */
3354 		if ((psp->pr_flags & PR_DSTOP) &&
3355 		    prismember(&Pstatus(P)->pr_sigpend, sig)) {
3356 			ctl[0] = PCUNKILL;
3357 			ctl[1] = sig;
3358 			(void) write(Pctlfd(P), ctl, sizeof (ctl));
3359 		}
3360 
3361 		mdb_dprintf(MDB_DBG_TGT, "fwd SIGCONT to %d\n", (int)pid);
3362 		(void) kill(pid, SIGCONT);
3363 	}
3364 }
3365 
3366 /*
3367  * Common code for step and continue: if no victim process has been created,
3368  * call pt_run() to create one.  Then set the victim running, clearing any
3369  * pending fault.  One special case is that if the victim was previously
3370  * stopped on reception of SIGINT, we know that SIGINT was traced and the user
3371  * requested the victim to stop, so clear this signal before continuing.
3372  * For all other traced signals, the signal will be delivered on continue.
3373  *
3374  * Once the victim process is running, we wait for it to stop on an event of
3375  * interest.  Although libproc provides the basic primitive to wait for the
3376  * victim, we must be careful in our handling of signals.  We want to allow the
3377  * user to issue a SIGINT or SIGQUIT using the designated terminal control
3378  * character (typically ^C and ^\), and have these signals stop the target and
3379  * return control to the debugger if the signals are traced.  There are three
3380  * cases to be considered in our implementation:
3381  *
3382  * (1) If the debugger and victim are in the same process group, both receive
3383  * the signal from the terminal driver.  The debugger returns from Pwait() with
3384  * errno = EINTR, so we want to loop back and continue waiting until the victim
3385  * stops on receipt of its SIGINT or SIGQUIT.
3386  *
3387  * (2) If the debugger and victim are in different process groups, and the
3388  * victim is a member of the foreground process group, it will receive the
3389  * signal from the terminal driver and the debugger will not.  As such, we
3390  * will remain blocked in Pwait() until the victim stops on its signal.
3391  *
3392  * (3) If the debugger and victim are in different process groups, and the
3393  * debugger is a member of the foreground process group, it will receive the
3394  * signal from the terminal driver, and the victim will not.  The debugger
3395  * returns from Pwait() with errno = EINTR, so we need to forward the signal
3396  * to the victim process directly and then Pwait() again for it to stop.
3397  *
3398  * We can observe that all three cases are handled by simply calling Pwait()
3399  * repeatedly if it fails with EINTR, and forwarding SIGINT and SIGQUIT to
3400  * the victim if it is in a different process group, using pt_sigfwd() above.
3401  *
3402  * An additional complication is that the process may not be able to field
3403  * the signal if it is currently stopped by job control.  In this case, we
3404  * also DSTOP the process, and then send it a SIGCONT to wake it up from
3405  * job control and force it to re-enter stop() under the control of /proc.
3406  *
3407  * Finally, we would like to allow the user to suspend the process using the
3408  * terminal suspend character (typically ^Z) if both are in the same session.
3409  * We again employ pt_sigfwd() to forward SIGTSTP to the victim, wait for it to
3410  * stop from job control, and then capture it using /proc.  Once the process
3411  * has stopped, normal SIGTSTP processing is restored and the user can issue
3412  * another ^Z in order to suspend the debugger and return to the parent shell.
3413  */
3414 static int
3415 pt_setrun(mdb_tgt_t *t, mdb_tgt_status_t *tsp, int flags)
3416 {
3417 	struct ps_prochandle *P = t->t_pshandle;
3418 	pt_data_t *pt = t->t_data;
3419 	pid_t old_pgid = -1;
3420 
3421 	mdb_signal_f *intf, *quitf, *tstpf;
3422 	const lwpstatus_t *psp;
3423 	void *intd, *quitd, *tstpd;
3424 
3425 	int sig = pt->p_signal;
3426 	int error = 0;
3427 	int pgid = -1;
3428 
3429 	pt->p_signal = 0; /* clear pending signal */
3430 
3431 	if (P == NULL && pt_run(t, 0, NULL) == -1)
3432 		return (-1); /* errno is set for us */
3433 
3434 	P = t->t_pshandle;
3435 	psp = &Pstatus(P)->pr_lwp;
3436 
3437 	if (sig == 0 && psp->pr_why == PR_SIGNALLED && psp->pr_what == SIGINT)
3438 		flags |= PRCSIG; /* clear pending SIGINT */
3439 	else
3440 		flags |= PRCFAULT; /* clear any pending fault (e.g. BPT) */
3441 
3442 	intf = mdb_signal_gethandler(SIGINT, &intd);
3443 	quitf = mdb_signal_gethandler(SIGQUIT, &quitd);
3444 	tstpf = mdb_signal_gethandler(SIGTSTP, &tstpd);
3445 
3446 	(void) mdb_signal_sethandler(SIGINT, (mdb_signal_f *)pt_sigfwd, t);
3447 	(void) mdb_signal_sethandler(SIGQUIT, (mdb_signal_f *)pt_sigfwd, t);
3448 	(void) mdb_signal_sethandler(SIGTSTP, (mdb_signal_f *)pt_sigfwd, t);
3449 
3450 	if (sig != 0 && Pstate(P) == PS_RUN &&
3451 	    kill(Pstatus(P)->pr_pid, sig) == -1) {
3452 		error = errno;
3453 		goto out;
3454 	}
3455 
3456 	/*
3457 	 * If we attached to a job stopped background process in the same
3458 	 * session, make its pgid the foreground process group before running
3459 	 * it.  Ignore SIGTTOU while doing this to avoid being suspended.
3460 	 */
3461 	if (mdb.m_flags & MDB_FL_JOBCTL) {
3462 		(void) mdb_signal_sethandler(SIGTTOU, SIG_IGN, NULL);
3463 		(void) IOP_CTL(mdb.m_term, TIOCGPGRP, &old_pgid);
3464 		(void) IOP_CTL(mdb.m_term, TIOCSPGRP,
3465 		    (void *)&Pstatus(P)->pr_pgid);
3466 		(void) mdb_signal_sethandler(SIGTTOU, SIG_DFL, NULL);
3467 	}
3468 
3469 	if (Pstate(P) != PS_RUN && Psetrun(P, sig, flags) == -1) {
3470 		error = errno;
3471 		goto out;
3472 	}
3473 
3474 	/*
3475 	 * If the process is stopped on job control, resume its process group
3476 	 * by sending it a SIGCONT if we are in the same session.  Otherwise
3477 	 * we have no choice but to wait for someone else to foreground it.
3478 	 */
3479 	if (psp->pr_why == PR_JOBCONTROL) {
3480 		if (mdb.m_flags & MDB_FL_JOBCTL)
3481 			(void) kill(-Pstatus(P)->pr_pgid, SIGCONT);
3482 		else if (mdb.m_term != NULL)
3483 			warn("process is still suspended by job control ...\n");
3484 	}
3485 
3486 	/*
3487 	 * Wait for the process to stop.  As described above, we loop around if
3488 	 * we are interrupted (EINTR).  If we lose control, attempt to re-open
3489 	 * the process, or call pt_exec() if that fails to handle a re-exec.
3490 	 * If the process dies (ENOENT) or Pwait() fails, break out of the loop.
3491 	 */
3492 	while (Pwait(P, 0) == -1) {
3493 		if (errno != EINTR) {
3494 			if (Pstate(P) == PS_LOST) {
3495 				if (Preopen(P) == 0)
3496 					continue; /* Pwait() again */
3497 				else
3498 					pt_exec(t, 0, NULL);
3499 			} else if (errno != ENOENT)
3500 				warn("failed to wait for event");
3501 			break;
3502 		}
3503 	}
3504 
3505 	/*
3506 	 * If we changed the foreground process group, restore the old pgid
3507 	 * while ignoring SIGTTOU so we are not accidentally suspended.
3508 	 */
3509 	if (old_pgid != -1) {
3510 		(void) mdb_signal_sethandler(SIGTTOU, SIG_IGN, NULL);
3511 		(void) IOP_CTL(mdb.m_term, TIOCSPGRP, &pgid);
3512 		(void) mdb_signal_sethandler(SIGTTOU, SIG_DFL, NULL);
3513 	}
3514 
3515 	/*
3516 	 * If we're now stopped on exit from a successful exec, release any
3517 	 * vfork parents and clean out their address space before returning
3518 	 * to tgt_continue() and perturbing the list of armed event specs.
3519 	 * If we're stopped for any other reason, just update the mappings.
3520 	 */
3521 	switch (Pstate(P)) {
3522 	case PS_STOP:
3523 		if (psp->pr_why == PR_SYSEXIT && psp->pr_errno == 0 &&
3524 		    (psp->pr_what == SYS_exec || psp->pr_what == SYS_execve))
3525 			pt_release_parents(t);
3526 		else
3527 			Pupdate_maps(P);
3528 		break;
3529 
3530 	case PS_UNDEAD:
3531 	case PS_LOST:
3532 		pt_release_parents(t);
3533 		break;
3534 	}
3535 
3536 out:
3537 	(void) mdb_signal_sethandler(SIGINT, intf, intd);
3538 	(void) mdb_signal_sethandler(SIGQUIT, quitf, quitd);
3539 	(void) mdb_signal_sethandler(SIGTSTP, tstpf, tstpd);
3540 	(void) pt_status(t, tsp);
3541 
3542 	return (error ? set_errno(error) : 0);
3543 }
3544 
3545 static int
3546 pt_step(mdb_tgt_t *t, mdb_tgt_status_t *tsp)
3547 {
3548 	return (pt_setrun(t, tsp, PRSTEP));
3549 }
3550 
3551 static int
3552 pt_continue(mdb_tgt_t *t, mdb_tgt_status_t *tsp)
3553 {
3554 	return (pt_setrun(t, tsp, 0));
3555 }
3556 
3557 static int
3558 pt_signal(mdb_tgt_t *t, int sig)
3559 {
3560 	pt_data_t *pt = t->t_data;
3561 
3562 	if (sig > 0 && sig <= pt->p_maxsig) {
3563 		pt->p_signal = sig; /* pending until next pt_setrun */
3564 		return (0);
3565 	}
3566 
3567 	return (set_errno(EMDB_BADSIGNUM));
3568 }
3569 
3570 static int
3571 pt_sysenter_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3572 {
3573 	struct ps_prochandle *P = t->t_pshandle;
3574 
3575 	if (P != NULL && Pstate(P) < PS_LOST) {
3576 		sep->se_data = args; /* data is raw system call number */
3577 		return (Psysentry(P, (intptr_t)args, TRUE) < 0 ? -1 : 0);
3578 	}
3579 
3580 	return (set_errno(EMDB_NOPROC));
3581 }
3582 
3583 static void
3584 pt_sysenter_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3585 {
3586 	(void) Psysentry(t->t_pshandle, (intptr_t)sep->se_data, FALSE);
3587 }
3588 
3589 /*ARGSUSED*/
3590 static char *
3591 pt_sysenter_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3592     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3593 {
3594 	char name[32];
3595 	int sysnum;
3596 
3597 	if (vep != NULL)
3598 		sysnum = (intptr_t)vep->ve_args;
3599 	else
3600 		sysnum = (intptr_t)sep->se_data;
3601 
3602 	(void) proc_sysname(sysnum, name, sizeof (name));
3603 	(void) mdb_iob_snprintf(buf, nbytes, "stop on entry to %s", name);
3604 
3605 	return (buf);
3606 }
3607 
3608 /*ARGSUSED*/
3609 static int
3610 pt_sysenter_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
3611 {
3612 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3613 	int sysnum = (intptr_t)sep->se_data;
3614 
3615 	return (psp->pr_why == PR_SYSENTRY && psp->pr_what == sysnum);
3616 }
3617 
3618 static const mdb_se_ops_t proc_sysenter_ops = {
3619 	pt_sysenter_ctor,	/* se_ctor */
3620 	pt_sysenter_dtor,	/* se_dtor */
3621 	pt_sysenter_info,	/* se_info */
3622 	no_se_secmp,		/* se_secmp */
3623 	no_se_vecmp,		/* se_vecmp */
3624 	no_se_arm,		/* se_arm */
3625 	no_se_disarm,		/* se_disarm */
3626 	no_se_cont,		/* se_cont */
3627 	pt_sysenter_match	/* se_match */
3628 };
3629 
3630 static int
3631 pt_sysexit_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3632 {
3633 	struct ps_prochandle *P = t->t_pshandle;
3634 
3635 	if (P != NULL && Pstate(P) < PS_LOST) {
3636 		sep->se_data = args; /* data is raw system call number */
3637 		return (Psysexit(P, (intptr_t)args, TRUE) < 0 ? -1 : 0);
3638 	}
3639 
3640 	return (set_errno(EMDB_NOPROC));
3641 }
3642 
3643 static void
3644 pt_sysexit_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3645 {
3646 	(void) Psysexit(t->t_pshandle, (intptr_t)sep->se_data, FALSE);
3647 }
3648 
3649 /*ARGSUSED*/
3650 static char *
3651 pt_sysexit_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3652     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3653 {
3654 	char name[32];
3655 	int sysnum;
3656 
3657 	if (vep != NULL)
3658 		sysnum = (intptr_t)vep->ve_args;
3659 	else
3660 		sysnum = (intptr_t)sep->se_data;
3661 
3662 	(void) proc_sysname(sysnum, name, sizeof (name));
3663 	(void) mdb_iob_snprintf(buf, nbytes, "stop on exit from %s", name);
3664 
3665 	return (buf);
3666 }
3667 
3668 /*ARGSUSED*/
3669 static int
3670 pt_sysexit_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
3671 {
3672 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3673 	int sysnum = (intptr_t)sep->se_data;
3674 
3675 	return (psp->pr_why == PR_SYSEXIT && psp->pr_what == sysnum);
3676 }
3677 
3678 static const mdb_se_ops_t proc_sysexit_ops = {
3679 	pt_sysexit_ctor,	/* se_ctor */
3680 	pt_sysexit_dtor,	/* se_dtor */
3681 	pt_sysexit_info,	/* se_info */
3682 	no_se_secmp,		/* se_secmp */
3683 	no_se_vecmp,		/* se_vecmp */
3684 	no_se_arm,		/* se_arm */
3685 	no_se_disarm,		/* se_disarm */
3686 	no_se_cont,		/* se_cont */
3687 	pt_sysexit_match	/* se_match */
3688 };
3689 
3690 static int
3691 pt_signal_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3692 {
3693 	struct ps_prochandle *P = t->t_pshandle;
3694 
3695 	if (P != NULL && Pstate(P) < PS_LOST) {
3696 		sep->se_data = args; /* data is raw signal number */
3697 		return (Psignal(P, (intptr_t)args, TRUE) < 0 ? -1 : 0);
3698 	}
3699 
3700 	return (set_errno(EMDB_NOPROC));
3701 }
3702 
3703 static void
3704 pt_signal_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3705 {
3706 	(void) Psignal(t->t_pshandle, (intptr_t)sep->se_data, FALSE);
3707 }
3708 
3709 /*ARGSUSED*/
3710 static char *
3711 pt_signal_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3712     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3713 {
3714 	char name[SIG2STR_MAX];
3715 	int signum;
3716 
3717 	if (vep != NULL)
3718 		signum = (intptr_t)vep->ve_args;
3719 	else
3720 		signum = (intptr_t)sep->se_data;
3721 
3722 	(void) proc_signame(signum, name, sizeof (name));
3723 	(void) mdb_iob_snprintf(buf, nbytes, "stop on %s", name);
3724 
3725 	return (buf);
3726 }
3727 
3728 /*ARGSUSED*/
3729 static int
3730 pt_signal_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
3731 {
3732 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3733 	int signum = (intptr_t)sep->se_data;
3734 
3735 	return (psp->pr_why == PR_SIGNALLED && psp->pr_what == signum);
3736 }
3737 
3738 static const mdb_se_ops_t proc_signal_ops = {
3739 	pt_signal_ctor,		/* se_ctor */
3740 	pt_signal_dtor,		/* se_dtor */
3741 	pt_signal_info,		/* se_info */
3742 	no_se_secmp,		/* se_secmp */
3743 	no_se_vecmp,		/* se_vecmp */
3744 	no_se_arm,		/* se_arm */
3745 	no_se_disarm,		/* se_disarm */
3746 	no_se_cont,		/* se_cont */
3747 	pt_signal_match		/* se_match */
3748 };
3749 
3750 static int
3751 pt_fault_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3752 {
3753 	struct ps_prochandle *P = t->t_pshandle;
3754 
3755 	if (P != NULL && Pstate(P) < PS_LOST) {
3756 		sep->se_data = args; /* data is raw fault number */
3757 		return (Pfault(P, (intptr_t)args, TRUE) < 0 ? -1 : 0);
3758 	}
3759 
3760 	return (set_errno(EMDB_NOPROC));
3761 }
3762 
3763 static void
3764 pt_fault_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3765 {
3766 	int fault = (intptr_t)sep->se_data;
3767 
3768 	if (fault != FLTBPT && fault != FLTTRACE && fault != FLTWATCH)
3769 		(void) Pfault(t->t_pshandle, fault, FALSE);
3770 }
3771 
3772 /*ARGSUSED*/
3773 static char *
3774 pt_fault_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3775     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3776 {
3777 	char name[32];
3778 	int fltnum;
3779 
3780 	if (vep != NULL)
3781 		fltnum = (intptr_t)vep->ve_args;
3782 	else
3783 		fltnum = (intptr_t)sep->se_data;
3784 
3785 	(void) proc_fltname(fltnum, name, sizeof (name));
3786 	(void) mdb_iob_snprintf(buf, nbytes, "stop on %s", name);
3787 
3788 	return (buf);
3789 }
3790 
3791 /*ARGSUSED*/
3792 static int
3793 pt_fault_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
3794 {
3795 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3796 	int fltnum = (intptr_t)sep->se_data;
3797 
3798 	return (psp->pr_why == PR_FAULTED && psp->pr_what == fltnum);
3799 }
3800 
3801 static const mdb_se_ops_t proc_fault_ops = {
3802 	pt_fault_ctor,		/* se_ctor */
3803 	pt_fault_dtor,		/* se_dtor */
3804 	pt_fault_info,		/* se_info */
3805 	no_se_secmp,		/* se_secmp */
3806 	no_se_vecmp,		/* se_vecmp */
3807 	no_se_arm,		/* se_arm */
3808 	no_se_disarm,		/* se_disarm */
3809 	no_se_cont,		/* se_cont */
3810 	pt_fault_match		/* se_match */
3811 };
3812 
3813 /*
3814  * Callback for pt_ignore() dcmd above: for each VID, determine if it
3815  * corresponds to a vespec that traces the specified signal, and delete it.
3816  */
3817 /*ARGSUSED*/
3818 static int
3819 pt_ignore_sig(mdb_tgt_t *t, void *sig, int vid, void *data)
3820 {
3821 	mdb_vespec_t *vep = mdb_tgt_vespec_lookup(t, vid);
3822 
3823 	if (vep->ve_se->se_ops == &proc_signal_ops && vep->ve_args == sig)
3824 		(void) mdb_tgt_vespec_delete(t, vid);
3825 
3826 	return (0);
3827 }
3828 
3829 static int
3830 pt_brkpt_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3831 {
3832 	pt_data_t *pt = t->t_data;
3833 	pt_bparg_t *pta = args;
3834 	pt_brkpt_t *ptb;
3835 	GElf_Sym s;
3836 
3837 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) >= PS_LOST)
3838 		return (set_errno(EMDB_NOPROC));
3839 
3840 	if (pta->pta_symbol != NULL) {
3841 		if (!pt->p_rtld_finished &&
3842 		    strchr(pta->pta_symbol, '`') == NULL)
3843 			return (set_errno(EMDB_NOSYM));
3844 		if (mdb_tgt_lookup_by_scope(t, pta->pta_symbol, &s,
3845 		    NULL) == -1) {
3846 			if (errno != EMDB_NOOBJ && !(errno == EMDB_NOSYM &&
3847 			    (!(mdb.m_flags & MDB_FL_BPTNOSYMSTOP) ||
3848 			    !pt->p_rtld_finished))) {
3849 				warn("breakpoint %s activation failed",
3850 				    pta->pta_symbol);
3851 			}
3852 			return (-1); /* errno is set for us */
3853 		}
3854 
3855 		pta->pta_addr = (uintptr_t)s.st_value;
3856 	}
3857 
3858 #ifdef __sparc
3859 	if (pta->pta_addr & 3)
3860 		return (set_errno(EMDB_BPALIGN));
3861 #endif
3862 
3863 	if (Paddr_to_map(t->t_pshandle, pta->pta_addr) == NULL)
3864 		return (set_errno(EMDB_NOMAP));
3865 
3866 	ptb = mdb_alloc(sizeof (pt_brkpt_t), UM_SLEEP);
3867 	ptb->ptb_addr = pta->pta_addr;
3868 	ptb->ptb_instr = NULL;
3869 	sep->se_data = ptb;
3870 
3871 	return (0);
3872 }
3873 
3874 /*ARGSUSED*/
3875 static void
3876 pt_brkpt_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
3877 {
3878 	mdb_free(sep->se_data, sizeof (pt_brkpt_t));
3879 }
3880 
3881 /*ARGSUSED*/
3882 static char *
3883 pt_brkpt_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
3884     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
3885 {
3886 	uintptr_t addr = NULL;
3887 
3888 	if (vep != NULL) {
3889 		pt_bparg_t *pta = vep->ve_args;
3890 
3891 		if (pta->pta_symbol != NULL) {
3892 			(void) mdb_iob_snprintf(buf, nbytes, "stop at %s",
3893 			    pta->pta_symbol);
3894 		} else {
3895 			(void) mdb_iob_snprintf(buf, nbytes, "stop at %a",
3896 			    pta->pta_addr);
3897 			addr = pta->pta_addr;
3898 		}
3899 
3900 	} else {
3901 		addr = ((pt_brkpt_t *)sep->se_data)->ptb_addr;
3902 		(void) mdb_iob_snprintf(buf, nbytes, "stop at %a", addr);
3903 	}
3904 
3905 	sp->spec_base = addr;
3906 	sp->spec_size = sizeof (instr_t);
3907 
3908 	return (buf);
3909 }
3910 
3911 static int
3912 pt_brkpt_secmp(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
3913 {
3914 	pt_brkpt_t *ptb = sep->se_data;
3915 	pt_bparg_t *pta = args;
3916 	GElf_Sym sym;
3917 
3918 	if (pta->pta_symbol != NULL) {
3919 		return (mdb_tgt_lookup_by_scope(t, pta->pta_symbol,
3920 		    &sym, NULL) == 0 && sym.st_value == ptb->ptb_addr);
3921 	}
3922 
3923 	return (pta->pta_addr == ptb->ptb_addr);
3924 }
3925 
3926 /*ARGSUSED*/
3927 static int
3928 pt_brkpt_vecmp(mdb_tgt_t *t, mdb_vespec_t *vep, void *args)
3929 {
3930 	pt_bparg_t *pta1 = vep->ve_args;
3931 	pt_bparg_t *pta2 = args;
3932 
3933 	if (pta1->pta_symbol != NULL && pta2->pta_symbol != NULL)
3934 		return (strcmp(pta1->pta_symbol, pta2->pta_symbol) == 0);
3935 
3936 	if (pta1->pta_symbol == NULL && pta2->pta_symbol == NULL)
3937 		return (pta1->pta_addr == pta2->pta_addr);
3938 
3939 	return (0); /* fail if one is symbolic, other is an explicit address */
3940 }
3941 
3942 static int
3943 pt_brkpt_arm(mdb_tgt_t *t, mdb_sespec_t *sep)
3944 {
3945 	pt_brkpt_t *ptb = sep->se_data;
3946 	return (Psetbkpt(t->t_pshandle, ptb->ptb_addr, &ptb->ptb_instr));
3947 }
3948 
3949 /*
3950  * In order to disarm a breakpoint, we replace the trap instruction at ptb_addr
3951  * with the saved instruction.  However, if we have stopped after a successful
3952  * exec(2), we do not want to restore ptb_instr because the address space has
3953  * now been replaced with the text of a different executable, and so restoring
3954  * the saved instruction would be incorrect.  The exec itself has effectively
3955  * removed all breakpoint trap instructions for us, so we can just return.
3956  */
3957 static int
3958 pt_brkpt_disarm(mdb_tgt_t *t, mdb_sespec_t *sep)
3959 {
3960 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3961 	pt_brkpt_t *ptb = sep->se_data;
3962 
3963 	if ((psp->pr_why == PR_SYSEXIT && psp->pr_errno == 0) &&
3964 	    (psp->pr_what == SYS_exec || psp->pr_what == SYS_execve))
3965 		return (0); /* do not restore saved instruction */
3966 
3967 	return (Pdelbkpt(t->t_pshandle, ptb->ptb_addr, ptb->ptb_instr));
3968 }
3969 
3970 /*
3971  * Determine whether the specified sespec is an armed watchpoint that overlaps
3972  * with the given breakpoint and has the given flags set.  We use this to find
3973  * conflicts with breakpoints, below.
3974  */
3975 static int
3976 pt_wp_overlap(mdb_sespec_t *sep, pt_brkpt_t *ptb, int flags)
3977 {
3978 	const prwatch_t *wp = sep->se_data;
3979 
3980 	return (sep->se_state == MDB_TGT_SPEC_ARMED &&
3981 	    sep->se_ops == &proc_wapt_ops && (wp->pr_wflags & flags) &&
3982 	    ptb->ptb_addr - wp->pr_vaddr < wp->pr_size);
3983 }
3984 
3985 /*
3986  * We step over breakpoints using Pxecbkpt() in libproc.  If a conflicting
3987  * watchpoint is present, we must temporarily remove it before stepping over
3988  * the breakpoint so we do not immediately re-trigger the watchpoint.  We know
3989  * the watchpoint has already triggered on our trap instruction as part of
3990  * fetching it.  Before we return, we must re-install any disabled watchpoints.
3991  */
3992 static int
3993 pt_brkpt_cont(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
3994 {
3995 	pt_brkpt_t *ptb = sep->se_data;
3996 	int status = -1;
3997 	int error;
3998 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
3999 
4000 	/*
4001 	 * If the PC no longer matches our original address, then the user has
4002 	 * changed it while we have been stopped. In this case, it no longer
4003 	 * makes any sense to continue over this breakpoint.  We return as if we
4004 	 * continued normally.
4005 	 */
4006 	if ((uintptr_t)psp->pr_info.si_addr != psp->pr_reg[R_PC])
4007 		return (pt_status(t, tsp));
4008 
4009 	for (sep = mdb_list_next(&t->t_active); sep; sep = mdb_list_next(sep)) {
4010 		if (pt_wp_overlap(sep, ptb, WA_EXEC))
4011 			(void) Pdelwapt(t->t_pshandle, sep->se_data);
4012 	}
4013 
4014 	if (Pxecbkpt(t->t_pshandle, ptb->ptb_instr) == 0 &&
4015 	    Pdelbkpt(t->t_pshandle, ptb->ptb_addr, ptb->ptb_instr) == 0)
4016 		status = pt_status(t, tsp);
4017 
4018 	error = errno; /* save errno from Pxecbkpt, Pdelbkpt, or pt_status */
4019 
4020 	for (sep = mdb_list_next(&t->t_active); sep; sep = mdb_list_next(sep)) {
4021 		if (pt_wp_overlap(sep, ptb, WA_EXEC) &&
4022 		    Psetwapt(t->t_pshandle, sep->se_data) == -1) {
4023 			sep->se_state = MDB_TGT_SPEC_ERROR;
4024 			sep->se_errno = errno;
4025 		}
4026 	}
4027 
4028 	(void) set_errno(error);
4029 	return (status);
4030 }
4031 
4032 /*ARGSUSED*/
4033 static int
4034 pt_brkpt_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
4035 {
4036 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
4037 	pt_brkpt_t *ptb = sep->se_data;
4038 
4039 	return (psp->pr_why == PR_FAULTED && psp->pr_what == FLTBPT &&
4040 	    psp->pr_reg[R_PC] == ptb->ptb_addr);
4041 }
4042 
4043 static const mdb_se_ops_t proc_brkpt_ops = {
4044 	pt_brkpt_ctor,		/* se_ctor */
4045 	pt_brkpt_dtor,		/* se_dtor */
4046 	pt_brkpt_info,		/* se_info */
4047 	pt_brkpt_secmp,		/* se_secmp */
4048 	pt_brkpt_vecmp,		/* se_vecmp */
4049 	pt_brkpt_arm,		/* se_arm */
4050 	pt_brkpt_disarm,	/* se_disarm */
4051 	pt_brkpt_cont,		/* se_cont */
4052 	pt_brkpt_match		/* se_match */
4053 };
4054 
4055 static int
4056 pt_wapt_ctor(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
4057 {
4058 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) >= PS_LOST)
4059 		return (set_errno(EMDB_NOPROC));
4060 
4061 	sep->se_data = mdb_alloc(sizeof (prwatch_t), UM_SLEEP);
4062 	bcopy(args, sep->se_data, sizeof (prwatch_t));
4063 	return (0);
4064 }
4065 
4066 /*ARGSUSED*/
4067 static void
4068 pt_wapt_dtor(mdb_tgt_t *t, mdb_sespec_t *sep)
4069 {
4070 	mdb_free(sep->se_data, sizeof (prwatch_t));
4071 }
4072 
4073 /*ARGSUSED*/
4074 static char *
4075 pt_wapt_info(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_vespec_t *vep,
4076     mdb_tgt_spec_desc_t *sp, char *buf, size_t nbytes)
4077 {
4078 	prwatch_t *wp = vep != NULL ? vep->ve_args : sep->se_data;
4079 	char desc[24];
4080 
4081 	ASSERT(wp->pr_wflags != 0);
4082 	desc[0] = '\0';
4083 
4084 	switch (wp->pr_wflags) {
4085 	case WA_READ:
4086 		(void) strcat(desc, "/read");
4087 		break;
4088 	case WA_WRITE:
4089 		(void) strcat(desc, "/write");
4090 		break;
4091 	case WA_EXEC:
4092 		(void) strcat(desc, "/exec");
4093 		break;
4094 	default:
4095 		if (wp->pr_wflags & WA_READ)
4096 			(void) strcat(desc, "/r");
4097 		if (wp->pr_wflags & WA_WRITE)
4098 			(void) strcat(desc, "/w");
4099 		if (wp->pr_wflags & WA_EXEC)
4100 			(void) strcat(desc, "/x");
4101 	}
4102 
4103 	(void) mdb_iob_snprintf(buf, nbytes, "stop on %s of [%la, %la)",
4104 	    desc + 1, wp->pr_vaddr, wp->pr_vaddr + wp->pr_size);
4105 
4106 	sp->spec_base = wp->pr_vaddr;
4107 	sp->spec_size = wp->pr_size;
4108 
4109 	return (buf);
4110 }
4111 
4112 /*ARGSUSED*/
4113 static int
4114 pt_wapt_secmp(mdb_tgt_t *t, mdb_sespec_t *sep, void *args)
4115 {
4116 	prwatch_t *wp1 = sep->se_data;
4117 	prwatch_t *wp2 = args;
4118 
4119 	return (wp1->pr_vaddr == wp2->pr_vaddr &&
4120 	    wp1->pr_size == wp2->pr_size && wp1->pr_wflags == wp2->pr_wflags);
4121 }
4122 
4123 /*ARGSUSED*/
4124 static int
4125 pt_wapt_vecmp(mdb_tgt_t *t, mdb_vespec_t *vep, void *args)
4126 {
4127 	prwatch_t *wp1 = vep->ve_args;
4128 	prwatch_t *wp2 = args;
4129 
4130 	return (wp1->pr_vaddr == wp2->pr_vaddr &&
4131 	    wp1->pr_size == wp2->pr_size && wp1->pr_wflags == wp2->pr_wflags);
4132 }
4133 
4134 static int
4135 pt_wapt_arm(mdb_tgt_t *t, mdb_sespec_t *sep)
4136 {
4137 	return (Psetwapt(t->t_pshandle, sep->se_data));
4138 }
4139 
4140 static int
4141 pt_wapt_disarm(mdb_tgt_t *t, mdb_sespec_t *sep)
4142 {
4143 	return (Pdelwapt(t->t_pshandle, sep->se_data));
4144 }
4145 
4146 /*
4147  * Determine whether the specified sespec is an armed breakpoint at the
4148  * given %pc.  We use this to find conflicts with watchpoints below.
4149  */
4150 static int
4151 pt_bp_overlap(mdb_sespec_t *sep, uintptr_t pc)
4152 {
4153 	pt_brkpt_t *ptb = sep->se_data;
4154 
4155 	return (sep->se_state == MDB_TGT_SPEC_ARMED &&
4156 	    sep->se_ops == &proc_brkpt_ops && ptb->ptb_addr == pc);
4157 }
4158 
4159 /*
4160  * We step over watchpoints using Pxecwapt() in libproc.  If a conflicting
4161  * breakpoint is present, we must temporarily disarm it before stepping
4162  * over the watchpoint so we do not immediately re-trigger the breakpoint.
4163  * This is similar to the case handled in pt_brkpt_cont(), above.
4164  */
4165 static int
4166 pt_wapt_cont(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
4167 {
4168 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
4169 	mdb_sespec_t *bep = NULL;
4170 	int status = -1;
4171 	int error;
4172 
4173 	/*
4174 	 * If the PC no longer matches our original address, then the user has
4175 	 * changed it while we have been stopped. In this case, it no longer
4176 	 * makes any sense to continue over this instruction.  We return as if
4177 	 * we continued normally.
4178 	 */
4179 	if ((uintptr_t)psp->pr_info.si_pc != psp->pr_reg[R_PC])
4180 		return (pt_status(t, tsp));
4181 
4182 	if (psp->pr_info.si_code != TRAP_XWATCH) {
4183 		for (bep = mdb_list_next(&t->t_active); bep != NULL;
4184 		    bep = mdb_list_next(bep)) {
4185 			if (pt_bp_overlap(bep, psp->pr_reg[R_PC])) {
4186 				(void) bep->se_ops->se_disarm(t, bep);
4187 				bep->se_state = MDB_TGT_SPEC_ACTIVE;
4188 				break;
4189 			}
4190 		}
4191 	}
4192 
4193 	if (Pxecwapt(t->t_pshandle, sep->se_data) == 0)
4194 		status = pt_status(t, tsp);
4195 
4196 	error = errno; /* save errno from Pxecwapt or pt_status */
4197 
4198 	if (bep != NULL)
4199 		mdb_tgt_sespec_arm_one(t, bep);
4200 
4201 	(void) set_errno(error);
4202 	return (status);
4203 }
4204 
4205 /*ARGSUSED*/
4206 static int
4207 pt_wapt_match(mdb_tgt_t *t, mdb_sespec_t *sep, mdb_tgt_status_t *tsp)
4208 {
4209 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
4210 	prwatch_t *wp = sep->se_data;
4211 
4212 	return (psp->pr_why == PR_FAULTED && psp->pr_what == FLTWATCH &&
4213 	    (uintptr_t)psp->pr_info.si_addr - wp->pr_vaddr < wp->pr_size);
4214 }
4215 
4216 static const mdb_se_ops_t proc_wapt_ops = {
4217 	pt_wapt_ctor,		/* se_ctor */
4218 	pt_wapt_dtor,		/* se_dtor */
4219 	pt_wapt_info,		/* se_info */
4220 	pt_wapt_secmp,		/* se_secmp */
4221 	pt_wapt_vecmp,		/* se_vecmp */
4222 	pt_wapt_arm,		/* se_arm */
4223 	pt_wapt_disarm,		/* se_disarm */
4224 	pt_wapt_cont,		/* se_cont */
4225 	pt_wapt_match		/* se_match */
4226 };
4227 
4228 static void
4229 pt_bparg_dtor(mdb_vespec_t *vep)
4230 {
4231 	pt_bparg_t *pta = vep->ve_args;
4232 
4233 	if (pta->pta_symbol != NULL)
4234 		strfree(pta->pta_symbol);
4235 
4236 	mdb_free(pta, sizeof (pt_bparg_t));
4237 }
4238 
4239 static int
4240 pt_add_vbrkpt(mdb_tgt_t *t, uintptr_t addr,
4241     int spec_flags, mdb_tgt_se_f *func, void *data)
4242 {
4243 	pt_bparg_t *pta = mdb_alloc(sizeof (pt_bparg_t), UM_SLEEP);
4244 
4245 	pta->pta_symbol = NULL;
4246 	pta->pta_addr = addr;
4247 
4248 	return (mdb_tgt_vespec_insert(t, &proc_brkpt_ops, spec_flags,
4249 	    func, data, pta, pt_bparg_dtor));
4250 }
4251 
4252 static int
4253 pt_add_sbrkpt(mdb_tgt_t *t, const char *sym,
4254     int spec_flags, mdb_tgt_se_f *func, void *data)
4255 {
4256 	pt_bparg_t *pta;
4257 
4258 	if (sym[0] == '`') {
4259 		(void) set_errno(EMDB_NOOBJ);
4260 		return (0);
4261 	}
4262 
4263 	if (sym[strlen(sym) - 1] == '`') {
4264 		(void) set_errno(EMDB_NOSYM);
4265 		return (0);
4266 	}
4267 
4268 	pta = mdb_alloc(sizeof (pt_bparg_t), UM_SLEEP);
4269 	pta->pta_symbol = strdup(sym);
4270 	pta->pta_addr = NULL;
4271 
4272 	return (mdb_tgt_vespec_insert(t, &proc_brkpt_ops, spec_flags,
4273 	    func, data, pta, pt_bparg_dtor));
4274 }
4275 
4276 static int
4277 pt_wparg_overlap(const prwatch_t *wp1, const prwatch_t *wp2)
4278 {
4279 	if (wp2->pr_vaddr + wp2->pr_size <= wp1->pr_vaddr)
4280 		return (0); /* no range overlap */
4281 
4282 	if (wp1->pr_vaddr + wp1->pr_size <= wp2->pr_vaddr)
4283 		return (0); /* no range overlap */
4284 
4285 	return (wp1->pr_vaddr != wp2->pr_vaddr ||
4286 	    wp1->pr_size != wp2->pr_size || wp1->pr_wflags != wp2->pr_wflags);
4287 }
4288 
4289 static void
4290 pt_wparg_dtor(mdb_vespec_t *vep)
4291 {
4292 	mdb_free(vep->ve_args, sizeof (prwatch_t));
4293 }
4294 
4295 static int
4296 pt_add_vwapt(mdb_tgt_t *t, uintptr_t addr, size_t len, uint_t wflags,
4297     int spec_flags, mdb_tgt_se_f *func, void *data)
4298 {
4299 	prwatch_t *wp = mdb_alloc(sizeof (prwatch_t), UM_SLEEP);
4300 	mdb_sespec_t *sep;
4301 
4302 	wp->pr_vaddr = addr;
4303 	wp->pr_size = len;
4304 	wp->pr_wflags = 0;
4305 
4306 	if (wflags & MDB_TGT_WA_R)
4307 		wp->pr_wflags |= WA_READ;
4308 	if (wflags & MDB_TGT_WA_W)
4309 		wp->pr_wflags |= WA_WRITE;
4310 	if (wflags & MDB_TGT_WA_X)
4311 		wp->pr_wflags |= WA_EXEC;
4312 
4313 	for (sep = mdb_list_next(&t->t_active); sep; sep = mdb_list_next(sep)) {
4314 		if (sep->se_ops == &proc_wapt_ops &&
4315 		    mdb_list_next(&sep->se_velist) != NULL &&
4316 		    pt_wparg_overlap(wp, sep->se_data))
4317 			goto dup;
4318 	}
4319 
4320 	for (sep = mdb_list_next(&t->t_idle); sep; sep = mdb_list_next(sep)) {
4321 		if (sep->se_ops == &proc_wapt_ops && pt_wparg_overlap(wp,
4322 		    ((mdb_vespec_t *)mdb_list_next(&sep->se_velist))->ve_args))
4323 			goto dup;
4324 	}
4325 
4326 	return (mdb_tgt_vespec_insert(t, &proc_wapt_ops, spec_flags,
4327 	    func, data, wp, pt_wparg_dtor));
4328 
4329 dup:
4330 	mdb_free(wp, sizeof (prwatch_t));
4331 	(void) set_errno(EMDB_WPDUP);
4332 	return (0);
4333 }
4334 
4335 static int
4336 pt_add_sysenter(mdb_tgt_t *t, int sysnum,
4337     int spec_flags, mdb_tgt_se_f *func, void *data)
4338 {
4339 	if (sysnum <= 0 || sysnum > PRMAXSYS) {
4340 		(void) set_errno(EMDB_BADSYSNUM);
4341 		return (0);
4342 	}
4343 
4344 	return (mdb_tgt_vespec_insert(t, &proc_sysenter_ops, spec_flags,
4345 	    func, data, (void *)(uintptr_t)sysnum, no_ve_dtor));
4346 }
4347 
4348 static int
4349 pt_add_sysexit(mdb_tgt_t *t, int sysnum,
4350     int spec_flags, mdb_tgt_se_f *func, void *data)
4351 {
4352 	if (sysnum <= 0 || sysnum > PRMAXSYS) {
4353 		(void) set_errno(EMDB_BADSYSNUM);
4354 		return (0);
4355 	}
4356 
4357 	return (mdb_tgt_vespec_insert(t, &proc_sysexit_ops, spec_flags,
4358 	    func, data, (void *)(uintptr_t)sysnum, no_ve_dtor));
4359 }
4360 
4361 static int
4362 pt_add_signal(mdb_tgt_t *t, int signum,
4363     int spec_flags, mdb_tgt_se_f *func, void *data)
4364 {
4365 	pt_data_t *pt = t->t_data;
4366 
4367 	if (signum <= 0 || signum > pt->p_maxsig) {
4368 		(void) set_errno(EMDB_BADSIGNUM);
4369 		return (0);
4370 	}
4371 
4372 	return (mdb_tgt_vespec_insert(t, &proc_signal_ops, spec_flags,
4373 	    func, data, (void *)(uintptr_t)signum, no_ve_dtor));
4374 }
4375 
4376 static int
4377 pt_add_fault(mdb_tgt_t *t, int fltnum,
4378     int spec_flags, mdb_tgt_se_f *func, void *data)
4379 {
4380 	if (fltnum <= 0 || fltnum > PRMAXFAULT) {
4381 		(void) set_errno(EMDB_BADFLTNUM);
4382 		return (0);
4383 	}
4384 
4385 	return (mdb_tgt_vespec_insert(t, &proc_fault_ops, spec_flags,
4386 	    func, data, (void *)(uintptr_t)fltnum, no_ve_dtor));
4387 }
4388 
4389 static int
4390 pt_getareg(mdb_tgt_t *t, mdb_tgt_tid_t tid,
4391     const char *rname, mdb_tgt_reg_t *rp)
4392 {
4393 	pt_data_t *pt = t->t_data;
4394 	prgregset_t grs;
4395 	mdb_var_t *v;
4396 
4397 	if (t->t_pshandle == NULL)
4398 		return (set_errno(EMDB_NOPROC));
4399 
4400 	if ((v = mdb_nv_lookup(&pt->p_regs, rname)) != NULL) {
4401 		uintmax_t rd_nval = mdb_nv_get_value(v);
4402 		ushort_t rd_num = MDB_TGT_R_NUM(rd_nval);
4403 		ushort_t rd_flags = MDB_TGT_R_FLAGS(rd_nval);
4404 
4405 		if (!MDB_TGT_R_IS_FP(rd_flags)) {
4406 			mdb_tgt_reg_t r = 0;
4407 
4408 #if defined(__sparc) && defined(_ILP32)
4409 			/*
4410 			 * If we are debugging on 32-bit SPARC, the globals and
4411 			 * outs can have 32 upper bits hiding in the xregs.
4412 			 */
4413 			/* gcc doesn't like >= R_G0 because R_G0 == 0 */
4414 			int is_g = (rd_num == R_G0 ||
4415 			    rd_num >= R_G1 && rd_num <= R_G7);
4416 			int is_o = (rd_num >= R_O0 && rd_num <= R_O7);
4417 			prxregset_t xrs;
4418 
4419 			if (is_g && PTL_GETXREGS(t, tid, &xrs) == 0 &&
4420 			    xrs.pr_type == XR_TYPE_V8P) {
4421 				r |= (uint64_t)xrs.pr_un.pr_v8p.pr_xg[
4422 				    rd_num - R_G0 + XR_G0] << 32;
4423 			}
4424 
4425 			if (is_o && PTL_GETXREGS(t, tid, &xrs) == 0 &&
4426 			    xrs.pr_type == XR_TYPE_V8P) {
4427 				r |= (uint64_t)xrs.pr_un.pr_v8p.pr_xo[
4428 				    rd_num - R_O0 + XR_O0] << 32;
4429 			}
4430 #endif	/* __sparc && _ILP32 */
4431 
4432 			/*
4433 			 * Avoid sign-extension by casting: recall that procfs
4434 			 * defines prgreg_t as a long or int and our native
4435 			 * register handling uses uint64_t's.
4436 			 */
4437 			if (PTL_GETREGS(t, tid, grs) == 0) {
4438 				*rp = r | (ulong_t)grs[rd_num];
4439 				return (0);
4440 			}
4441 			return (-1);
4442 		} else
4443 			return (pt_getfpreg(t, tid, rd_num, rd_flags, rp));
4444 	}
4445 
4446 	return (set_errno(EMDB_BADREG));
4447 }
4448 
4449 static int
4450 pt_putareg(mdb_tgt_t *t, mdb_tgt_tid_t tid, const char *rname, mdb_tgt_reg_t r)
4451 {
4452 	pt_data_t *pt = t->t_data;
4453 	prgregset_t grs;
4454 	mdb_var_t *v;
4455 
4456 	if (t->t_pshandle == NULL)
4457 		return (set_errno(EMDB_NOPROC));
4458 
4459 	if ((v = mdb_nv_lookup(&pt->p_regs, rname)) != NULL) {
4460 		uintmax_t rd_nval = mdb_nv_get_value(v);
4461 		ushort_t rd_num = MDB_TGT_R_NUM(rd_nval);
4462 		ushort_t rd_flags = MDB_TGT_R_FLAGS(rd_nval);
4463 
4464 		if (!MDB_TGT_R_IS_FP(rd_flags)) {
4465 #if defined(__sparc) && defined(_ILP32)
4466 			/*
4467 			 * If we are debugging on 32-bit SPARC, the globals and
4468 			 * outs can have 32 upper bits stored in the xregs.
4469 			 */
4470 			int is_g = (rd_num == R_G0 ||
4471 			    rd_num >= R_G1 && rd_num <= R_G7);
4472 			int is_o = (rd_num >= R_O0 && rd_num <= R_O7);
4473 			prxregset_t xrs;
4474 
4475 			if ((is_g || is_o) && PTL_GETXREGS(t, tid, &xrs) == 0 &&
4476 			    xrs.pr_type == XR_TYPE_V8P) {
4477 				if (is_g) {
4478 					xrs.pr_un.pr_v8p.pr_xg[rd_num -
4479 					    R_G0 + XR_G0] = (uint32_t)(r >> 32);
4480 				} else if (is_o) {
4481 					xrs.pr_un.pr_v8p.pr_xo[rd_num -
4482 					    R_O0 + XR_O0] = (uint32_t)(r >> 32);
4483 				}
4484 
4485 				if (PTL_SETXREGS(t, tid, &xrs) == -1)
4486 					return (-1);
4487 			}
4488 #endif	/* __sparc && _ILP32 */
4489 
4490 			if (PTL_GETREGS(t, tid, grs) == 0) {
4491 				grs[rd_num] = (prgreg_t)r;
4492 				return (PTL_SETREGS(t, tid, grs));
4493 			}
4494 			return (-1);
4495 		} else
4496 			return (pt_putfpreg(t, tid, rd_num, rd_flags, r));
4497 	}
4498 
4499 	return (set_errno(EMDB_BADREG));
4500 }
4501 
4502 static int
4503 pt_stack_call(pt_stkarg_t *psp, const prgregset_t grs, uint_t argc, long *argv)
4504 {
4505 	psp->pstk_gotpc |= (grs[R_PC] != 0);
4506 
4507 	if (!psp->pstk_gotpc)
4508 		return (0); /* skip initial zeroed frames */
4509 
4510 	return (psp->pstk_func(psp->pstk_private, grs[R_PC],
4511 	    argc, argv, (const struct mdb_tgt_gregset *)grs));
4512 }
4513 
4514 static int
4515 pt_stack_iter(mdb_tgt_t *t, const mdb_tgt_gregset_t *gsp,
4516     mdb_tgt_stack_f *func, void *arg)
4517 {
4518 	if (t->t_pshandle != NULL) {
4519 		pt_stkarg_t pstk;
4520 
4521 		pstk.pstk_func = func;
4522 		pstk.pstk_private = arg;
4523 		pstk.pstk_gotpc = FALSE;
4524 
4525 		(void) Pstack_iter(t->t_pshandle, gsp->gregs,
4526 		    (proc_stack_f *)pt_stack_call, &pstk);
4527 
4528 		return (0);
4529 	}
4530 
4531 	return (set_errno(EMDB_NOPROC));
4532 }
4533 
4534 static int
4535 pt_auxv(mdb_tgt_t *t, const auxv_t **auxvp)
4536 {
4537 	if (t->t_pshandle != NULL) {
4538 		*auxvp = Pgetauxvec(t->t_pshandle);
4539 		return (0);
4540 	}
4541 
4542 	return (set_errno(EMDB_NOPROC));
4543 }
4544 
4545 
4546 static const mdb_tgt_ops_t proc_ops = {
4547 	pt_setflags,				/* t_setflags */
4548 	(int (*)()) mdb_tgt_notsup,		/* t_setcontext */
4549 	pt_activate,				/* t_activate */
4550 	pt_deactivate,				/* t_deactivate */
4551 	pt_periodic,				/* t_periodic */
4552 	pt_destroy,				/* t_destroy */
4553 	pt_name,				/* t_name */
4554 	(const char *(*)()) mdb_conf_isa,	/* t_isa */
4555 	pt_platform,				/* t_platform */
4556 	pt_uname,				/* t_uname */
4557 	pt_dmodel,				/* t_dmodel */
4558 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_aread */
4559 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_awrite */
4560 	pt_vread,				/* t_vread */
4561 	pt_vwrite,				/* t_vwrite */
4562 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_pread */
4563 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_pwrite */
4564 	pt_fread,				/* t_fread */
4565 	pt_fwrite,				/* t_fwrite */
4566 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_ioread */
4567 	(ssize_t (*)()) mdb_tgt_notsup,		/* t_iowrite */
4568 	(int (*)()) mdb_tgt_notsup,		/* t_vtop */
4569 	pt_lookup_by_name,			/* t_lookup_by_name */
4570 	pt_lookup_by_addr,			/* t_lookup_by_addr */
4571 	pt_symbol_iter,				/* t_symbol_iter */
4572 	pt_mapping_iter,			/* t_mapping_iter */
4573 	pt_object_iter,				/* t_object_iter */
4574 	pt_addr_to_map,				/* t_addr_to_map */
4575 	pt_name_to_map,				/* t_name_to_map */
4576 	pt_addr_to_ctf,				/* t_addr_to_ctf */
4577 	pt_name_to_ctf,				/* t_name_to_ctf */
4578 	pt_status,				/* t_status */
4579 	pt_run,					/* t_run */
4580 	pt_step,				/* t_step */
4581 	pt_step_out,				/* t_step_out */
4582 	(int (*)()) mdb_tgt_notsup,		/* t_step_branch */
4583 	pt_next,				/* t_next */
4584 	pt_continue,				/* t_cont */
4585 	pt_signal,				/* t_signal */
4586 	pt_add_vbrkpt,				/* t_add_vbrkpt */
4587 	pt_add_sbrkpt,				/* t_add_sbrkpt */
4588 	(int (*)()) mdb_tgt_null,		/* t_add_pwapt */
4589 	pt_add_vwapt,				/* t_add_vwapt */
4590 	(int (*)()) mdb_tgt_null,		/* t_add_iowapt */
4591 	pt_add_sysenter,			/* t_add_sysenter */
4592 	pt_add_sysexit,				/* t_add_sysexit */
4593 	pt_add_signal,				/* t_add_signal */
4594 	pt_add_fault,				/* t_add_fault */
4595 	pt_getareg,				/* t_getareg */
4596 	pt_putareg,				/* t_putareg */
4597 	pt_stack_iter,				/* t_stack_iter */
4598 	pt_auxv					/* t_auxv */
4599 };
4600 
4601 /*
4602  * Utility function for converting libproc errno values to mdb error values
4603  * for the ptl calls below.  Currently, we only need to convert ENOENT to
4604  * EMDB_NOTHREAD to produce a more useful error message for the user.
4605  */
4606 static int
4607 ptl_err(int error)
4608 {
4609 	if (error != 0 && errno == ENOENT)
4610 		return (set_errno(EMDB_NOTHREAD));
4611 
4612 	return (error);
4613 }
4614 
4615 /*ARGSUSED*/
4616 static mdb_tgt_tid_t
4617 pt_lwp_tid(mdb_tgt_t *t, void *tap)
4618 {
4619 	if (t->t_pshandle != NULL)
4620 		return (Pstatus(t->t_pshandle)->pr_lwp.pr_lwpid);
4621 
4622 	return (set_errno(EMDB_NOPROC));
4623 }
4624 
4625 static int
4626 pt_lwp_add(mdb_addrvec_t *ap, const lwpstatus_t *psp)
4627 {
4628 	mdb_addrvec_unshift(ap, psp->pr_lwpid);
4629 	return (0);
4630 }
4631 
4632 /*ARGSUSED*/
4633 static int
4634 pt_lwp_iter(mdb_tgt_t *t, void *tap, mdb_addrvec_t *ap)
4635 {
4636 	if (t->t_pshandle != NULL)
4637 		return (Plwp_iter(t->t_pshandle, (proc_lwp_f *)pt_lwp_add, ap));
4638 
4639 	return (set_errno(EMDB_NOPROC));
4640 }
4641 
4642 /*ARGSUSED*/
4643 static int
4644 pt_lwp_getregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prgregset_t gregs)
4645 {
4646 	if (t->t_pshandle != NULL) {
4647 		return (ptl_err(Plwp_getregs(t->t_pshandle,
4648 		    (lwpid_t)tid, gregs)));
4649 	}
4650 	return (set_errno(EMDB_NOPROC));
4651 }
4652 
4653 /*ARGSUSED*/
4654 static int
4655 pt_lwp_setregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prgregset_t gregs)
4656 {
4657 	if (t->t_pshandle != NULL) {
4658 		return (ptl_err(Plwp_setregs(t->t_pshandle,
4659 		    (lwpid_t)tid, gregs)));
4660 	}
4661 	return (set_errno(EMDB_NOPROC));
4662 }
4663 
4664 #ifdef	__sparc
4665 
4666 /*ARGSUSED*/
4667 static int
4668 pt_lwp_getxregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prxregset_t *xregs)
4669 {
4670 	if (t->t_pshandle != NULL) {
4671 		return (ptl_err(Plwp_getxregs(t->t_pshandle,
4672 		    (lwpid_t)tid, xregs)));
4673 	}
4674 	return (set_errno(EMDB_NOPROC));
4675 }
4676 
4677 /*ARGSUSED*/
4678 static int
4679 pt_lwp_setxregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4680     const prxregset_t *xregs)
4681 {
4682 	if (t->t_pshandle != NULL) {
4683 		return (ptl_err(Plwp_setxregs(t->t_pshandle,
4684 		    (lwpid_t)tid, xregs)));
4685 	}
4686 	return (set_errno(EMDB_NOPROC));
4687 }
4688 
4689 #endif	/* __sparc */
4690 
4691 /*ARGSUSED*/
4692 static int
4693 pt_lwp_getfpregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4694     prfpregset_t *fpregs)
4695 {
4696 	if (t->t_pshandle != NULL) {
4697 		return (ptl_err(Plwp_getfpregs(t->t_pshandle,
4698 		    (lwpid_t)tid, fpregs)));
4699 	}
4700 	return (set_errno(EMDB_NOPROC));
4701 }
4702 
4703 /*ARGSUSED*/
4704 static int
4705 pt_lwp_setfpregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4706     const prfpregset_t *fpregs)
4707 {
4708 	if (t->t_pshandle != NULL) {
4709 		return (ptl_err(Plwp_setfpregs(t->t_pshandle,
4710 		    (lwpid_t)tid, fpregs)));
4711 	}
4712 	return (set_errno(EMDB_NOPROC));
4713 }
4714 
4715 static const pt_ptl_ops_t proc_lwp_ops = {
4716 	(int (*)()) mdb_tgt_nop,
4717 	(void (*)()) mdb_tgt_nop,
4718 	pt_lwp_tid,
4719 	pt_lwp_iter,
4720 	pt_lwp_getregs,
4721 	pt_lwp_setregs,
4722 #ifdef __sparc
4723 	pt_lwp_getxregs,
4724 	pt_lwp_setxregs,
4725 #endif
4726 	pt_lwp_getfpregs,
4727 	pt_lwp_setfpregs
4728 };
4729 
4730 static int
4731 pt_tdb_ctor(mdb_tgt_t *t)
4732 {
4733 	pt_data_t *pt = t->t_data;
4734 	td_thragent_t *tap;
4735 	td_err_e err;
4736 
4737 	if ((err = pt->p_tdb_ops->td_ta_new(t->t_pshandle, &tap)) != TD_OK)
4738 		return (set_errno(tdb_to_errno(err)));
4739 
4740 	pt->p_ptl_hdl = tap;
4741 	return (0);
4742 }
4743 
4744 static void
4745 pt_tdb_dtor(mdb_tgt_t *t, void *tap)
4746 {
4747 	pt_data_t *pt = t->t_data;
4748 
4749 	ASSERT(tap == pt->p_ptl_hdl);
4750 	(void) pt->p_tdb_ops->td_ta_delete(tap);
4751 	pt->p_ptl_hdl = NULL;
4752 }
4753 
4754 static mdb_tgt_tid_t
4755 pt_tdb_tid(mdb_tgt_t *t, void *tap)
4756 {
4757 	pt_data_t *pt = t->t_data;
4758 
4759 	td_thrhandle_t th;
4760 	td_thrinfo_t ti;
4761 	td_err_e err;
4762 
4763 	if (t->t_pshandle == NULL)
4764 		return (set_errno(EMDB_NOPROC));
4765 
4766 	if ((err = pt->p_tdb_ops->td_ta_map_lwp2thr(tap,
4767 	    Pstatus(t->t_pshandle)->pr_lwp.pr_lwpid, &th)) != TD_OK)
4768 		return (set_errno(tdb_to_errno(err)));
4769 
4770 	if ((err = pt->p_tdb_ops->td_thr_get_info(&th, &ti)) != TD_OK)
4771 		return (set_errno(tdb_to_errno(err)));
4772 
4773 	return (ti.ti_tid);
4774 }
4775 
4776 static int
4777 pt_tdb_add(const td_thrhandle_t *thp, pt_addarg_t *pap)
4778 {
4779 	td_thrinfo_t ti;
4780 
4781 	if (pap->pa_pt->p_tdb_ops->td_thr_get_info(thp, &ti) == TD_OK &&
4782 	    ti.ti_state != TD_THR_ZOMBIE)
4783 		mdb_addrvec_unshift(pap->pa_ap, ti.ti_tid);
4784 
4785 	return (0);
4786 }
4787 
4788 static int
4789 pt_tdb_iter(mdb_tgt_t *t, void *tap, mdb_addrvec_t *ap)
4790 {
4791 	pt_data_t *pt = t->t_data;
4792 	pt_addarg_t arg;
4793 	int err;
4794 
4795 	if (t->t_pshandle == NULL)
4796 		return (set_errno(EMDB_NOPROC));
4797 
4798 	arg.pa_pt = pt;
4799 	arg.pa_ap = ap;
4800 
4801 	if ((err = pt->p_tdb_ops->td_ta_thr_iter(tap, (td_thr_iter_f *)
4802 	    pt_tdb_add, &arg, TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
4803 	    TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS)) != TD_OK)
4804 		return (set_errno(tdb_to_errno(err)));
4805 
4806 	return (0);
4807 }
4808 
4809 static int
4810 pt_tdb_getregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prgregset_t gregs)
4811 {
4812 	pt_data_t *pt = t->t_data;
4813 
4814 	td_thrhandle_t th;
4815 	td_err_e err;
4816 
4817 	if (t->t_pshandle == NULL)
4818 		return (set_errno(EMDB_NOPROC));
4819 
4820 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
4821 		return (set_errno(tdb_to_errno(err)));
4822 
4823 	err = pt->p_tdb_ops->td_thr_getgregs(&th, gregs);
4824 	if (err != TD_OK && err != TD_PARTIALREG)
4825 		return (set_errno(tdb_to_errno(err)));
4826 
4827 	return (0);
4828 }
4829 
4830 static int
4831 pt_tdb_setregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prgregset_t gregs)
4832 {
4833 	pt_data_t *pt = t->t_data;
4834 
4835 	td_thrhandle_t th;
4836 	td_err_e err;
4837 
4838 	if (t->t_pshandle == NULL)
4839 		return (set_errno(EMDB_NOPROC));
4840 
4841 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
4842 		return (set_errno(tdb_to_errno(err)));
4843 
4844 	err = pt->p_tdb_ops->td_thr_setgregs(&th, gregs);
4845 	if (err != TD_OK && err != TD_PARTIALREG)
4846 		return (set_errno(tdb_to_errno(err)));
4847 
4848 	return (0);
4849 }
4850 
4851 #ifdef __sparc
4852 
4853 static int
4854 pt_tdb_getxregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid, prxregset_t *xregs)
4855 {
4856 	pt_data_t *pt = t->t_data;
4857 
4858 	td_thrhandle_t th;
4859 	td_err_e err;
4860 
4861 	if (t->t_pshandle == NULL)
4862 		return (set_errno(EMDB_NOPROC));
4863 
4864 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
4865 		return (set_errno(tdb_to_errno(err)));
4866 
4867 	err = pt->p_tdb_ops->td_thr_getxregs(&th, xregs);
4868 	if (err != TD_OK && err != TD_PARTIALREG)
4869 		return (set_errno(tdb_to_errno(err)));
4870 
4871 	return (0);
4872 }
4873 
4874 static int
4875 pt_tdb_setxregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4876     const prxregset_t *xregs)
4877 {
4878 	pt_data_t *pt = t->t_data;
4879 
4880 	td_thrhandle_t th;
4881 	td_err_e err;
4882 
4883 	if (t->t_pshandle == NULL)
4884 		return (set_errno(EMDB_NOPROC));
4885 
4886 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
4887 		return (set_errno(tdb_to_errno(err)));
4888 
4889 	err = pt->p_tdb_ops->td_thr_setxregs(&th, xregs);
4890 	if (err != TD_OK && err != TD_PARTIALREG)
4891 		return (set_errno(tdb_to_errno(err)));
4892 
4893 	return (0);
4894 }
4895 
4896 #endif	/* __sparc */
4897 
4898 static int
4899 pt_tdb_getfpregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4900     prfpregset_t *fpregs)
4901 {
4902 	pt_data_t *pt = t->t_data;
4903 
4904 	td_thrhandle_t th;
4905 	td_err_e err;
4906 
4907 	if (t->t_pshandle == NULL)
4908 		return (set_errno(EMDB_NOPROC));
4909 
4910 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
4911 		return (set_errno(tdb_to_errno(err)));
4912 
4913 	err = pt->p_tdb_ops->td_thr_getfpregs(&th, fpregs);
4914 	if (err != TD_OK && err != TD_PARTIALREG)
4915 		return (set_errno(tdb_to_errno(err)));
4916 
4917 	return (0);
4918 }
4919 
4920 static int
4921 pt_tdb_setfpregs(mdb_tgt_t *t, void *tap, mdb_tgt_tid_t tid,
4922     const prfpregset_t *fpregs)
4923 {
4924 	pt_data_t *pt = t->t_data;
4925 
4926 	td_thrhandle_t th;
4927 	td_err_e err;
4928 
4929 	if (t->t_pshandle == NULL)
4930 		return (set_errno(EMDB_NOPROC));
4931 
4932 	if ((err = pt->p_tdb_ops->td_ta_map_id2thr(tap, tid, &th)) != TD_OK)
4933 		return (set_errno(tdb_to_errno(err)));
4934 
4935 	err = pt->p_tdb_ops->td_thr_setfpregs(&th, fpregs);
4936 	if (err != TD_OK && err != TD_PARTIALREG)
4937 		return (set_errno(tdb_to_errno(err)));
4938 
4939 	return (0);
4940 }
4941 
4942 static const pt_ptl_ops_t proc_tdb_ops = {
4943 	pt_tdb_ctor,
4944 	pt_tdb_dtor,
4945 	pt_tdb_tid,
4946 	pt_tdb_iter,
4947 	pt_tdb_getregs,
4948 	pt_tdb_setregs,
4949 #ifdef __sparc
4950 	pt_tdb_getxregs,
4951 	pt_tdb_setxregs,
4952 #endif
4953 	pt_tdb_getfpregs,
4954 	pt_tdb_setfpregs
4955 };
4956 
4957 static ssize_t
4958 pt_xd_auxv(mdb_tgt_t *t, void *buf, size_t nbytes)
4959 {
4960 	struct ps_prochandle *P = t->t_pshandle;
4961 	const auxv_t *auxp, *auxv = NULL;
4962 	int auxn = 0;
4963 
4964 	if (P != NULL && (auxv = Pgetauxvec(P)) != NULL &&
4965 	    auxv->a_type != AT_NULL) {
4966 		for (auxp = auxv, auxn = 1; auxp->a_type != NULL; auxp++)
4967 			auxn++;
4968 	}
4969 
4970 	if (buf == NULL && nbytes == 0)
4971 		return (sizeof (auxv_t) * auxn);
4972 
4973 	if (auxn == 0)
4974 		return (set_errno(ENODATA));
4975 
4976 	nbytes = MIN(nbytes, sizeof (auxv_t) * auxn);
4977 	bcopy(auxv, buf, nbytes);
4978 	return (nbytes);
4979 }
4980 
4981 static ssize_t
4982 pt_xd_cred(mdb_tgt_t *t, void *buf, size_t nbytes)
4983 {
4984 	prcred_t cr, *crp;
4985 	size_t cbytes = 0;
4986 
4987 	if (t->t_pshandle != NULL && Pcred(t->t_pshandle, &cr, 1) == 0) {
4988 		cbytes = (cr.pr_ngroups <= 1) ? sizeof (prcred_t) :
4989 		    (sizeof (prcred_t) + (cr.pr_ngroups - 1) * sizeof (gid_t));
4990 	}
4991 
4992 	if (buf == NULL && nbytes == 0)
4993 		return (cbytes);
4994 
4995 	if (cbytes == 0)
4996 		return (set_errno(ENODATA));
4997 
4998 	crp = mdb_alloc(cbytes, UM_SLEEP);
4999 
5000 	if (Pcred(t->t_pshandle, crp, cr.pr_ngroups) == -1)
5001 		return (set_errno(ENODATA));
5002 
5003 	nbytes = MIN(nbytes, cbytes);
5004 	bcopy(crp, buf, nbytes);
5005 	mdb_free(crp, cbytes);
5006 	return (nbytes);
5007 }
5008 
5009 static ssize_t
5010 pt_xd_ehdr(mdb_tgt_t *t, void *buf, size_t nbytes)
5011 {
5012 	pt_data_t *pt = t->t_data;
5013 
5014 	if (buf == NULL && nbytes == 0)
5015 		return (sizeof (GElf_Ehdr));
5016 
5017 	if (pt->p_file == NULL)
5018 		return (set_errno(ENODATA));
5019 
5020 	nbytes = MIN(nbytes, sizeof (GElf_Ehdr));
5021 	bcopy(&pt->p_file->gf_ehdr, buf, nbytes);
5022 	return (nbytes);
5023 }
5024 
5025 static int
5026 pt_copy_lwp(lwpstatus_t **lspp, const lwpstatus_t *lsp)
5027 {
5028 	bcopy(lsp, *lspp, sizeof (lwpstatus_t));
5029 	(*lspp)++;
5030 	return (0);
5031 }
5032 
5033 static ssize_t
5034 pt_xd_lwpstatus(mdb_tgt_t *t, void *buf, size_t nbytes)
5035 {
5036 	lwpstatus_t *lsp, *lbuf;
5037 	const pstatus_t *psp;
5038 	int nlwp = 0;
5039 
5040 	if (t->t_pshandle != NULL && (psp = Pstatus(t->t_pshandle)) != NULL)
5041 		nlwp = psp->pr_nlwp;
5042 
5043 	if (buf == NULL && nbytes == 0)
5044 		return (sizeof (lwpstatus_t) * nlwp);
5045 
5046 	if (nlwp == 0)
5047 		return (set_errno(ENODATA));
5048 
5049 	lsp = lbuf = mdb_alloc(sizeof (lwpstatus_t) * nlwp, UM_SLEEP);
5050 	nbytes = MIN(nbytes, sizeof (lwpstatus_t) * nlwp);
5051 
5052 	(void) Plwp_iter(t->t_pshandle, (proc_lwp_f *)pt_copy_lwp, &lsp);
5053 	bcopy(lbuf, buf, nbytes);
5054 
5055 	mdb_free(lbuf, sizeof (lwpstatus_t) * nlwp);
5056 	return (nbytes);
5057 }
5058 
5059 static ssize_t
5060 pt_xd_pshandle(mdb_tgt_t *t, void *buf, size_t nbytes)
5061 {
5062 	if (buf == NULL && nbytes == 0)
5063 		return (sizeof (struct ps_prochandle *));
5064 
5065 	if (t->t_pshandle == NULL || nbytes != sizeof (struct ps_prochandle *))
5066 		return (set_errno(ENODATA));
5067 
5068 	bcopy(&t->t_pshandle, buf, nbytes);
5069 	return (nbytes);
5070 }
5071 
5072 static ssize_t
5073 pt_xd_psinfo(mdb_tgt_t *t, void *buf, size_t nbytes)
5074 {
5075 	const psinfo_t *psp;
5076 
5077 	if (buf == NULL && nbytes == 0)
5078 		return (sizeof (psinfo_t));
5079 
5080 	if (t->t_pshandle == NULL || (psp = Ppsinfo(t->t_pshandle)) == NULL)
5081 		return (set_errno(ENODATA));
5082 
5083 	nbytes = MIN(nbytes, sizeof (psinfo_t));
5084 	bcopy(psp, buf, nbytes);
5085 	return (nbytes);
5086 }
5087 
5088 static ssize_t
5089 pt_xd_pstatus(mdb_tgt_t *t, void *buf, size_t nbytes)
5090 {
5091 	const pstatus_t *psp;
5092 
5093 	if (buf == NULL && nbytes == 0)
5094 		return (sizeof (pstatus_t));
5095 
5096 	if (t->t_pshandle == NULL || (psp = Pstatus(t->t_pshandle)) == NULL)
5097 		return (set_errno(ENODATA));
5098 
5099 	nbytes = MIN(nbytes, sizeof (pstatus_t));
5100 	bcopy(psp, buf, nbytes);
5101 	return (nbytes);
5102 }
5103 
5104 static ssize_t
5105 pt_xd_utsname(mdb_tgt_t *t, void *buf, size_t nbytes)
5106 {
5107 	struct utsname uts;
5108 
5109 	if (buf == NULL && nbytes == 0)
5110 		return (sizeof (struct utsname));
5111 
5112 	if (t->t_pshandle == NULL || Puname(t->t_pshandle, &uts) != 0)
5113 		return (set_errno(ENODATA));
5114 
5115 	nbytes = MIN(nbytes, sizeof (struct utsname));
5116 	bcopy(&uts, buf, nbytes);
5117 	return (nbytes);
5118 }
5119 
5120 int
5121 mdb_proc_tgt_create(mdb_tgt_t *t, int argc, const char *argv[])
5122 {
5123 	pt_data_t *pt = mdb_zalloc(sizeof (pt_data_t), UM_SLEEP);
5124 
5125 	const char *aout_path = argc > 0 ? argv[0] : PT_EXEC_PATH;
5126 	const char *core_path = argc > 1 ? argv[1] : NULL;
5127 
5128 	const mdb_tgt_regdesc_t *rdp;
5129 	char execname[MAXPATHLEN];
5130 	struct stat64 st;
5131 	int perr;
5132 	int state;
5133 	struct rlimit rlim;
5134 	int i;
5135 
5136 	if (argc > 2) {
5137 		mdb_free(pt, sizeof (pt_data_t));
5138 		return (set_errno(EINVAL));
5139 	}
5140 
5141 	if (t->t_flags & MDB_TGT_F_RDWR)
5142 		pt->p_oflags = O_RDWR;
5143 	else
5144 		pt->p_oflags = O_RDONLY;
5145 
5146 	if (t->t_flags & MDB_TGT_F_FORCE)
5147 		pt->p_gflags |= PGRAB_FORCE;
5148 	if (t->t_flags & MDB_TGT_F_NOSTOP)
5149 		pt->p_gflags |= PGRAB_NOSTOP;
5150 
5151 	pt->p_ptl_ops = &proc_lwp_ops;
5152 	pt->p_maxsig = sysconf(_SC_SIGRT_MAX);
5153 
5154 	(void) mdb_nv_create(&pt->p_regs, UM_SLEEP);
5155 	(void) mdb_nv_create(&pt->p_env, UM_SLEEP);
5156 
5157 	t->t_ops = &proc_ops;
5158 	t->t_data = pt;
5159 
5160 	/*
5161 	 * If no core file name was specified, but the file ./core is present,
5162 	 * infer that we want to debug it.  I find this behavior confusing,
5163 	 * so we only do this when precise adb(1) compatibility is required.
5164 	 */
5165 	if (core_path == NULL && (mdb.m_flags & MDB_FL_ADB) &&
5166 	    access(PT_CORE_PATH, F_OK) == 0)
5167 		core_path = PT_CORE_PATH;
5168 
5169 	/*
5170 	 * For compatibility with adb(1), the special name "-" may be used
5171 	 * to suppress the loading of the executable or core file.
5172 	 */
5173 	if (aout_path != NULL && strcmp(aout_path, "-") == 0)
5174 		aout_path = NULL;
5175 	if (core_path != NULL && strcmp(core_path, "-") == 0)
5176 		core_path = NULL;
5177 
5178 	/*
5179 	 * If a core file or pid was specified, attempt to grab it now using
5180 	 * proc_arg_grab(); otherwise we'll create a fresh process later.
5181 	 */
5182 	if (core_path != NULL && (t->t_pshandle = proc_arg_xgrab(core_path,
5183 	    aout_path == PT_EXEC_PATH ? NULL : aout_path, PR_ARG_ANY,
5184 	    pt->p_gflags, &perr, NULL)) == NULL) {
5185 		mdb_warn("cannot debug %s: %s\n", core_path, Pgrab_error(perr));
5186 		goto err;
5187 	}
5188 
5189 	if (aout_path != NULL &&
5190 	    (pt->p_idlehandle = Pgrab_file(aout_path, &perr)) != NULL &&
5191 	    t->t_pshandle == NULL)
5192 		t->t_pshandle = pt->p_idlehandle;
5193 
5194 	if (t->t_pshandle != NULL)
5195 		state = Pstate(t->t_pshandle);
5196 
5197 	/*
5198 	 * Make sure we'll have enough file descriptors to handle a target
5199 	 * has many many mappings.
5200 	 */
5201 	if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
5202 		rlim.rlim_cur = rlim.rlim_max;
5203 		(void) setrlimit(RLIMIT_NOFILE, &rlim);
5204 		(void) enable_extended_FILE_stdio(-1, -1);
5205 	}
5206 
5207 	/*
5208 	 * If we don't have an executable path or the executable path is the
5209 	 * /proc/<pid>/object/a.out path, but we now have a libproc handle,
5210 	 * attempt to derive the executable path using Pexecname().  We need
5211 	 * to do this in the /proc case in order to open the executable for
5212 	 * writing because /proc/object/<file> permission are masked with 0555.
5213 	 * If Pexecname() fails us, fall back to /proc/<pid>/object/a.out.
5214 	 */
5215 	if (t->t_pshandle != NULL && (aout_path == NULL || (stat64(aout_path,
5216 	    &st) == 0 && strcmp(st.st_fstype, "proc") == 0))) {
5217 		GElf_Sym s;
5218 		aout_path = Pexecname(t->t_pshandle, execname, MAXPATHLEN);
5219 		if (aout_path == NULL && state != PS_DEAD && state != PS_IDLE) {
5220 			(void) mdb_iob_snprintf(execname, sizeof (execname),
5221 			    "/proc/%d/object/a.out",
5222 			    (int)Pstatus(t->t_pshandle)->pr_pid);
5223 			aout_path = execname;
5224 		}
5225 		if (aout_path == NULL &&
5226 		    Plookup_by_name(t->t_pshandle, "a.out", "_start", &s) != 0)
5227 			mdb_warn("warning: failed to infer pathname to "
5228 			    "executable; symbol table will not be available\n");
5229 
5230 		mdb_dprintf(MDB_DBG_TGT, "a.out is %s\n", aout_path);
5231 	}
5232 
5233 	/*
5234 	 * Attempt to open the executable file.  We only want this operation
5235 	 * to actually cause the constructor to abort if the executable file
5236 	 * name was given explicitly.  If we defaulted to PT_EXEC_PATH or
5237 	 * derived the executable using Pexecname, then we want to continue
5238 	 * along with p_fio and p_file set to NULL.
5239 	 */
5240 	if (aout_path != NULL && (pt->p_aout_fio = mdb_fdio_create_path(NULL,
5241 	    aout_path, pt->p_oflags, 0)) == NULL && argc > 0) {
5242 		mdb_warn("failed to open %s", aout_path);
5243 		goto err;
5244 	}
5245 
5246 	/*
5247 	 * Now create an ELF file from the input file, if we have one.  Again,
5248 	 * only abort the constructor if the name was given explicitly.
5249 	 */
5250 	if (pt->p_aout_fio != NULL && pt_open_aout(t,
5251 	    mdb_io_hold(pt->p_aout_fio)) == NULL && argc > 0)
5252 		goto err;
5253 
5254 	/*
5255 	 * If we've successfully opened an ELF file, select the appropriate
5256 	 * disassembler based on the ELF header.
5257 	 */
5258 	if (pt->p_file != NULL)
5259 		(void) mdb_dis_select(pt_disasm(&pt->p_file->gf_ehdr));
5260 	else
5261 		(void) mdb_dis_select(pt_disasm(NULL));
5262 
5263 	/*
5264 	 * Add each register described in the target ISA register description
5265 	 * list to our hash table of register descriptions and then add any
5266 	 * appropriate ISA-specific floating-point register descriptions.
5267 	 */
5268 	for (rdp = pt_regdesc; rdp->rd_name != NULL; rdp++) {
5269 		(void) mdb_nv_insert(&pt->p_regs, rdp->rd_name, NULL,
5270 		    MDB_TGT_R_NVAL(rdp->rd_num, rdp->rd_flags), MDB_NV_RDONLY);
5271 	}
5272 	pt_addfpregs(t);
5273 
5274 	/*
5275 	 * Certain important /proc structures may be of interest to mdb
5276 	 * modules and their dcmds.  Export these using the xdata interface:
5277 	 */
5278 	(void) mdb_tgt_xdata_insert(t, "auxv",
5279 	    "procfs auxv_t array", pt_xd_auxv);
5280 	(void) mdb_tgt_xdata_insert(t, "cred",
5281 	    "procfs prcred_t structure", pt_xd_cred);
5282 	(void) mdb_tgt_xdata_insert(t, "ehdr",
5283 	    "executable file GElf_Ehdr structure", pt_xd_ehdr);
5284 	(void) mdb_tgt_xdata_insert(t, "lwpstatus",
5285 	    "procfs lwpstatus_t array", pt_xd_lwpstatus);
5286 	(void) mdb_tgt_xdata_insert(t, "pshandle",
5287 	    "libproc proc service API handle", pt_xd_pshandle);
5288 	(void) mdb_tgt_xdata_insert(t, "psinfo",
5289 	    "procfs psinfo_t structure", pt_xd_psinfo);
5290 	(void) mdb_tgt_xdata_insert(t, "pstatus",
5291 	    "procfs pstatus_t structure", pt_xd_pstatus);
5292 	(void) mdb_tgt_xdata_insert(t, "utsname",
5293 	    "utsname structure", pt_xd_utsname);
5294 
5295 	/*
5296 	 * Force a status update now so that we fill in t_status with the
5297 	 * latest information based on any successful grab.
5298 	 */
5299 	(void) mdb_tgt_status(t, &t->t_status);
5300 
5301 	/*
5302 	 * If we're not examining a core file, trace SIGINT and all signals
5303 	 * that cause the process to dump core as part of our initialization.
5304 	 */
5305 	if ((t->t_pshandle != NULL && state != PS_DEAD && state != PS_IDLE) ||
5306 	    (pt->p_file != NULL && pt->p_file->gf_ehdr.e_type == ET_EXEC)) {
5307 
5308 		int tflag = MDB_TGT_SPEC_STICKY; /* default sigs are sticky */
5309 
5310 		(void) mdb_tgt_add_signal(t, SIGINT, tflag, no_se_f, NULL);
5311 		(void) mdb_tgt_add_signal(t, SIGQUIT, tflag, no_se_f, NULL);
5312 		(void) mdb_tgt_add_signal(t, SIGILL, tflag, no_se_f, NULL);
5313 		(void) mdb_tgt_add_signal(t, SIGTRAP, tflag, no_se_f, NULL);
5314 		(void) mdb_tgt_add_signal(t, SIGABRT, tflag, no_se_f, NULL);
5315 		(void) mdb_tgt_add_signal(t, SIGEMT, tflag, no_se_f, NULL);
5316 		(void) mdb_tgt_add_signal(t, SIGFPE, tflag, no_se_f, NULL);
5317 		(void) mdb_tgt_add_signal(t, SIGBUS, tflag, no_se_f, NULL);
5318 		(void) mdb_tgt_add_signal(t, SIGSEGV, tflag, no_se_f, NULL);
5319 		(void) mdb_tgt_add_signal(t, SIGSYS, tflag, no_se_f, NULL);
5320 		(void) mdb_tgt_add_signal(t, SIGXCPU, tflag, no_se_f, NULL);
5321 		(void) mdb_tgt_add_signal(t, SIGXFSZ, tflag, no_se_f, NULL);
5322 	}
5323 
5324 	/*
5325 	 * If we've grabbed a live process, establish our initial breakpoints
5326 	 * and librtld_db agent so we can track rtld activity.  If FL_VCREATE
5327 	 * is set, this process was created by a previous instantiation of
5328 	 * the debugger, so reset pr_flags to kill it; otherwise we attached
5329 	 * to an already running process.  Pgrab() has already set the PR_RLC
5330 	 * flag appropriately based on whether the process was stopped when we
5331 	 * attached.
5332 	 */
5333 	if (t->t_pshandle != NULL && state != PS_DEAD && state != PS_IDLE) {
5334 		if (mdb.m_flags & MDB_FL_VCREATE) {
5335 			(void) Punsetflags(t->t_pshandle, PR_RLC);
5336 			(void) Psetflags(t->t_pshandle, PR_KLC);
5337 			pt->p_rflags = PRELEASE_KILL;
5338 		} else {
5339 			(void) Punsetflags(t->t_pshandle, PR_KLC);
5340 		}
5341 		pt_post_attach(t);
5342 	}
5343 
5344 	/*
5345 	 * Initialize a local copy of the environment, which can be modified
5346 	 * before running the program.
5347 	 */
5348 	for (i = 0; mdb.m_env[i] != NULL; i++)
5349 		pt_env_set(pt, mdb.m_env[i]);
5350 
5351 	/*
5352 	 * If adb(1) compatibility mode is on, then print the appropriate
5353 	 * greeting message if we have grabbed a core file.
5354 	 */
5355 	if ((mdb.m_flags & MDB_FL_ADB) && t->t_pshandle != NULL &&
5356 	    state == PS_DEAD) {
5357 		const pstatus_t *psp = Pstatus(t->t_pshandle);
5358 		int cursig = psp->pr_lwp.pr_cursig;
5359 		char signame[SIG2STR_MAX];
5360 
5361 		mdb_printf("core file = %s -- program ``%s'' on platform %s\n",
5362 		    core_path, aout_path ? aout_path : "?", pt_platform(t));
5363 
5364 		if (cursig != 0 && sig2str(cursig, signame) == 0)
5365 			mdb_printf("SIG%s: %s\n", signame, strsignal(cursig));
5366 	}
5367 
5368 	return (0);
5369 
5370 err:
5371 	pt_destroy(t);
5372 	return (-1);
5373 }
5374