Home | History | Annotate | Download | only in mdb
      1 /*
      2  * CDDL HEADER START
      3  *
      4  * The contents of this file are subject to the terms of the
      5  * Common Development and Distribution License (the "License").
      6  * You may not use this file except in compliance with the License.
      7  *
      8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
      9  * or http://www.opensolaris.org/os/licensing.
     10  * See the License for the specific language governing permissions
     11  * and limitations under the License.
     12  *
     13  * When distributing Covered Code, include this CDDL HEADER in each
     14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
     15  * If applicable, add the following below this CDDL HEADER, with the
     16  * fields enclosed by brackets "[]" replaced with your own identifying
     17  * information: Portions Copyright [yyyy] [name of copyright owner]
     18  *
     19  * CDDL HEADER END
     20  */
     21 /*
     22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
     23  * Use is subject to license terms.
     24  */
     25 
     26 /*
     27  * User Process Target
     28  *
     29  * The user process target is invoked when the -u or -p command-line options
     30  * are used, or when an ELF executable file or ELF core file is specified on
     31  * the command-line.  This target is also selected by default when no target
     32  * options are present.  In this case, it defaults the executable name to
     33  * "a.out".  If no process or core file is currently attached, the target
     34  * functions as a kind of virtual /dev/zero (in accordance with adb(1)
     35  * semantics); reads from the virtual address space return zeroes and writes
     36  * fail silently.  The proc target itself is designed as a wrapper around the
     37  * services provided by libproc.so: t->t_pshandle is set to the struct
     38  * ps_prochandle pointer returned as a handle by libproc.  The target also
     39  * opens the executable file itself using the MDB GElf services, for
     40  * interpreting the .symtab and .dynsym if no libproc handle has been
     41  * initialized, and for handling i/o to and from the object file.  Currently,
     42  * the only ISA-dependent portions of the proc target are the $r and ::fpregs
     43  * dcmds, the callbacks for t_next() and t_step_out(), and the list of named
     44  * registers; these are linked in from the proc_isadep.c file for each ISA and
     45  * called from the common code in this file.
     46  *
     47  * The user process target implements complete user process control using the
     48  * facilities provided by libproc.so.  The MDB execution control model and
     49  * an overview of software event management is described in mdb_target.c.  The
     50  * proc target implements breakpoints by replacing the instruction of interest
     51  * with a trap instruction, and then restoring the original instruction to step
     52  * over the breakpoint.  The idea of replacing program text with instructions
     53  * that transfer control to the debugger dates back as far as 1951 [1].  When
     54  * the target stops, we replace each breakpoint with the original instruction
     55  * as part of the disarm operation.  This means that no special processing is
     56  * required for t_vread() because the instrumented instructions will never be
     57  * seen by the debugger once the target stops.  Some debuggers have improved
     58  * start/stop performance by leaving breakpoint traps in place and then
     59  * handling a read from a breakpoint address as a special case.  Although this
     60  * improves efficiency for a source-level debugger, it runs somewhat contrary
     61  * to the philosophy of the low-level debugger.  Since we remove the
     62  * instructions, users can apply other external debugging tools to the process
     63  * once it has stopped (e.g. the proc(1) tools) and not be misled by MDB
     64  * instrumentation.  The tracing of faults, signals, system calls, and
     65  * watchpoints and general process inspection is implemented directly using
     66  * the mechanisms provided by /proc, as described originally in [2] and [3].
     67  *
     68  * References
     69  *
     70  * [1] S. Gill, "The Diagnosis Of Mistakes In Programmes on the EDSAC",
     71  *     Proceedings of the Royal Society Series A Mathematical and Physical
     72  *     Sciences, Cambridge University Press, 206(1087), May 1951, pp. 538-554.
     73  *
     74  * [2] T.J. Killian, "Processes as Files", Proceedings of the USENIX Association
     75  *     Summer Conference, Salt Lake City, June 1984, pp. 203-207.
     76  *
     77  * [3] Roger Faulkner and Ron Gomes, "The Process File System and Process
     78  *     Model in UNIX System V", Proceedings of the USENIX Association
     79  *     Winter Conference, Dallas, January 1991, pp. 243-252.
     80  */
     81 
     82 #include <mdb/mdb_proc.h>
     83 #include <mdb/mdb_disasm.h>
     84 #include <mdb/mdb_signal.h>
     85 #include <mdb/mdb_string.h>
     86 #include <mdb/mdb_module.h>
     87 #include <mdb/mdb_debug.h>
     88 #include <mdb/mdb_conf.h>
     89 #include <mdb/mdb_err.h>
     90 #include <mdb/mdb_types.h>
     91 #include <mdb/mdb.h>
     92 
     93 #include <sys/utsname.h>
     94 #include <sys/wait.h>
     95 #include <sys/stat.h>
     96 #include <termio.h>
     97 #include <signal.h>
     98 #include <stdio_ext.h>
     99 #include <stdlib.h>
    100 #include <string.h>
    101 
    102 #define	PC_FAKE		-1UL			/* illegal pc value unequal 0 */
    103 
    104 static const char PT_EXEC_PATH[] = "a.out";	/* Default executable */
    105 static const char PT_CORE_PATH[] = "core";	/* Default core file */
    106 
    107 static const pt_ptl_ops_t proc_lwp_ops;
    108 static const pt_ptl_ops_t proc_tdb_ops;
    109 static const mdb_se_ops_t proc_brkpt_ops;
    110 static const mdb_se_ops_t proc_wapt_ops;
    111 
    112 static int pt_setrun(mdb_tgt_t *, mdb_tgt_status_t *, int);
    113 static void pt_activate_common(mdb_tgt_t *);
    114 static mdb_tgt_vespec_f pt_ignore_sig;
    115 static mdb_tgt_se_f pt_fork;
    116 static mdb_tgt_se_f pt_exec;
    117 
    118 static int pt_lookup_by_name_thr(mdb_tgt_t *, const char *,
    119     const char *, GElf_Sym *, mdb_syminfo_t *, mdb_tgt_tid_t);
    120 static int tlsbase(mdb_tgt_t *, mdb_tgt_tid_t, Lmid_t, const char *,
    121     psaddr_t *);
    122 
    123 /*
    124  * The Perror_printf() function interposes on the default, empty libproc
    125  * definition.  It will be called to report additional information on complex
    126  * errors, such as a corrupt core file.  We just pass the args to vwarn.
    127  */
    128 /*ARGSUSED*/
    129 void
    130 Perror_printf(struct ps_prochandle *P, const char *format, ...)
    131 {
    132 	va_list alist;
    133 
    134 	va_start(alist, format);
    135 	vwarn(format, alist);
    136 	va_end(alist);
    137 }
    138 
    139 /*
    140  * Open the specified i/o backend as the a.out executable file, and attempt to
    141  * load its standard and dynamic symbol tables.  Note that if mdb_gelf_create
    142  * succeeds, io is assigned to p_fio and is automatically held by gelf_create.
    143  */
    144 static mdb_gelf_file_t *
    145 pt_open_aout(mdb_tgt_t *t, mdb_io_t *io)
    146 {
    147 	pt_data_t *pt = t->t_data;
    148 	GElf_Sym s1, s2;
    149 
    150 	if ((pt->p_file = mdb_gelf_create(io, ET_NONE, GF_FILE)) == NULL)
    151 		return (NULL);
    152 
    153 	pt->p_symtab = mdb_gelf_symtab_create_file(pt->p_file,
    154 	    SHT_SYMTAB, MDB_TGT_SYMTAB);
    155 	pt->p_dynsym = mdb_gelf_symtab_create_file(pt->p_file,
    156 	    SHT_DYNSYM, MDB_TGT_DYNSYM);
    157 
    158 	/*
    159 	 * If we've got an _start symbol with a zero size, prime the private
    160 	 * symbol table with a copy of _start with its size set to the distance
    161 	 * between _mcount and _start.  We do this because DevPro has shipped
    162 	 * the Intel crt1.o without proper .size directives for years, which
    163 	 * precludes proper identification of _start in stack traces.
    164 	 */
    165 	if (mdb_gelf_symtab_lookup_by_name(pt->p_dynsym, "_start", &s1,
    166 	    NULL) == 0 && s1.st_size == 0 &&
    167 	    GELF_ST_TYPE(s1.st_info) == STT_FUNC) {
    168 		if (mdb_gelf_symtab_lookup_by_name(pt->p_dynsym, "_mcount",
    169 		    &s2, NULL) == 0 && GELF_ST_TYPE(s2.st_info) == STT_FUNC) {
    170 			s1.st_size = s2.st_value - s1.st_value;
    171 			mdb_gelf_symtab_insert(mdb.m_prsym, "_start", &s1);
    172 		}
    173 	}
    174 
    175 	pt->p_fio = io;
    176 	return (pt->p_file);
    177 }
    178 
    179 /*
    180  * Destroy the symbol tables and GElf file object associated with p_fio.  Note
    181  * that we do not need to explicitly free p_fio: its reference count is
    182  * automatically decremented by mdb_gelf_destroy, which will free it if needed.
    183  */
    184 static void
    185 pt_close_aout(mdb_tgt_t *t)
    186 {
    187 	pt_data_t *pt = t->t_data;
    188 
    189 	if (pt->p_symtab != NULL) {
    190 		mdb_gelf_symtab_destroy(pt->p_symtab);
    191 		pt->p_symtab = NULL;
    192 	}
    193 
    194 	if (pt->p_dynsym != NULL) {
    195 		mdb_gelf_symtab_destroy(pt->p_dynsym);
    196 		pt->p_dynsym = NULL;
    197 	}
    198 
    199 	if (pt->p_file != NULL) {
    200 		mdb_gelf_destroy(pt->p_file);
    201 		pt->p_file = NULL;
    202 	}
    203 
    204 	mdb_gelf_symtab_delete(mdb.m_prsym, "_start", NULL);
    205 	pt->p_fio = NULL;
    206 }
    207 
    208 typedef struct tdb_mapping {
    209 	const char *tm_thr_lib;
    210 	const char *tm_db_dir;
    211 	const char *tm_db_name;
    212 } tdb_mapping_t;
    213 
    214 static const tdb_mapping_t tdb_map[] = {
    215 	{ "/lwp/amd64/libthread.so",	"/usr/lib/lwp/", "libthread_db.so" },
    216 	{ "/lwp/sparcv9/libthread.so",	"/usr/lib/lwp/", "libthread_db.so" },
    217 	{ "/lwp/libthread.so",		"/usr/lib/lwp/", "libthread_db.so" },
    218 	{ "/libthread.so",		"/lib/", "libthread_db.so" },
    219 	{ "/libc_hwcap",		"/lib/", "libc_db.so" },
    220 	{ "/libc.so",			"/lib/", "libc_db.so" }
    221 };
    222 
    223 /*
    224  * Pobject_iter callback that we use to search for the presence of libthread in
    225  * order to load the corresponding libthread_db support.  We derive the
    226  * libthread_db path dynamically based on the libthread path.  If libthread is
    227  * found, this function returns 1 (and thus Pobject_iter aborts and returns 1)
    228  * regardless of whether it was successful in loading the libthread_db support.
    229  * If we iterate over all objects and no libthread is found, 0 is returned.
    230  * Since libthread_db support was then merged into libc_db, we load either
    231  * libc_db or libthread_db, depending on which library we see first.
    232  */
    233 /*ARGSUSED*/
    234 static int
    235 thr_check(mdb_tgt_t *t, const prmap_t *pmp, const char *name)
    236 {
    237 	pt_data_t *pt = t->t_data;
    238 	const mdb_tdb_ops_t *ops;
    239 	char *p;
    240 
    241 	char path[MAXPATHLEN];
    242 
    243 	int libn;
    244 
    245 	if (name == NULL)
    246 		return (0); /* no rtld_db object name; keep going */
    247 
    248 	for (libn = 0; libn < sizeof (tdb_map) / sizeof (tdb_map[0]); libn++) {
    249 		if ((p = strstr(name, tdb_map[libn].tm_thr_lib)) != NULL)
    250 			break;
    251 	}
    252 
    253 	if (p == NULL)
    254 		return (0); /* no match; keep going */
    255 
    256 	path[0] = '\0';
    257 	(void) strlcat(path, mdb.m_root, sizeof (path));
    258 	(void) strlcat(path, tdb_map[libn].tm_db_dir, sizeof (path));
    259 #if !defined(_ILP32)
    260 	(void) strlcat(path, "64/", sizeof (path));
    261 #endif /* !_ILP32 */
    262 	(void) strlcat(path, tdb_map[libn].tm_db_name, sizeof (path));
    263 
    264 	/* Append the trailing library version number. */
    265 	(void) strlcat(path, strrchr(name, '.'), sizeof (path));
    266 
    267 	if ((ops = mdb_tdb_load(path)) == NULL) {
    268 		if (libn != 0 || errno != ENOENT)
    269 			warn("failed to load %s", path);
    270 		goto err;
    271 	}
    272 
    273 	if (ops == pt->p_tdb_ops)
    274 		return (1); /* no changes needed */
    275 
    276 	PTL_DTOR(t);
    277 	pt->p_tdb_ops = ops;
    278 	pt->p_ptl_ops = &proc_tdb_ops;
    279 	pt->p_ptl_hdl = NULL;
    280 
    281 	if (PTL_CTOR(t) == -1) {
    282 		warn("failed to initialize %s", path);
    283 		goto err;
    284 	}
    285 
    286 	mdb_dprintf(MDB_DBG_TGT, "loaded %s for debugging %s\n", path, name);
    287 	(void) mdb_tgt_status(t, &t->t_status);
    288 	return (1);
    289 err:
    290 	PTL_DTOR(t);
    291 	pt->p_tdb_ops = NULL;
    292 	pt->p_ptl_ops = &proc_lwp_ops;
    293 	pt->p_ptl_hdl = NULL;
    294 
    295 	if (libn != 0 || errno != ENOENT) {
    296 		warn("warning: debugger will only be able to "
    297 		    "examine raw LWPs\n");
    298 	}
    299 
    300 	(void) mdb_tgt_status(t, &t->t_status);
    301 	return (1);
    302 }
    303 
    304 /*
    305  * Whenever the link map is consistent following an add or delete event, we ask
    306  * libproc to update its mappings, check to see if we need to load libthread_db,
    307  * and then update breakpoints which have been mapped or unmapped.
    308  */
    309 /*ARGSUSED*/
    310 static void
    311 pt_rtld_event(mdb_tgt_t *t, int vid, void *private)
    312 {
    313 	struct ps_prochandle *P = t->t_pshandle;
    314 	pt_data_t *pt = t->t_data;
    315 	rd_event_msg_t rdm;
    316 	int docontinue = 1;
    317 
    318 	if (rd_event_getmsg(pt->p_rtld, &rdm) == RD_OK) {
    319 
    320 		mdb_dprintf(MDB_DBG_TGT, "rtld event type 0x%x state 0x%x\n",
    321 		    rdm.type, rdm.u.state);
    322 
    323 		if (rdm.type == RD_DLACTIVITY && rdm.u.state == RD_CONSISTENT) {
    324 			mdb_sespec_t *sep, *nsep = mdb_list_next(&t->t_active);
    325 			pt_brkpt_t *ptb;
    326 
    327 			Pupdate_maps(P);
    328 
    329 			if (Pobject_iter(P, (proc_map_f *)thr_check, t) == 0 &&
    330 			    pt->p_ptl_ops != &proc_lwp_ops) {
    331 				mdb_dprintf(MDB_DBG_TGT, "unloading thread_db "
    332 				    "support after dlclose\n");
    333 				PTL_DTOR(t);
    334 				pt->p_tdb_ops = NULL;
    335 				pt->p_ptl_ops = &proc_lwp_ops;
    336 				pt->p_ptl_hdl = NULL;
    337 				(void) mdb_tgt_status(t, &t->t_status);
    338 			}
    339 
    340 			for (sep = nsep; sep != NULL; sep = nsep) {
    341 				nsep = mdb_list_next(sep);
    342 				ptb = sep->se_data;
    343 
    344 				if (sep->se_ops == &proc_brkpt_ops &&
    345 				    Paddr_to_map(P, ptb->ptb_addr) == NULL)
    346 					mdb_tgt_sespec_idle_one(t, sep,
    347 					    EMDB_NOMAP);
    348 			}
    349 
    350 			if (!mdb_tgt_sespec_activate_all(t) &&
    351 			    (mdb.m_flags & MDB_FL_BPTNOSYMSTOP) &&
    352 			    pt->p_rtld_finished) {
    353 				/*
    354 				 * We weren't able to activate the breakpoints.
    355 				 * If so requested, we'll return without
    356 				 * calling continue, thus throwing the user into
    357 				 * the debugger.
    358 				 */
    359 				docontinue = 0;
    360 			}
    361 
    362 			if (pt->p_rdstate == PT_RD_ADD)
    363 				pt->p_rdstate = PT_RD_CONSIST;
    364 		}
    365 
    366 		if (rdm.type == RD_PREINIT)
    367 			(void) mdb_tgt_sespec_activate_all(t);
    368 
    369 		if (rdm.type == RD_POSTINIT) {
    370 			pt->p_rtld_finished = TRUE;
    371 			if (!mdb_tgt_sespec_activate_all(t) &&
    372 			    (mdb.m_flags & MDB_FL_BPTNOSYMSTOP)) {
    373 				/*
    374 				 * Now that rtld has been initialized, we
    375 				 * should be able to initialize all deferred
    376 				 * breakpoints.  If we can't, don't let the
    377 				 * target continue.
    378 				 */
    379 				docontinue = 0;
    380 			}
    381 		}
    382 
    383 		if (rdm.type == RD_DLACTIVITY && rdm.u.state == RD_ADD &&
    384 		    pt->p_rtld_finished)
    385 			pt->p_rdstate = MAX(pt->p_rdstate, PT_RD_ADD);
    386 	}
    387 
    388 	if (docontinue)
    389 		(void) mdb_tgt_continue(t, NULL);
    390 }
    391 
    392 static void
    393 pt_post_attach(mdb_tgt_t *t)
    394 {
    395 	struct ps_prochandle *P = t->t_pshandle;
    396 	const lwpstatus_t *psp = &Pstatus(P)->pr_lwp;
    397 	pt_data_t *pt = t->t_data;
    398 	int hflag = MDB_TGT_SPEC_HIDDEN;
    399 
    400 	mdb_dprintf(MDB_DBG_TGT, "attach pr_flags=0x%x pr_why=%d pr_what=%d\n",
    401 	    psp->pr_flags, psp->pr_why, psp->pr_what);
    402 
    403 	/*
    404 	 * When we grab a process, the initial setting of p_rtld_finished
    405 	 * should be false if the process was just created by exec; otherwise
    406 	 * we permit unscoped references to resolve because we do not know how
    407 	 * far the process has proceeded through linker initialization.
    408 	 */
    409 	if ((psp->pr_flags & PR_ISTOP) && psp->pr_why == PR_SYSEXIT &&
    410 	    psp->pr_errno == 0 && (psp->pr_what == SYS_exec ||
    411 	    psp->pr_what == SYS_execve)) {
    412 		if (mdb.m_target == NULL) {
    413 			warn("target performed exec of %s\n",
    414 			    IOP_NAME(pt->p_fio));
    415 		}
    416 		pt->p_rtld_finished = FALSE;
    417 	} else
    418 		pt->p_rtld_finished = TRUE;
    419 
    420 	/*
    421 	 * When we grab a process, if it is stopped by job control and part of
    422 	 * the same session (i.e. same controlling tty), set MDB_FL_JOBCTL so
    423 	 * we will know to bring it to the foreground when we continue it.
    424 	 */
    425 	if (mdb.m_term != NULL && (psp->pr_flags & PR_STOPPED) &&
    426 	    psp->pr_why == PR_JOBCONTROL && getsid(0) == Pstatus(P)->pr_sid)
    427 		mdb.m_flags |= MDB_FL_JOBCTL;
    428 
    429 	/*
    430 	 * When we grab control of a live process, set F_RDWR so that the
    431 	 * target layer permits writes to the target's address space.
    432 	 */
    433 	t->t_flags |= MDB_TGT_F_RDWR;
    434 
    435 	(void) Pfault(P, FLTBPT, TRUE);		/* always trace breakpoints */
    436 	(void) Pfault(P, FLTWATCH, TRUE);	/* always trace watchpoints */
    437 	(void) Pfault(P, FLTTRACE, TRUE);	/* always trace single-step */
    438 
    439 	(void) Punsetflags(P, PR_ASYNC);	/* require synchronous mode */
    440 	(void) Psetflags(P, PR_BPTADJ);		/* always adjust eip on x86 */
    441 	(void) Psetflags(P, PR_FORK);		/* inherit tracing on fork */
    442 
    443 	/*
    444 	 * Install event specifiers to track fork and exec activities:
    445 	 */
    446 	(void) mdb_tgt_add_sysexit(t, SYS_forkall, hflag, pt_fork, NULL);
    447 	(void) mdb_tgt_add_sysexit(t, SYS_fork1, hflag, pt_fork, NULL);
    448 	(void) mdb_tgt_add_sysexit(t, SYS_vfork, hflag, pt_fork, NULL);
    449 	(void) mdb_tgt_add_sysexit(t, SYS_forksys, hflag, pt_fork, NULL);
    450 	(void) mdb_tgt_add_sysexit(t, SYS_exec, hflag, pt_exec, NULL);
    451 	(void) mdb_tgt_add_sysexit(t, SYS_execve, hflag, pt_exec, NULL);
    452 
    453 	/*
    454 	 * Attempt to instantiate the librtld_db agent and set breakpoints
    455 	 * to track rtld activity.  We will legitimately fail to instantiate
    456 	 * the rtld_db agent if the target is statically linked.
    457 	 */
    458 	if (pt->p_rtld == NULL && (pt->p_rtld = Prd_agent(P)) != NULL) {
    459 		rd_notify_t rdn;
    460 		rd_err_e err;
    461 
    462 		if ((err = rd_event_enable(pt->p_rtld, TRUE)) != RD_OK) {
    463 			warn("failed to enable rtld_db event tracing: %s\n",
    464 			    rd_errstr(err));
    465 			goto out;
    466 		}
    467 
    468 		if ((err = rd_event_addr(pt->p_rtld, RD_PREINIT,
    469 		    &rdn)) == RD_OK && rdn.type == RD_NOTIFY_BPT) {
    470 			(void) mdb_tgt_add_vbrkpt(t, rdn.u.bptaddr,
    471 			    hflag, pt_rtld_event, NULL);
    472 		} else {
    473 			warn("failed to install rtld_db preinit tracing: %s\n",
    474 			    rd_errstr(err));
    475 		}
    476 
    477 		if ((err = rd_event_addr(pt->p_rtld, RD_POSTINIT,
    478 		    &rdn)) == RD_OK && rdn.type == RD_NOTIFY_BPT) {
    479 			(void) mdb_tgt_add_vbrkpt(t, rdn.u.bptaddr,
    480 			    hflag, pt_rtld_event, NULL);
    481 		} else {
    482 			warn("failed to install rtld_db postinit tracing: %s\n",
    483 			    rd_errstr(err));
    484 		}
    485 
    486 		if ((err = rd_event_addr(pt->p_rtld, RD_DLACTIVITY,
    487 		    &rdn)) == RD_OK && rdn.type == RD_NOTIFY_BPT) {
    488 			(void) mdb_tgt_add_vbrkpt(t, rdn.u.bptaddr,
    489 			    hflag, pt_rtld_event, NULL);
    490 		} else {
    491 			warn("failed to install rtld_db activity tracing: %s\n",
    492 			    rd_errstr(err));
    493 		}
    494 	}
    495 out:
    496 	Pupdate_maps(P);
    497 	Psync(P);
    498 
    499 	/*
    500 	 * If librtld_db failed to initialize due to an error or because we are
    501 	 * debugging a statically linked executable, allow unscoped references.
    502 	 */
    503 	if (pt->p_rtld == NULL)
    504 		pt->p_rtld_finished = TRUE;
    505 
    506 	(void) mdb_tgt_sespec_activate_all(t);
    507 }
    508 
    509 /*ARGSUSED*/
    510 static int
    511 pt_vespec_delete(mdb_tgt_t *t, void *private, int id, void *data)
    512 {
    513 	if (id < 0) {
    514 		ASSERT(data == NULL); /* we don't use any ve_data */
    515 		(void) mdb_tgt_vespec_delete(t, id);
    516 	}
    517 	return (0);
    518 }
    519 
    520 static void
    521 pt_pre_detach(mdb_tgt_t *t, int clear_matched)
    522 {
    523 	const lwpstatus_t *psp = &Pstatus(t->t_pshandle)->pr_lwp;
    524 	pt_data_t *pt = t->t_data;
    525 	long cmd = 0;
    526 
    527 	/*
    528 	 * If we are about to release the process and it is stopped on a traced
    529 	 * SIGINT, breakpoint fault, single-step fault, or watchpoint, make
    530 	 * sure to clear this event prior to releasing the process so that it
    531 	 * does not subsequently reissue the fault and die from SIGTRAP.
    532 	 */
    533 	if (psp->pr_flags & PR_ISTOP) {
    534 		if (psp->pr_why == PR_FAULTED && (psp->pr_what == FLTBPT ||
    535 		    psp->pr_what == FLTTRACE || psp->pr_what == FLTWATCH))
    536 			cmd = PCCFAULT;
    537 		else if (psp->pr_why == PR_SIGNALLED && psp->pr_what == SIGINT)
    538 			cmd = PCCSIG;
    539 
    540 		if (cmd != 0)
    541 			(void) write(Pctlfd(t->t_pshandle), &cmd, sizeof (cmd));
    542 	}
    543 
    544 	if (Pstate(t->t_pshandle) == PS_UNDEAD)
    545 		(void) waitpid(Pstatus(t->t_pshandle)->pr_pid, NULL, WNOHANG);
    546 
    547 	(void) mdb_tgt_vespec_iter(t, pt_vespec_delete, NULL);
    548 	mdb_tgt_sespec_idle_all(t, EMDB_NOPROC, clear_matched);
    549 
    550 	if (pt->p_fio != pt->p_aout_fio) {
    551 		pt_close_aout(t);
    552 		(void) pt_open_aout(t, pt->p_aout_fio);
    553 	}
    554 
    555 	PTL_DTOR(t);
    556 	pt->p_tdb_ops = NULL;
    557 	pt->p_ptl_ops = &proc_lwp_ops;
    558 	pt->p_ptl_hdl = NULL;
    559 
    560 	pt->p_rtld = NULL;
    561 	pt->p_signal = 0;
    562 	pt->p_rtld_finished = FALSE;
    563 	pt->p_rdstate = PT_RD_NONE;
    564 }
    565 
    566 static void
    567 pt_release_parents(mdb_tgt_t *t)
    568 {
    569 	struct ps_prochandle *P = t->t_pshandle;
    570 	pt_data_t *pt = t->t_data;
    571 
    572 	mdb_sespec_t *sep;
    573 	pt_vforkp_t *vfp;
    574 
    575 	while ((vfp = mdb_list_next(&pt->p_vforkp)) != NULL) {
    576 		mdb_dprintf(MDB_DBG_TGT, "releasing vfork parent %d\n",
    577 		    (int)Pstatus(vfp->p_pshandle)->pr_pid);
    578 
    579 		/*
    580 		 * To release vfork parents, we must also wipe out any armed
    581 		 * events in the parent by switching t_pshandle and calling
    582 		 * se_disarm().  Do not change states or lose the matched list.
    583 		 */
    584 		t->t_pshandle = vfp->p_pshandle;
    585 
    586 		for (sep = mdb_list_next(&t->t_active); sep != NULL;
    587 		    sep = mdb_list_next(sep)) {
    588 			if (sep->se_state == MDB_TGT_SPEC_ARMED)
    589 				(void) sep->se_ops->se_disarm(t, sep);
    590 		}
    591 
    592 		t->t_pshandle = P;
    593 
    594 		Prelease(vfp->p_pshandle, PRELEASE_CLEAR);
    595 		mdb_list_delete(&pt->p_vforkp, vfp);
    596 		mdb_free(vfp, sizeof (pt_vforkp_t));
    597 	}
    598 }
    599 
    600 /*ARGSUSED*/
    601 static void
    602 pt_fork(mdb_tgt_t *t, int vid, void *private)
    603 {
    604 	struct ps_prochandle *P = t->t_pshandle;
    605 	const lwpstatus_t *psp = &Pstatus(P)->pr_lwp;
    606 	pt_data_t *pt = t->t_data;
    607 	mdb_sespec_t *sep;
    608 
    609 	int follow_parent = mdb.m_forkmode != MDB_FM_CHILD;
    610 	int is_vfork = (psp->pr_what == SYS_vfork ||
    611 	    (psp->pr_what == SYS_forksys && psp->pr_sysarg[0] == 2));
    612 
    613 	struct ps_prochandle *C;
    614 	const lwpstatus_t *csp;
    615 	char sysname[32];
    616 	int gcode;
    617 	char c;
    618 
    619 	mdb_dprintf(MDB_DBG_TGT, "parent %s: errno=%d rv1=%ld rv2=%ld\n",
    620 	    proc_sysname(psp->pr_what, sysname, sizeof (sysname)),
    621 	    psp->pr_errno, psp->pr_rval1, psp->pr_rval2);
    622 
    623 	if (psp->pr_errno != 0) {
    624 		(void) mdb_tgt_continue(t, NULL);
    625 		return; /* fork failed */
    626 	}
    627 
    628 	/*
    629 	 * If forkmode is ASK and stdout is a terminal, then ask the user to
    630 	 * explicitly set the fork behavior for this particular fork.
    631 	 */
    632 	if (mdb.m_forkmode == MDB_FM_ASK && mdb.m_term != NULL) {
    633 		mdb_iob_printf(mdb.m_err, "%s: %s detected: follow (p)arent "
    634 		    "or (c)hild? ", mdb.m_pname, sysname);
    635 		mdb_iob_flush(mdb.m_err);
    636 
    637 		while (IOP_READ(mdb.m_term, &c, sizeof (c)) == sizeof (c)) {
    638 			if (c == 'P' || c == 'p') {
    639 				mdb_iob_printf(mdb.m_err, "%c\n", c);
    640 				follow_parent = TRUE;
    641 				break;
    642 			} else if (c == 'C' || c == 'c') {
    643 				mdb_iob_printf(mdb.m_err, "%c\n", c);
    644 				follow_parent = FALSE;
    645 				break;
    646 			}
    647 		}
    648 	}
    649 
    650 	/*
    651 	 * The parent is now stopped on exit from its fork call.  We must now
    652 	 * grab the child on its return from fork in order to manipulate it.
    653 	 */
    654 	if ((C = Pgrab(psp->pr_rval1, PGRAB_RETAIN, &gcode)) == NULL) {
    655 		warn("failed to grab forked child process %ld: %s\n",
    656 		    psp->pr_rval1, Pgrab_error(gcode));
    657 		return; /* just stop if we failed to grab the child */
    658 	}
    659 
    660 	/*
    661 	 * We may have grabbed the child and stopped it prematurely before it
    662 	 * stopped on exit from fork.  If so, wait up to 1 sec for it to settle.
    663 	 */
    664 	if (Pstatus(C)->pr_lwp.pr_why != PR_SYSEXIT)
    665 		(void) Pwait(C, MILLISEC);
    666 
    667 	csp = &Pstatus(C)->pr_lwp;
    668 
    669 	if (csp->pr_why != PR_SYSEXIT ||
    670 	    (csp->pr_what != SYS_forkall &&
    671 	    csp->pr_what != SYS_fork1 &&
    672 	    csp->pr_what != SYS_vfork &&
    673 	    csp->pr_what != SYS_forksys)) {
    674 		warn("forked child process %ld did not stop on exit from "
    675 		    "fork as expected\n", psp->pr_rval1);
    676 	}
    677 
    678 	warn("target forked child process %ld (debugger following %s)\n",
    679 	    psp->pr_rval1, follow_parent ? "parent" : "child");
    680 
    681 	(void) Punsetflags(C, PR_ASYNC);	/* require synchronous mode */
    682 	(void) Psetflags(C, PR_BPTADJ);		/* always adjust eip on x86 */
    683 	(void) Prd_agent(C);			/* initialize librtld_db */
    684 
    685 	/*
    686 	 * At the time pt_fork() is called, the target event engine has already
    687 	 * disarmed the specifiers on the active list, clearing out events in
    688 	 * the parent process.  However, this means that events that change
    689 	 * the address space (e.g. breakpoints) have not been effectively
    690 	 * disarmed in the child since its address space reflects the state of
    691 	 * the process at the time of fork when events were armed.  We must
    692 	 * therefore handle this as a special case and re-invoke the disarm
    693 	 * callback of each active specifier to clean out the child process.
    694 	 */
    695 	if (!is_vfork) {
    696 		for (t->t_pshandle = C, sep = mdb_list_next(&t->t_active);
    697 		    sep != NULL; sep = mdb_list_next(sep)) {
    698 			if (sep->se_state == MDB_TGT_SPEC_ACTIVE)
    699 				(void) sep->se_ops->se_disarm(t, sep);
    700 		}
    701 
    702 		t->t_pshandle = P; /* restore pshandle to parent */
    703 	}
    704 
    705 	/*
    706 	 * If we're following the parent process, we need to temporarily change
    707 	 * t_pshandle to refer to the child handle C so that we can clear out
    708 	 * all the events in the child prior to releasing it below.  If we are
    709 	 * tracing a vfork, we also need to explicitly wait for the child to
    710 	 * exec, exit, or die before we can reset and continue the parent.  We
    711 	 * avoid having to deal with the vfork child forking again by clearing
    712 	 * PR_FORK and setting PR_RLC; if it does fork it will effectively be
    713 	 * released from our control and we will continue following the parent.
    714 	 */
    715 	if (follow_parent) {
    716 		if (is_vfork) {
    717 			mdb_tgt_status_t status;
    718 
    719 			ASSERT(psp->pr_flags & PR_VFORKP);
    720 			mdb_tgt_sespec_idle_all(t, EBUSY, FALSE);
    721 			t->t_pshandle = C;
    722 
    723 			(void) Psysexit(C, SYS_exec, TRUE);
    724 			(void) Psysexit(C, SYS_execve, TRUE);
    725 
    726 			(void) Punsetflags(C, PR_FORK | PR_KLC);
    727 			(void) Psetflags(C, PR_RLC);
    728 
    729 			do {
    730 				if (pt_setrun(t, &status, 0) == -1 ||
    731 				    status.st_state == MDB_TGT_UNDEAD ||
    732 				    status.st_state == MDB_TGT_LOST)
    733 					break; /* failure or process died */
    734 
    735 			} while (csp->pr_why != PR_SYSEXIT ||
    736 			    csp->pr_errno != 0 || (csp->pr_what != SYS_exec &&
    737 			    csp->pr_what != SYS_execve));
    738 		} else
    739 			t->t_pshandle = C;
    740 	}
    741 
    742 	/*
    743 	 * If we are following the child, destroy any active libthread_db
    744 	 * handle before we release the parent process.
    745 	 */
    746 	if (!follow_parent) {
    747 		PTL_DTOR(t);
    748 		pt->p_tdb_ops = NULL;
    749 		pt->p_ptl_ops = &proc_lwp_ops;
    750 		pt->p_ptl_hdl = NULL;
    751 	}
    752 
    753 	/*
    754 	 * Idle all events to make sure the address space and tracing flags are
    755 	 * restored, and then release the process we are not tracing.  If we
    756 	 * are following the child of a vfork, we push the parent's pshandle
    757 	 * on to a list of vfork parents to be released when we exec or exit.
    758 	 */
    759 	if (is_vfork && !follow_parent) {
    760 		pt_vforkp_t *vfp = mdb_alloc(sizeof (pt_vforkp_t), UM_SLEEP);
    761 
    762 		ASSERT(psp->pr_flags & PR_VFORKP);
    763 		vfp->p_pshandle = P;
    764 		mdb_list_append(&pt->p_vforkp, vfp);
    765 		mdb_tgt_sespec_idle_all(t, EBUSY, FALSE);
    766 
    767 	} else {
    768 		mdb_tgt_sespec_idle_all(t, EBUSY, FALSE);
    769 		Prelease(t->t_pshandle, PRELEASE_CLEAR);
    770 		if (!follow_parent)
    771 			pt_release_parents(t);
    772 	}
    773 
    774 	/*
    775 	 * Now that all the hard stuff is done, switch t_pshandle back to the
    776 	 * process we are following and reset our events to the ACTIVE state.
    777 	 * If we are following the child, reset the libthread_db handle as well
    778 	 * as the rtld agent.
    779 	 */
    780 	if (follow_parent)
    781 		t->t_pshandle = P;
    782 	else {
    783 		t->t_pshandle = C;
    784 		pt->p_rtld = Prd_agent(C);
    785 		(void) Pobject_iter(t->t_pshandle, (proc_map_f *)thr_check, t);
    786 	}
    787 
    788 	(void) mdb_tgt_sespec_activate_all(t);
    789 	(void) mdb_tgt_continue(t, NULL);
    790 }
    791 
    792 /*ARGSUSED*/
    793 static void
    794 pt_exec(mdb_tgt_t *t, int vid, void *private)
    795 {
    796 	struct ps_prochandle *P = t->t_pshandle;
    797 	const pstatus_t *psp = Pstatus(P);
    798 	pt_data_t *pt = t->t_data;
    799 	int follow_exec = mdb.m_execmode == MDB_EM_FOLLOW;
    800 	pid_t pid = psp->pr_pid;
    801 
    802 	char execname[MAXPATHLEN];
    803 	mdb_sespec_t *sep, *nsep;
    804 	mdb_io_t *io;
    805 	char c;
    806 
    807 	mdb_dprintf(MDB_DBG_TGT, "exit from %s: errno=%d\n", proc_sysname(
    808 	    psp->pr_lwp.pr_what, execname, sizeof (execname)),
    809 	    psp->pr_lwp.pr_errno);
    810 
    811 	if (psp->pr_lwp.pr_errno != 0) {
    812 		(void) mdb_tgt_continue(t, NULL);
    813 		return; /* exec failed */
    814 	}
    815 
    816 	/*
    817 	 * If execmode is ASK and stdout is a terminal, then ask the user to
    818 	 * explicitly set the exec behavior for this particular exec.  If
    819 	 * Pstate() still shows PS_LOST, we are being called from pt_setrun()
    820 	 * directly and therefore we must resume the terminal since it is still
    821 	 * in the suspended state as far as tgt_continue() is concerned.
    822 	 */
    823 	if (mdb.m_execmode == MDB_EM_ASK && mdb.m_term != NULL) {
    824 		if (Pstate(P) == PS_LOST)
    825 			IOP_RESUME(mdb.m_term);
    826 
    827 		mdb_iob_printf(mdb.m_err, "%s: %s detected: (f)ollow new "
    828 		    "program or (s)top? ", mdb.m_pname, execname);
    829 		mdb_iob_flush(mdb.m_err);
    830 
    831 		while (IOP_READ(mdb.m_term, &c, sizeof (c)) == sizeof (c)) {
    832 			if (c == 'F' || c == 'f') {
    833 				mdb_iob_printf(mdb.m_err, "%c\n", c);
    834 				follow_exec = TRUE;
    835 				break;
    836 			} else if (c == 'S' || c == 's') {
    837 				mdb_iob_printf(mdb.m_err, "%c\n", c);
    838 				follow_exec = FALSE;
    839 				break;
    840 			}
    841 		}
    842 
    843 		if (Pstate(P) == PS_LOST)
    844 			IOP_SUSPEND(mdb.m_term);
    845 	}
    846 
    847 	pt_release_parents(t);	/* release any waiting vfork parents */
    848 	pt_pre_detach(t, FALSE); /* remove our breakpoints and idle events */
    849 	Preset_maps(P);		/* libproc must delete mappings and symtabs */
    850 	pt_close_aout(t);	/* free pt symbol tables and GElf file data */
    851 
    852 	/*
    853 	 * If we lost control of the process across the exec and are not able
    854 	 * to reopen it, we have no choice but to clear the matched event list
    855 	 * and wait for the user to quit or otherwise release the process.
    856 	 */
    857 	if (Pstate(P) == PS_LOST && Preopen(P) == -1) {
    858 		int error = errno;
    859 
    860 		warn("lost control of PID %d due to exec of %s executable\n",
    861 		    (int)pid, error == EOVERFLOW ? "64-bit" : "set-id");
    862 
    863 		for (sep = t->t_matched; sep != T_SE_END; sep = nsep) {
    864 			nsep = sep->se_matched;
    865 			sep->se_matched = NULL;
    866 			mdb_tgt_sespec_rele(t, sep);
    867 		}
    868 
    869 		if (error != EOVERFLOW)
    870 			return; /* just stop if we exec'd a set-id executable */
    871 	}
    872 
    873 	if (Pstate(P) != PS_LOST) {
    874 		if (Pexecname(P, execname, sizeof (execname)) == NULL) {
    875 			(void) mdb_iob_snprintf(execname, sizeof (execname),
    876 			    "/proc/%d/object/a.out", (int)pid);
    877 		}
    878 
    879 		if (follow_exec == FALSE || psp->pr_dmodel == PR_MODEL_NATIVE)
    880 			warn("target performed exec of %s\n", execname);
    881 
    882 		io = mdb_fdio_create_path(NULL, execname, pt->p_oflags, 0);
    883 		if (io == NULL) {
    884 			warn("failed to open %s", execname);
    885 			warn("a.out symbol tables will not be available\n");
    886 		} else if (pt_open_aout(t, io) == NULL) {
    887 			(void) mdb_dis_select(pt_disasm(NULL));
    888 			mdb_io_destroy(io);
    889 		} else
    890 			(void) mdb_dis_select(pt_disasm(&pt->p_file->gf_ehdr));
    891 	}
    892 
    893 	/*
    894 	 * We reset our libthread_db state here, but deliberately do NOT call
    895 	 * PTL_DTOR because we do not want to call libthread_db's td_ta_delete.
    896 	 * This interface is hopelessly broken in that it writes to the process
    897 	 * address space (which we do not want it to do after an exec) and it
    898 	 * doesn't bother deallocating any of its storage anyway.
    899 	 */
    900 	pt->p_tdb_ops = NULL;
    901 	pt->p_ptl_ops = &proc_lwp_ops;
    902 	pt->p_ptl_hdl = NULL;
    903 
    904 	if (follow_exec && psp->pr_dmodel != PR_MODEL_NATIVE) {
    905 		const char *argv[3];
    906 		char *state, *env;
    907 		char pidarg[16];
    908 		size_t envlen;
    909 
    910 		if (realpath(getexecname(), execname) == NULL) {
    911 			warn("cannot follow PID %d -- failed to resolve "
    912 			    "debugger pathname for re-exec", (int)pid);
    913 			return;
    914 		}
    915 
    916 		warn("restarting debugger to follow PID %d ...\n", (int)pid);
    917 		mdb_dprintf(MDB_DBG_TGT, "re-exec'ing %s\n", execname);
    918 
    919 		(void) mdb_snprintf(pidarg, sizeof (pidarg), "-p%d", (int)pid);
    920 
    921 		state = mdb_get_config();
    922 		envlen = strlen(MDB_CONFIG_ENV_VAR) + 1 + strlen(state) + 1;
    923 		env = mdb_alloc(envlen, UM_SLEEP);
    924 		snprintf(env, envlen, "%s=%s", MDB_CONFIG_ENV_VAR, state);
    925 
    926 		(void) putenv(env);
    927 
    928 		argv[0] = mdb.m_pname;
    929 		argv[1] = pidarg;
    930 		argv[2] = NULL;
    931 
    932 		if (mdb.m_term != NULL)
    933 			IOP_SUSPEND(mdb.m_term);
    934 
    935 		Prelease(P, PRELEASE_CLEAR | PRELEASE_HANG);
    936 		(void) execv(execname, (char *const *)argv);
    937 		warn("failed to re-exec debugger");
    938 
    939 		if (mdb.m_term != NULL)
    940 			IOP_RESUME(mdb.m_term);
    941 
    942 		t->t_pshandle = pt->p_idlehandle;
    943 		return;
    944 	}
    945 
    946 	pt_post_attach(t);	/* install tracing flags and activate events */
    947 	pt_activate_common(t);	/* initialize librtld_db and libthread_db */
    948 
    949 	if (psp->pr_dmodel != PR_MODEL_NATIVE && mdb.m_term != NULL) {
    950 		warn("loadable dcmds will not operate on non-native %d-bit "
    951 		    "data model\n", psp->pr_dmodel == PR_MODEL_ILP32 ? 32 : 64);
    952 		warn("use ::release -a and then run mdb -p %d to restart "
    953 		    "debugger\n", (int)pid);
    954 	}
    955 
    956 	if (follow_exec)
    957 		(void) mdb_tgt_continue(t, NULL);
    958 }
    959 
    960 static int
    961 pt_setflags(mdb_tgt_t *t, int flags)
    962 {
    963 	pt_data_t *pt = t->t_data;
    964 
    965 	if ((flags ^ t->t_flags) & MDB_TGT_F_RDWR) {
    966 		int mode = (flags & MDB_TGT_F_RDWR) ? O_RDWR : O_RDONLY;
    967 		mdb_io_t *io;
    968 
    969 		if (pt->p_fio == NULL)
    970 			return (set_errno(EMDB_NOEXEC));
    971 
    972 		io = mdb_fdio_create_path(NULL, IOP_NAME(pt->p_fio), mode, 0);
    973 
    974 		if (io == NULL)
    975 			return (-1); /* errno is set for us */
    976 
    977 		t->t_flags = (t->t_flags & ~MDB_TGT_F_RDWR) |
    978 		    (flags & MDB_TGT_F_RDWR);
    979 
    980 		pt->p_fio = mdb_io_hold(io);
    981 		mdb_io_rele(pt->p_file->gf_io);
    982 		pt->p_file->gf_io = pt->p_fio;
    983 	}
    984 
    985 	if (flags & MDB_TGT_F_FORCE) {
    986 		t->t_flags |= MDB_TGT_F_FORCE;
    987 		pt->p_gflags |= PGRAB_FORCE;
    988 	}
    989 
    990 	return (0);
    991 }
    992 
    993 /*ARGSUSED*/
    994 static int
    995 pt_frame(void *arglim, uintptr_t pc, uint_t argc, const long *argv,
    996     const mdb_tgt_gregset_t *gregs)
    997 {
    998 	argc = MIN(argc, (uint_t)(uintptr_t)arglim);
    999 	mdb_printf("%a(", pc);
   1000 
   1001 	if (argc != 0) {
   1002 		mdb_printf("%lr", *argv++);
   1003 		for (argc--; argc != 0; argc--)
   1004 			mdb_printf(", %lr", *argv++);
   1005 	}
   1006 
   1007 	mdb_printf(")\n");
   1008 	return (0);
   1009 }
   1010 
   1011 static int
   1012 pt_framev(void *arglim, uintptr_t pc, uint_t argc, const long *argv,
   1013     const mdb_tgt_gregset_t *gregs)
   1014 {
   1015 	argc = MIN(argc, (uint_t)(uintptr_t)arglim);
   1016 #if defined(__i386) || defined(__amd64)
   1017 	mdb_printf("%0?lr %a(", gregs->gregs[R_FP], pc);
   1018 #else
   1019 	mdb_printf("%0?lr %a(", gregs->gregs[R_SP], pc);
   1020 #endif
   1021 	if (argc != 0) {
   1022 		mdb_printf("%lr", *argv++);
   1023 		for (argc--; argc != 0; argc--)
   1024 			mdb_printf(", %lr", *argv++);
   1025 	}
   1026 
   1027 	mdb_printf(")\n");
   1028 	return (0);
   1029 }
   1030 
   1031 static int
   1032 pt_framer(void *arglim, uintptr_t pc, uint_t argc, const long *argv,
   1033     const mdb_tgt_gregset_t *gregs)
   1034 {
   1035 	if (pt_frameregs(arglim, pc, argc, argv, gregs, pc == PC_FAKE) == -1) {
   1036 		/*
   1037 		 * Use verbose format if register format is not supported.
   1038 		 */
   1039 		return (pt_framev(arglim, pc, argc, argv, gregs));
   1040 	}
   1041 
   1042 	return (0);
   1043 }
   1044 
   1045 /*ARGSUSED*/
   1046 static int
   1047 pt_stack_common(uintptr_t addr, uint_t flags, int argc,
   1048     const mdb_arg_t *argv, mdb_tgt_stack_f *func, prgreg_t saved_pc)
   1049 {
   1050 	void *arg = (void *)(uintptr_t)mdb.m_nargs;
   1051 	mdb_tgt_t *t = mdb.m_target;
   1052 	mdb_tgt_gregset_t gregs;
   1053 
   1054 	if (argc != 0) {
   1055 		if (argv->a_type == MDB_TYPE_CHAR || argc > 1)
   1056 			return (DCMD_USAGE);
   1057 
   1058 		if (argv->a_type == MDB_TYPE_STRING)
   1059 			arg = (void *)(uintptr_t)mdb_strtoull(argv->a_un.a_str);
   1060 		else
   1061 			arg = (void *)(uintptr_t)argv->a_un.a_val;
   1062 	}
   1063 
   1064 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) == PS_IDLE) {
   1065 		mdb_warn("no process active\n");
   1066 		return (DCMD_ERR);
   1067 	}
   1068 
   1069 	/*
   1070 	 * In the universe of sparcv7, sparcv9, ia32, and amd64 this code can be
   1071 	 * common: <sys/procfs_isa.h> conveniently #defines R_FP to be the
   1072 	 * appropriate register we need to set in order to perform a stack
   1073 	 * traceback from a given frame address.
   1074 	 */
   1075 	if (flags & DCMD_ADDRSPEC) {
   1076 		bzero(&gregs, sizeof (gregs));
   1077 		gregs.gregs[R_FP] = addr;
   1078 #ifdef __sparc
   1079 		gregs.gregs[R_I7] = saved_pc;
   1080 #endif /* __sparc */
   1081 	} else if (PTL_GETREGS(t, PTL_TID(t), gregs.gregs) != 0) {
   1082 		mdb_warn("failed to get current register set");
   1083 		return (DCMD_ERR);
   1084 	}
   1085 
   1086 	(void) mdb_tgt_stack_iter(t, &gregs, func, arg);
   1087 	return (DCMD_OK);
   1088 }
   1089 
   1090 static int
   1091 pt_stack(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1092 {
   1093 	return (pt_stack_common(addr, flags, argc, argv, pt_frame, 0));
   1094 }
   1095 
   1096 static int
   1097 pt_stackv(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1098 {
   1099 	return (pt_stack_common(addr, flags, argc, argv, pt_framev, 0));
   1100 }
   1101 
   1102 static int
   1103 pt_stackr(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1104 {
   1105 	/*
   1106 	 * Force printing of first register window, by setting  the
   1107 	 * saved pc (%i7) to PC_FAKE.
   1108 	 */
   1109 	return (pt_stack_common(addr, flags, argc, argv, pt_framer, PC_FAKE));
   1110 }
   1111 
   1112 /*ARGSUSED*/
   1113 static int
   1114 pt_ignored(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1115 {
   1116 	struct ps_prochandle *P = mdb.m_target->t_pshandle;
   1117 	char buf[PRSIGBUFSZ];
   1118 
   1119 	if ((flags & DCMD_ADDRSPEC) || argc != 0)
   1120 		return (DCMD_USAGE);
   1121 
   1122 	if (P == NULL) {
   1123 		mdb_warn("no process is currently active\n");
   1124 		return (DCMD_ERR);
   1125 	}
   1126 
   1127 	mdb_printf("%s\n", proc_sigset2str(&Pstatus(P)->pr_sigtrace, " ",
   1128 	    FALSE, buf, sizeof (buf)));
   1129 
   1130 	return (DCMD_OK);
   1131 }
   1132 
   1133 /*ARGSUSED*/
   1134 static int
   1135 pt_lwpid(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1136 {
   1137 	struct ps_prochandle *P = mdb.m_target->t_pshandle;
   1138 
   1139 	if ((flags & DCMD_ADDRSPEC) || argc != 0)
   1140 		return (DCMD_USAGE);
   1141 
   1142 	if (P == NULL) {
   1143 		mdb_warn("no process is currently active\n");
   1144 		return (DCMD_ERR);
   1145 	}
   1146 
   1147 	mdb_printf("%d\n", Pstatus(P)->pr_lwp.pr_lwpid);
   1148 	return (DCMD_OK);
   1149 }
   1150 
   1151 static int
   1152 pt_print_lwpid(int *n, const lwpstatus_t *psp)
   1153 {
   1154 	struct ps_prochandle *P = mdb.m_target->t_pshandle;
   1155 	int nlwp = Pstatus(P)->pr_nlwp;
   1156 
   1157 	if (*n == nlwp - 2)
   1158 		mdb_printf("%d and ", (int)psp->pr_lwpid);
   1159 	else if (*n == nlwp - 1)
   1160 		mdb_printf("%d are", (int)psp->pr_lwpid);
   1161 	else
   1162 		mdb_printf("%d, ", (int)psp->pr_lwpid);
   1163 
   1164 	(*n)++;
   1165 	return (0);
   1166 }
   1167 
   1168 /*ARGSUSED*/
   1169 static int
   1170 pt_lwpids(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1171 {
   1172 	struct ps_prochandle *P = mdb.m_target->t_pshandle;
   1173 	int n = 0;
   1174 
   1175 	if (P == NULL) {
   1176 		mdb_warn("no process is currently active\n");
   1177 		return (DCMD_ERR);
   1178 	}
   1179 
   1180 	switch (Pstatus(P)->pr_nlwp) {
   1181 	case 0:
   1182 		mdb_printf("no lwps are");
   1183 		break;
   1184 	case 1:
   1185 		mdb_printf("lwpid %d is the only lwp",
   1186 		    Pstatus(P)->pr_lwp.pr_lwpid);
   1187 		break;
   1188 	default:
   1189 		mdb_printf("lwpids ");
   1190 		(void) Plwp_iter(P, (proc_lwp_f *)pt_print_lwpid, &n);
   1191 	}
   1192 
   1193 	switch (Pstate(P)) {
   1194 	case PS_DEAD:
   1195 		mdb_printf(" in core of process %d.\n", Pstatus(P)->pr_pid);
   1196 		break;
   1197 	case PS_IDLE:
   1198 		mdb_printf(" in idle target.\n");
   1199 		break;
   1200 	default:
   1201 		mdb_printf(" in process %d.\n", (int)Pstatus(P)->pr_pid);
   1202 		break;
   1203 	}
   1204 
   1205 	return (DCMD_OK);
   1206 }
   1207 
   1208 /*ARGSUSED*/
   1209 static int
   1210 pt_ignore(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1211 {
   1212 	pt_data_t *pt = mdb.m_target->t_data;
   1213 
   1214 	if (!(flags & DCMD_ADDRSPEC) || argc != 0)
   1215 		return (DCMD_USAGE);
   1216 
   1217 	if (addr < 1 || addr > pt->p_maxsig) {
   1218 		mdb_warn("invalid signal number -- 0t%lu\n", addr);
   1219 		return (DCMD_ERR);
   1220 	}
   1221 
   1222 	(void) mdb_tgt_vespec_iter(mdb.m_target, pt_ignore_sig, (void *)addr);
   1223 	return (DCMD_OK);
   1224 }
   1225 
   1226 /*ARGSUSED*/
   1227 static int
   1228 pt_attach(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1229 {
   1230 	mdb_tgt_t *t = mdb.m_target;
   1231 	pt_data_t *pt = t->t_data;
   1232 	int state, perr;
   1233 
   1234 	if (!(flags & DCMD_ADDRSPEC) && argc == 0)
   1235 		return (DCMD_USAGE);
   1236 
   1237 	if (((flags & DCMD_ADDRSPEC) && argc != 0) || argc > 1 ||
   1238 	    (argc != 0 && argv->a_type != MDB_TYPE_STRING))
   1239 		return (DCMD_USAGE);
   1240 
   1241 	if (t->t_pshandle != NULL && Pstate(t->t_pshandle) != PS_IDLE) {
   1242 		mdb_warn("debugger is already attached to a %s\n",
   1243 		    (Pstate(t->t_pshandle) == PS_DEAD) ? "core" : "process");
   1244 		return (DCMD_ERR);
   1245 	}
   1246 
   1247 	if (pt->p_fio == NULL) {
   1248 		mdb_warn("attach requires executable to be specified on "
   1249 		    "command-line (or use -p)\n");
   1250 		return (DCMD_ERR);
   1251 	}
   1252 
   1253 	if (flags & DCMD_ADDRSPEC)
   1254 		t->t_pshandle = Pgrab((pid_t)addr, pt->p_gflags, &perr);
   1255 	else
   1256 		t->t_pshandle = proc_arg_grab(argv->a_un.a_str,
   1257 		    PR_ARG_ANY, pt->p_gflags, &perr);
   1258 
   1259 	if (t->t_pshandle == NULL) {
   1260 		t->t_pshandle = pt->p_idlehandle;
   1261 		mdb_warn("cannot attach: %s\n", Pgrab_error(perr));
   1262 		return (DCMD_ERR);
   1263 	}
   1264 
   1265 	state = Pstate(t->t_pshandle);
   1266 	if (state != PS_DEAD && state != PS_IDLE) {
   1267 		(void) Punsetflags(t->t_pshandle, PR_KLC);
   1268 		(void) Psetflags(t->t_pshandle, PR_RLC);
   1269 		pt_post_attach(t);
   1270 		pt_activate_common(t);
   1271 	}
   1272 
   1273 	(void) mdb_tgt_status(t, &t->t_status);
   1274 	mdb_module_load_all(0);
   1275 	return (DCMD_OK);
   1276 }
   1277 
   1278 static int
   1279 pt_regstatus(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1280 {
   1281 	mdb_tgt_t *t = mdb.m_target;
   1282 
   1283 	if (t->t_pshandle != NULL) {
   1284 		const pstatus_t *psp = Pstatus(t->t_pshandle);
   1285 		int cursig = psp->pr_lwp.pr_cursig;
   1286 		char signame[SIG2STR_MAX];
   1287 		int state = Pstate(t->t_pshandle);
   1288 
   1289 		if (state != PS_DEAD && state != PS_IDLE)
   1290 			mdb_printf("process id = %d\n", psp->pr_pid);
   1291 		else
   1292 			mdb_printf("no process\n");
   1293 
   1294 		if (cursig != 0 && sig2str(cursig, signame) == 0)
   1295 			mdb_printf("SIG%s: %s\n", signame, strsignal(cursig));
   1296 	}
   1297 
   1298 	return (pt_regs(addr, flags, argc, argv));
   1299 }
   1300 
   1301 static int
   1302 pt_findstack(uintptr_t tid, uint_t flags, int argc, const mdb_arg_t *argv)
   1303 {
   1304 	mdb_tgt_t *t = mdb.m_target;
   1305 	mdb_tgt_gregset_t gregs;
   1306 	int showargs = 0;
   1307 	int count;
   1308 	uintptr_t pc, sp;
   1309 
   1310 	if (!(flags & DCMD_ADDRSPEC))
   1311 		return (DCMD_USAGE);
   1312 
   1313 	count = mdb_getopts(argc, argv, 'v', MDB_OPT_SETBITS, TRUE, &showargs,
   1314 	    NULL);
   1315 	argc -= count;
   1316 	argv += count;
   1317 
   1318 	if (argc > 1 || (argc == 1 && argv->a_type != MDB_TYPE_STRING))
   1319 		return (DCMD_USAGE);
   1320 
   1321 	if (PTL_GETREGS(t, tid, gregs.gregs) != 0) {
   1322 		mdb_warn("failed to get register set for thread %p", tid);
   1323 		return (DCMD_ERR);
   1324 	}
   1325 
   1326 	pc = gregs.gregs[R_PC];
   1327 #if defined(__i386) || defined(__amd64)
   1328 	sp = gregs.gregs[R_FP];
   1329 #else
   1330 	sp = gregs.gregs[R_SP];
   1331 #endif
   1332 	mdb_printf("stack pointer for thread %p: %p\n", tid, sp);
   1333 	if (pc != 0)
   1334 		mdb_printf("[ %0?lr %a() ]\n", sp, pc);
   1335 
   1336 	(void) mdb_inc_indent(2);
   1337 	mdb_set_dot(sp);
   1338 
   1339 	if (argc == 1)
   1340 		(void) mdb_eval(argv->a_un.a_str);
   1341 	else if (showargs)
   1342 		(void) mdb_eval("<.$C");
   1343 	else
   1344 		(void) mdb_eval("<.$C0");
   1345 
   1346 	(void) mdb_dec_indent(2);
   1347 	return (DCMD_OK);
   1348 }
   1349 
   1350 /*ARGSUSED*/
   1351 static int
   1352 pt_gcore(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1353 {
   1354 	mdb_tgt_t *t = mdb.m_target;
   1355 	char *prefix = "core";
   1356 	char *content_str = NULL;
   1357 	core_content_t content = CC_CONTENT_DEFAULT;
   1358 	size_t size;
   1359 	char *fname;
   1360 	pid_t pid;
   1361 
   1362 	if (flags & DCMD_ADDRSPEC)
   1363 		return (DCMD_USAGE);
   1364 
   1365 	if (mdb_getopts(argc, argv,
   1366 	    'o', MDB_OPT_STR, &prefix,
   1367 	    'c', MDB_OPT_STR, &content_str, NULL) != argc)
   1368 		return (DCMD_USAGE);
   1369 
   1370 	if (content_str != NULL &&
   1371 	    (proc_str2content(content_str, &content) != 0 ||
   1372 	    content == CC_CONTENT_INVALID)) {
   1373 		mdb_warn("invalid content string '%s'\n", content_str);
   1374 		return (DCMD_ERR);
   1375 	}
   1376 
   1377 	if (t->t_pshandle == NULL) {
   1378 		mdb_warn("no process active\n");
   1379 		return (DCMD_ERR);
   1380 	}
   1381 
   1382 	pid = Pstatus(t->t_pshandle)->pr_pid;
   1383 	size = 1 + mdb_snprintf(NULL, 0, "%s.%d", prefix, (int)pid);
   1384 	fname = mdb_alloc(size, UM_SLEEP | UM_GC);
   1385 	(void) mdb_snprintf(fname, size, "%s.%d", prefix, (int)pid);
   1386 
   1387 	if (Pgcore(t->t_pshandle, fname, content) != 0) {
   1388 		mdb_warn("couldn't dump core");
   1389 		return (DCMD_ERR);
   1390 	}
   1391 
   1392 	mdb_warn("%s dumped\n", fname);
   1393 
   1394 	return (DCMD_OK);
   1395 }
   1396 
   1397 /*ARGSUSED*/
   1398 static int
   1399 pt_kill(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1400 {
   1401 	mdb_tgt_t *t = mdb.m_target;
   1402 	pt_data_t *pt = t->t_data;
   1403 	int state;
   1404 
   1405 	if ((flags & DCMD_ADDRSPEC) || argc != 0)
   1406 		return (DCMD_USAGE);
   1407 
   1408 	if (t->t_pshandle != NULL &&
   1409 	    (state = Pstate(t->t_pshandle)) != PS_DEAD && state != PS_IDLE) {
   1410 		mdb_warn("victim process PID %d forcibly terminated\n",
   1411 		    (int)Pstatus(t->t_pshandle)->pr_pid);
   1412 		pt_pre_detach(t, TRUE);
   1413 		pt_release_parents(t);
   1414 		Prelease(t->t_pshandle, PRELEASE_KILL);
   1415 		t->t_pshandle = pt->p_idlehandle;
   1416 		(void) mdb_tgt_status(t, &t->t_status);
   1417 		mdb.m_flags &= ~(MDB_FL_VCREATE | MDB_FL_JOBCTL);
   1418 	} else
   1419 		mdb_warn("no victim process is currently under control\n");
   1420 
   1421 	return (DCMD_OK);
   1422 }
   1423 
   1424 /*ARGSUSED*/
   1425 static int
   1426 pt_detach(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1427 {
   1428 	mdb_tgt_t *t = mdb.m_target;
   1429 	pt_data_t *pt = t->t_data;
   1430 	int rflags = pt->p_rflags;
   1431 
   1432 	if (argc != 0 && argv->a_type == MDB_TYPE_STRING &&
   1433 	    strcmp(argv->a_un.a_str, "-a") == 0) {
   1434 		rflags = PRELEASE_HANG | PRELEASE_CLEAR;
   1435 		argv++;
   1436 		argc--;
   1437 	}
   1438 
   1439 	if ((flags & DCMD_ADDRSPEC) || argc != 0)
   1440 		return (DCMD_USAGE);
   1441 
   1442 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) == PS_IDLE) {
   1443 		mdb_warn("debugger is not currently attached to a process "
   1444 		    "or core file\n");
   1445 		return (DCMD_ERR);
   1446 	}
   1447 
   1448 	pt_pre_detach(t, TRUE);
   1449 	pt_release_parents(t);
   1450 	Prelease(t->t_pshandle, rflags);
   1451 	t->t_pshandle = pt->p_idlehandle;
   1452 	(void) mdb_tgt_status(t, &t->t_status);
   1453 	mdb.m_flags &= ~(MDB_FL_VCREATE | MDB_FL_JOBCTL);
   1454 
   1455 	return (DCMD_OK);
   1456 }
   1457 
   1458 static uintmax_t
   1459 reg_disc_get(const mdb_var_t *v)
   1460 {
   1461 	mdb_tgt_t *t = MDB_NV_COOKIE(v);
   1462 	mdb_tgt_tid_t tid = PTL_TID(t);
   1463 	mdb_tgt_reg_t r = 0;
   1464 
   1465 	if (tid != (mdb_tgt_tid_t)-1L)
   1466 		(void) mdb_tgt_getareg(t, tid, mdb_nv_get_name(v), &r);
   1467 
   1468 	return (r);
   1469 }
   1470 
   1471 static void
   1472 reg_disc_set(mdb_var_t *v, uintmax_t r)
   1473 {
   1474 	mdb_tgt_t *t = MDB_NV_COOKIE(v);
   1475 	mdb_tgt_tid_t tid = PTL_TID(t);
   1476 
   1477 	if (tid != (mdb_tgt_tid_t)-1L && mdb_tgt_putareg(t, tid,
   1478 	    mdb_nv_get_name(v), r) == -1)
   1479 		mdb_warn("failed to modify %%%s register", mdb_nv_get_name(v));
   1480 }
   1481 
   1482 static void
   1483 pt_print_reason(const lwpstatus_t *psp)
   1484 {
   1485 	char name[SIG2STR_MAX + 4]; /* enough for SIG+name+\0, syscall or flt */
   1486 	const char *desc;
   1487 
   1488 	switch (psp->pr_why) {
   1489 	case PR_REQUESTED:
   1490 		mdb_printf("stopped by debugger");
   1491 		break;
   1492 	case PR_SIGNALLED:
   1493 		mdb_printf("stopped on %s (%s)", proc_signame(psp->pr_what,
   1494 		    name, sizeof (name)), strsignal(psp->pr_what));
   1495 		break;
   1496 	case PR_SYSENTRY:
   1497 		mdb_printf("stopped on entry to %s system call",
   1498 		    proc_sysname(psp->pr_what, name, sizeof (name)));
   1499 		break;
   1500 	case PR_SYSEXIT:
   1501 		mdb_printf("stopped on exit from %s system call",
   1502 		    proc_sysname(psp->pr_what, name, sizeof (name)));
   1503 		break;
   1504 	case PR_JOBCONTROL:
   1505 		mdb_printf("stopped by job control");
   1506 		break;
   1507 	case PR_FAULTED:
   1508 		if (psp->pr_what == FLTBPT) {
   1509 			mdb_printf("stopped on a breakpoint");
   1510 		} else if (psp->pr_what == FLTWATCH) {
   1511 			switch (psp->pr_info.si_code) {
   1512 			case TRAP_RWATCH:
   1513 				desc = "read";
   1514 				break;
   1515 			case TRAP_WWATCH:
   1516 				desc = "write";
   1517 				break;
   1518 			case TRAP_XWATCH:
   1519 				desc = "execute";
   1520 				break;
   1521 			default:
   1522 				desc = "unknown";
   1523 			}
   1524 			mdb_printf("stopped %s a watchpoint (%s access to %p)",
   1525 			    psp->pr_info.si_trapafter ? "after" : "on",
   1526 			    desc, psp->pr_info.si_addr);
   1527 		} else if (psp->pr_what == FLTTRACE) {
   1528 			mdb_printf("stopped after a single-step");
   1529 		} else {
   1530 			mdb_printf("stopped on a %s fault",
   1531 			    proc_fltname(psp->pr_what, name, sizeof (name)));
   1532 		}
   1533 		break;
   1534 	case PR_SUSPENDED:
   1535 	case PR_CHECKPOINT:
   1536 		mdb_printf("suspended by the kernel");
   1537 		break;
   1538 	default:
   1539 		mdb_printf("stopped for unknown reason (%d/%d)",
   1540 		    psp->pr_why, psp->pr_what);
   1541 	}
   1542 }
   1543 
   1544 /*ARGSUSED*/
   1545 static int
   1546 pt_status_dcmd(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1547 {
   1548 	mdb_tgt_t *t = mdb.m_target;
   1549 	struct ps_prochandle *P = t->t_pshandle;
   1550 	pt_data_t *pt = t->t_data;
   1551 
   1552 	if (P != NULL) {
   1553 		const psinfo_t *pip = Ppsinfo(P);
   1554 		const pstatus_t *psp = Pstatus(P);
   1555 		int cursig = 0, bits = 0, coredump = 0;
   1556 		int state;
   1557 		GElf_Sym sym;
   1558 		uintptr_t panicstr;
   1559 		char panicbuf[128];
   1560 		const siginfo_t *sip = &(psp->pr_lwp.pr_info);
   1561 
   1562 		char execname[MAXPATHLEN], buf[BUFSIZ];
   1563 		char signame[SIG2STR_MAX + 4]; /* enough for SIG+name+\0 */
   1564 
   1565 		mdb_tgt_spec_desc_t desc;
   1566 		mdb_sespec_t *sep;
   1567 
   1568 		struct utsname uts;
   1569 		prcred_t cred;
   1570 		psinfo_t pi;
   1571 
   1572 		(void) strcpy(uts.nodename, "unknown machine");
   1573 		(void) Puname(P, &uts);
   1574 
   1575 		if (pip != NULL) {
   1576 			bcopy(pip, &pi, sizeof (psinfo_t));
   1577 			proc_unctrl_psinfo(&pi);
   1578 		} else
   1579 			bzero(&pi, sizeof (psinfo_t));
   1580 
   1581 		bits = pi.pr_dmodel == PR_MODEL_ILP32 ? 32 : 64;
   1582 
   1583 		state = Pstate(P);
   1584 		if (psp != NULL && state != PS_UNDEAD && state != PS_IDLE)
   1585 			cursig = psp->pr_lwp.pr_cursig;
   1586 
   1587 		if (state == PS_DEAD && pip != NULL) {
   1588 			mdb_printf("debugging core file of %s (%d-bit) "
   1589 			    "from %s\n", pi.pr_fname, bits, uts.nodename);
   1590 
   1591 		} else if (state == PS_DEAD) {
   1592 			mdb_printf("debugging core file\n");
   1593 
   1594 		} else if (state == PS_IDLE) {
   1595 			const GElf_Ehdr *ehp = &pt->p_file->gf_ehdr;
   1596 
   1597 			mdb_printf("debugging %s file (%d-bit)\n",
   1598 			    ehp->e_type == ET_EXEC ? "executable" : "object",
   1599 			    ehp->e_ident[EI_CLASS] == ELFCLASS32 ? 32 : 64);
   1600 
   1601 		} else if (state == PS_UNDEAD && pi.pr_pid == 0) {
   1602 			mdb_printf("debugging defunct process\n");
   1603 
   1604 		} else {
   1605 			mdb_printf("debugging PID %d (%d-bit)\n",
   1606 			    pi.pr_pid, bits);
   1607 		}
   1608 
   1609 		if (Pexecname(P, execname, sizeof (execname)) != NULL)
   1610 			mdb_printf("file: %s\n", execname);
   1611 
   1612 		if (pip != NULL && state == PS_DEAD)
   1613 			mdb_printf("initial argv: %s\n", pi.pr_psargs);
   1614 
   1615 		if (state != PS_UNDEAD && state != PS_IDLE) {
   1616 			mdb_printf("threading model: ");
   1617 			if (pt->p_ptl_ops == &proc_lwp_ops)
   1618 				mdb_printf("raw lwps\n");
   1619 			else
   1620 				mdb_printf("native threads\n");
   1621 		}
   1622 
   1623 		mdb_printf("status: ");
   1624 		switch (state) {
   1625 		case PS_RUN:
   1626 			ASSERT(!(psp->pr_flags & PR_STOPPED));
   1627 			mdb_printf("process is running");
   1628 			if (psp->pr_flags & PR_DSTOP)
   1629 				mdb_printf(", debugger stop directive pending");
   1630 			mdb_printf("\n");
   1631 			break;
   1632 
   1633 		case PS_STOP:
   1634 			ASSERT(psp->pr_flags & PR_STOPPED);
   1635 			pt_print_reason(&psp->pr_lwp);
   1636 
   1637 			if (psp->pr_flags & PR_DSTOP)
   1638 				mdb_printf(", debugger stop directive pending");
   1639 			if (psp->pr_flags & PR_ASLEEP)
   1640 				mdb_printf(", sleeping in %s system call",
   1641 				    proc_sysname(psp->pr_lwp.pr_syscall,
   1642 				    signame, sizeof (signame)));
   1643 
   1644 			mdb_printf("\n");
   1645 
   1646 			for (sep = t->t_matched; sep != T_SE_END;
   1647 			    sep = sep->se_matched) {
   1648 				mdb_printf("event: %s\n", sep->se_ops->se_info(
   1649 				    t, sep, mdb_list_next(&sep->se_velist),
   1650 				    &desc, buf, sizeof (buf)));
   1651 			}
   1652 			break;
   1653 
   1654 		case PS_LOST:
   1655 			mdb_printf("debugger lost control of process\n");
   1656 			break;
   1657 
   1658 		case PS_UNDEAD:
   1659 			coredump = WIFSIGNALED(pi.pr_wstat) &&
   1660 			    WCOREDUMP(pi.pr_wstat);
   1661 			/*FALLTHRU*/
   1662 
   1663 		case PS_DEAD:
   1664 			if (cursig == 0 && WIFSIGNALED(pi.pr_wstat))
   1665 				cursig = WTERMSIG(pi.pr_wstat);
   1666 			/*
   1667 			 * We can only use pr_wstat == 0 as a test for gcore if
   1668 			 * an NT_PRCRED note is present; these features were
   1669 			 * added at the same time in Solaris 8.
   1670 			 */
   1671 			if (pi.pr_wstat == 0 && Pstate(P) == PS_DEAD &&
   1672 			    Pcred(P, &cred, 1) == 0) {
   1673 				mdb_printf("process core file generated "
   1674 				    "with gcore(1)\n");
   1675 			} else if (cursig != 0) {
   1676 				mdb_printf("process terminated by %s (%s)",
   1677 				    proc_signame(cursig, signame,
   1678 				    sizeof (signame)), strsignal(cursig));
   1679 
   1680 				if (sip->si_signo != 0 && SI_FROMUSER(sip) &&
   1681 				    sip->si_pid != 0) {
   1682 					mdb_printf(", pid=%d uid=%u",
   1683 					    (int)sip->si_pid, sip->si_uid);
   1684 					if (sip->si_code != 0) {
   1685 						mdb_printf(" code=%d",
   1686 						    sip->si_code);
   1687 					}
   1688 				} else {
   1689 					switch (sip->si_signo) {
   1690 					case SIGILL:
   1691 					case SIGTRAP:
   1692 					case SIGFPE:
   1693 					case SIGSEGV:
   1694 					case SIGBUS:
   1695 					case SIGEMT:
   1696 						mdb_printf(", addr=%p",
   1697 						    sip->si_addr);
   1698 					default:
   1699 						break;
   1700 					}
   1701 				}
   1702 
   1703 				if (coredump)
   1704 					mdb_printf(" - core file dumped");
   1705 				mdb_printf("\n");
   1706 			} else {
   1707 				mdb_printf("process terminated with exit "
   1708 				    "status %d\n", WEXITSTATUS(pi.pr_wstat));
   1709 			}
   1710 
   1711 			if (Plookup_by_name(t->t_pshandle, "libc.so",
   1712 			    "panicstr", &sym) == 0 &&
   1713 			    Pread(t->t_pshandle, &panicstr, sizeof (panicstr),
   1714 			    sym.st_value) == sizeof (panicstr) &&
   1715 			    Pread_string(t->t_pshandle, panicbuf,
   1716 			    sizeof (panicbuf), panicstr) > 0) {
   1717 				mdb_printf("panic message: %s",
   1718 				    panicbuf);
   1719 			}
   1720 
   1721 
   1722 			break;
   1723 
   1724 		case PS_IDLE:
   1725 			mdb_printf("idle\n");
   1726 			break;
   1727 
   1728 		default:
   1729 			mdb_printf("unknown libproc Pstate: %d\n", Pstate(P));
   1730 		}
   1731 
   1732 	} else if (pt->p_file != NULL) {
   1733 		const GElf_Ehdr *ehp = &pt->p_file->gf_ehdr;
   1734 
   1735 		mdb_printf("debugging %s file (%d-bit)\n",
   1736 		    ehp->e_type == ET_EXEC ? "executable" : "object",
   1737 		    ehp->e_ident[EI_CLASS] == ELFCLASS32 ? 32 : 64);
   1738 		mdb_printf("executable file: %s\n", IOP_NAME(pt->p_fio));
   1739 		mdb_printf("status: idle\n");
   1740 	}
   1741 
   1742 	return (DCMD_OK);
   1743 }
   1744 
   1745 static int
   1746 pt_tls(uintptr_t tid, uint_t flags, int argc, const mdb_arg_t *argv)
   1747 {
   1748 	const char *name;
   1749 	const char *object;
   1750 	GElf_Sym sym;
   1751 	mdb_syminfo_t si;
   1752 	mdb_tgt_t *t = mdb.m_target;
   1753 
   1754 	if (!(flags & DCMD_ADDRSPEC) || argc > 1)
   1755 		return (DCMD_USAGE);
   1756 
   1757 	if (argc == 0) {
   1758 		psaddr_t b;
   1759 
   1760 		if (tlsbase(t, tid, PR_LMID_EVERY, MDB_TGT_OBJ_EXEC, &b) != 0) {
   1761 			mdb_warn("failed to lookup tlsbase for %r", tid);
   1762 			return (DCMD_ERR);
   1763 		}
   1764 
   1765 		mdb_printf("%lr\n", b);
   1766 		mdb_set_dot(b);
   1767 
   1768 		return (DCMD_OK);
   1769 	}
   1770 
   1771 	name = argv[0].a_un.a_str;
   1772 	object = MDB_TGT_OBJ_EVERY;
   1773 
   1774 	if (pt_lookup_by_name_thr(t, object, name, &sym, &si, tid) != 0) {
   1775 		mdb_warn("failed to lookup %s", name);
   1776 		return (DCMD_ABORT); /* avoid repeated failure */
   1777 	}
   1778 
   1779 	if (GELF_ST_TYPE(sym.st_info) != STT_TLS && DCMD_HDRSPEC(flags))
   1780 		mdb_warn("%s does not refer to thread local storage\n", name);
   1781 
   1782 	mdb_printf("%llr\n", sym.st_value);
   1783 	mdb_set_dot(sym.st_value);
   1784 
   1785 	return (DCMD_OK);
   1786 }
   1787 
   1788 /*ARGSUSED*/
   1789 static int
   1790 pt_tmodel(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1791 {
   1792 	mdb_tgt_t *t = mdb.m_target;
   1793 	pt_data_t *pt = t->t_data;
   1794 	const pt_ptl_ops_t *ptl_ops;
   1795 
   1796 	if (argc != 1 || argv->a_type != MDB_TYPE_STRING)
   1797 		return (DCMD_USAGE);
   1798 
   1799 	if (strcmp(argv->a_un.a_str, "thread") == 0)
   1800 		ptl_ops = &proc_tdb_ops;
   1801 	else if (strcmp(argv->a_un.a_str, "lwp") == 0)
   1802 		ptl_ops = &proc_lwp_ops;
   1803 	else
   1804 		return (DCMD_USAGE);
   1805 
   1806 	if (t->t_pshandle != NULL && pt->p_ptl_ops != ptl_ops) {
   1807 		PTL_DTOR(t);
   1808 		pt->p_tdb_ops = NULL;
   1809 		pt->p_ptl_ops = &proc_lwp_ops;
   1810 		pt->p_ptl_hdl = NULL;
   1811 
   1812 		if (ptl_ops == &proc_tdb_ops) {
   1813 			(void) Pobject_iter(t->t_pshandle, (proc_map_f *)
   1814 			    thr_check, t);
   1815 		}
   1816 	}
   1817 
   1818 	(void) mdb_tgt_status(t, &t->t_status);
   1819 	return (DCMD_OK);
   1820 }
   1821 
   1822 static const char *
   1823 env_match(const char *cmp, const char *nameval)
   1824 {
   1825 	const char *loc;
   1826 	size_t cmplen = strlen(cmp);
   1827 
   1828 	loc = strchr(nameval, '=');
   1829 	if (loc != NULL && (loc - nameval) == cmplen &&
   1830 	    strncmp(nameval, cmp, cmplen) == 0) {
   1831 		return (loc + 1);
   1832 	}
   1833 
   1834 	return (NULL);
   1835 }
   1836 
   1837 /*ARGSUSED*/
   1838 static int
   1839 print_env(void *data, struct ps_prochandle *P, uintptr_t addr,
   1840     const char *nameval)
   1841 {
   1842 	const char *value;
   1843 
   1844 	if (nameval == NULL) {
   1845 		mdb_printf("<0x%p>\n", addr);
   1846 	} else {
   1847 		if (data == NULL)
   1848 			mdb_printf("%s\n", nameval);
   1849 		else if ((value = env_match(data, nameval)) != NULL)
   1850 			mdb_printf("%s\n", value);
   1851 	}
   1852 
   1853 	return (0);
   1854 }
   1855 
   1856 /*ARGSUSED*/
   1857 static int
   1858 pt_getenv(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1859 {
   1860 	mdb_tgt_t *t = mdb.m_target;
   1861 	pt_data_t *pt = t->t_data;
   1862 	int i;
   1863 	uint_t opt_t = 0;
   1864 	mdb_var_t *v;
   1865 
   1866 	i = mdb_getopts(argc, argv,
   1867 	    't', MDB_OPT_SETBITS, TRUE, &opt_t, NULL);
   1868 
   1869 	argc -= i;
   1870 	argv += i;
   1871 
   1872 	if ((flags & DCMD_ADDRSPEC) || argc > 1)
   1873 		return (DCMD_USAGE);
   1874 
   1875 	if (argc == 1 && argv->a_type != MDB_TYPE_STRING)
   1876 		return (DCMD_USAGE);
   1877 
   1878 	if (opt_t && t->t_pshandle == NULL) {
   1879 		mdb_warn("no process active\n");
   1880 		return (DCMD_ERR);
   1881 	}
   1882 
   1883 	if (opt_t && (Pstate(t->t_pshandle) == PS_IDLE ||
   1884 	    Pstate(t->t_pshandle) == PS_UNDEAD)) {
   1885 		mdb_warn("-t option requires target to be running\n");
   1886 		return (DCMD_ERR);
   1887 	}
   1888 
   1889 	if (opt_t != 0) {
   1890 		if (Penv_iter(t->t_pshandle, print_env,
   1891 		    argc == 0 ? NULL : (void *)argv->a_un.a_str) != 0)
   1892 			return (DCMD_ERR);
   1893 	} else if (argc == 1) {
   1894 		if ((v = mdb_nv_lookup(&pt->p_env, argv->a_un.a_str)) == NULL)
   1895 			return (DCMD_ERR);
   1896 
   1897 		ASSERT(strchr(mdb_nv_get_cookie(v), '=') != NULL);
   1898 		mdb_printf("%s\n", strchr(mdb_nv_get_cookie(v), '=') + 1);
   1899 	} else {
   1900 
   1901 		mdb_nv_rewind(&pt->p_env);
   1902 		while ((v = mdb_nv_advance(&pt->p_env)) != NULL)
   1903 			mdb_printf("%s\n", mdb_nv_get_cookie(v));
   1904 	}
   1905 
   1906 	return (DCMD_OK);
   1907 }
   1908 
   1909 /*
   1910  * Function to set a variable in the internal environment, which is used when
   1911  * creating new processes.  Note that it is possible that 'nameval' can refer to
   1912  * read-only memory, if mdb calls putenv() on an existing value before calling
   1913  * this function.  While we should avoid this situation, this function is
   1914  * designed to be robust in the face of such changes.
   1915  */
   1916 static void
   1917 pt_env_set(pt_data_t *pt, const char *nameval)
   1918 {
   1919 	mdb_var_t *v;
   1920 	char *equals, *val;
   1921 	const char *name;
   1922 	size_t len;
   1923 
   1924 	if ((equals = strchr(nameval, '=')) != NULL) {
   1925 		val = strdup(nameval);
   1926 		equals = val + (equals - nameval);
   1927 	} else {
   1928 		/*
   1929 		 * nameval doesn't contain an equals character.  Convert this to
   1930 		 * be 'nameval='.
   1931 		 */
   1932 		len = strlen(nameval);
   1933 		val = mdb_alloc(len + 2, UM_SLEEP);
   1934 		(void) mdb_snprintf(val, len + 2, "%s=", nameval);
   1935 		equals = val + len;
   1936 	}
   1937 
   1938 	/* temporary truncate the string for lookup/insert */
   1939 	*equals = '\0';
   1940 	v = mdb_nv_lookup(&pt->p_env, val);
   1941 
   1942 	if (v != NULL) {
   1943 		char *old = mdb_nv_get_cookie(v);
   1944 		mdb_free(old, strlen(old) + 1);
   1945 		name = mdb_nv_get_name(v);
   1946 	} else {
   1947 		/*
   1948 		 * The environment is created using MDB_NV_EXTNAME, so we must
   1949 		 * provide external storage for the variable names.
   1950 		 */
   1951 		name = strdup(val);
   1952 	}
   1953 
   1954 	*equals = '=';
   1955 
   1956 	(void) mdb_nv_insert(&pt->p_env, name, NULL, (uintptr_t)val,
   1957 	    MDB_NV_EXTNAME);
   1958 
   1959 	if (equals)
   1960 		*equals = '=';
   1961 }
   1962 
   1963 /*
   1964  * Clears the internal environment.
   1965  */
   1966 static void
   1967 pt_env_clear(pt_data_t *pt)
   1968 {
   1969 	mdb_var_t *v;
   1970 	char *val, *name;
   1971 
   1972 	mdb_nv_rewind(&pt->p_env);
   1973 	while ((v = mdb_nv_advance(&pt->p_env)) != NULL) {
   1974 
   1975 		name = (char *)mdb_nv_get_name(v);
   1976 		val = mdb_nv_get_cookie(v);
   1977 
   1978 		mdb_nv_remove(&pt->p_env, v);
   1979 
   1980 		mdb_free(name, strlen(name) + 1);
   1981 		mdb_free(val, strlen(val) + 1);
   1982 	}
   1983 }
   1984 
   1985 /*ARGSUSED*/
   1986 static int
   1987 pt_setenv(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   1988 {
   1989 	mdb_tgt_t *t = mdb.m_target;
   1990 	pt_data_t *pt = t->t_data;
   1991 	char *nameval;
   1992 	size_t len;
   1993 	int alloc;
   1994 
   1995 	if ((flags & DCMD_ADDRSPEC) || argc == 0 || argc > 2)
   1996 		return (DCMD_USAGE);
   1997 
   1998 	if ((argc > 0 && argv[0].a_type != MDB_TYPE_STRING) ||
   1999 	    (argc > 1 && argv[1].a_type != MDB_TYPE_STRING))
   2000 		return (DCMD_USAGE);
   2001 
   2002 	if (t->t_pshandle == NULL) {
   2003 		mdb_warn("no process active\n");
   2004 		return (DCMD_ERR);
   2005 	}
   2006 
   2007 	/*
   2008 	 * If the process is in some sort of running state, warn the user that
   2009 	 * changes won't immediately take effect.
   2010 	 */
   2011 	if (Pstate(t->t_pshandle) == PS_RUN ||
   2012 	    Pstate(t->t_pshandle) == PS_STOP) {
   2013 		mdb_warn("warning: changes will not take effect until process"
   2014 		    " is restarted\n");
   2015 	}
   2016 
   2017 	/*
   2018 	 * We allow two forms of operation.  The first is the usual "name=value"
   2019 	 * parameter.  We also allow the user to specify two arguments, where
   2020 	 * the first is the name of the variable, and the second is the value.
   2021 	 */
   2022 	alloc = 0;
   2023 	if (argc == 1) {
   2024 		nameval = (char *)argv->a_un.a_str;
   2025 	} else {
   2026 		len = strlen(argv[0].a_un.a_str) +
   2027 		    strlen(argv[1].a_un.a_str) + 2;
   2028 		nameval = mdb_alloc(len, UM_SLEEP);
   2029 		(void) mdb_snprintf(nameval, len, "%s=%s", argv[0].a_un.a_str,
   2030 		    argv[1].a_un.a_str);
   2031 		alloc = 1;
   2032 	}
   2033 
   2034 	pt_env_set(pt, nameval);
   2035 
   2036 	if (alloc)
   2037 		mdb_free(nameval, strlen(nameval) + 1);
   2038 
   2039 	return (DCMD_OK);
   2040 }
   2041 
   2042 /*ARGSUSED*/
   2043 static int
   2044 pt_unsetenv(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
   2045 {
   2046 	mdb_tgt_t *t = mdb.m_target;
   2047 	pt_data_t *pt = t->t_data;
   2048 	mdb_var_t *v;
   2049 	char *value, *name;
   2050 
   2051 	if ((flags & DCMD_ADDRSPEC) || argc > 1)
   2052 		return (DCMD_USAGE);
   2053 
   2054 	if (argc == 1 && argv->a_type != MDB_TYPE_STRING)
   2055 		return (DCMD_USAGE);
   2056 
   2057 	if (t->t_pshandle == NULL) {
   2058 		mdb_warn("no process active\n");
   2059 		return (DCMD_ERR);
   2060 	}
   2061 
   2062 	/*
   2063 	 * If the process is in some sort of running state, warn the user that
   2064 	 * changes won't immediately take effect.
   2065 	 */
   2066 	if (Pstate(t->t_pshandle) == PS_RUN ||
   2067 	    Pstate(t->t_pshandle) == PS_STOP) {
   2068 		mdb_warn("warning: changes will not take effect until process"
   2069 		    " is restarted\n");
   2070 	}
   2071 
   2072 	if (argc == 0) {
   2073 		pt_env_clear(pt);
   2074 	} else {
   2075 		if ((v = mdb_nv_lookup(&pt->p_env, argv->a_un.a_str)) != NULL) {
   2076 			name = (char *)mdb_nv_get_name(v);
   2077 			value = mdb_nv_get_cookie(v);
   2078 
   2079 			mdb_nv_remove(&pt->p_env, v);
   2080 
   2081 			mdb_free(name, strlen(name) + 1);
   2082 			mdb_free(value, strlen(value) + 1);
   2083 		}
   2084 	}
   2085 
   2086 	return (DCMD_OK);
   2087 }
   2088 
   2089 void
   2090 getenv_help(void)
   2091 {
   2092 	mdb_printf("-t  show current process environment"
   2093 	    " instead of initial environment.\n");
   2094 }
   2095 
   2096 static const mdb_dcmd_t pt_dcmds[] = {
   2097 	{ "$c", "?[cnt]", "print stack backtrace", pt_stack },
   2098 	{ "$C", "?[cnt]", "print stack backtrace", pt_stackv },
   2099 	{ "$i", NULL, "print signals that are ignored", pt_ignored },
   2100 	{ "$l", NULL, "print the representative thread's lwp id", pt_lwpid },
   2101 	{ "$L", NULL, "print list of the active lwp ids", pt_lwpids },
   2102 	{ "$r", "?", "print general-purpose registers", pt_regs },
   2103 	{ "$x", "?", "print floating point registers", pt_fpregs },
   2104 	{ "$X", "?", "print floating point registers", pt_fpregs },
   2105 	{ "$y", "?", "print floating point registers", pt_fpregs },
   2106 	{ "$Y", "?", "print floating point registers", pt_fpregs },
   2107 	{ "$?", "?", "print status and registers", pt_regstatus },
   2108 	{ ":A", "?[core|pid]", "attach to process or core file", pt_attach },
   2109 	{ ":i", ":", "ignore signal (delete all matching events)", pt_ignore },
   2110 	{ ":k", NULL, "forcibly kill and release target", pt_kill },
   2111 	{ ":R", "[-a]", "release the previously attached process", pt_detach },
   2112 	{ "attach", "?[core|pid]",
   2113 	    "attach to process or core file", pt_attach },
   2114 	{ "findstack", ":[-v]", "find user thread stack", pt_findstack },
   2115 	{ "gcore", "[-o prefix] [-c content]",
   2116 	    "produce a core file for the attached process", pt_gcore },
   2117 	{ "getenv", "[-t] [name]", "display an environment variable",
   2118 		pt_getenv, getenv_help },
   2119 	{ "kill", NULL, "forcibly kill and release target", pt_kill },
   2120 	{ "release", "[-a]",
   2121 	    "release the previously attached process", pt_detach },
   2122 	{ "regs", "?", "print general-purpose registers", pt_regs },
   2123 	{ "fpregs", "?[-dqs]", "print floating point registers", pt_fpregs },
   2124 	{ "setenv", "name=value", "set an environment variable", pt_setenv },
   2125 	{ "stack", "?[cnt]", "print stack backtrace", pt_stack },
   2126 	{ "stackregs", "?", "print stack backtrace and registers", pt_stackr },
   2127 	{ "status", NULL, "print summary of current target", pt_status_dcmd },
   2128 	{ "tls", ":symbol",
   2129 	    "lookup TLS data in the context of a given thread", pt_tls },
   2130 	{ "tmodel", "{thread|lwp}", NULL, pt_tmodel },
   2131 	{ "unsetenv", "[name]", "clear an environment variable", pt_unsetenv },
   2132 	{ NULL }
   2133 };
   2134 
   2135 static void
   2136 pt_thr_walk_fini(mdb_walk_state_t *wsp)
   2137 {
   2138 	mdb_addrvec_destroy(wsp->walk_data);
   2139 	mdb_free(wsp->walk_data, sizeof (mdb_addrvec_t));
   2140 }
   2141 
   2142 static int
   2143 pt_thr_walk_init(mdb_walk_state_t *wsp)
   2144 {
   2145 	wsp->walk_data = mdb_zalloc(sizeof (mdb_addrvec_t), UM_SLEEP);
   2146 	mdb_addrvec_create(wsp->walk_data);
   2147 
   2148 	if (PTL_ITER(mdb.m_target, wsp->walk_data) == -1) {
   2149 		mdb_warn("failed to iterate over threads");
   2150 		pt_thr_walk_fini(wsp);
   2151 		return (WALK_ERR);
   2152 	}
   2153 
   2154 	return (WALK_NEXT);
   2155 }
   2156 
   2157 static int
   2158 pt_thr_walk_step(mdb_walk_state_t *wsp)
   2159 {
   2160 	if (mdb_addrvec_length(wsp->walk_data) != 0) {
   2161 		return (wsp->walk_callback(mdb_addrvec_shift(wsp->walk_data),
   2162 		    NULL, wsp->walk_cbdata));
   2163 	}
   2164 	return (WALK_DONE);
   2165 }
   2166 
   2167 static const mdb_walker_t pt_walkers[] = {
   2168 	{ "thread", "walk list of valid thread identifiers",
   2169 	    pt_thr_walk_init, pt_thr_walk_step, pt_thr_walk_fini },
   2170 	{ NULL }
   2171 };
   2172 
   2173 
   2174 static void
   2175 pt_activate_common(mdb_tgt_t *t)
   2176 {
   2177 	pt_data_t *pt = t->t_data;
   2178 	GElf_Sym sym;
   2179 
   2180 	/*
   2181 	 * If we have a libproc handle and AT_BASE is set, the process or core
   2182 	 * is dynamically linked.  We call Prd_agent() to force libproc to
   2183 	 * try to initialize librtld_db, and issue a warning if that fails.
   2184 	 */
   2185 	if (t->t_pshandle != NULL && Pgetauxval(t->t_pshandle,
   2186 	    AT_BASE) != -1L && Prd_agent(t->t_pshandle) == NULL) {
   2187 		mdb_warn("warning: librtld_db failed to initialize; shared "
   2188 		    "library information will not be available\n");
   2189 	}
   2190 
   2191 	/*
   2192 	 * If we have a libproc handle and libthread is loaded, attempt to load
   2193 	 * and initialize the corresponding libthread_db.  If this fails, fall
   2194 	 * back to our native LWP implementation and issue a warning.
   2195 	 */
   2196 	if (t->t_pshandle != NULL && Pstate(t->t_pshandle) != PS_IDLE)
   2197 		(void) Pobject_iter(t->t_pshandle, (proc_map_f *)thr_check, t);
   2198 
   2199 	/*
   2200 	 * If there's a global object named '_mdb_abort_info', assuming we're
   2201 	 * debugging mdb itself and load the developer support module.
   2202 	 */
   2203 	if (mdb_gelf_symtab_lookup_by_name(pt->p_symtab, "_mdb_abort_info",
   2204 	    &sym, NULL) == 0 && GELF_ST_TYPE(sym.st_info) == STT_OBJECT) {
   2205 		if (mdb_module_load("mdb_ds", MDB_MOD_SILENT) < 0)
   2206 			mdb_warn("warning: failed to load developer support\n");
   2207 	}
   2208 
   2209 	mdb_tgt_elf_export(pt->p_file);
   2210 }
   2211 
   2212 static void
   2213 pt_activate(mdb_tgt_t *t)
   2214 {
   2215 	static const mdb_nv_disc_t reg_disc = { reg_disc_set, reg_disc_get };
   2216 
   2217 	pt_data_t *pt = t->t_data;
   2218 	struct utsname u1, u2;
   2219 	mdb_var_t *v;
   2220 	core_content_t content;
   2221 
   2222 	if (t->t_pshandle) {
   2223 		mdb_prop_postmortem = (Pstate(t->t_pshandle) == PS_DEAD);
   2224 		mdb_prop_kernel = FALSE;
   2225 	} else
   2226 		mdb_prop_kernel = mdb_prop_postmortem = FALSE;
   2227 
   2228 	mdb_prop_datamodel = MDB_TGT_MODEL_NATIVE;
   2229 
   2230 	/*
   2231 	 * If we're examining a core file that doesn't contain program text,
   2232 	 * and uname(2) doesn't match the NT_UTSNAME note recorded in the
   2233 	 * core file, issue a warning.
   2234 	 */
   2235 	if (mdb_prop_postmortem == TRUE &&
   2236 	    ((content = Pcontent(t->t_pshandle)) == CC_CONTENT_INVALID ||
   2237 	    !(content & CC_CONTENT_TEXT)) &&
   2238 	    uname(&u1) >= 0 && Puname(t->t_pshandle, &u2) == 0 &&
   2239 	    (strcmp(u1.release, u2.release) != 0 ||
   2240 	    strcmp(u1.version, u2.version) != 0)) {
   2241 		mdb_warn("warning: core file is from %s %s %s; shared text "
   2242 		    "mappings may not match installed libraries\n",
   2243 		    u2.sysname, u2.release, u2.version);
   2244 	}
   2245 
   2246 	/*
   2247 	 * Perform the common initialization tasks -- these are shared with
   2248 	 * the pt_exec() and pt_run() subroutines.
   2249 	 */
   2250 	pt_activate_common(t);
   2251 
   2252 	(void) mdb_tgt_register_dcmds(t, &pt_dcmds[0], MDB_MOD_FORCE);
   2253 	(void) mdb_tgt_register_walkers(t, &pt_walkers[0], MDB_MOD_FORCE);
   2254 
   2255 	/*
   2256 	 * Iterate through our register description list and export
   2257 	 * each register as a named variable.
   2258 	 */
   2259 	mdb_nv_rewind(&pt->p_regs);
   2260 	while ((v = mdb_nv_advance(&pt->p_regs)) != NULL) {
   2261 		ushort_t rd_flags = MDB_TGT_R_FLAGS(mdb_nv_get_value(v));
   2262 
   2263 		if (!(rd_flags & MDB_TGT_R_EXPORT))
   2264 			continue; /* Don't export register as a variable */
   2265 
   2266 		(void) mdb_nv_insert(&mdb.m_nv, mdb_nv_get_name(v), &reg_disc,
   2267 		    (uintptr_t)t, MDB_NV_PERSIST);
   2268 	}
   2269 }
   2270 
   2271 static void
   2272 pt_deactivate(mdb_tgt_t *t)
   2273 {
   2274 	pt_data_t *pt = t->t_data;
   2275 	const mdb_dcmd_t *dcp;
   2276 	const mdb_walker_t *wp;
   2277 	mdb_var_t *v, *w;
   2278 
   2279 	mdb_nv_rewind(&pt->p_regs);
   2280 	while ((v = mdb_nv_advance(&pt->p_regs)) != NULL) {
   2281 		ushort_t rd_flags = MDB_TGT_R_FLAGS(mdb_nv_get_value(v));
   2282 
   2283 		if (!(rd_flags & MDB_TGT_R_EXPORT))
   2284 			continue; /* Didn't export register as a variable */
   2285 
   2286 		if (w = mdb_nv_lookup(&mdb.m_nv, mdb_nv_get_name(v))) {
   2287 			w->v_flags &= ~MDB_NV_PERSIST;
   2288 			mdb_nv_remove(&mdb.m_nv, w);
   2289 		}
   2290 	}
   2291 
   2292 	for (wp = &pt_walkers[0]; wp->walk_name != NULL; wp++) {
   2293 		if (mdb_module_remove_walker(t->t_module, wp->walk_name) == -1)
   2294 			warn("failed to remove walk %s", wp->walk_name);
   2295 	}
   2296 
   2297 	for (dcp = &pt_dcmds[0]; dcp->dc_name != NULL; dcp++) {
   2298 		if (mdb_module_remove_dcmd(t->t_module, dcp->dc_name) == -1)
   2299 			warn("failed to remove dcmd %s", dcp->dc_name);
   2300 	}
   2301 
   2302 	mdb_prop_postmortem = FALSE;
   2303 	mdb_prop_kernel = FALSE;
   2304 	mdb_prop_datamodel = MDB_TGT_MODEL_UNKNOWN;
   2305 }
   2306 
   2307 static void
   2308 pt_periodic(mdb_tgt_t *t)
   2309 {
   2310 	pt_data_t *pt = t->t_data;
   2311 
   2312 	if (pt->p_rdstate == PT_RD_CONSIST) {
   2313 		if (t->t_pshandle != NULL && Pstate(t->t_pshandle) < PS_LOST &&
   2314 		    !(mdb.m_flags & MDB_FL_NOMODS)) {
   2315 			mdb_printf("%s: You've got symbols!\n", mdb.m_pname);
   2316 			mdb_module_load_all(0);
   2317 		}
   2318 		pt->p_rdstate = PT_RD_NONE;
   2319 	}
   2320 }
   2321 
   2322 static void
   2323 pt_destroy(mdb_tgt_t *t)
   2324 {
   2325 	pt_data_t *pt = t->t_data;
   2326 
   2327 	if (pt->p_idlehandle != NULL && pt->p_idlehandle != t->t_pshandle)
   2328 		Prelease(pt->p_idlehandle, 0);
   2329 
   2330 	if (t->t_pshandle != NULL) {
   2331 		PTL_DTOR(t);
   2332 		pt_release_parents(t);
   2333 		pt_pre_detach(t, TRUE);
   2334 		Prelease(t->t_pshandle, pt->p_rflags);
   2335 	}
   2336 
   2337 	mdb.m_flags &= ~(MDB_FL_VCREATE | MDB_FL_JOBCTL);
   2338 	pt_close_aout(t);
   2339 
   2340 	if (pt->p_aout_fio != NULL)
   2341 		mdb_io_rele(pt->p_aout_fio);
   2342 
   2343 	pt_env_clear(pt);
   2344 	mdb_nv_destroy(&pt->p_env);
   2345 
   2346 	mdb_nv_destroy(&pt->p_regs);
   2347 	mdb_free(pt, sizeof (pt_data_t));
   2348 }
   2349 
   2350 /*ARGSUSED*/
   2351 static const char *
   2352 pt_name(mdb_tgt_t *t)
   2353 {
   2354 	return ("proc");
   2355 }
   2356 
   2357 static const char *
   2358 pt_platform(mdb_tgt_t *t)
   2359 {
   2360 	pt_data_t *pt = t->t_data;
   2361 
   2362 	if (t->t_pshandle != NULL &&
   2363 	    Pplatform(t->t_pshandle, pt->p_platform, MAXNAMELEN) != NULL)
   2364 		return (pt->p_platform);
   2365 
   2366 	return (mdb_conf_platform());
   2367 }
   2368 
   2369 static int
   2370 pt_uname(mdb_tgt_t *t, struct utsname *utsp)
   2371 {
   2372 	if (t->t_pshandle != NULL)
   2373 		return (Puname(t->t_pshandle, utsp));
   2374 
   2375 	return (uname(utsp) >= 0 ? 0 : -1);
   2376 }
   2377 
   2378 static int
   2379 pt_dmodel(mdb_tgt_t *t)
   2380 {
   2381 	if (t->t_pshandle == NULL)
   2382 		return (MDB_TGT_MODEL_NATIVE);
   2383 
   2384 	switch (Pstatus(t->t_pshandle)->pr_dmodel) {
   2385 	case PR_MODEL_ILP32:
   2386 		return (MDB_TGT_MODEL_ILP32);
   2387 	case PR_MODEL_LP64:
   2388 		return (MDB_TGT_MODEL_LP64);
   2389 	}
   2390 
   2391 	return (MDB_TGT_MODEL_UNKNOWN);
   2392 }
   2393 
   2394 static ssize_t
   2395 pt_vread(mdb_tgt_t *t, void *buf, size_t nbytes, uintptr_t addr)
   2396 {
   2397 	ssize_t n;
   2398 
   2399 	/*
   2400 	 * If no handle is open yet, reads from virtual addresses are
   2401 	 * allowed to succeed but return zero-filled memory.
   2402 	 */
   2403 	if (t->t_pshandle == NULL) {
   2404 		bzero(buf, nbytes);
   2405 		return (nbytes);
   2406 	}
   2407 
   2408 	if ((n = Pread(t->t_pshandle, buf, nbytes, addr)) <= 0)
   2409 		return (set_errno(EMDB_NOMAP));
   2410 
   2411 	return (n);
   2412 }
   2413 
   2414 static ssize_t
   2415 pt_vwrite(mdb_tgt_t *t, const void *buf, size_t nbytes, uintptr_t addr)
   2416 {
   2417 	ssize_t n;
   2418 
   2419 	/*
   2420 	 * If no handle is open yet, writes to virtual addresses are
   2421 	 * allowed to succeed but do not actually modify anything.
   2422 	 */
   2423 	if (t->t_pshandle == NULL)
   2424 		return (nbytes);
   2425 
   2426 	n = Pwrite(t->t_pshandle, buf, nbytes, addr);
   2427 
   2428 	if (n == -1 && errno == EIO)
   2429 		return (set_errno(EMDB_NOMAP));
   2430 
   2431 	return (n);
   2432 }
   2433 
   2434 static ssize_t
   2435 pt_fread(mdb_tgt_t *t, void *buf, size_t nbytes, uintptr_t addr)
   2436 {
   2437 	pt_data_t *pt = t->t_data;
   2438 
   2439 	if (pt->p_file != NULL) {
   2440 		return (mdb_gelf_rw(pt->p_file, buf, nbytes, addr,
   2441 		    IOPF_READ(pt->p_fio), GIO_READ));
   2442 	}
   2443 
   2444 	bzero(buf, nbytes);
   2445 	return (nbytes);
   2446 }
   2447 
   2448 static ssize_t
   2449 pt_fwrite(mdb_tgt_t *t, const void *buf, size_t nbytes, uintptr_t addr)
   2450 {
   2451 	pt_data_t *pt = t->t_data;
   2452 
   2453 	if (pt->p_file != NULL) {
   2454 		return (mdb_gelf_rw(pt->p_file, (void *)buf, nbytes, addr,
   2455 		    IOPF_WRITE(pt->p_fio), GIO_WRITE));
   2456 	}
   2457 
   2458 	return (nbytes);
   2459 }
   2460 
   2461 static const char *
   2462 pt_resolve_lmid(const char *object, Lmid_t *lmidp)
   2463 {
   2464 	Lmid_t lmid = PR_LMID_EVERY;
   2465 	const char *p;
   2466 
   2467 	if (object == MDB_TGT_OBJ_EVERY || object == MDB_TGT_OBJ_EXEC)
   2468 		lmid = LM_ID_BASE; /* restrict scope to a.out's link map */
   2469 	else if (object != MDB_TGT_OBJ_RTLD && strncmp(object, "LM", 2) == 0 &&
   2470 	    (p = strchr(object, '`')) != NULL) {
   2471 		object += 2;	/* skip past initial "LM" prefix */
   2472 		lmid = strntoul(object, (size_t)(p - object), mdb.m_radix);
   2473 		object = p + 1;	/* skip past link map specifier */
   2474 	}
   2475 
   2476 	*lmidp = lmid;
   2477 	return (object);
   2478 }
   2479 
   2480 static int
   2481 tlsbase(mdb_tgt_t *t, mdb_tgt_tid_t tid, Lmid_t lmid, const char *object,
   2482     psaddr_t *basep)
   2483 {
   2484 	pt_data_t *pt = t->t_data;
   2485 	const rd_loadobj_t *loadobjp;
   2486 	td_thrhandle_t th;
   2487 	td_err_e err;
   2488 
   2489 	if (object == MDB_TGT_OBJ_EVERY)
   2490 		return (set_errno(EINVAL));
   2491 
   2492 	if (t->t_pshandle == NULL || Pstate(t->t_pshandle) == PS_IDLE)
   2493 		return (set_errno(EMDB_NOPROC));
   2494 
   2495 	if (pt->p_tdb_ops == NULL)
   2496 		return (set_errno(EMDB_TDB));
   2497 
   2498 	err = pt->p_tdb_ops->td_ta_map_id2thr(pt->p_ptl_hdl, tid, &th);
   2499 	if (err != TD_OK)
   2500 		return (set_errno(tdb_to_errno(err)));
   2501 
   2502 	/*
   2503 	 * If this fails, rtld_db has failed to initialize properly.
   2504 	 */
   2505 	if ((loadobjp = Plmid_to_loadobj(t->t_pshandle, lmid, object)) == NULL)
   2506 		return (set_errno(EMDB_NORTLD));
   2507 
   2508 	/*
   2509 	 * This will fail if the TLS block has not been allocated for the
   2510 	 * object that contains the TLS symbol in question.
   2511 	 */
   2512 	err = pt->p_tdb_ops->td_thr_tlsbase(&th, loadobjp->rl_tlsmodid, basep);
   2513 	if (err != TD_OK)
   2514 		return (set_errno(tdb_to_errno(err)));
   2515 
   2516 	return (0);
   2517 }
   2518 
   2519 typedef struct {
   2520 	mdb_tgt_t	*pl_tgt;
   2521 	const char	*pl_name;
   2522 	Lmid_t		pl_lmid;
   2523 	GElf_Sym	*pl_symp;
   2524 	mdb_syminfo_t	*pl_sip;
   2525 	mdb_tgt_tid_t	pl_tid;
   2526 	mdb_bool_t	pl_found;
   2527 } pt_lookup_t;
   2528 
   2529 /*ARGSUSED*/
   2530 static int
   2531 pt_lookup_cb(void *data, const prmap_t *pmp, const char *object)
   2532 {
   2533 	pt_lookup_t *plp = data;
   2534 	struct ps_prochandle *P = plp->pl_tgt->t_pshandle;
   2535 	prsyminfo_t si;
   2536 	GElf_Sym sym;
   2537 
   2538 	if (Pxlookup_by_name(P, plp->pl_lmid, object, plp->pl_name, &sym,
   2539 	    &si) != 0)
   2540 		return (0);
   2541 
   2542 	/*
   2543 	 * If we encounter a match with SHN_UNDEF, keep looking for a
   2544 	 * better match. Return the first match with SHN_UNDEF set if no
   2545 	 * better match is found.
   2546 	 */
   2547 	if (sym.st_shndx == SHN_UNDEF) {
   2548 		if (!plp->pl_found) {
   2549 			plp->pl_found = TRUE;
   2550 			*plp->pl_symp = sym;
   2551 			plp->pl_sip->sym_table = si.prs_table;
   2552 			plp->pl_sip->sym_id = si.prs_id;
   2553 		}
   2554 
   2555 		return (0);
   2556 	}
   2557 
   2558 	/*
   2559 	 * Note that if the symbol's st_shndx is SHN_UNDEF we don't have the
   2560 	 * TLS offset anyway, so adding in the tlsbase would be worthless.
   2561 	 */
   2562 	if (GELF_ST_TYPE(sym.st_info) == STT_TLS &&
   2563 	    plp->pl_tid != (mdb_tgt_tid_t)-1) {
   2564 		psaddr_t base;
   2565 
   2566 		if (tlsbase(plp->pl_tgt, plp->pl_tid, plp->pl_lmid, object,
   2567 		    &base) != 0)
   2568 			return (-1); /* errno is set for us */
   2569 
   2570 		sym.st_value += base;
   2571 	}
   2572 
   2573 	plp->pl_found = TRUE;
   2574 	*plp->pl_symp = sym;
   2575 	plp->pl_sip->sym_table = si.prs_table;
   2576 	plp->pl_sip->sym_id = si.prs_id;
   2577 
   2578 	return (1);
   2579 }
   2580 
   2581 /*
   2582  * Lookup the symbol with a thread context so that we can adjust TLS symbols
   2583  * to get the values as they would appear in the context of the given thread.
   2584  */
   2585 static int
   2586 pt_lookup_by_name_thr(mdb_tgt_t *t, const char *object,
   2587     const char *name, GElf_Sym *symp, mdb_syminfo_t *sip, mdb_tgt_tid_t tid)
   2588 {
   2589 	struct ps_prochandle *P = t->t_pshandle;
   2590 	pt_data_t *pt = t->t_data;
   2591 	Lmid_t lmid;
   2592 	uint_t i;
   2593 	const rd_loadobj_t *aout_lop;
   2594 
   2595 	object = pt_resolve_lmid(object, &lmid);
   2596 
   2597 	if (P != NULL) {
   2598 		pt_lookup_t pl;
   2599 
   2600 		pl.pl_tgt = t;
   2601 		pl.pl_name = name;
   2602 		pl.pl_lmid = lmid;
   2603 		pl.pl_symp = symp;
   2604 		pl.pl_sip = sip;
   2605 		pl.pl_tid = tid;
   2606 		pl.pl_found = FALSE;
   2607 
   2608 		if (object == MDB_TGT_OBJ_EVERY) {
   2609 			if (Pobject_iter_resolved(P, pt_lookup_cb, &pl) == -1)
   2610 				return (-1); /* errno is set for us */
   2611 			if ((!pl.pl_found) &&
   2612 			    (Pobject_iter(P, pt_lookup_cb, &pl) == -1))
   2613 				return (-1); /* errno is set for us */
   2614 		} else {
   2615 			const prmap_t *pmp;
   2616 
   2617 			/*
   2618 			 * This can fail either due to an invalid lmid or
   2619 			 * an invalid object. To determine which is
   2620 			 * faulty, we test the lmid against known valid
   2621 			 * lmids and then see if using a wild-card lmid
   2622 			 * improves ths situation.
   2623 			 */
   2624 			if ((pmp = Plmid_to_map(P, lmid, object)) == NULL) {
   2625 				if (lmid != PR_LMID_EVERY &&
   2626 				    lmid != LM_ID_BASE &&
   2627 				    lmid != LM_ID_LDSO &&
   2628 				    Plmid_to_map(P, PR_LMID_EVERY, object)
   2629 				    != NULL)
   2630 					return (set_errno(EMDB_NOLMID));
   2631 				else
   2632 					return (set_errno(EMDB_NOOBJ));
   2633 			}
   2634 
   2635 			if (pt_lookup_cb(&pl, pmp, object) == -1)
   2636 				return (-1); /* errno is set for us */
   2637 		}
   2638 
   2639 		if (pl.pl_found)
   2640 			return (0);
   2641 	}
   2642 
   2643 	/*
   2644 	 * If libproc doesn't have the symbols for rtld, we're cooked --
   2645 	 * mdb doesn't have those symbols either.
   2646 	 */
   2647 	if (object == MDB_TGT_OBJ_RTLD)
   2648 		return (set_errno(EMDB_NOSYM));
   2649 
   2650 	if (object != MDB_TGT_OBJ_EXEC && object != MDB_TGT_OBJ_EVERY) {
   2651 		int status = mdb_gelf_symtab_lookup_by_file(pt->p_symtab,
   2652 		    object, name, symp, &sip->sym_id);
   2653 
   2654 		if (status != 0) {
   2655 			if (P != NULL &&
   2656 			    Plmid_to_map(P, PR_LMID_EVERY, object) != NULL)
   2657 				return (set_errno(EMDB_NOSYM));
   2658 			else
   2659 				return (-1); /* errno set from lookup_by_file */
   2660 		}
   2661 
   2662 		goto found;
   2663 	}
   2664 
   2665 	if (mdb_gelf_symtab_lookup_by_name(pt->p_symtab, name, symp, &i) == 0) {
   2666 		sip->sym_table = MDB_TGT_SYMTAB;
   2667 		sip->sym_id = i;
   2668 		goto local_found;
   2669 	}
   2670 
   2671 	if (mdb_gelf_symtab_lookup_by_name(pt->p_dynsym, name, symp, &i) == 0) {
   2672 		sip->sym_table = MDB_TGT_DYNSYM;
   2673 		sip->sym_id = i;
   2674 		goto local_found;
   2675 	}
   2676 
   2677 	return (set_errno(EMDB_NOSYM));
   2678 
   2679 local_found:
   2680 	if (pt->p_file != NULL &&
   2681 	    pt->p_file->gf_ehdr.e_type == ET_DYN &&
   2682 	    P != NULL &&
   2683 	    (aout_lop = Pname_to_loadobj(P, PR_OBJ_EXEC)) != NULL)
   2684 		symp->st_value += aout_lop->rl_base;
   2685 
   2686 found:
   2687 	/*
   2688 	 * If the symbol has type TLS, libproc should have found the symbol
   2689 	 * if it exists and has been allocated.
   2690 	 */
   2691 	if (GELF_ST_TYPE(symp->st_info) == STT_TLS)
   2692 		return (set_errno(EMDB_TLS));
   2693 
   2694 	return (0);
   2695 }
   2696 
   2697 static int
   2698 pt_lookup_by_name(mdb_tgt_t *t, const char *object,
   2699     const char *name, GElf_Sym *symp, mdb_syminfo_t *sip)
   2700 {
   2701 	return (pt_lookup_by_name_thr(t, object, name, symp, sip, PTL_TID(t)));
   2702 }
   2703 
   2704 static int
   2705 pt_lookup_by_addr(mdb_tgt_t *t, uintptr_t addr, uint_t flags,
   2706     char *buf, size_t nbytes, GElf_Sym *symp, mdb_syminfo_t *sip)
   2707 {
   2708 	struct ps_prochandle *P = t->t_pshandle;
   2709 	pt_data_t *pt = t->t_data;
   2710 	rd_plt_info_t rpi = { 0 };
   2711 
   2712 	const char *pltsym;
   2713 	int rv, match, i;
   2714 
   2715 	mdb_gelf_symtab_t *gsts[3];	/* mdb.m_prsym, .symtab, .dynsym */
   2716 	int gstc = 0;			/* number of valid gsts[] entries */
   2717 
   2718 	mdb_gelf_symtab_t *gst = NULL;	/* set if 'sym' is from a gst */
   2719 	const prmap_t *pmp = NULL;	/* set if 'sym' is from libproc */
   2720 	GElf_Sym sym;			/* best symbol found so far if !exact */
   2721 	prsyminfo_t si;
   2722 
   2723 	/*
   2724 	 * Fill in our array of symbol table pointers with the private symbol
   2725 	 * table, static symbol table, and dynamic symbol table if applicable.
   2726 	 * These are done in order of precedence so that if we match and
   2727 	 * MDB_TGT_SYM_EXACT is set, we need not look any further.
   2728 	 */
   2729 	if (mdb.m_prsym != NULL)
   2730 		gsts[gstc++] = mdb.m_prsym;
   2731 	if (P == NULL && pt->p_symtab != NULL)
   2732 		gsts[gstc++] = pt->p_symtab;
   2733 	if (P == NULL && pt->p_dynsym != NULL)
   2734 		gsts[gstc++] = pt->p_dynsym;
   2735 
   2736 	/*
   2737 	 * Loop through our array attempting to match the address.  If we match
   2738 	 * and we're in exact mode, we're done.  Otherwise save the symbol in
   2739 	 * the local sym variable if it is closer than our previous match.
   2740 	 * We explicitly watch for zero-valued symbols since DevPro insists
   2741 	 * on storing __fsr_init_value's value as the symbol value instead
   2742 	 * of storing it in a constant integer.
   2743 	 */
   2744 	for (i = 0; i < gstc; i++) {
   2745 		if (mdb_gelf_symtab_lookup_by_addr(gsts[i], addr, flags, buf,
   2746 		    nbytes, symp, &sip->sym_id) != 0 || symp->st_value == 0)
   2747 			continue;
   2748 
   2749 		if (flags & MDB_TGT_SYM_EXACT) {
   2750 			gst = gsts[i];
   2751 			goto found;
   2752 		}
   2753 
   2754 		if (gst == NULL || mdb_gelf_sym_closer(symp, &sym, addr)) {
   2755 			gst = gsts[i];
   2756 			sym = *symp;
   2757 		}
   2758 	}
   2759 
   2760 	/*
   2761 	 * If we have no libproc handle active, we're done: fail if gst is
   2762 	 * NULL; otherwise copy out our best symbol and skip to the end.
   2763 	 * We also skip to found if gst is the private symbol table: we
   2764 	 * want this to always take precedence over PLT re-vectoring.
   2765 	 */
   2766 	if (P == NULL || (gst != NULL && gst == mdb.m_prsym)) {
   2767 		if (gst == NULL)
   2768 			return (set_errno(EMDB_NOSYMADDR));
   2769 		*symp = sym;
   2770 		goto found;
   2771 	}
   2772 
   2773 	/*
   2774 	 * Check to see if the address is in a PLT: if it is, use librtld_db to
   2775 	 * attempt to resolve the PLT entry.  If the entry is bound, reset addr
   2776 	 * to the bound address, add a special prefix to the caller's buf,
   2777 	 * forget our previous guess, and then continue using the new addr.
   2778 	 * If the entry is not bound, copy the corresponding symbol name into
   2779 	 * buf and return a fake symbol for the given address.
   2780 	 */
   2781 	if ((pltsym = Ppltdest(P, addr)) != NULL) {
   2782 		const rd_loadobj_t *rlp;
   2783 		rd_agent_t *rap;
   2784 
   2785 		if ((rap = Prd_agent(P)) != NULL &&
   2786 		    (rlp = Paddr_to_loadobj(P, addr)) != NULL &&
   2787 		    rd_plt_resolution(rap, addr, Pstatus(P)->pr_lwp.pr_lwpid,
   2788 		    rlp->rl_plt_base, &rpi) == RD_OK &&
   2789 		    (rpi.pi_flags & RD_FLG_PI_PLTBOUND)) {
   2790 			size_t n;
   2791 			n = mdb_iob_snprintf(buf, nbytes, "PLT=");
   2792 			addr = rpi.pi_baddr;
   2793 			if (n > nbytes) {
   2794 				buf += nbytes;
   2795 				nbytes = 0;
   2796 			} else {
   2797 				buf += n;
   2798 				nbytes -= n;
   2799 			}
   2800 			gst = NULL;
   2801 		} else {
   2802 			(void) mdb_iob_snprintf(buf, nbytes, "PLT:%s", pltsym);
   2803 			bzero(symp, sizeof (GElf_Sym));
   2804 			symp->st_value = addr;
   2805 			symp->st_info = GELF_ST_INFO(STB_GLOBAL, STT_FUNC);
   2806 			return (0);
   2807 		}
   2808 	}
   2809 
   2810 	/*
   2811 	 * Ask libproc to convert the address to the closest symbol for us.
   2812 	 * Once we get the closest symbol, we perform the EXACT match or
   2813 	 * smart-mode or absolute distance check ourself:
   2814 	 */
   2815 	if ((mdb.m_flags & MDB_FL_LMRAW) == 0) {
   2816 		rv = Pxlookup_by_addr_resolved(P, addr, buf, nbytes,
   2817 		    symp, &si);
   2818 	} else {
   2819 		rv = Pxlookup_by_addr(P, addr, buf, nbytes,
   2820 		    symp, &si);
   2821 	}
   2822 	if ((rv == 0) && (symp->st_value != 0) &&
   2823 	    (gst == NULL || mdb_gelf_sym_closer(symp, &sym, addr))) {
   2824 
   2825 		if (flags & MDB_TGT_SYM_EXACT)
   2826 			match = (addr == symp->st_value);
   2827 		else if (mdb.m_symdist == 0)
   2828 			match = (addr >= symp->st_value &&
   2829 			    addr < symp->st_value + symp->st_size);
   2830 		else
   2831 			match = (addr >= symp->st_value &&
   2832 			    addr < symp->st_value + mdb.m_symdist);
   2833 
   2834 		if (match) {
   2835 			pmp = Paddr_to_map(P, addr);
   2836 			gst = NULL;
   2837 			sip->sym_table = si.prs_table;
   2838 			sip->sym_id = si.prs_id;
   2839 			goto found;
   2840 		}
   2841 	}
   2842 
   2843 	/*
   2844 	 * If we get here, Plookup_by_addr has failed us.  If we have no
   2845 	 * previous best symbol (gst == NULL), we've failed completely.
   2846 	 * Otherwise we copy out that symbol and continue on to 'found'.
   2847 	 */
   2848 	if (gst == NULL)
   2849 		return (set_errno(EMDB_NOSYMADDR));
   2850 	*symp = sym;
   2851 found:
   2852 	/*
   2853 	 * Once we've found something, copy the final name into the caller's
   2854 	 * buffer and prefix it with the mapping name if appropriate.
   2855 	 */
   2856 	if (pmp != NULL && pmp != Pname_to_map(P, PR_OBJ_EXEC)) {
   2857 		const char *prefix = pmp->pr_mapname;
   2858 		Lmid_t lmid;
   2859 
   2860 		if ((mdb.m_flags & MDB_FL_LMRAW) == 0) {
   2861 			if (Pobjname_resolved(P, addr, pt->p_objname,
   2862 			    MDB_TGT_MAPSZ))
   2863 				prefix = pt->p_objname;
   2864 		} else {
   2865 			if (Pobjname(P, addr, pt->p_objname, MDB_TGT_MAPSZ))
   2866 				prefix = pt->p_objname;
   2867 		}
   2868 
   2869 		if (buf != NULL && nbytes > 1) {
   2870 			(void) strncpy(pt->p_symname, buf, MDB_TGT_SYM_NAMLEN);
   2871 			pt->p_symname[MDB_TGT_SYM_NAMLEN - 1] = '\0';
   2872 		} else {
   2873 			pt->p_symname[0] = '\0';
   2874 		}
   2875 
   2876 		if (prefix == pt->p_objname && Plmid(P, addr, &lmid) == 0 && (
   2877 		    (lmid != LM_ID_BASE && lmid != LM_ID_LDSO) ||
   2878 		    (mdb.m_flags & MDB_FL_SHOWLMID))) {
   2879 			(void) mdb_iob_snprintf(buf, nbytes, "LM%lr`%s`%s",
   2880 			    lmid, strbasename(prefix), pt->p_symname);
   2881 		} else {
   2882 			(void) mdb_iob_snprintf(buf, nbytes, "%s`%s",
   2883 			    strbasename(prefix), pt->p_symname);
   2884 		}
   2885 
   2886 	} else if (gst != NULL && buf != NULL && nbytes > 0) {
   2887 		(void) strncpy(buf, mdb_gelf_sym_name(gst, symp), nbytes);
   2888 		buf[nbytes - 1] = '\0';
   2889 	}
   2890 
   2891 	return (0);
   2892 }
   2893 
   2894 
   2895 static int
   2896 pt_symbol_iter_cb(void *arg, const GElf_Sym *sym, const char *name,
   2897     const prsyminfo_t *sip)
   2898 {
   2899 	pt_symarg_t *psp = arg;
   2900 
   2901 	psp->psym_info.sym_id = sip->prs_id;
   2902 
   2903 	return (psp->psym_func(psp->psym_private, sym, name, &psp->psym_info,
   2904 	    psp->psym_obj));
   2905 }
   2906 
   2907 static int
   2908 pt_objsym_iter(void *arg, const prmap_t *pmp, const char *object)
   2909 {
   2910 	Lmid_t lmid = PR_LMID_EVERY;
   2911 	pt_symarg_t *psp = arg;
   2912 
   2913 	psp->psym_obj = object;
   2914 
   2915 	(void) Plmid(psp->psym_targ->t_pshandle, pmp->pr_vaddr, &lmid);
   2916 	(void) Pxsymbol_iter(psp->psym_targ->t_pshandle, lmid, object,
   2917 	    psp->psym_which, psp->psym_type, pt_symbol_iter_cb, arg);
   2918 
   2919 	return (0);
   2920 }
   2921 
   2922 static int
   2923 pt_symbol_filt(void *arg, const GElf_Sym *sym, const char *name, uint_t id)
   2924 {
   2925 	pt_symarg_t *psp = arg;
   2926 
   2927 	if (mdb_tgt_sym_match(sym, psp->psym_type)) {
   2928 		psp->psym_info.sym_id = id;
   2929 		return (psp->psym_func(psp->psym_private, sym, name,
   2930 		    &psp->psym_info, psp->psym_obj));
   2931 	}
   2932 
   2933 	return (0);
   2934 }
   2935 
   2936 static int
   2937 pt_symbol_iter(mdb_tgt_t *t, const char *object, uint_t which,
   2938     uint_t type, mdb_tgt_sym_f *func, void *private)
   2939 {
   2940 	pt_data_t *pt = t->t_data;
   2941 	mdb_gelf_symtab_t *gst;
   2942 	pt_symarg_t ps;
   2943 	Lmid_t lmid;
   2944 
   2945 	object = pt_resolve_lmid(object, &lmid);
   2946 
   2947 	ps.psym_targ = t;
   2948 	ps.psym_which = which;
   2949 	ps.psym_type = type;
   2950 	ps.psym_func = func;
   2951 	ps.psym_private = private;
   2952 	ps.psym_obj = object;
   2953 
   2954 	if (t->t_pshandle != NULL) {
   2955 		if (object != MDB_TGT_OBJ_EVERY) {
   2956 			if (Plmid_to_map(t->t_pshandle, lmid, object) == NULL)
   2957 				return (set_errno(EMDB_NOOBJ));
   2958 			(void) Pxsymbol_iter(t->t_pshandle, lmid, object,
   2959 			    which, type, pt_symbol_iter_cb, &ps);
   2960 			return (0);
   2961 		} else if (Prd_agent(t->t_pshandle) != NULL) {
   2962 			if ((mdb.m_flags & MDB_FL_LMRAW) == 0) {
   2963 				(void) Pobject_iter_resolved(t->t_pshandle,
   2964 				    pt_objsym_iter, &ps);
   2965 			} else {
   2966 				(void) Pobject_iter(t->t_pshandle,
   2967 				    pt_objsym_iter, &ps);
   2968 			}
   2969 			return (0);
   2970 		}
   2971 	}
   2972 
   2973 	if (lmid != LM_ID_BASE && lmid != PR_LMID_EVERY)
   2974 		return (set_errno(EMDB_NOLMID));
   2975 
   2976 	if (object != MDB_TGT_OBJ_EXEC && object != MDB_TGT_OBJ_EVERY &&
   2977 	    pt->p_fio != NULL &&
   2978 	    strcmp(object, IOP_NAME(pt->p_fio)) != 0)
   2979 		return (set_errno(EMDB_NOOBJ));
   2980 
   2981 	if (which == MDB_TGT_SYMTAB)
   2982 		gst = pt->p_symtab;
   2983 	else
   2984 		gst = pt->p_dynsym;
   2985 
   2986 	if (gst != NULL) {
   2987 		ps.psym_info.sym_table = gst->gst_tabid;
   2988 		mdb_gelf_symtab_iter(gst, pt_symbol_filt, &ps);
   2989 	}
   2990 
   2991 	return (0);
   2992 }
   2993 
   2994 static const mdb_map_t *
   2995 pt_prmap_to_mdbmap(mdb_tgt_t *t, const prmap_t *prp, mdb_map_t *mp)
   2996 {
   2997 	struct ps_prochandle *P = t->t_pshandle;
   2998 	char *rv, name[MAXPATHLEN];
   2999 	Lmid_t lmid;
   3000 
   3001 	if ((mdb.m_flags & MDB_FL_LMRAW) == 0) {
   3002 		rv = Pobjname_resolved(P, prp->pr_vaddr, name, sizeof (name));
   3003 	} else {
   3004 		rv = Pobjname(P, prp->pr_vaddr, name, sizeof (name));
   3005 	}
   3006 
   3007 	if (rv != NULL) {
   3008 		if (Plmid(P, prp->pr_vaddr, &lmid) == 0 && (
   3009 		    (lmid != LM_ID_BASE && lmid != LM_ID_LDSO) ||
   3010 		    (mdb.m_flags & MDB_FL_SHOWLMID))) {
   3011 			(void) mdb_iob_snprintf(mp->map_name, MDB_TGT_MAPSZ,
   3012 			    "LM%lr`%s", lmid, name);
   3013 		} else {
   3014 			(void) strncpy(mp->map_name, name, MDB_TGT_MAPSZ - 1);
   3015 			mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
   3016 		}
   3017 	} else {
   3018 		(void) strncpy(mp->map_name, prp->pr_mapname,
   3019 		    MDB_TGT_MAPSZ - 1);
   3020 		mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
   3021 	}
   3022 
   3023 	mp->map_base = prp->pr_vaddr;
   3024 	mp->map_size = prp->pr_size;
   3025 	mp->map_flags = 0;
   3026 
   3027 	if (prp->pr_mflags & MA_READ)
   3028 		mp->map_flags |= MDB_TGT_MAP_R;
   3029 	if (prp->pr_mflags & MA_WRITE)
   3030 		mp->map_flags |= MDB_TGT_MAP_W;
   3031 	if (prp->pr_mflags & MA_EXEC)
   3032 		mp->map_flags |= MDB_TGT_MAP_X;
   3033 
   3034 	if (prp->pr_mflags & MA_SHM)
   3035 		mp->map_flags |= MDB_TGT_MAP_SHMEM;
   3036 	if (prp->pr_mflags & MA_BREAK)
   3037 		mp->map_flags |= MDB_TGT_MAP_HEAP;
   3038 	if (prp->pr_mflags & MA_STACK)
   3039 		mp->map_flags |= MDB_TGT_MAP_STACK;
   3040 	if (prp->pr_mflags & MA_ANON)
   3041 		mp->map_flags |= MDB_TGT_MAP_ANON;
   3042 
   3043 	return (mp);
   3044 }
   3045 
   3046 /*ARGSUSED*/
   3047 static int
   3048 pt_map_apply(void *arg, const prmap_t *prp, const char *name)
   3049 {
   3050 	pt_maparg_t *pmp = arg;
   3051 	mdb_map_t map;
   3052 
   3053 	return (pmp->pmap_func(pmp->pmap_private,
   3054 	    pt_prmap_to_mdbmap(pmp->pmap_targ, prp, &map), map.map_name));
   3055 }
   3056 
   3057 static int
   3058 pt_mapping_iter(mdb_tgt_t *t, mdb_tgt_map_f *func, void *private)
   3059 {
   3060 	if (t->t_pshandle != NULL) {
   3061 		pt_maparg_t pm;
   3062 
   3063 		pm.pmap_targ = t;
   3064 		pm.pmap_func = func;
   3065 		pm.pmap_private = private;
   3066 
   3067 		if ((mdb.m_flags & MDB_FL_LMRAW) == 0) {
   3068 			(void) Pmapping_iter_resolved(t->t_pshandle,
   3069 			    pt_map_apply, &pm);
   3070 		} else {
   3071 			(void) Pmapping_iter(t->t_pshandle,
   3072 			    pt_map_apply, &pm);
   3073 		}
   3074 		return (0);
   3075 	}
   3076 
   3077 	return (set_errno(EMDB_NOPROC));
   3078 }
   3079 
   3080 static int
   3081 pt_object_iter(mdb_tgt_t *t, mdb_tgt_map_f *func, void *private)
   3082 {
   3083 	pt_data_t *pt = t->t_data;
   3084 
   3085 	/*
   3086 	 * If we have a libproc handle, we can just call Pobject_iter to
   3087 	 * iterate over its list of load object information.
   3088 	 */
   3089 	if (t->t_pshandle != NULL) {
   3090 		pt_maparg_t pm;
   3091 
   3092 		pm.pmap_targ = t;
   3093 		pm.pmap_func = func;
   3094 		pm.pmap_private = private;
   3095 
   3096 		if ((mdb.m_flags & MDB_FL_LMRAW) == 0) {
   3097 			(void) Pobject_iter_resolved(t->t_pshandle,
   3098 			    pt_map_apply, &pm);
   3099 		} else {
   3100 			(void) Pobject_iter(t->t_pshandle,
   3101 			    pt_map_apply, &pm);
   3102 		}
   3103 		return (0);
   3104 	}
   3105 
   3106 	/*
   3107 	 * If we're examining an executable or other ELF file but we have no
   3108 	 * libproc handle, fake up some information based on DT_NEEDED entries.
   3109 	 */
   3110 	if (pt->p_dynsym != NULL && pt->p_file->gf_dyns != NULL &&
   3111 	    pt->p_fio != NULL) {
   3112 		mdb_gelf_sect_t *gsp = pt->p_dynsym->gst_ssect;
   3113 		GElf_Dyn *dynp = pt->p_file->gf_dyns;
   3114 		mdb_map_t *mp = &pt->p_map;
   3115 		const char *s = IOP_NAME(pt->p_fio);
   3116 		size_t i;
   3117 
   3118 		(void) strncpy(mp->map_name, s, MDB_TGT_MAPSZ);
   3119 		mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
   3120 		mp->map_flags = MDB_TGT_MAP_R | MDB_TGT_MAP_X;
   3121 		mp->map_base = NULL;
   3122 		mp->map_size = 0;
   3123 
   3124 		if (func(private, mp, s) != 0)
   3125 			return (0);
   3126 
   3127 		for (i = 0; i < pt->p_file->gf_ndyns; i++, dynp++) {
   3128 			if (dynp->d_tag == DT_NEEDED) {
   3129 				s = (char *)gsp->gs_data + dynp->d_un.d_val;
   3130 				(void) strncpy(mp->map_name, s, MDB_TGT_MAPSZ);
   3131 				mp->map_name[MDB_TGT_MAPSZ - 1] = '\0';
   3132 				if (func(private, mp, s) != 0)
   3133 					return (0);
   3134 			}
   3135 		}
   3136 
   3137 		return (0);
   3138 	}
   3139 
   3140 	return (set_errno(EMDB_NOPROC));
   3141 }
   3142 
   3143 static const mdb_map_t *
   3144 pt_addr_to_map(mdb_tgt_t *t, uintptr_t addr)
   3145 {
   3146 	pt_data_t *pt = t->t_data;
   3147 	const prmap_t *pmp;
   3148 
   3149 	if (t->t_pshandle == NULL) {
   3150 		(void) set_errno(EMDB_NOPROC);
   3151 		return (NULL);
   3152 	}
   3153 
   3154 	if ((pmp = Paddr_to_map(t->t_pshandle, addr)) == NULL) {
   3155 		(void) set_errno(EMDB_NOMAP);
   3156 		return (NULL);
   3157 	}
   3158 
   3159 	return (pt_prmap_to_mdbmap(t, pmp, &pt->p_map));
   3160 }
   3161 
   3162 static const mdb_map_t *
   3163 pt_name_to_map(mdb_tgt_t *t, const char *object)
   3164 {
   3165 	pt_data_t *pt = t->t_data;
   3166 	const prmap_t *pmp;
   3167 	Lmid_t lmid;
   3168 
   3169 	if (t->t_pshandle == NULL) {
   3170 		(void) set_errno(EMDB_NOPROC);
   3171 		return (NULL);
   3172 	}
   3173 
   3174 	object = pt_resolve_lmid(object, &lmid);
   3175 
   3176 	if ((pmp = Plmid_to_map(t->t_pshandle, lmid, object)) == NULL) {
   3177 		(void) set_errno(EMDB_NOOBJ);
   3178 		return (NULL);
   3179 	}
   3180 
   3181 	return (pt_prmap_to_mdbmap(t, pmp, &pt->p_map));
   3182 }
   3183 
   3184 static ctf_file_t *
   3185 pt_addr_to_ctf(mdb_tgt_t *t, uintptr_t addr)
   3186 {
   3187 	ctf_file_t *ret;
   3188 
   3189 	if (t->t_pshandle == NULL) {
   3190 		(void) set_errno(EMDB_NOPROC);
   3191 		return (NULL);
   3192 	}
   3193 
   3194 	if ((ret = Paddr_to_ctf(t->t_pshandle, addr)) == NULL) {
   3195 		(void) set_errno(EMDB_NOOBJ);
   3196 		return (NULL);
   3197 	}
   3198 
   3199 	return (ret);
   3200 }
   3201 
   3202 static ctf_file_t *
   3203 pt_name_to_ctf(mdb_tgt_t *t, const char *name)
   3204 {
   3205 	ctf_file_t *ret;
   3206 
   3207 	if (t->t_pshandle == NULL) {
   3208 		(void) set_errno(EMDB_NOPROC);
   3209 		return (NULL);
   3210 	}
   3211 
   3212 	if ((ret = Pname_to_ctf(t->t_pshandle, name)) == NULL) {
   3213 		(void) set_errno(EMDB_NOOBJ);
   3214 		return (NULL);
   3215 	}
   3216 
   3217 	return (ret);
   3218 }
   3219 
   3220 static int
   3221 pt_status(mdb_tgt_t *t, mdb_tgt_status_t *tsp)
   3222 {
   3223 	const pstatus_t *psp;
   3224 	prgregset_t gregs;
   3225 	int state;
   3226 
   3227 	bzero(tsp, sizeof (mdb_tgt_status_t));
   3228 
   3229 	if (t->t_pshandle == NULL) {
   3230 		tsp->st_state = MDB_TGT_IDLE;
   3231 		return (0);
   3232 	}
   3233 
   3234 	switch (state = Pstate(t->t_pshandle)) {
   3235 	case PS_RUN:
   3236 		tsp->st_state = MDB_TGT_RUNNING;
   3237 		break;
   3238 
   3239 	case PS_STOP:
   3240 		tsp->st_state = MDB_TGT_STOPPED;
   3241 		psp = Pstatus(t->t_pshandle);
   3242 
   3243 		tsp->st_tid = PTL_TID(t);
   3244 		if (PTL_GETREGS(t, tsp->st_tid, gregs) == 0)
   3245 			tsp->st_pc = gregs[R_PC];
   3246 
   3247 		if (psp->pr_flags & PR_ISTOP)
   3248 			tsp->st_flags |= MDB_TGT_ISTOP;
   3249 		if (psp->pr_flags & PR_DSTOP)
   3250 			tsp->st_flags |= MDB_TGT_DSTOP;
   3251 
   3252 		break;
   3253 
   3254 	case PS_LOST:
   3255 		tsp->st_state = MDB_TGT_LOST;
   3256 		break;
   3257 	case PS_UNDEAD:
   3258 		tsp->st_state = MDB_TGT_UNDEAD;
   3259 		break;
   3260 	case PS_DEAD:
   3261 		tsp->st_state = MDB_TGT_DEAD;
   3262 		break;
   3263 	case PS_IDLE:
   3264 		tsp->st_state = MDB_TGT_IDLE;
   3265 		break;
   3266 	default:
   3267 		fail("unknown libproc state (%d)\n", state);
   3268 	}
   3269 
   3270 	if (t->t_flags & MDB_TGT_F_BUSY)
   3271 		tsp->st_flags |= MDB_TGT_BUSY;
   3272 
   3273 	return (0);
   3274 }
   3275 
   3276 static void
   3277 pt_dupfd(const char *file, int oflags, mode_t mode, int dfd)
   3278 {
   3279 	int fd;
   3280 
   3281 	if ((fd = open(file, oflags, mode)) >= 0) {
   3282 		(void) fcntl(fd, F_DUP2FD, dfd);
   3283 		(void) close(fd);
   3284 	} else
   3285 		warn("failed to open %s as descriptor %d", file, dfd);
   3286 }
   3287 
   3288 /*
   3289  * The Pcreate_callback() function interposes on the default, empty libproc
   3290  * definition.  It will be called following a fork of a new child process by
   3291  * Pcreate() below, but before the exec of the new process image.  We use this
   3292  * callback to optionally redirect stdin and stdout and reset the dispositions
   3293  * of SIGPIPE and SIGQUIT from SIG_IGN back to SIG_DFL.
   3294  */
   3295 /*ARGSUSED*/
   3296 void
   3297 Pcreate_callback(struct ps_prochandle *P)
   3298 {
   3299 	pt_data_t *pt = mdb.m_target->t_data;
   3300 
   3301 	if (pt->p_stdin != NULL)
   3302 		pt_dupfd(pt->p_stdin, O_RDWR, 0, STDIN_FILENO);
   3303 	if (pt->p_stdout != NULL)
   3304 		pt_dupfd(pt->p_stdout, O_CREAT | O_WRONLY, 0666, STDOUT_FILENO);
   3305 
   3306 	(void) mdb_signal_sethandler(SIGPIPE, SIG_DFL, NULL);
   3307 	(void) mdb_signal_sethandler(SIGQUIT, SIG_DFL, NULL);
   3308 }
   3309 
   3310 static int
   3311 pt_run(mdb_tgt_t *t, int argc, const mdb_arg_t *argv)
   3312 {
   3313 	pt_data_t *pt = t->t_data;
   3314 	struct ps_prochandle *P;
   3315 	char execname[MAXPATHLEN];
   3316 	const char **pargv;
   3317 	int pargc = 0;
   3318 	int i, perr;
   3319 	char **penv;
   3320 	mdb_var_t *v;
   3321 
   3322 	if (pt->p_aout_fio == NULL) {
   3323 		warn("run requires executable to be specified on "
   3324 		    "command-line\n");
   3325 		return (set_errno(EMDB_TGT));
   3326 	}
   3327 
   3328 	pargv = mdb_alloc(sizeof (char *) * (argc + 2), UM_SLEEP);
   3329 	pargv[pargc++] = strbasename(IOP_NAME(pt->p_aout_fio));
   3330 
   3331 	for (i = 0; i < argc; i++) {
   3332 		if (argv[i].a_type != MDB_TYPE_STRING) {
   3333 			mdb_free(pargv, sizeof (char *) * (argc + 2));
   3334 			return (set_errno(EINVAL));
   3335 		}
   3336 		if (argv[i].a_un.a_str[0] == '<')
   3337 			pt->p_stdin = argv[i].a_un.a_str + 1;
   3338 		else if (argv[i].a_un.a_str[0] == '>')
   3339 			pt->p_stdout = argv[i].a_un.a_str + 1;
   3340 		else
   3341 			pargv[pargc++] = argv[i].a_un.a_str;
   3342 	}
   3343 	pargv[pargc] = NULL;
   3344 
   3345 	/*
   3346 	 * Since Pcreate() uses execvp() and "." may not be present in $PATH,
   3347 	 * we must manually prepend "./" when the executable is a simple name.
   3348 	 */
   3349 	if (strchr(IOP_NAME(pt->p_aout_fio), '/') == NULL) {
   3350 		(void) snprintf(execname, sizeof (execname), "./%s",
   3351 		    IOP_NAME(pt->p_aout_fio));
   3352 	} else {
   3353 		(void) snprintf(execname, sizeof (execname), "%s",
   3354 		    IOP_NAME(pt->p_aout_fio));
   3355 	}
   3356 
   3357 	penv = mdb_alloc((mdb_nv_size(&pt->p_env)+ 1) * sizeof (char *),
   3358 	    UM_SLEEP);
   3359 	for (mdb_nv_rewind(&pt->p_env), i = 0;
   3360 	    (v = mdb_nv_advance(&pt->p_env)) != NULL; i++)
   3361 		penv[i] = mdb_nv_get_cookie(v);
   3362 	penv[i] = NULL;
   3363 
   3364 	P = Pxcreate(execname, (char **)pargv, penv, &perr, NULL, 0);
   3365 	mdb_free(pargv, sizeof (char *) * (argc + 2));
   3366 	pt->p_stdin = pt->p_stdout = NULL;
   3367 
   3368 	mdb_free(penv, i * sizeof (char *));
   3369 
   3370 	if (P == NULL) {
   3371 		warn("failed to create process: %s\n", Pcreate_error(perr));
   3372 		return (set_errno(EMDB_TGT));
   3373 	}
   3374 
   3375 	if (t->t_pshandle != NULL) {
   3376 		pt_pre_detach(t, TRUE);
   3377 		if (t->t_pshandle != pt->p_idlehandle)
   3378 			Prelease(t->t_pshandle, pt->p_rflags);
   3379 	}
   3380 
   3381 	(void) Punsetflags(P, PR_RLC);	/* make sure run-on-last-close is off */
   3382 	(void) Psetflags(P, PR_KLC);	/* kill on last close by debugger */
   3383 	pt->p_rflags = PRELEASE_KILL;	/* kill on debugger Prelease */
   3384 	t->t_pshandle = P;
   3385 
   3386 	pt_post_attach(t);
   3387 	pt_activate_common(t);
   3388 	(void) mdb_tgt_status(t, &t->t_status);
   3389 	mdb.m_flags |= MDB_FL_VCREATE;
   3390 
   3391 	return (0);
   3392 }
   3393 
   3394 /*
   3395  * Forward a signal to the victim process in order to force it to stop or die.
   3396  * Refer to the comments above pt_setrun(), below, for more info.
   3397  */
   3398 /*ARGSUSED*/
   3399 static void
   3400 pt_sigfwd(int sig, siginfo_t *sip, ucontext_t *ucp, mdb_tgt_t *t)
   3401 {
   3402 	struct ps_prochandle *P = t->t_pshandle;
   3403 	const lwpstatus_t *psp = &Pstatus(P)->pr_lwp;
   3404 	pid_t pid = Pstatus(P)->pr_pid;
   3405 	long ctl[2];
   3406 
   3407 	if (getpgid(pid) != mdb.m_pgid) {
   3408 		mdb_dprintf(MDB_DBG_TGT, "fwd SIG#%d to %d\n", sig, (int)pid);
   3409 		(void) kill(pid, sig);
   3410 	}
   3411 
   3412 	if (Pwait(P, 1) == 0 && (psp->pr_flags & PR_STOPPED) &&
   3413 	    psp->pr_why == PR_JOBCONTROL && Pdstop(P) == 0) {
   3414 		/*
   3415 		 * If we're job control stopped and our DSTOP is pending, the
   3416 		 * victim will never see our signal, so undo the kill() and
   3417 		 * then send SIGCONT the victim to kick it out of the job
   3418 		 * control stop and force our DSTOP to take effect.
   3419 		 */
   3420 		if ((psp->pr_flags & PR_DSTOP) &&
   3421 		    prismember(&Pstatus(P)->pr_sigpend, sig)) {
   3422 			ctl[0] = PCUNKILL;
   3423 			ctl[1] = sig;
   3424 			(void) write(Pctlfd(P), ctl, sizeof (ctl));
   3425 		}
   3426 
   3427 		mdb_dprintf(MDB_DBG_TGT, "fwd SIGCONT to %d\n", (int)pid);
   3428 		(void) kill(pid, SIGCONT);
   3429 	}
   3430 }
   3431 
   3432 /*
   3433  * Common code for step and continue: if no victim process has been created,
   3434  * call pt_run() to create one.  Then set the victim running, clearing any
   3435  * pending fault.  One special case is that if the victim was previously
   3436  * stopped on reception of SIGINT, we know that SIGINT was traced and the user
   3437  * requested the victim to stop, so clear this signal before continuing.
   3438  * For all other traced signals, the signal will be delivered on continue.
   3439  *
   3440  * Once the victim process is running, we wait for it to stop on an event of
   3441  * interest.  Although libproc provides the basic primitive to wait for the
   3442  * victim, we must be careful in our handling of signals.  We want to allow the
   3443  * user to issue a SIGINT or SIGQUIT using the designated terminal control
   3444  * character (typically ^C and ^\), and have these signals stop the target and
   3445  * return control to the debugger if the signals are traced.  There are three
   3446  * cases to be considered in our implementation:
   3447  *
   3448  * (1) If the debugger and victim are in the same process group, both receive
   3449  * the signal from the terminal driver.  The debugger returns from Pwait() with
   3450  * errno = EINTR, so we want to loop back and continue waiting until the victim
   3451  * stops on receipt of its SIGINT or SIGQUIT.
   3452  *
   3453  * (2) If the debugger and victim are in different process groups, and the
   3454  * victim is a member of the foreground process group, it will receive the
   3455  * signal from the terminal driver and the debugger will not.  As such, we
   3456  * will remain blocked in Pwait() until the victim stops on its signal.
   3457  *
   3458  * (3) If the debugger and victim are in different process groups, and the
   3459  * debugger is a member of the foreground process group, it will receive the
   3460  * signal from the terminal driver, and the victim will not.  The debugger
   3461  * returns from Pwait() with errno = EINTR, so we need to forward the signal
   3462  * to the victim process directly and then Pwait() again for it to stop.
   3463  *
   3464  * We can observe that all three cases are handled by simply calling Pwait()
   3465  * repeatedly if it fails with EINTR, and forwarding SIGINT and SIGQUIT to
   3466  * the victim if it is in a different process group, using pt_sigfwd() above.
   3467  *
   3468  * An additional complication is that the process may not be able to field
   3469  * the signal if it is currently stopped by job control.  In this case, we
   3470  * also DSTOP the process, and then send it a SIGCONT to wake it up from
   3471  * job control and force it to re-enter stop() under the control of /proc.
   3472  *
   3473  * Finally, we would like to allow the user to suspend the process using the
   3474  * terminal suspend character (typically ^Z) if both are in the same session.
   3475  * We again employ pt_sigfwd() to forward SIGTSTP to the victim, wait for it to
   3476  * stop from job control, and then capture it using /proc.  Once the process
   3477  * has stopped, normal SIGTSTP processing is restored and the user can issue
   3478  * another ^Z in order to suspend the debugger and return to the parent shell.
   3479  */
   3480 static int
   3481 pt_setrun(mdb_tgt_t *t, mdb_tgt_status_t *tsp, int flags)
   3482 {
   3483 	struct ps_prochandle *P = t->t_pshandle;
   3484 	pt_data_t *pt = t->t_data;
   3485 	pid_t old_pgid = -1;
   3486 
   3487 	mdb_signal_f *intf, *quitf, *tstpf;
   3488 	const lwpstatus_t *psp;
   3489 	void *intd, *quitd, *tstpd;
   3490 
   3491 	int sig = pt->p_signal;
   3492 	int error = 0;
   3493 	int pgid = -1;
   3494 
   3495 	pt->p_signal = 0; /* clear pending signal */
   3496 
   3497 	if (P == NULL && pt_run(t, 0, NULL) == -1)
   3498 		return (-1); /* errno is set for us */
   3499 
   3500 	P = t->t_pshandle;
   3501 	psp = &Pstatus(P)->pr_lwp;
   3502 
   3503 	if (sig == 0 && psp->pr_why == PR_SIGNALLED && psp->pr_what == SIGINT)
   3504 		flags |= PRCSIG; /* clear pending SIGINT */
   3505 	else
   3506 		flags |= PRCFAULT; /* clear any pending fault (e.g. BPT) */
   3507 
   3508 	intf = mdb_signal_gethandler(SIGINT, &intd);
   3509 	quitf = mdb_signal_gethandler(SIGQUIT, &quitd);
   3510 	tstpf = mdb_signal_gethandler(SIGTSTP, &tstpd);
   3511 
   3512 	(void) mdb_signal_sethandler(SIGINT, (mdb_signal_f *)pt_sigfwd, t);
   3513 	(void) mdb_signal_sethandler(SIGQUIT, (mdb_signal_f *)pt_sigfwd, t);
   3514 	(void)