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