xref: /illumos-gate/usr/src/cmd/mdb/common/mdb/mdb_print.c (revision 2f045fd6af922f819146b314d143b660b58b20b7)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * Copyright (c) 2013 by Delphix. All rights reserved.
28  * Copyright (c) 2012 Joyent, Inc. All rights reserved.
29  */
30 
31 #include <mdb/mdb_modapi.h>
32 #include <mdb/mdb_target.h>
33 #include <mdb/mdb_argvec.h>
34 #include <mdb/mdb_string.h>
35 #include <mdb/mdb_stdlib.h>
36 #include <mdb/mdb_err.h>
37 #include <mdb/mdb_debug.h>
38 #include <mdb/mdb_fmt.h>
39 #include <mdb/mdb_ctf.h>
40 #include <mdb/mdb_ctf_impl.h>
41 #include <mdb/mdb.h>
42 #include <mdb/mdb_tab.h>
43 
44 #include <sys/isa_defs.h>
45 #include <sys/param.h>
46 #include <sys/sysmacros.h>
47 #include <netinet/in.h>
48 #include <strings.h>
49 #include <libctf.h>
50 #include <ctype.h>
51 
52 typedef struct holeinfo {
53 	ulong_t hi_offset;		/* expected offset */
54 	uchar_t hi_isunion;		/* represents a union */
55 } holeinfo_t;
56 
57 typedef struct printarg {
58 	mdb_tgt_t *pa_tgt;		/* current target */
59 	mdb_tgt_t *pa_realtgt;		/* real target (for -i) */
60 	mdb_tgt_t *pa_immtgt;		/* immediate target (for -i) */
61 	mdb_tgt_as_t pa_as;		/* address space to use for i/o */
62 	mdb_tgt_addr_t pa_addr;		/* base address for i/o */
63 	ulong_t pa_armemlim;		/* limit on array elements to print */
64 	ulong_t pa_arstrlim;		/* limit on array chars to print */
65 	const char *pa_delim;		/* element delimiter string */
66 	const char *pa_prefix;		/* element prefix string */
67 	const char *pa_suffix;		/* element suffix string */
68 	holeinfo_t *pa_holes;		/* hole detection information */
69 	int pa_nholes;			/* size of holes array */
70 	int pa_flags;			/* formatting flags (see below) */
71 	int pa_depth;			/* previous depth */
72 	int pa_nest;			/* array nesting depth */
73 	int pa_tab;			/* tabstop width */
74 	uint_t pa_maxdepth;		/* Limit max depth */
75 	uint_t pa_nooutdepth;		/* don't print output past this depth */
76 } printarg_t;
77 
78 #define	PA_SHOWTYPE	0x001		/* print type name */
79 #define	PA_SHOWBASETYPE	0x002		/* print base type name */
80 #define	PA_SHOWNAME	0x004		/* print member name */
81 #define	PA_SHOWADDR	0x008		/* print address */
82 #define	PA_SHOWVAL	0x010		/* print value */
83 #define	PA_SHOWHOLES	0x020		/* print holes in structs */
84 #define	PA_INTHEX	0x040		/* print integer values in hex */
85 #define	PA_INTDEC	0x080		/* print integer values in decimal */
86 #define	PA_NOSYMBOLIC	0x100		/* don't print ptrs as func+offset */
87 
88 #define	IS_CHAR(e) \
89 	(((e).cte_format & (CTF_INT_CHAR | CTF_INT_SIGNED)) == \
90 	(CTF_INT_CHAR | CTF_INT_SIGNED) && (e).cte_bits == NBBY)
91 
92 #define	COMPOSITE_MASK	((1 << CTF_K_STRUCT) | \
93 			(1 << CTF_K_UNION) | (1 << CTF_K_ARRAY))
94 #define	IS_COMPOSITE(k)	(((1 << k) & COMPOSITE_MASK) != 0)
95 
96 #define	SOU_MASK	((1 << CTF_K_STRUCT) | (1 << CTF_K_UNION))
97 #define	IS_SOU(k)	(((1 << k) & SOU_MASK) != 0)
98 
99 #define	MEMBER_DELIM_ERR	-1
100 #define	MEMBER_DELIM_DONE	0
101 #define	MEMBER_DELIM_PTR	1
102 #define	MEMBER_DELIM_DOT	2
103 #define	MEMBER_DELIM_LBR	3
104 
105 typedef int printarg_f(const char *, const char *,
106     mdb_ctf_id_t, mdb_ctf_id_t, ulong_t, printarg_t *);
107 
108 static int elt_print(const char *, mdb_ctf_id_t, mdb_ctf_id_t, ulong_t, int,
109     void *);
110 static void print_close_sou(printarg_t *, int);
111 
112 /*
113  * Given an address, look up the symbol ID of the specified symbol in its
114  * containing module.  We only support lookups for exact matches.
115  */
116 static const char *
117 addr_to_sym(mdb_tgt_t *t, uintptr_t addr, char *name, size_t namelen,
118     GElf_Sym *symp, mdb_syminfo_t *sip)
119 {
120 	const mdb_map_t *mp;
121 	const char *p;
122 
123 	if (mdb_tgt_lookup_by_addr(t, addr, MDB_TGT_SYM_EXACT, name,
124 	    namelen, NULL, NULL) == -1)
125 		return (NULL); /* address does not exactly match a symbol */
126 
127 	if ((p = strrsplit(name, '`')) != NULL) {
128 		if (mdb_tgt_lookup_by_name(t, name, p, symp, sip) == -1)
129 			return (NULL);
130 		return (p);
131 	}
132 
133 	if ((mp = mdb_tgt_addr_to_map(t, addr)) == NULL)
134 		return (NULL); /* address does not fall within a mapping */
135 
136 	if (mdb_tgt_lookup_by_name(t, mp->map_name, name, symp, sip) == -1)
137 		return (NULL);
138 
139 	return (name);
140 }
141 
142 /*
143  * This lets dcmds be a little fancy with their processing of type arguments
144  * while still treating them more or less as a single argument.
145  * For example, if a command is invokes like this:
146  *
147  *   ::<dcmd> proc_t ...
148  *
149  * this function will just copy "proc_t" into the provided buffer. If the
150  * command is instead invoked like this:
151  *
152  *   ::<dcmd> struct proc ...
153  *
154  * this function will place the string "struct proc" into the provided buffer
155  * and increment the caller's argv and argc. This allows the caller to still
156  * treat the type argument logically as it would an other atomic argument.
157  */
158 int
159 args_to_typename(int *argcp, const mdb_arg_t **argvp, char *buf, size_t len)
160 {
161 	int argc = *argcp;
162 	const mdb_arg_t *argv = *argvp;
163 
164 	if (argc < 1 || argv->a_type != MDB_TYPE_STRING)
165 		return (DCMD_USAGE);
166 
167 	if (strcmp(argv->a_un.a_str, "struct") == 0 ||
168 	    strcmp(argv->a_un.a_str, "enum") == 0 ||
169 	    strcmp(argv->a_un.a_str, "union") == 0) {
170 		if (argc <= 1) {
171 			mdb_warn("%s is not a valid type\n", argv->a_un.a_str);
172 			return (DCMD_ABORT);
173 		}
174 
175 		if (argv[1].a_type != MDB_TYPE_STRING)
176 			return (DCMD_USAGE);
177 
178 		(void) mdb_snprintf(buf, len, "%s %s",
179 		    argv[0].a_un.a_str, argv[1].a_un.a_str);
180 
181 		*argcp = argc - 1;
182 		*argvp = argv + 1;
183 	} else {
184 		(void) mdb_snprintf(buf, len, "%s", argv[0].a_un.a_str);
185 	}
186 
187 	return (0);
188 }
189 
190 /*ARGSUSED*/
191 int
192 cmd_sizeof(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
193 {
194 	mdb_ctf_id_t id;
195 	char tn[MDB_SYM_NAMLEN];
196 	int ret;
197 
198 	if (flags & DCMD_ADDRSPEC)
199 		return (DCMD_USAGE);
200 
201 	if ((ret = args_to_typename(&argc, &argv, tn, sizeof (tn))) != 0)
202 		return (ret);
203 
204 	if (argc != 1)
205 		return (DCMD_USAGE);
206 
207 	if (mdb_ctf_lookup_by_name(tn, &id) != 0) {
208 		mdb_warn("failed to look up type %s", tn);
209 		return (DCMD_ERR);
210 	}
211 
212 	if (flags & DCMD_PIPE_OUT)
213 		mdb_printf("%#lr\n", mdb_ctf_type_size(id));
214 	else
215 		mdb_printf("sizeof (%s) = %#lr\n", tn, mdb_ctf_type_size(id));
216 
217 	return (DCMD_OK);
218 }
219 
220 int
221 cmd_sizeof_tab(mdb_tab_cookie_t *mcp, uint_t flags, int argc,
222     const mdb_arg_t *argv)
223 {
224 	char tn[MDB_SYM_NAMLEN];
225 	int ret;
226 
227 	if (argc == 0 && !(flags & DCMD_TAB_SPACE))
228 		return (0);
229 
230 	if (argc == 0 && (flags & DCMD_TAB_SPACE))
231 		return (mdb_tab_complete_type(mcp, NULL, MDB_TABC_NOPOINT));
232 
233 	if ((ret = mdb_tab_typename(&argc, &argv, tn, sizeof (tn))) < 0)
234 		return (ret);
235 
236 	if (argc == 1)
237 		return (mdb_tab_complete_type(mcp, tn, MDB_TABC_NOPOINT));
238 
239 	return (0);
240 }
241 
242 /*ARGSUSED*/
243 int
244 cmd_offsetof(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
245 {
246 	const char *member;
247 	mdb_ctf_id_t id;
248 	ulong_t off;
249 	char tn[MDB_SYM_NAMLEN];
250 	ssize_t sz;
251 	int ret;
252 
253 	if (flags & DCMD_ADDRSPEC)
254 		return (DCMD_USAGE);
255 
256 	if ((ret = args_to_typename(&argc, &argv, tn, sizeof (tn))) != 0)
257 		return (ret);
258 
259 	if (argc != 2 || argv[1].a_type != MDB_TYPE_STRING)
260 		return (DCMD_USAGE);
261 
262 	if (mdb_ctf_lookup_by_name(tn, &id) != 0) {
263 		mdb_warn("failed to look up type %s", tn);
264 		return (DCMD_ERR);
265 	}
266 
267 	member = argv[1].a_un.a_str;
268 
269 	if (mdb_ctf_member_info(id, member, &off, &id) != 0) {
270 		mdb_warn("failed to find member %s of type %s", member, tn);
271 		return (DCMD_ERR);
272 	}
273 
274 	if (flags & DCMD_PIPE_OUT) {
275 		if (off % NBBY != 0) {
276 			mdb_warn("member %s of type %s is not byte-aligned\n",
277 			    member, tn);
278 			return (DCMD_ERR);
279 		}
280 		mdb_printf("%#lr", off / NBBY);
281 		return (DCMD_OK);
282 	}
283 
284 	mdb_printf("offsetof (%s, %s) = %#lr",
285 	    tn, member, off / NBBY);
286 	if (off % NBBY != 0)
287 		mdb_printf(".%lr", off % NBBY);
288 
289 	if ((sz = mdb_ctf_type_size(id)) > 0)
290 		mdb_printf(", sizeof (...->%s) = %#lr", member, sz);
291 
292 	mdb_printf("\n");
293 
294 	return (DCMD_OK);
295 }
296 
297 /*ARGSUSED*/
298 static int
299 enum_prefix_scan_cb(const char *name, int value, void *arg)
300 {
301 	char *str = arg;
302 
303 	/*
304 	 * This function is called with every name in the enum.  We make
305 	 * "arg" be the common prefix, if any.
306 	 */
307 	if (str[0] == 0) {
308 		if (strlcpy(arg, name, MDB_SYM_NAMLEN) >= MDB_SYM_NAMLEN)
309 			return (1);
310 		return (0);
311 	}
312 
313 	while (*name == *str) {
314 		if (*str == 0) {
315 			if (str != arg) {
316 				str--;	/* don't smother a name completely */
317 			}
318 			break;
319 		}
320 		name++;
321 		str++;
322 	}
323 	*str = 0;
324 
325 	return (str == arg);	/* only continue if prefix is non-empty */
326 }
327 
328 struct enum_p2_info {
329 	intmax_t e_value;	/* value we're processing */
330 	char	*e_buf;		/* buffer for holding names */
331 	size_t	e_size;		/* size of buffer */
332 	size_t	e_prefix;	/* length of initial prefix */
333 	uint_t	e_allprefix;	/* apply prefix to first guy, too */
334 	uint_t	e_bits;		/* bits seen */
335 	uint8_t	e_found;	/* have we seen anything? */
336 	uint8_t	e_first;	/* does buf contain the first one? */
337 	uint8_t	e_zero;		/* have we seen a zero value? */
338 };
339 
340 static int
341 enum_p2_cb(const char *name, int bit_arg, void *arg)
342 {
343 	struct enum_p2_info *eiip = arg;
344 	uintmax_t bit = bit_arg;
345 
346 	if (bit != 0 && !ISP2(bit))
347 		return (1);	/* non-power-of-2; abort processing */
348 
349 	if ((bit == 0 && eiip->e_zero) ||
350 	    (bit != 0 && (eiip->e_bits & bit) != 0)) {
351 		return (0);	/* already seen this value */
352 	}
353 
354 	if (bit == 0)
355 		eiip->e_zero = 1;
356 	else
357 		eiip->e_bits |= bit;
358 
359 	if (eiip->e_buf != NULL && (eiip->e_value & bit) != 0) {
360 		char *buf = eiip->e_buf;
361 		size_t prefix = eiip->e_prefix;
362 
363 		if (eiip->e_found) {
364 			(void) strlcat(buf, "|", eiip->e_size);
365 
366 			if (eiip->e_first && !eiip->e_allprefix && prefix > 0) {
367 				char c1 = buf[prefix];
368 				char c2 = buf[prefix + 1];
369 				buf[prefix] = '{';
370 				buf[prefix + 1] = 0;
371 				mdb_printf("%s", buf);
372 				buf[prefix] = c1;
373 				buf[prefix + 1] = c2;
374 				mdb_printf("%s", buf + prefix);
375 			} else {
376 				mdb_printf("%s", buf);
377 			}
378 
379 		}
380 		/* skip the common prefix as necessary */
381 		if ((eiip->e_found || eiip->e_allprefix) &&
382 		    strlen(name) > prefix)
383 			name += prefix;
384 
385 		(void) strlcpy(eiip->e_buf, name, eiip->e_size);
386 		eiip->e_first = !eiip->e_found;
387 		eiip->e_found = 1;
388 	}
389 	return (0);
390 }
391 
392 static int
393 enum_is_p2(mdb_ctf_id_t id)
394 {
395 	struct enum_p2_info eii;
396 	bzero(&eii, sizeof (eii));
397 
398 	return (mdb_ctf_type_kind(id) == CTF_K_ENUM &&
399 	    mdb_ctf_enum_iter(id, enum_p2_cb, &eii) == 0 &&
400 	    eii.e_bits != 0);
401 }
402 
403 static int
404 enum_value_print_p2(mdb_ctf_id_t id, intmax_t value, uint_t allprefix)
405 {
406 	struct enum_p2_info eii;
407 	char prefix[MDB_SYM_NAMLEN + 2];
408 	intmax_t missed;
409 
410 	bzero(&eii, sizeof (eii));
411 
412 	eii.e_value = value;
413 	eii.e_buf = prefix;
414 	eii.e_size = sizeof (prefix);
415 	eii.e_allprefix = allprefix;
416 
417 	prefix[0] = 0;
418 	if (mdb_ctf_enum_iter(id, enum_prefix_scan_cb, prefix) == 0)
419 		eii.e_prefix = strlen(prefix);
420 
421 	if (mdb_ctf_enum_iter(id, enum_p2_cb, &eii) != 0 || eii.e_bits == 0)
422 		return (-1);
423 
424 	missed = (value & ~(intmax_t)eii.e_bits);
425 
426 	if (eii.e_found) {
427 		/* push out any final value, with a | if we missed anything */
428 		if (!eii.e_first)
429 			(void) strlcat(prefix, "}", sizeof (prefix));
430 		if (missed != 0)
431 			(void) strlcat(prefix, "|", sizeof (prefix));
432 
433 		mdb_printf("%s", prefix);
434 	}
435 
436 	if (!eii.e_found || missed) {
437 		mdb_printf("%#llx", missed);
438 	}
439 
440 	return (0);
441 }
442 
443 struct enum_cbinfo {
444 	uint_t		e_flags;
445 	const char	*e_string;	/* NULL for value searches */
446 	size_t		e_prefix;
447 	intmax_t	e_value;
448 	uint_t		e_found;
449 	mdb_ctf_id_t	e_id;
450 };
451 #define	E_PRETTY		0x01
452 #define	E_HEX			0x02
453 #define	E_SEARCH_STRING		0x04
454 #define	E_SEARCH_VALUE		0x08
455 #define	E_ELIDE_PREFIX		0x10
456 
457 static void
458 enum_print(struct enum_cbinfo *info, const char *name, int value)
459 {
460 	uint_t flags = info->e_flags;
461 	uint_t elide_prefix = (info->e_flags & E_ELIDE_PREFIX);
462 
463 	if (name != NULL && info->e_prefix && strlen(name) > info->e_prefix)
464 		name += info->e_prefix;
465 
466 	if (flags & E_PRETTY) {
467 		uint_t indent = 5 + ((flags & E_HEX) ? 8 : 11);
468 
469 		mdb_printf((flags & E_HEX)? "%8x " : "%11d ", value);
470 		(void) mdb_inc_indent(indent);
471 		if (name != NULL) {
472 			mdb_iob_puts(mdb.m_out, name);
473 		} else {
474 			(void) enum_value_print_p2(info->e_id, value,
475 			    elide_prefix);
476 		}
477 		(void) mdb_dec_indent(indent);
478 		mdb_printf("\n");
479 	} else {
480 		mdb_printf("%#r\n", value);
481 	}
482 }
483 
484 static int
485 enum_cb(const char *name, int value, void *arg)
486 {
487 	struct enum_cbinfo *info = arg;
488 	uint_t flags = info->e_flags;
489 
490 	if (flags & E_SEARCH_STRING) {
491 		if (strcmp(name, info->e_string) != 0)
492 			return (0);
493 
494 	} else if (flags & E_SEARCH_VALUE) {
495 		if (value != info->e_value)
496 			return (0);
497 	}
498 
499 	enum_print(info, name, value);
500 
501 	info->e_found = 1;
502 	return (0);
503 }
504 
505 void
506 enum_help(void)
507 {
508 	mdb_printf("%s",
509 "Without an address and name, print all values for the enumeration \"enum\".\n"
510 "With an address, look up a particular value in \"enum\".  With a name, look\n"
511 "up a particular name in \"enum\".\n");
512 
513 	(void) mdb_dec_indent(2);
514 	mdb_printf("\n%<b>OPTIONS%</b>\n");
515 	(void) mdb_inc_indent(2);
516 
517 	mdb_printf("%s",
518 "   -e    remove common prefixes from enum names\n"
519 "   -x    report enum values in hexadecimal\n");
520 }
521 
522 /*ARGSUSED*/
523 int
524 cmd_enum(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
525 {
526 	struct enum_cbinfo info;
527 
528 	char type[MDB_SYM_NAMLEN + sizeof ("enum ")];
529 	char tn2[MDB_SYM_NAMLEN + sizeof ("enum ")];
530 	char prefix[MDB_SYM_NAMLEN];
531 	mdb_ctf_id_t id;
532 	mdb_ctf_id_t idr;
533 
534 	int i;
535 	intmax_t search;
536 	uint_t isp2;
537 
538 	info.e_flags = (flags & DCMD_PIPE_OUT)? 0 : E_PRETTY;
539 	info.e_string = NULL;
540 	info.e_value = 0;
541 	info.e_found = 0;
542 
543 	i = mdb_getopts(argc, argv,
544 	    'e', MDB_OPT_SETBITS, E_ELIDE_PREFIX, &info.e_flags,
545 	    'x', MDB_OPT_SETBITS, E_HEX, &info.e_flags,
546 	    NULL);
547 
548 	argc -= i;
549 	argv += i;
550 
551 	if ((i = args_to_typename(&argc, &argv, type, MDB_SYM_NAMLEN)) != 0)
552 		return (i);
553 
554 	if (strchr(type, ' ') == NULL) {
555 		/*
556 		 * Check as an enumeration tag first, and fall back
557 		 * to checking for a typedef.  Yes, this means that
558 		 * anonymous enumerations whose typedefs conflict with
559 		 * an enum tag can't be accessed.  Don't do that.
560 		 */
561 		(void) mdb_snprintf(tn2, sizeof (tn2), "enum %s", type);
562 
563 		if (mdb_ctf_lookup_by_name(tn2, &id) == 0) {
564 			(void) strcpy(type, tn2);
565 		} else if (mdb_ctf_lookup_by_name(type, &id) != 0) {
566 			mdb_warn("types '%s', '%s'", tn2, type);
567 			return (DCMD_ERR);
568 		}
569 	} else {
570 		if (mdb_ctf_lookup_by_name(type, &id) != 0) {
571 			mdb_warn("'%s'", type);
572 			return (DCMD_ERR);
573 		}
574 	}
575 
576 	/* resolve it, and make sure we're looking at an enumeration */
577 	if (mdb_ctf_type_resolve(id, &idr) == -1) {
578 		mdb_warn("unable to resolve '%s'", type);
579 		return (DCMD_ERR);
580 	}
581 	if (mdb_ctf_type_kind(idr) != CTF_K_ENUM) {
582 		mdb_warn("'%s': not an enumeration\n", type);
583 		return (DCMD_ERR);
584 	}
585 
586 	info.e_id = idr;
587 
588 	if (argc > 2)
589 		return (DCMD_USAGE);
590 
591 	if (argc == 2) {
592 		if (flags & DCMD_ADDRSPEC) {
593 			mdb_warn("may only specify one of: name, address\n");
594 			return (DCMD_USAGE);
595 		}
596 
597 		if (argv[1].a_type == MDB_TYPE_STRING) {
598 			info.e_flags |= E_SEARCH_STRING;
599 			info.e_string = argv[1].a_un.a_str;
600 		} else if (argv[1].a_type == MDB_TYPE_IMMEDIATE) {
601 			info.e_flags |= E_SEARCH_VALUE;
602 			search = argv[1].a_un.a_val;
603 		} else {
604 			return (DCMD_USAGE);
605 		}
606 	}
607 
608 	if (flags & DCMD_ADDRSPEC) {
609 		info.e_flags |= E_SEARCH_VALUE;
610 		search = mdb_get_dot();
611 	}
612 
613 	if (info.e_flags & E_SEARCH_VALUE) {
614 		if ((int)search != search) {
615 			mdb_warn("value '%lld' out of enumeration range\n",
616 			    search);
617 		}
618 		info.e_value = search;
619 	}
620 
621 	isp2 = enum_is_p2(idr);
622 	if (isp2)
623 		info.e_flags |= E_HEX;
624 
625 	if (DCMD_HDRSPEC(flags) && (info.e_flags & E_PRETTY)) {
626 		if (info.e_flags & E_HEX)
627 			mdb_printf("%<u>%8s %-64s%</u>\n", "VALUE", "NAME");
628 		else
629 			mdb_printf("%<u>%11s %-64s%</u>\n", "VALUE", "NAME");
630 	}
631 
632 	/* if the enum is a power-of-two one, process it that way */
633 	if ((info.e_flags & E_SEARCH_VALUE) && isp2) {
634 		enum_print(&info, NULL, info.e_value);
635 		return (DCMD_OK);
636 	}
637 
638 	prefix[0] = 0;
639 	if ((info.e_flags & E_ELIDE_PREFIX) &&
640 	    mdb_ctf_enum_iter(id, enum_prefix_scan_cb, prefix) == 0)
641 		info.e_prefix = strlen(prefix);
642 
643 	if (mdb_ctf_enum_iter(idr, enum_cb, &info) == -1) {
644 		mdb_warn("cannot walk '%s' as enum", type);
645 		return (DCMD_ERR);
646 	}
647 
648 	if (info.e_found == 0 &&
649 	    (info.e_flags & (E_SEARCH_STRING | E_SEARCH_VALUE)) != 0) {
650 		if (info.e_flags & E_SEARCH_STRING)
651 			mdb_warn("name \"%s\" not in '%s'\n", info.e_string,
652 			    type);
653 		else
654 			mdb_warn("value %#lld not in '%s'\n", info.e_value,
655 			    type);
656 
657 		return (DCMD_ERR);
658 	}
659 
660 	return (DCMD_OK);
661 }
662 
663 static int
664 setup_vcb(const char *name, uintptr_t addr)
665 {
666 	const char *p;
667 	mdb_var_t *v;
668 
669 	if ((v = mdb_nv_lookup(&mdb.m_nv, name)) == NULL) {
670 		if ((p = strbadid(name)) != NULL) {
671 			mdb_warn("'%c' may not be used in a variable "
672 			    "name\n", *p);
673 			return (DCMD_ABORT);
674 		}
675 
676 		if ((v = mdb_nv_insert(&mdb.m_nv, name, NULL, addr, 0)) == NULL)
677 			return (DCMD_ERR);
678 	} else {
679 		if (v->v_flags & MDB_NV_RDONLY) {
680 			mdb_warn("variable %s is read-only\n", name);
681 			return (DCMD_ABORT);
682 		}
683 	}
684 
685 	/*
686 	 * If there already exists a vcb for this variable, we may be
687 	 * calling the dcmd in a loop.  We only create a vcb for this
688 	 * variable on the first invocation.
689 	 */
690 	if (mdb_vcb_find(v, mdb.m_frame) == NULL)
691 		mdb_vcb_insert(mdb_vcb_create(v), mdb.m_frame);
692 
693 	return (0);
694 }
695 
696 /*ARGSUSED*/
697 int
698 cmd_list(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
699 {
700 	int offset;
701 	uintptr_t a, tmp;
702 	int ret;
703 
704 	if (!(flags & DCMD_ADDRSPEC) || argc == 0)
705 		return (DCMD_USAGE);
706 
707 	if (argv->a_type != MDB_TYPE_STRING) {
708 		/*
709 		 * We are being given a raw offset in lieu of a type and
710 		 * member; confirm the number of arguments and argument
711 		 * type.
712 		 */
713 		if (argc != 1 || argv->a_type != MDB_TYPE_IMMEDIATE)
714 			return (DCMD_USAGE);
715 
716 		offset = argv->a_un.a_val;
717 
718 		argv++;
719 		argc--;
720 
721 		if (offset % sizeof (uintptr_t)) {
722 			mdb_warn("offset must fall on a word boundary\n");
723 			return (DCMD_ABORT);
724 		}
725 	} else {
726 		const char *member;
727 		char buf[MDB_SYM_NAMLEN];
728 		int ret;
729 
730 		/*
731 		 * Check that we were provided 2 arguments: a type name
732 		 * and a member of that type.
733 		 */
734 		if (argc != 2)
735 			return (DCMD_USAGE);
736 
737 		ret = args_to_typename(&argc, &argv, buf, sizeof (buf));
738 		if (ret != 0)
739 			return (ret);
740 
741 		argv++;
742 		argc--;
743 
744 		member = argv->a_un.a_str;
745 		offset = mdb_ctf_offsetof_by_name(buf, member);
746 		if (offset == -1)
747 			return (DCMD_ABORT);
748 
749 		argv++;
750 		argc--;
751 
752 		if (offset % (sizeof (uintptr_t)) != 0) {
753 			mdb_warn("%s is not a word-aligned member\n", member);
754 			return (DCMD_ABORT);
755 		}
756 	}
757 
758 	/*
759 	 * If we have any unchewed arguments, a variable name must be present.
760 	 */
761 	if (argc == 1) {
762 		if (argv->a_type != MDB_TYPE_STRING)
763 			return (DCMD_USAGE);
764 
765 		if ((ret = setup_vcb(argv->a_un.a_str, addr)) != 0)
766 			return (ret);
767 
768 	} else if (argc != 0) {
769 		return (DCMD_USAGE);
770 	}
771 
772 	a = addr;
773 
774 	do {
775 		mdb_printf("%lr\n", a);
776 
777 		if (mdb_vread(&tmp, sizeof (tmp), a + offset) == -1) {
778 			mdb_warn("failed to read next pointer from object %p",
779 			    a);
780 			return (DCMD_ERR);
781 		}
782 
783 		a = tmp;
784 	} while (a != addr && a != NULL);
785 
786 	return (DCMD_OK);
787 }
788 
789 int
790 cmd_array(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
791 {
792 	mdb_ctf_id_t id;
793 	ssize_t elemsize = 0;
794 	char tn[MDB_SYM_NAMLEN];
795 	int ret, nelem = -1;
796 
797 	mdb_tgt_t *t = mdb.m_target;
798 	GElf_Sym sym;
799 	mdb_ctf_arinfo_t ar;
800 	mdb_syminfo_t s_info;
801 
802 	if (!(flags & DCMD_ADDRSPEC))
803 		return (DCMD_USAGE);
804 
805 	if (argc >= 2) {
806 		ret = args_to_typename(&argc, &argv, tn, sizeof (tn));
807 		if (ret != 0)
808 			return (ret);
809 
810 		if (argc == 1)	/* unquoted compound type without count */
811 			return (DCMD_USAGE);
812 
813 		if (mdb_ctf_lookup_by_name(tn, &id) != 0) {
814 			mdb_warn("failed to look up type %s", tn);
815 			return (DCMD_ABORT);
816 		}
817 
818 		if (argv[1].a_type == MDB_TYPE_IMMEDIATE)
819 			nelem = argv[1].a_un.a_val;
820 		else
821 			nelem = mdb_strtoull(argv[1].a_un.a_str);
822 
823 		elemsize = mdb_ctf_type_size(id);
824 	} else if (addr_to_sym(t, addr, tn, sizeof (tn), &sym, &s_info)
825 	    != NULL && mdb_ctf_lookup_by_symbol(&sym, &s_info, &id)
826 	    == 0 && mdb_ctf_type_kind(id) == CTF_K_ARRAY &&
827 	    mdb_ctf_array_info(id, &ar) != -1) {
828 		elemsize = mdb_ctf_type_size(id) / ar.mta_nelems;
829 		nelem = ar.mta_nelems;
830 	} else {
831 		mdb_warn("no symbol information for %a", addr);
832 		return (DCMD_ERR);
833 	}
834 
835 	if (argc == 3 || argc == 1) {
836 		if (argv[argc - 1].a_type != MDB_TYPE_STRING)
837 			return (DCMD_USAGE);
838 
839 		if ((ret = setup_vcb(argv[argc - 1].a_un.a_str, addr)) != 0)
840 			return (ret);
841 
842 	} else if (argc > 3) {
843 		return (DCMD_USAGE);
844 	}
845 
846 	for (; nelem > 0; nelem--) {
847 		mdb_printf("%lr\n", addr);
848 		addr = addr + elemsize;
849 	}
850 
851 	return (DCMD_OK);
852 }
853 
854 /*
855  * Print an integer bitfield in hexadecimal by reading the enclosing byte(s)
856  * and then shifting and masking the data in the lower bits of a uint64_t.
857  */
858 static int
859 print_bitfield(ulong_t off, printarg_t *pap, ctf_encoding_t *ep)
860 {
861 	mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
862 	size_t size = (ep->cte_bits + (NBBY - 1)) / NBBY;
863 	uint64_t mask = (1ULL << ep->cte_bits) - 1;
864 	uint64_t value = 0;
865 	uint8_t *buf = (uint8_t *)&value;
866 	uint8_t shift;
867 
868 	const char *format;
869 
870 	if (!(pap->pa_flags & PA_SHOWVAL))
871 		return (0);
872 
873 	if (ep->cte_bits > sizeof (value) * NBBY - 1) {
874 		mdb_printf("??? (invalid bitfield size %u)", ep->cte_bits);
875 		return (0);
876 	}
877 
878 	/*
879 	 * On big-endian machines, we need to adjust the buf pointer to refer
880 	 * to the lowest 'size' bytes in 'value', and we need shift based on
881 	 * the offset from the end of the data, not the offset of the start.
882 	 */
883 #ifdef _BIG_ENDIAN
884 	buf += sizeof (value) - size;
885 	off += ep->cte_bits;
886 #endif
887 	if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, buf, size, addr) != size) {
888 		mdb_warn("failed to read %lu bytes at %llx",
889 		    (ulong_t)size, addr);
890 		return (1);
891 	}
892 
893 	shift = off % NBBY;
894 
895 	/*
896 	 * Offsets are counted from opposite ends on little- and
897 	 * big-endian machines.
898 	 */
899 #ifdef _BIG_ENDIAN
900 	shift = NBBY - shift;
901 #endif
902 
903 	/*
904 	 * If the bits we want do not begin on a byte boundary, shift the data
905 	 * right so that the value is in the lowest 'cte_bits' of 'value'.
906 	 */
907 	if (off % NBBY != 0)
908 		value >>= shift;
909 	value &= mask;
910 
911 	/*
912 	 * We default to printing signed bitfields as decimals,
913 	 * and unsigned bitfields in hexadecimal.  If they specify
914 	 * hexadecimal, we treat the field as unsigned.
915 	 */
916 	if ((pap->pa_flags & PA_INTHEX) ||
917 	    !(ep->cte_format & CTF_INT_SIGNED)) {
918 		format = (pap->pa_flags & PA_INTDEC)? "%#llu" : "%#llx";
919 	} else {
920 		int sshift = sizeof (value) * NBBY - ep->cte_bits;
921 
922 		/* sign-extend value, and print as a signed decimal */
923 		value = ((int64_t)value << sshift) >> sshift;
924 		format = "%#lld";
925 	}
926 	mdb_printf(format, value);
927 
928 	return (0);
929 }
930 
931 /*
932  * Print out a character or integer value.  We use some simple heuristics,
933  * described below, to determine the appropriate radix to use for output.
934  */
935 static int
936 print_int_val(const char *type, ctf_encoding_t *ep, ulong_t off,
937     printarg_t *pap)
938 {
939 	static const char *const sformat[] = { "%#d", "%#d", "%#d", "%#lld" };
940 	static const char *const uformat[] = { "%#u", "%#u", "%#u", "%#llu" };
941 	static const char *const xformat[] = { "%#x", "%#x", "%#x", "%#llx" };
942 
943 	mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
944 	const char *const *fsp;
945 	size_t size;
946 
947 	union {
948 		uint64_t i8;
949 		uint32_t i4;
950 		uint16_t i2;
951 		uint8_t i1;
952 		time_t t;
953 		ipaddr_t I;
954 	} u;
955 
956 	if (!(pap->pa_flags & PA_SHOWVAL))
957 		return (0);
958 
959 	if (ep->cte_format & CTF_INT_VARARGS) {
960 		mdb_printf("...\n");
961 		return (0);
962 	}
963 
964 	/*
965 	 * If the size is not a power-of-two number of bytes in the range 1-8
966 	 * then we assume it is a bitfield and print it as such.
967 	 */
968 	size = ep->cte_bits / NBBY;
969 	if (size > 8 || (ep->cte_bits % NBBY) != 0 || (size & (size - 1)) != 0)
970 		return (print_bitfield(off, pap, ep));
971 
972 	if (IS_CHAR(*ep)) {
973 		mdb_printf("'");
974 		if (mdb_fmt_print(pap->pa_tgt, pap->pa_as,
975 		    addr, 1, 'C') == addr)
976 			return (1);
977 		mdb_printf("'");
978 		return (0);
979 	}
980 
981 	if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.i8, size, addr) != size) {
982 		mdb_warn("failed to read %lu bytes at %llx",
983 		    (ulong_t)size, addr);
984 		return (1);
985 	}
986 
987 	/*
988 	 * We pretty-print some integer based types.  time_t values are
989 	 * printed as a calendar date and time, and IPv4 addresses as human
990 	 * readable dotted quads.
991 	 */
992 	if (!(pap->pa_flags & (PA_INTHEX | PA_INTDEC))) {
993 		if (strcmp(type, "time_t") == 0 && u.t != 0) {
994 			mdb_printf("%Y", u.t);
995 			return (0);
996 		}
997 		if (strcmp(type, "ipaddr_t") == 0 ||
998 		    strcmp(type, "in_addr_t") == 0) {
999 			mdb_printf("%I", u.I);
1000 			return (0);
1001 		}
1002 	}
1003 
1004 	/*
1005 	 * The default format is hexadecimal.
1006 	 */
1007 	if (!(pap->pa_flags & PA_INTDEC))
1008 		fsp = xformat;
1009 	else if (ep->cte_format & CTF_INT_SIGNED)
1010 		fsp = sformat;
1011 	else
1012 		fsp = uformat;
1013 
1014 	switch (size) {
1015 	case sizeof (uint8_t):
1016 		mdb_printf(fsp[0], u.i1);
1017 		break;
1018 	case sizeof (uint16_t):
1019 		mdb_printf(fsp[1], u.i2);
1020 		break;
1021 	case sizeof (uint32_t):
1022 		mdb_printf(fsp[2], u.i4);
1023 		break;
1024 	case sizeof (uint64_t):
1025 		mdb_printf(fsp[3], u.i8);
1026 		break;
1027 	}
1028 	return (0);
1029 }
1030 
1031 /*ARGSUSED*/
1032 static int
1033 print_int(const char *type, const char *name, mdb_ctf_id_t id,
1034     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1035 {
1036 	ctf_encoding_t e;
1037 
1038 	if (!(pap->pa_flags & PA_SHOWVAL))
1039 		return (0);
1040 
1041 	if (mdb_ctf_type_encoding(base, &e) != 0) {
1042 		mdb_printf("??? (%s)", mdb_strerror(errno));
1043 		return (0);
1044 	}
1045 
1046 	return (print_int_val(type, &e, off, pap));
1047 }
1048 
1049 /*
1050  * Print out a floating point value.  We only provide support for floats in
1051  * the ANSI-C float, double, and long double formats.
1052  */
1053 /*ARGSUSED*/
1054 static int
1055 print_float(const char *type, const char *name, mdb_ctf_id_t id,
1056     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1057 {
1058 #ifndef _KMDB
1059 	mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1060 	ctf_encoding_t e;
1061 
1062 	union {
1063 		float f;
1064 		double d;
1065 		long double ld;
1066 	} u;
1067 
1068 	if (!(pap->pa_flags & PA_SHOWVAL))
1069 		return (0);
1070 
1071 	if (mdb_ctf_type_encoding(base, &e) == 0) {
1072 		if (e.cte_format == CTF_FP_SINGLE &&
1073 		    e.cte_bits == sizeof (float) * NBBY) {
1074 			if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.f,
1075 			    sizeof (u.f), addr) != sizeof (u.f)) {
1076 				mdb_warn("failed to read float at %llx", addr);
1077 				return (1);
1078 			}
1079 			mdb_printf("%s", doubletos(u.f, 7, 'e'));
1080 
1081 		} else if (e.cte_format == CTF_FP_DOUBLE &&
1082 		    e.cte_bits == sizeof (double) * NBBY) {
1083 			if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.d,
1084 			    sizeof (u.d), addr) != sizeof (u.d)) {
1085 				mdb_warn("failed to read float at %llx", addr);
1086 				return (1);
1087 			}
1088 			mdb_printf("%s", doubletos(u.d, 7, 'e'));
1089 
1090 		} else if (e.cte_format == CTF_FP_LDOUBLE &&
1091 		    e.cte_bits == sizeof (long double) * NBBY) {
1092 			if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.ld,
1093 			    sizeof (u.ld), addr) != sizeof (u.ld)) {
1094 				mdb_warn("failed to read float at %llx", addr);
1095 				return (1);
1096 			}
1097 			mdb_printf("%s", longdoubletos(&u.ld, 16, 'e'));
1098 
1099 		} else {
1100 			mdb_printf("??? (unsupported FP format %u / %u bits\n",
1101 			    e.cte_format, e.cte_bits);
1102 		}
1103 	} else
1104 		mdb_printf("??? (%s)", mdb_strerror(errno));
1105 #else
1106 	mdb_printf("<FLOAT>");
1107 #endif
1108 	return (0);
1109 }
1110 
1111 
1112 /*
1113  * Print out a pointer value as a symbol name + offset or a hexadecimal value.
1114  * If the pointer itself is a char *, we attempt to read a bit of the data
1115  * referenced by the pointer and display it if it is a printable ASCII string.
1116  */
1117 /*ARGSUSED*/
1118 static int
1119 print_ptr(const char *type, const char *name, mdb_ctf_id_t id,
1120     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1121 {
1122 	mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1123 	ctf_encoding_t e;
1124 	uintptr_t value;
1125 	char buf[256];
1126 	ssize_t len;
1127 
1128 	if (!(pap->pa_flags & PA_SHOWVAL))
1129 		return (0);
1130 
1131 	if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as,
1132 	    &value, sizeof (value), addr) != sizeof (value)) {
1133 		mdb_warn("failed to read %s pointer at %llx", name, addr);
1134 		return (1);
1135 	}
1136 
1137 	if (pap->pa_flags & PA_NOSYMBOLIC) {
1138 		mdb_printf("%#lx", value);
1139 		return (0);
1140 	}
1141 
1142 	mdb_printf("%a", value);
1143 
1144 	if (value == NULL || strcmp(type, "caddr_t") == 0)
1145 		return (0);
1146 
1147 	if (mdb_ctf_type_kind(base) == CTF_K_POINTER &&
1148 	    mdb_ctf_type_reference(base, &base) != -1 &&
1149 	    mdb_ctf_type_resolve(base, &base) != -1 &&
1150 	    mdb_ctf_type_encoding(base, &e) == 0 && IS_CHAR(e)) {
1151 		if ((len = mdb_tgt_readstr(pap->pa_realtgt, pap->pa_as,
1152 		    buf, sizeof (buf), value)) >= 0 && strisprint(buf)) {
1153 			if (len == sizeof (buf))
1154 				(void) strabbr(buf, sizeof (buf));
1155 			mdb_printf(" \"%s\"", buf);
1156 		}
1157 	}
1158 
1159 	return (0);
1160 }
1161 
1162 
1163 /*
1164  * Print out a fixed-size array.  We special-case arrays of characters
1165  * and attempt to print them out as ASCII strings if possible.  For other
1166  * arrays, we iterate over a maximum of pa_armemlim members and call
1167  * mdb_ctf_type_visit() again on each element to print its value.
1168  */
1169 /*ARGSUSED*/
1170 static int
1171 print_array(const char *type, const char *name, mdb_ctf_id_t id,
1172     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1173 {
1174 	mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1175 	printarg_t pa = *pap;
1176 	ssize_t eltsize;
1177 	mdb_ctf_arinfo_t r;
1178 	ctf_encoding_t e;
1179 	uint_t i, kind, limit;
1180 	int d, sou;
1181 	char buf[8];
1182 	char *str;
1183 
1184 	if (!(pap->pa_flags & PA_SHOWVAL))
1185 		return (0);
1186 
1187 	if (pap->pa_depth == pap->pa_maxdepth) {
1188 		mdb_printf("[ ... ]");
1189 		return (0);
1190 	}
1191 
1192 	/*
1193 	 * Determine the base type and size of the array's content.  If this
1194 	 * fails, we cannot print anything and just give up.
1195 	 */
1196 	if (mdb_ctf_array_info(base, &r) == -1 ||
1197 	    mdb_ctf_type_resolve(r.mta_contents, &base) == -1 ||
1198 	    (eltsize = mdb_ctf_type_size(base)) == -1) {
1199 		mdb_printf("[ ??? ] (%s)", mdb_strerror(errno));
1200 		return (0);
1201 	}
1202 
1203 	/*
1204 	 * Read a few bytes and determine if the content appears to be
1205 	 * printable ASCII characters.  If so, read the entire array and
1206 	 * attempt to display it as a string if it is printable.
1207 	 */
1208 	if ((pap->pa_arstrlim == MDB_ARR_NOLIMIT ||
1209 	    r.mta_nelems <= pap->pa_arstrlim) &&
1210 	    mdb_ctf_type_encoding(base, &e) == 0 && IS_CHAR(e) &&
1211 	    mdb_tgt_readstr(pap->pa_tgt, pap->pa_as, buf,
1212 	    MIN(sizeof (buf), r.mta_nelems), addr) > 0 && strisprint(buf)) {
1213 
1214 		str = mdb_alloc(r.mta_nelems + 1, UM_SLEEP | UM_GC);
1215 		str[r.mta_nelems] = '\0';
1216 
1217 		if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, str,
1218 		    r.mta_nelems, addr) != r.mta_nelems) {
1219 			mdb_warn("failed to read char array at %llx", addr);
1220 			return (1);
1221 		}
1222 
1223 		if (strisprint(str)) {
1224 			mdb_printf("[ \"%s\" ]", str);
1225 			return (0);
1226 		}
1227 	}
1228 
1229 	if (pap->pa_armemlim != MDB_ARR_NOLIMIT)
1230 		limit = MIN(r.mta_nelems, pap->pa_armemlim);
1231 	else
1232 		limit = r.mta_nelems;
1233 
1234 	if (limit == 0) {
1235 		mdb_printf("[ ... ]");
1236 		return (0);
1237 	}
1238 
1239 	kind = mdb_ctf_type_kind(base);
1240 	sou = IS_COMPOSITE(kind);
1241 
1242 	pa.pa_addr = addr;		/* set base address to start of array */
1243 	pa.pa_maxdepth = pa.pa_maxdepth - pa.pa_depth - 1;
1244 	pa.pa_nest += pa.pa_depth + 1;	/* nesting level is current depth + 1 */
1245 	pa.pa_depth = 0;		/* reset depth to 0 for new scope */
1246 	pa.pa_prefix = NULL;
1247 
1248 	if (sou) {
1249 		pa.pa_delim = "\n";
1250 		mdb_printf("[\n");
1251 	} else {
1252 		pa.pa_flags &= ~(PA_SHOWTYPE | PA_SHOWNAME | PA_SHOWADDR);
1253 		pa.pa_delim = ", ";
1254 		mdb_printf("[ ");
1255 	}
1256 
1257 	for (i = 0; i < limit; i++, pa.pa_addr += eltsize) {
1258 		if (i == limit - 1 && !sou) {
1259 			if (limit < r.mta_nelems)
1260 				pa.pa_delim = ", ... ]";
1261 			else
1262 				pa.pa_delim = " ]";
1263 		}
1264 
1265 		if (mdb_ctf_type_visit(r.mta_contents, elt_print, &pa) == -1) {
1266 			mdb_warn("failed to print array data");
1267 			return (1);
1268 		}
1269 	}
1270 
1271 	if (sou) {
1272 		for (d = pa.pa_depth - 1; d >= 0; d--)
1273 			print_close_sou(&pa, d);
1274 
1275 		if (limit < r.mta_nelems) {
1276 			mdb_printf("%*s... ]",
1277 			    (pap->pa_depth + pap->pa_nest) * pap->pa_tab, "");
1278 		} else {
1279 			mdb_printf("%*s]",
1280 			    (pap->pa_depth + pap->pa_nest) * pap->pa_tab, "");
1281 		}
1282 	}
1283 
1284 	/* copy the hole array info, since it may have been grown */
1285 	pap->pa_holes = pa.pa_holes;
1286 	pap->pa_nholes = pa.pa_nholes;
1287 
1288 	return (0);
1289 }
1290 
1291 /*
1292  * Print out a struct or union header.  We need only print the open brace
1293  * because mdb_ctf_type_visit() itself will automatically recurse through
1294  * all members of the given struct or union.
1295  */
1296 /*ARGSUSED*/
1297 static int
1298 print_sou(const char *type, const char *name, mdb_ctf_id_t id,
1299     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1300 {
1301 	mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1302 
1303 	/*
1304 	 * We have pretty-printing for some structures where displaying
1305 	 * structure contents has no value.
1306 	 */
1307 	if (pap->pa_flags & PA_SHOWVAL) {
1308 		if (strcmp(type, "in6_addr_t") == 0 ||
1309 		    strcmp(type, "struct in6_addr") == 0) {
1310 			in6_addr_t in6addr;
1311 
1312 			if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &in6addr,
1313 			    sizeof (in6addr), addr) != sizeof (in6addr)) {
1314 				mdb_warn("failed to read %s pointer at %llx",
1315 				    name, addr);
1316 				return (1);
1317 			}
1318 			mdb_printf("%N", &in6addr);
1319 			/*
1320 			 * Don't print anything further down in the
1321 			 * structure.
1322 			 */
1323 			pap->pa_nooutdepth = pap->pa_depth;
1324 			return (0);
1325 		}
1326 		if (strcmp(type, "struct in_addr") == 0) {
1327 			in_addr_t inaddr;
1328 
1329 			if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &inaddr,
1330 			    sizeof (inaddr), addr) != sizeof (inaddr)) {
1331 				mdb_warn("failed to read %s pointer at %llx",
1332 				    name, addr);
1333 				return (1);
1334 			}
1335 			mdb_printf("%I", inaddr);
1336 			pap->pa_nooutdepth = pap->pa_depth;
1337 			return (0);
1338 		}
1339 	}
1340 
1341 	if (pap->pa_depth == pap->pa_maxdepth)
1342 		mdb_printf("{ ... }");
1343 	else
1344 		mdb_printf("{");
1345 	pap->pa_delim = "\n";
1346 	return (0);
1347 }
1348 
1349 /*
1350  * Print an enum value.  We attempt to convert the value to the corresponding
1351  * enum name and print that if possible.
1352  */
1353 /*ARGSUSED*/
1354 static int
1355 print_enum(const char *type, const char *name, mdb_ctf_id_t id,
1356     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1357 {
1358 	mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1359 	const char *ename;
1360 	int value;
1361 	int isp2 = enum_is_p2(base);
1362 	int flags = pap->pa_flags | (isp2 ? PA_INTHEX : 0);
1363 
1364 	if (!(flags & PA_SHOWVAL))
1365 		return (0);
1366 
1367 	if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as,
1368 	    &value, sizeof (value), addr) != sizeof (value)) {
1369 		mdb_warn("failed to read %s integer at %llx", name, addr);
1370 		return (1);
1371 	}
1372 
1373 	if (flags & PA_INTHEX)
1374 		mdb_printf("%#x", value);
1375 	else
1376 		mdb_printf("%#d", value);
1377 
1378 	(void) mdb_inc_indent(8);
1379 	mdb_printf(" (");
1380 
1381 	if (!isp2 || enum_value_print_p2(base, value, 0) != 0) {
1382 		ename = mdb_ctf_enum_name(base, value);
1383 		if (ename == NULL) {
1384 			ename = "???";
1385 		}
1386 		mdb_printf("%s", ename);
1387 	}
1388 	mdb_printf(")");
1389 	(void) mdb_dec_indent(8);
1390 
1391 	return (0);
1392 }
1393 
1394 /*
1395  * This will only get called if the structure isn't found in any available CTF
1396  * data.
1397  */
1398 /*ARGSUSED*/
1399 static int
1400 print_tag(const char *type, const char *name, mdb_ctf_id_t id,
1401     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1402 {
1403 	char basename[MDB_SYM_NAMLEN];
1404 
1405 	if (pap->pa_flags & PA_SHOWVAL)
1406 		mdb_printf("; ");
1407 
1408 	if (mdb_ctf_type_name(base, basename, sizeof (basename)) != NULL)
1409 		mdb_printf("<forward declaration of %s>", basename);
1410 	else
1411 		mdb_printf("<forward declaration of unknown type>");
1412 
1413 	return (0);
1414 }
1415 
1416 static void
1417 print_hole(printarg_t *pap, int depth, ulong_t off, ulong_t endoff)
1418 {
1419 	ulong_t bits = endoff - off;
1420 	ulong_t size = bits / NBBY;
1421 	ctf_encoding_t e;
1422 
1423 	static const char *const name = "<<HOLE>>";
1424 	char type[MDB_SYM_NAMLEN];
1425 
1426 	int bitfield =
1427 	    (off % NBBY != 0 ||
1428 	    bits % NBBY != 0 ||
1429 	    size > 8 ||
1430 	    (size & (size - 1)) != 0);
1431 
1432 	ASSERT(off < endoff);
1433 
1434 	if (bits > NBBY * sizeof (uint64_t)) {
1435 		ulong_t end;
1436 
1437 		/*
1438 		 * The hole is larger than the largest integer type.  To
1439 		 * handle this, we split up the hole at 8-byte-aligned
1440 		 * boundaries, recursing to print each subsection.  For
1441 		 * normal C structures, we'll loop at most twice.
1442 		 */
1443 		for (; off < endoff; off = end) {
1444 			end = P2END(off, NBBY * sizeof (uint64_t));
1445 			if (end > endoff)
1446 				end = endoff;
1447 
1448 			ASSERT((end - off) <= NBBY * sizeof (uint64_t));
1449 			print_hole(pap, depth, off, end);
1450 		}
1451 		ASSERT(end == endoff);
1452 
1453 		return;
1454 	}
1455 
1456 	if (bitfield)
1457 		(void) mdb_snprintf(type, sizeof (type), "unsigned");
1458 	else
1459 		(void) mdb_snprintf(type, sizeof (type), "uint%d_t", bits);
1460 
1461 	if (pap->pa_flags & (PA_SHOWTYPE | PA_SHOWNAME | PA_SHOWADDR))
1462 		mdb_printf("%*s", (depth + pap->pa_nest) * pap->pa_tab, "");
1463 
1464 	if (pap->pa_flags & PA_SHOWADDR) {
1465 		if (off % NBBY == 0)
1466 			mdb_printf("%llx ", pap->pa_addr + off / NBBY);
1467 		else
1468 			mdb_printf("%llx.%lx ",
1469 			    pap->pa_addr + off / NBBY, off % NBBY);
1470 	}
1471 
1472 	if (pap->pa_flags & PA_SHOWTYPE)
1473 		mdb_printf("%s ", type);
1474 
1475 	if (pap->pa_flags & PA_SHOWNAME)
1476 		mdb_printf("%s", name);
1477 
1478 	if (bitfield && (pap->pa_flags & PA_SHOWTYPE))
1479 		mdb_printf(" :%d", bits);
1480 
1481 	mdb_printf("%s ", (pap->pa_flags & PA_SHOWVAL)? " =" : "");
1482 
1483 	/*
1484 	 * We fake up a ctf_encoding_t, and use print_int_val() to print
1485 	 * the value.  Holes are always processed as unsigned integers.
1486 	 */
1487 	bzero(&e, sizeof (e));
1488 	e.cte_format = 0;
1489 	e.cte_offset = 0;
1490 	e.cte_bits = bits;
1491 
1492 	if (print_int_val(type, &e, off, pap) != 0)
1493 		mdb_iob_discard(mdb.m_out);
1494 	else
1495 		mdb_iob_puts(mdb.m_out, pap->pa_delim);
1496 }
1497 
1498 /*
1499  * The print_close_sou() function is called for each structure or union
1500  * which has been completed.  For structures, we detect and print any holes
1501  * before printing the closing brace.
1502  */
1503 static void
1504 print_close_sou(printarg_t *pap, int newdepth)
1505 {
1506 	int d = newdepth + pap->pa_nest;
1507 
1508 	if ((pap->pa_flags & PA_SHOWHOLES) && !pap->pa_holes[d].hi_isunion) {
1509 		ulong_t end = pap->pa_holes[d + 1].hi_offset;
1510 		ulong_t expected = pap->pa_holes[d].hi_offset;
1511 
1512 		if (end < expected)
1513 			print_hole(pap, newdepth + 1, end, expected);
1514 	}
1515 	/* if the struct is an array element, print a comma after the } */
1516 	mdb_printf("%*s}%s\n", d * pap->pa_tab, "",
1517 	    (newdepth == 0 && pap->pa_nest > 0)? "," : "");
1518 }
1519 
1520 static printarg_f *const printfuncs[] = {
1521 	print_int,	/* CTF_K_INTEGER */
1522 	print_float,	/* CTF_K_FLOAT */
1523 	print_ptr,	/* CTF_K_POINTER */
1524 	print_array,	/* CTF_K_ARRAY */
1525 	print_ptr,	/* CTF_K_FUNCTION */
1526 	print_sou,	/* CTF_K_STRUCT */
1527 	print_sou,	/* CTF_K_UNION */
1528 	print_enum,	/* CTF_K_ENUM */
1529 	print_tag	/* CTF_K_FORWARD */
1530 };
1531 
1532 /*
1533  * The elt_print function is used as the mdb_ctf_type_visit callback.  For
1534  * each element, we print an appropriate name prefix and then call the
1535  * print subroutine for this type class in the array above.
1536  */
1537 static int
1538 elt_print(const char *name, mdb_ctf_id_t id, mdb_ctf_id_t base,
1539     ulong_t off, int depth, void *data)
1540 {
1541 	char type[MDB_SYM_NAMLEN + sizeof (" <<12345678...>>")];
1542 	int kind, rc, d;
1543 	printarg_t *pap = data;
1544 
1545 	for (d = pap->pa_depth - 1; d >= depth; d--) {
1546 		if (d < pap->pa_nooutdepth)
1547 			print_close_sou(pap, d);
1548 	}
1549 
1550 	/*
1551 	 * Reset pa_nooutdepth if we've come back out of the structure we
1552 	 * didn't want to print.
1553 	 */
1554 	if (depth <= pap->pa_nooutdepth)
1555 		pap->pa_nooutdepth = (uint_t)-1;
1556 
1557 	if (depth > pap->pa_maxdepth || depth > pap->pa_nooutdepth)
1558 		return (0);
1559 
1560 	if (!mdb_ctf_type_valid(base) ||
1561 	    (kind = mdb_ctf_type_kind(base)) == -1)
1562 		return (-1); /* errno is set for us */
1563 
1564 	if (mdb_ctf_type_name(id, type, MDB_SYM_NAMLEN) == NULL)
1565 		(void) strcpy(type, "(?)");
1566 
1567 	if (pap->pa_flags & PA_SHOWBASETYPE) {
1568 		/*
1569 		 * If basetype is different and informative, concatenate
1570 		 * <<basetype>> (or <<baset...>> if it doesn't fit)
1571 		 *
1572 		 * We just use the end of the buffer to store the type name, and
1573 		 * only connect it up if that's necessary.
1574 		 */
1575 
1576 		char *type_end = type + strlen(type);
1577 		char *basetype;
1578 		size_t sz;
1579 
1580 		(void) strlcat(type, " <<", sizeof (type));
1581 
1582 		basetype = type + strlen(type);
1583 		sz = sizeof (type) - (basetype - type);
1584 
1585 		*type_end = '\0'; /* restore the end of type for strcmp() */
1586 
1587 		if (mdb_ctf_type_name(base, basetype, sz) != NULL &&
1588 		    strcmp(basetype, type) != 0 &&
1589 		    strcmp(basetype, "struct ") != 0 &&
1590 		    strcmp(basetype, "enum ") != 0 &&
1591 		    strcmp(basetype, "union ") != 0) {
1592 			type_end[0] = ' ';	/* reconnect */
1593 			if (strlcat(type, ">>", sizeof (type)) >= sizeof (type))
1594 				(void) strlcpy(
1595 				    type + sizeof (type) - 6, "...>>", 6);
1596 		}
1597 	}
1598 
1599 	if (pap->pa_flags & PA_SHOWHOLES) {
1600 		ctf_encoding_t e;
1601 		ssize_t nsize;
1602 		ulong_t newoff;
1603 		holeinfo_t *hole;
1604 		int extra = IS_COMPOSITE(kind)? 1 : 0;
1605 
1606 		/*
1607 		 * grow the hole array, if necessary
1608 		 */
1609 		if (pap->pa_nest + depth + extra >= pap->pa_nholes) {
1610 			int new = MAX(MAX(8, pap->pa_nholes * 2),
1611 			    pap->pa_nest + depth + extra + 1);
1612 
1613 			holeinfo_t *nhi = mdb_zalloc(
1614 			    sizeof (*nhi) * new, UM_NOSLEEP | UM_GC);
1615 
1616 			bcopy(pap->pa_holes, nhi,
1617 			    pap->pa_nholes * sizeof (*nhi));
1618 
1619 			pap->pa_holes = nhi;
1620 			pap->pa_nholes = new;
1621 		}
1622 
1623 		hole = &pap->pa_holes[depth + pap->pa_nest];
1624 
1625 		if (depth != 0 && off > hole->hi_offset)
1626 			print_hole(pap, depth, hole->hi_offset, off);
1627 
1628 		/* compute the next expected offset */
1629 		if (kind == CTF_K_INTEGER &&
1630 		    mdb_ctf_type_encoding(base, &e) == 0)
1631 			newoff = off + e.cte_bits;
1632 		else if ((nsize = mdb_ctf_type_size(base)) >= 0)
1633 			newoff = off + nsize * NBBY;
1634 		else {
1635 			/* something bad happened, disable hole checking */
1636 			newoff = -1UL;		/* ULONG_MAX */
1637 		}
1638 
1639 		hole->hi_offset = newoff;
1640 
1641 		if (IS_COMPOSITE(kind)) {
1642 			hole->hi_isunion = (kind == CTF_K_UNION);
1643 			hole++;
1644 			hole->hi_offset = off;
1645 		}
1646 	}
1647 
1648 	if (pap->pa_flags & (PA_SHOWTYPE | PA_SHOWNAME | PA_SHOWADDR))
1649 		mdb_printf("%*s", (depth + pap->pa_nest) * pap->pa_tab, "");
1650 
1651 	if (pap->pa_flags & PA_SHOWADDR) {
1652 		if (off % NBBY == 0)
1653 			mdb_printf("%llx ", pap->pa_addr + off / NBBY);
1654 		else
1655 			mdb_printf("%llx.%lx ",
1656 			    pap->pa_addr + off / NBBY, off % NBBY);
1657 	}
1658 
1659 	if ((pap->pa_flags & PA_SHOWTYPE)) {
1660 		mdb_printf("%s", type);
1661 		/*
1662 		 * We want to avoid printing a trailing space when
1663 		 * dealing with pointers in a structure, so we end
1664 		 * up with:
1665 		 *
1666 		 *	label_t *t_onfault = 0
1667 		 *
1668 		 * If depth is zero, always print the trailing space unless
1669 		 * we also have a prefix.
1670 		 */
1671 		if (type[strlen(type) - 1] != '*' ||
1672 		    (depth == 0 && (!(pap->pa_flags & PA_SHOWNAME) ||
1673 		    pap->pa_prefix == NULL)))
1674 			mdb_printf(" ");
1675 	}
1676 
1677 	if (pap->pa_flags & PA_SHOWNAME) {
1678 		if (pap->pa_prefix != NULL && depth <= 1)
1679 			mdb_printf("%s%s", pap->pa_prefix,
1680 			    (depth == 0) ? "" : pap->pa_suffix);
1681 		mdb_printf("%s", name);
1682 	}
1683 
1684 	if ((pap->pa_flags & PA_SHOWTYPE) && kind == CTF_K_INTEGER) {
1685 		ctf_encoding_t e;
1686 
1687 		if (mdb_ctf_type_encoding(base, &e) == 0) {
1688 			ulong_t bits = e.cte_bits;
1689 			ulong_t size = bits / NBBY;
1690 
1691 			if (bits % NBBY != 0 ||
1692 			    off % NBBY != 0 ||
1693 			    size > 8 ||
1694 			    size != mdb_ctf_type_size(base))
1695 				mdb_printf(" :%d", bits);
1696 		}
1697 	}
1698 
1699 	if (depth != 0 ||
1700 	    ((pap->pa_flags & PA_SHOWNAME) && pap->pa_prefix != NULL))
1701 		mdb_printf("%s ", pap->pa_flags & PA_SHOWVAL ? " =" : "");
1702 
1703 	if (depth == 0 && pap->pa_prefix != NULL)
1704 		name = pap->pa_prefix;
1705 
1706 	pap->pa_depth = depth;
1707 	if (kind <= CTF_K_UNKNOWN || kind >= CTF_K_TYPEDEF) {
1708 		mdb_warn("unknown ctf for %s type %s kind %d\n",
1709 		    name, type, kind);
1710 		return (-1);
1711 	}
1712 	rc = printfuncs[kind - 1](type, name, id, base, off, pap);
1713 
1714 	if (rc != 0)
1715 		mdb_iob_discard(mdb.m_out);
1716 	else
1717 		mdb_iob_puts(mdb.m_out, pap->pa_delim);
1718 
1719 	return (rc);
1720 }
1721 
1722 /*
1723  * Special semantics for pipelines.
1724  */
1725 static int
1726 pipe_print(mdb_ctf_id_t id, ulong_t off, void *data)
1727 {
1728 	printarg_t *pap = data;
1729 	ssize_t size;
1730 	static const char *const fsp[] = { "%#r", "%#r", "%#r", "%#llr" };
1731 	uintptr_t value;
1732 	uintptr_t addr = pap->pa_addr + off / NBBY;
1733 	mdb_ctf_id_t base;
1734 	ctf_encoding_t e;
1735 
1736 	union {
1737 		uint64_t i8;
1738 		uint32_t i4;
1739 		uint16_t i2;
1740 		uint8_t i1;
1741 	} u;
1742 
1743 	if (mdb_ctf_type_resolve(id, &base) == -1) {
1744 		mdb_warn("could not resolve type");
1745 		return (-1);
1746 	}
1747 
1748 	/*
1749 	 * If the user gives -a, then always print out the address of the
1750 	 * member.
1751 	 */
1752 	if ((pap->pa_flags & PA_SHOWADDR)) {
1753 		mdb_printf("%#lr\n", addr);
1754 		return (0);
1755 	}
1756 
1757 again:
1758 	switch (mdb_ctf_type_kind(base)) {
1759 	case CTF_K_POINTER:
1760 		if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as,
1761 		    &value, sizeof (value), addr) != sizeof (value)) {
1762 			mdb_warn("failed to read pointer at %p", addr);
1763 			return (-1);
1764 		}
1765 		mdb_printf("%#lr\n", value);
1766 		break;
1767 
1768 	case CTF_K_INTEGER:
1769 	case CTF_K_ENUM:
1770 		if (mdb_ctf_type_encoding(base, &e) != 0) {
1771 			mdb_printf("could not get type encoding\n");
1772 			return (-1);
1773 		}
1774 
1775 		/*
1776 		 * For immediate values, we just print out the value.
1777 		 */
1778 		size = e.cte_bits / NBBY;
1779 		if (size > 8 || (e.cte_bits % NBBY) != 0 ||
1780 		    (size & (size - 1)) != 0) {
1781 			return (print_bitfield(off, pap, &e));
1782 		}
1783 
1784 		if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.i8, size,
1785 		    addr) != size) {
1786 			mdb_warn("failed to read %lu bytes at %p",
1787 			    (ulong_t)size, pap->pa_addr);
1788 			return (-1);
1789 		}
1790 
1791 		switch (size) {
1792 		case sizeof (uint8_t):
1793 			mdb_printf(fsp[0], u.i1);
1794 			break;
1795 		case sizeof (uint16_t):
1796 			mdb_printf(fsp[1], u.i2);
1797 			break;
1798 		case sizeof (uint32_t):
1799 			mdb_printf(fsp[2], u.i4);
1800 			break;
1801 		case sizeof (uint64_t):
1802 			mdb_printf(fsp[3], u.i8);
1803 			break;
1804 		}
1805 		mdb_printf("\n");
1806 		break;
1807 
1808 	case CTF_K_FUNCTION:
1809 	case CTF_K_FLOAT:
1810 	case CTF_K_ARRAY:
1811 	case CTF_K_UNKNOWN:
1812 	case CTF_K_STRUCT:
1813 	case CTF_K_UNION:
1814 	case CTF_K_FORWARD:
1815 		/*
1816 		 * For these types, always print the address of the member
1817 		 */
1818 		mdb_printf("%#lr\n", addr);
1819 		break;
1820 
1821 	default:
1822 		mdb_warn("unknown type %d", mdb_ctf_type_kind(base));
1823 		break;
1824 	}
1825 
1826 	return (0);
1827 }
1828 
1829 static int
1830 parse_delimiter(char **strp)
1831 {
1832 	switch (**strp) {
1833 	case '\0':
1834 		return (MEMBER_DELIM_DONE);
1835 
1836 	case '.':
1837 		*strp = *strp + 1;
1838 		return (MEMBER_DELIM_DOT);
1839 
1840 	case '[':
1841 		*strp = *strp + 1;
1842 		return (MEMBER_DELIM_LBR);
1843 
1844 	case '-':
1845 		*strp = *strp + 1;
1846 		if (**strp == '>') {
1847 			*strp = *strp + 1;
1848 			return (MEMBER_DELIM_PTR);
1849 		}
1850 		*strp = *strp - 1;
1851 		/*FALLTHROUGH*/
1852 	default:
1853 		return (MEMBER_DELIM_ERR);
1854 	}
1855 }
1856 
1857 static int
1858 deref(printarg_t *pap, size_t size)
1859 {
1860 	uint32_t a32;
1861 	mdb_tgt_as_t as = pap->pa_as;
1862 	mdb_tgt_addr_t *ap = &pap->pa_addr;
1863 
1864 	if (size == sizeof (mdb_tgt_addr_t)) {
1865 		if (mdb_tgt_aread(mdb.m_target, as, ap, size, *ap) == -1) {
1866 			mdb_warn("could not dereference pointer %llx\n", *ap);
1867 			return (-1);
1868 		}
1869 	} else {
1870 		if (mdb_tgt_aread(mdb.m_target, as, &a32, size, *ap) == -1) {
1871 			mdb_warn("could not dereference pointer %x\n", *ap);
1872 			return (-1);
1873 		}
1874 
1875 		*ap = (mdb_tgt_addr_t)a32;
1876 	}
1877 
1878 	/*
1879 	 * We've dereferenced at least once, we must be on the real
1880 	 * target. If we were in the immediate target, reset to the real
1881 	 * target; it's reset as needed when we return to the print
1882 	 * routines.
1883 	 */
1884 	if (pap->pa_tgt == pap->pa_immtgt)
1885 		pap->pa_tgt = pap->pa_realtgt;
1886 
1887 	return (0);
1888 }
1889 
1890 static int
1891 parse_member(printarg_t *pap, const char *str, mdb_ctf_id_t id,
1892     mdb_ctf_id_t *idp, ulong_t *offp, int *last_deref)
1893 {
1894 	int delim;
1895 	char member[64];
1896 	char buf[128];
1897 	uint_t index;
1898 	char *start = (char *)str;
1899 	char *end;
1900 	ulong_t off = 0;
1901 	mdb_ctf_arinfo_t ar;
1902 	mdb_ctf_id_t rid;
1903 	int kind;
1904 	ssize_t size;
1905 	int non_array = FALSE;
1906 
1907 	/*
1908 	 * id always has the unresolved type for printing error messages
1909 	 * that include the type; rid always has the resolved type for
1910 	 * use in mdb_ctf_* calls.  It is possible for this command to fail,
1911 	 * however, if the resolved type is in the parent and it is currently
1912 	 * unavailable.  Note that we also can't print out the name of the
1913 	 * type, since that would also rely on looking up the resolved name.
1914 	 */
1915 	if (mdb_ctf_type_resolve(id, &rid) != 0) {
1916 		mdb_warn("failed to resolve type");
1917 		return (-1);
1918 	}
1919 
1920 	delim = parse_delimiter(&start);
1921 	/*
1922 	 * If the user fails to specify an initial delimiter, guess -> for
1923 	 * pointer types and . for non-pointer types.
1924 	 */
1925 	if (delim == MEMBER_DELIM_ERR)
1926 		delim = (mdb_ctf_type_kind(rid) == CTF_K_POINTER) ?
1927 		    MEMBER_DELIM_PTR : MEMBER_DELIM_DOT;
1928 
1929 	*last_deref = FALSE;
1930 
1931 	while (delim != MEMBER_DELIM_DONE) {
1932 		switch (delim) {
1933 		case MEMBER_DELIM_PTR:
1934 			kind = mdb_ctf_type_kind(rid);
1935 			if (kind != CTF_K_POINTER) {
1936 				mdb_warn("%s is not a pointer type\n",
1937 				    mdb_ctf_type_name(id, buf, sizeof (buf)));
1938 				return (-1);
1939 			}
1940 
1941 			size = mdb_ctf_type_size(id);
1942 			if (deref(pap, size) != 0)
1943 				return (-1);
1944 
1945 			(void) mdb_ctf_type_reference(rid, &id);
1946 			(void) mdb_ctf_type_resolve(id, &rid);
1947 
1948 			off = 0;
1949 			break;
1950 
1951 		case MEMBER_DELIM_DOT:
1952 			kind = mdb_ctf_type_kind(rid);
1953 			if (kind != CTF_K_STRUCT && kind != CTF_K_UNION) {
1954 				mdb_warn("%s is not a struct or union type\n",
1955 				    mdb_ctf_type_name(id, buf, sizeof (buf)));
1956 				return (-1);
1957 			}
1958 			break;
1959 
1960 		case MEMBER_DELIM_LBR:
1961 			end = strchr(start, ']');
1962 			if (end == NULL) {
1963 				mdb_warn("no trailing ']'\n");
1964 				return (-1);
1965 			}
1966 
1967 			(void) mdb_snprintf(member, end - start + 1, "%s",
1968 			    start);
1969 
1970 			index = mdb_strtoull(member);
1971 
1972 			switch (mdb_ctf_type_kind(rid)) {
1973 			case CTF_K_POINTER:
1974 				size = mdb_ctf_type_size(rid);
1975 
1976 				if (deref(pap, size) != 0)
1977 					return (-1);
1978 
1979 				(void) mdb_ctf_type_reference(rid, &id);
1980 				(void) mdb_ctf_type_resolve(id, &rid);
1981 
1982 				size = mdb_ctf_type_size(id);
1983 				if (size <= 0) {
1984 					mdb_warn("cannot dereference void "
1985 					    "type\n");
1986 					return (-1);
1987 				}
1988 
1989 				pap->pa_addr += index * size;
1990 				off = 0;
1991 
1992 				if (index == 0 && non_array)
1993 					*last_deref = TRUE;
1994 				break;
1995 
1996 			case CTF_K_ARRAY:
1997 				(void) mdb_ctf_array_info(rid, &ar);
1998 
1999 				if (index >= ar.mta_nelems) {
2000 					mdb_warn("index %r is outside of "
2001 					    "array bounds [0 .. %r]\n",
2002 					    index, ar.mta_nelems - 1);
2003 				}
2004 
2005 				id = ar.mta_contents;
2006 				(void) mdb_ctf_type_resolve(id, &rid);
2007 
2008 				size = mdb_ctf_type_size(id);
2009 				if (size <= 0) {
2010 					mdb_warn("cannot dereference void "
2011 					    "type\n");
2012 					return (-1);
2013 				}
2014 
2015 				pap->pa_addr += index * size;
2016 				off = 0;
2017 				break;
2018 
2019 			default:
2020 				mdb_warn("cannot index into non-array, "
2021 				    "non-pointer type\n");
2022 				return (-1);
2023 			}
2024 
2025 			start = end + 1;
2026 			delim = parse_delimiter(&start);
2027 			continue;
2028 
2029 		case MEMBER_DELIM_ERR:
2030 		default:
2031 			mdb_warn("'%c' is not a valid delimiter\n", *start);
2032 			return (-1);
2033 		}
2034 
2035 		*last_deref = FALSE;
2036 		non_array = TRUE;
2037 
2038 		/*
2039 		 * Find the end of the member name; assume that a member
2040 		 * name is at least one character long.
2041 		 */
2042 		for (end = start + 1; isalnum(*end) || *end == '_'; end++)
2043 			continue;
2044 
2045 		(void) mdb_snprintf(member, end - start + 1, "%s", start);
2046 
2047 		if (mdb_ctf_member_info(rid, member, &off, &id) != 0) {
2048 			mdb_warn("failed to find member %s of %s", member,
2049 			    mdb_ctf_type_name(id, buf, sizeof (buf)));
2050 			return (-1);
2051 		}
2052 		(void) mdb_ctf_type_resolve(id, &rid);
2053 
2054 		pap->pa_addr += off / NBBY;
2055 
2056 		start = end;
2057 		delim = parse_delimiter(&start);
2058 	}
2059 
2060 	*idp = id;
2061 	*offp = off;
2062 
2063 	return (0);
2064 }
2065 
2066 static int
2067 cmd_print_tab_common(mdb_tab_cookie_t *mcp, uint_t flags, int argc,
2068     const mdb_arg_t *argv)
2069 {
2070 	char tn[MDB_SYM_NAMLEN];
2071 	char member[64];
2072 	int delim, kind;
2073 	int ret = 0;
2074 	mdb_ctf_id_t id, rid;
2075 	mdb_ctf_arinfo_t ar;
2076 	char *start, *end;
2077 	ulong_t dul;
2078 
2079 	if (argc == 0 && !(flags & DCMD_TAB_SPACE))
2080 		return (0);
2081 
2082 	if (argc == 0 && (flags & DCMD_TAB_SPACE))
2083 		return (mdb_tab_complete_type(mcp, NULL, MDB_TABC_NOPOINT |
2084 		    MDB_TABC_NOARRAY));
2085 
2086 	if ((ret = mdb_tab_typename(&argc, &argv, tn, sizeof (tn))) < 0)
2087 		return (ret);
2088 
2089 	if (argc == 1 && (!(flags & DCMD_TAB_SPACE) || ret == 1))
2090 		return (mdb_tab_complete_type(mcp, tn, MDB_TABC_NOPOINT |
2091 		    MDB_TABC_NOARRAY));
2092 
2093 	if (argc == 1 && (flags & DCMD_TAB_SPACE))
2094 		return (mdb_tab_complete_member(mcp, tn, NULL));
2095 
2096 	/*
2097 	 * This is the reason that tab completion was created. We're going to go
2098 	 * along and walk the delimiters until we find something a member that
2099 	 * we don't recognize, at which point we'll try and tab complete it.
2100 	 * Note that ::print takes multiple args, so this is going to operate on
2101 	 * whatever the last arg that we have is.
2102 	 */
2103 	if (mdb_ctf_lookup_by_name(tn, &id) != 0)
2104 		return (1);
2105 
2106 	(void) mdb_ctf_type_resolve(id, &rid);
2107 	start = (char *)argv[argc-1].a_un.a_str;
2108 	delim = parse_delimiter(&start);
2109 
2110 	/*
2111 	 * If we hit the case where we actually have no delimiters, than we need
2112 	 * to make sure that we properly set up the fields the loops would.
2113 	 */
2114 	if (delim == MEMBER_DELIM_DONE)
2115 		(void) mdb_snprintf(member, sizeof (member), "%s", start);
2116 
2117 	while (delim != MEMBER_DELIM_DONE) {
2118 		switch (delim) {
2119 		case MEMBER_DELIM_PTR:
2120 			kind = mdb_ctf_type_kind(rid);
2121 			if (kind != CTF_K_POINTER)
2122 				return (1);
2123 
2124 			(void) mdb_ctf_type_reference(rid, &id);
2125 			(void) mdb_ctf_type_resolve(id, &rid);
2126 			break;
2127 		case MEMBER_DELIM_DOT:
2128 			kind = mdb_ctf_type_kind(rid);
2129 			if (kind != CTF_K_STRUCT && kind != CTF_K_UNION)
2130 				return (1);
2131 			break;
2132 		case MEMBER_DELIM_LBR:
2133 			end = strchr(start, ']');
2134 			/*
2135 			 * We're not going to try and tab complete the indexes
2136 			 * here. So for now, punt on it. Also, we're not going
2137 			 * to try and validate you're within the bounds, just
2138 			 * that you get the type you asked for.
2139 			 */
2140 			if (end == NULL)
2141 				return (1);
2142 
2143 			switch (mdb_ctf_type_kind(rid)) {
2144 			case CTF_K_POINTER:
2145 				(void) mdb_ctf_type_reference(rid, &id);
2146 				(void) mdb_ctf_type_resolve(id, &rid);
2147 				break;
2148 			case CTF_K_ARRAY:
2149 				(void) mdb_ctf_array_info(rid, &ar);
2150 				id = ar.mta_contents;
2151 				(void) mdb_ctf_type_resolve(id, &rid);
2152 				break;
2153 			default:
2154 				return (1);
2155 			}
2156 
2157 			start = end + 1;
2158 			delim = parse_delimiter(&start);
2159 			break;
2160 		case MEMBER_DELIM_ERR:
2161 		default:
2162 			break;
2163 		}
2164 
2165 		for (end = start + 1; isalnum(*end) || *end == '_'; end++)
2166 			continue;
2167 
2168 		(void) mdb_snprintf(member, end - start + 1, start);
2169 
2170 		/*
2171 		 * We are going to try to resolve this name as a member. There
2172 		 * are a few two different questions that we need to answer. The
2173 		 * first is do we recognize this member. The second is are we at
2174 		 * the end of the string. If we encounter a member that we don't
2175 		 * recognize before the end, then we have to error out and can't
2176 		 * complete it. But if there are no more delimiters then we can
2177 		 * try and complete it.
2178 		 */
2179 		ret = mdb_ctf_member_info(rid, member, &dul, &id);
2180 		start = end;
2181 		delim = parse_delimiter(&start);
2182 		if (ret != 0 && errno == EMDB_CTFNOMEMB) {
2183 			if (delim != MEMBER_DELIM_DONE)
2184 				return (1);
2185 			continue;
2186 		} else if (ret != 0)
2187 			return (1);
2188 
2189 		if (delim == MEMBER_DELIM_DONE)
2190 			return (mdb_tab_complete_member_by_id(mcp, rid,
2191 			    member));
2192 
2193 		(void) mdb_ctf_type_resolve(id, &rid);
2194 	}
2195 
2196 	/*
2197 	 * If we've reached here, then we need to try and tab complete the last
2198 	 * field, which is currently member, based on the ctf type id that we
2199 	 * already have in rid.
2200 	 */
2201 	return (mdb_tab_complete_member_by_id(mcp, rid, member));
2202 }
2203 
2204 int
2205 cmd_print_tab(mdb_tab_cookie_t *mcp, uint_t flags, int argc,
2206     const mdb_arg_t *argv)
2207 {
2208 	int i, dummy;
2209 
2210 	/*
2211 	 * This getopts is only here to make the tab completion work better when
2212 	 * including options in the ::print arguments. None of the values should
2213 	 * be used. This should only be updated with additional arguments, if
2214 	 * they are added to cmd_print.
2215 	 */
2216 	i = mdb_getopts(argc, argv,
2217 	    'a', MDB_OPT_SETBITS, PA_SHOWADDR, &dummy,
2218 	    'C', MDB_OPT_SETBITS, TRUE, &dummy,
2219 	    'c', MDB_OPT_UINTPTR, &dummy,
2220 	    'd', MDB_OPT_SETBITS, PA_INTDEC, &dummy,
2221 	    'h', MDB_OPT_SETBITS, PA_SHOWHOLES, &dummy,
2222 	    'i', MDB_OPT_SETBITS, TRUE, &dummy,
2223 	    'L', MDB_OPT_SETBITS, TRUE, &dummy,
2224 	    'l', MDB_OPT_UINTPTR, &dummy,
2225 	    'n', MDB_OPT_SETBITS, PA_NOSYMBOLIC, &dummy,
2226 	    'p', MDB_OPT_SETBITS, TRUE, &dummy,
2227 	    's', MDB_OPT_UINTPTR, &dummy,
2228 	    'T', MDB_OPT_SETBITS, PA_SHOWTYPE | PA_SHOWBASETYPE, &dummy,
2229 	    't', MDB_OPT_SETBITS, PA_SHOWTYPE, &dummy,
2230 	    'x', MDB_OPT_SETBITS, PA_INTHEX, &dummy,
2231 	    NULL);
2232 
2233 	argc -= i;
2234 	argv += i;
2235 
2236 	return (cmd_print_tab_common(mcp, flags, argc, argv));
2237 }
2238 
2239 /*
2240  * Recursively descend a print a given data structure.  We create a struct of
2241  * the relevant print arguments and then call mdb_ctf_type_visit() to do the
2242  * traversal, using elt_print() as the callback for each element.
2243  */
2244 /*ARGSUSED*/
2245 int
2246 cmd_print(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2247 {
2248 	uintptr_t opt_c = MDB_ARR_NOLIMIT, opt_l = MDB_ARR_NOLIMIT;
2249 	uint_t opt_C = FALSE, opt_L = FALSE, opt_p = FALSE, opt_i = FALSE;
2250 	uintptr_t opt_s = (uintptr_t)-1ul;
2251 	int uflags = (flags & DCMD_ADDRSPEC) ? PA_SHOWVAL : 0;
2252 	mdb_ctf_id_t id;
2253 	int err = DCMD_OK;
2254 
2255 	mdb_tgt_t *t = mdb.m_target;
2256 	printarg_t pa;
2257 	int d, i;
2258 
2259 	char s_name[MDB_SYM_NAMLEN];
2260 	mdb_syminfo_t s_info;
2261 	GElf_Sym sym;
2262 
2263 	/*
2264 	 * If a new option is added, make sure the getopts above in
2265 	 * cmd_print_tab is also updated.
2266 	 */
2267 	i = mdb_getopts(argc, argv,
2268 	    'a', MDB_OPT_SETBITS, PA_SHOWADDR, &uflags,
2269 	    'C', MDB_OPT_SETBITS, TRUE, &opt_C,
2270 	    'c', MDB_OPT_UINTPTR, &opt_c,
2271 	    'd', MDB_OPT_SETBITS, PA_INTDEC, &uflags,
2272 	    'h', MDB_OPT_SETBITS, PA_SHOWHOLES, &uflags,
2273 	    'i', MDB_OPT_SETBITS, TRUE, &opt_i,
2274 	    'L', MDB_OPT_SETBITS, TRUE, &opt_L,
2275 	    'l', MDB_OPT_UINTPTR, &opt_l,
2276 	    'n', MDB_OPT_SETBITS, PA_NOSYMBOLIC, &uflags,
2277 	    'p', MDB_OPT_SETBITS, TRUE, &opt_p,
2278 	    's', MDB_OPT_UINTPTR, &opt_s,
2279 	    'T', MDB_OPT_SETBITS, PA_SHOWTYPE | PA_SHOWBASETYPE, &uflags,
2280 	    't', MDB_OPT_SETBITS, PA_SHOWTYPE, &uflags,
2281 	    'x', MDB_OPT_SETBITS, PA_INTHEX, &uflags,
2282 	    NULL);
2283 
2284 	if (uflags & PA_INTHEX)
2285 		uflags &= ~PA_INTDEC;	/* -x and -d are mutually exclusive */
2286 
2287 	uflags |= PA_SHOWNAME;
2288 
2289 	if (opt_p && opt_i) {
2290 		mdb_warn("-p and -i options are incompatible\n");
2291 		return (DCMD_ERR);
2292 	}
2293 
2294 	argc -= i;
2295 	argv += i;
2296 
2297 	if (argc != 0 && argv->a_type == MDB_TYPE_STRING) {
2298 		const char *t_name = s_name;
2299 		int ret;
2300 
2301 		if (strchr("+-", argv->a_un.a_str[0]) != NULL)
2302 			return (DCMD_USAGE);
2303 
2304 		if ((ret = args_to_typename(&argc, &argv, s_name,
2305 		    sizeof (s_name))) != 0)
2306 			return (ret);
2307 
2308 		if (mdb_ctf_lookup_by_name(t_name, &id) != 0) {
2309 			if (!(flags & DCMD_ADDRSPEC) || opt_i ||
2310 			    addr_to_sym(t, addr, s_name, sizeof (s_name),
2311 			    &sym, &s_info) == NULL ||
2312 			    mdb_ctf_lookup_by_symbol(&sym, &s_info, &id) != 0) {
2313 
2314 				mdb_warn("failed to look up type %s", t_name);
2315 				return (DCMD_ABORT);
2316 			}
2317 		} else {
2318 			argc--;
2319 			argv++;
2320 		}
2321 
2322 	} else if (!(flags & DCMD_ADDRSPEC) || opt_i) {
2323 		return (DCMD_USAGE);
2324 
2325 	} else if (addr_to_sym(t, addr, s_name, sizeof (s_name),
2326 	    &sym, &s_info) == NULL) {
2327 		mdb_warn("no symbol information for %a", addr);
2328 		return (DCMD_ERR);
2329 
2330 	} else if (mdb_ctf_lookup_by_symbol(&sym, &s_info, &id) != 0) {
2331 		mdb_warn("no type data available for %a [%u]", addr,
2332 		    s_info.sym_id);
2333 		return (DCMD_ERR);
2334 	}
2335 
2336 	pa.pa_tgt = mdb.m_target;
2337 	pa.pa_realtgt = pa.pa_tgt;
2338 	pa.pa_immtgt = NULL;
2339 	pa.pa_as = opt_p ? MDB_TGT_AS_PHYS : MDB_TGT_AS_VIRT;
2340 	pa.pa_armemlim = mdb.m_armemlim;
2341 	pa.pa_arstrlim = mdb.m_arstrlim;
2342 	pa.pa_delim = "\n";
2343 	pa.pa_flags = uflags;
2344 	pa.pa_nest = 0;
2345 	pa.pa_tab = 4;
2346 	pa.pa_prefix = NULL;
2347 	pa.pa_suffix = NULL;
2348 	pa.pa_holes = NULL;
2349 	pa.pa_nholes = 0;
2350 	pa.pa_depth = 0;
2351 	pa.pa_maxdepth = opt_s;
2352 	pa.pa_nooutdepth = (uint_t)-1;
2353 
2354 	if ((flags & DCMD_ADDRSPEC) && !opt_i)
2355 		pa.pa_addr = opt_p ? mdb_get_dot() : addr;
2356 	else
2357 		pa.pa_addr = NULL;
2358 
2359 	if (opt_i) {
2360 		const char *vargv[2];
2361 		uintmax_t dot = mdb_get_dot();
2362 		size_t outsize = mdb_ctf_type_size(id);
2363 		vargv[0] = (const char *)&dot;
2364 		vargv[1] = (const char *)&outsize;
2365 		pa.pa_immtgt = mdb_tgt_create(mdb_value_tgt_create,
2366 		    0, 2, vargv);
2367 		pa.pa_tgt = pa.pa_immtgt;
2368 	}
2369 
2370 	if (opt_c != MDB_ARR_NOLIMIT)
2371 		pa.pa_arstrlim = opt_c;
2372 	if (opt_C)
2373 		pa.pa_arstrlim = MDB_ARR_NOLIMIT;
2374 	if (opt_l != MDB_ARR_NOLIMIT)
2375 		pa.pa_armemlim = opt_l;
2376 	if (opt_L)
2377 		pa.pa_armemlim = MDB_ARR_NOLIMIT;
2378 
2379 	if (argc > 0) {
2380 		for (i = 0; i < argc; i++) {
2381 			mdb_ctf_id_t mid;
2382 			int last_deref;
2383 			ulong_t off;
2384 			int kind;
2385 			char buf[MDB_SYM_NAMLEN];
2386 
2387 			mdb_tgt_t *oldtgt = pa.pa_tgt;
2388 			mdb_tgt_as_t oldas = pa.pa_as;
2389 			mdb_tgt_addr_t oldaddr = pa.pa_addr;
2390 
2391 			if (argv->a_type == MDB_TYPE_STRING) {
2392 				const char *member = argv[i].a_un.a_str;
2393 				mdb_ctf_id_t rid;
2394 
2395 				if (parse_member(&pa, member, id, &mid,
2396 				    &off, &last_deref) != 0) {
2397 					err = DCMD_ABORT;
2398 					goto out;
2399 				}
2400 
2401 				/*
2402 				 * If the member string ends with a "[0]"
2403 				 * (last_deref * is true) and the type is a
2404 				 * structure or union, * print "->" rather
2405 				 * than "[0]." in elt_print.
2406 				 */
2407 				(void) mdb_ctf_type_resolve(mid, &rid);
2408 				kind = mdb_ctf_type_kind(rid);
2409 				if (last_deref && IS_SOU(kind)) {
2410 					char *end;
2411 					(void) mdb_snprintf(buf, sizeof (buf),
2412 					    "%s", member);
2413 					end = strrchr(buf, '[');
2414 					*end = '\0';
2415 					pa.pa_suffix = "->";
2416 					member = &buf[0];
2417 				} else if (IS_SOU(kind)) {
2418 					pa.pa_suffix = ".";
2419 				} else {
2420 					pa.pa_suffix = "";
2421 				}
2422 
2423 				pa.pa_prefix = member;
2424 			} else {
2425 				ulong_t moff;
2426 
2427 				moff = (ulong_t)argv[i].a_un.a_val;
2428 
2429 				if (mdb_ctf_offset_to_name(id, moff * NBBY,
2430 				    buf, sizeof (buf), 0, &mid, &off) == -1) {
2431 					mdb_warn("invalid offset %lx\n", moff);
2432 					err = DCMD_ABORT;
2433 					goto out;
2434 				}
2435 
2436 				pa.pa_prefix = buf;
2437 				pa.pa_addr += moff - off / NBBY;
2438 				pa.pa_suffix = strlen(buf) == 0 ? "" : ".";
2439 			}
2440 
2441 			off %= NBBY;
2442 			if (flags & DCMD_PIPE_OUT) {
2443 				if (pipe_print(mid, off, &pa) != 0) {
2444 					mdb_warn("failed to print type");
2445 					err = DCMD_ERR;
2446 					goto out;
2447 				}
2448 			} else if (off != 0) {
2449 				mdb_ctf_id_t base;
2450 				(void) mdb_ctf_type_resolve(mid, &base);
2451 
2452 				if (elt_print("", mid, base, off, 0,
2453 				    &pa) != 0) {
2454 					mdb_warn("failed to print type");
2455 					err = DCMD_ERR;
2456 					goto out;
2457 				}
2458 			} else {
2459 				if (mdb_ctf_type_visit(mid, elt_print,
2460 				    &pa) == -1) {
2461 					mdb_warn("failed to print type");
2462 					err = DCMD_ERR;
2463 					goto out;
2464 				}
2465 
2466 				for (d = pa.pa_depth - 1; d >= 0; d--)
2467 					print_close_sou(&pa, d);
2468 			}
2469 
2470 			pa.pa_depth = 0;
2471 			pa.pa_tgt = oldtgt;
2472 			pa.pa_as = oldas;
2473 			pa.pa_addr = oldaddr;
2474 			pa.pa_delim = "\n";
2475 		}
2476 
2477 	} else if (flags & DCMD_PIPE_OUT) {
2478 		if (pipe_print(id, 0, &pa) != 0) {
2479 			mdb_warn("failed to print type");
2480 			err = DCMD_ERR;
2481 			goto out;
2482 		}
2483 	} else {
2484 		if (mdb_ctf_type_visit(id, elt_print, &pa) == -1) {
2485 			mdb_warn("failed to print type");
2486 			err = DCMD_ERR;
2487 			goto out;
2488 		}
2489 
2490 		for (d = pa.pa_depth - 1; d >= 0; d--)
2491 			print_close_sou(&pa, d);
2492 	}
2493 
2494 	mdb_set_dot(addr + mdb_ctf_type_size(id));
2495 	err = DCMD_OK;
2496 out:
2497 	if (pa.pa_immtgt)
2498 		mdb_tgt_destroy(pa.pa_immtgt);
2499 	return (err);
2500 }
2501 
2502 void
2503 print_help(void)
2504 {
2505 	mdb_printf(
2506 	    "-a         show address of object\n"
2507 	    "-C         unlimit the length of character arrays\n"
2508 	    "-c limit   limit the length of character arrays\n"
2509 	    "-d         output values in decimal\n"
2510 	    "-h         print holes in structures\n"
2511 	    "-i         interpret address as data of the given type\n"
2512 	    "-L         unlimit the length of standard arrays\n"
2513 	    "-l limit   limit the length of standard arrays\n"
2514 	    "-n         don't print pointers as symbol offsets\n"
2515 	    "-p         interpret address as a physical memory address\n"
2516 	    "-s depth   limit the recursion depth\n"
2517 	    "-T         show type and <<base type>> of object\n"
2518 	    "-t         show type of object\n"
2519 	    "-x         output values in hexadecimal\n"
2520 	    "\n"
2521 	    "type may be omitted if the C type of addr can be inferred.\n"
2522 	    "\n"
2523 	    "Members may be specified with standard C syntax using the\n"
2524 	    "array indexing operator \"[index]\", structure member\n"
2525 	    "operator \".\", or structure pointer operator \"->\".\n"
2526 	    "\n"
2527 	    "Offsets must use the $[ expression ] syntax\n");
2528 }
2529 
2530 static int
2531 printf_signed(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt,
2532     boolean_t sign)
2533 {
2534 	ssize_t size;
2535 	mdb_ctf_id_t base;
2536 	ctf_encoding_t e;
2537 
2538 	union {
2539 		uint64_t ui8;
2540 		uint32_t ui4;
2541 		uint16_t ui2;
2542 		uint8_t ui1;
2543 		int64_t i8;
2544 		int32_t i4;
2545 		int16_t i2;
2546 		int8_t i1;
2547 	} u;
2548 
2549 	if (mdb_ctf_type_resolve(id, &base) == -1) {
2550 		mdb_warn("could not resolve type");
2551 		return (DCMD_ABORT);
2552 	}
2553 
2554 	if (mdb_ctf_type_kind(base) != CTF_K_INTEGER) {
2555 		mdb_warn("expected integer type\n");
2556 		return (DCMD_ABORT);
2557 	}
2558 
2559 	if (mdb_ctf_type_encoding(base, &e) != 0) {
2560 		mdb_warn("could not get type encoding");
2561 		return (DCMD_ABORT);
2562 	}
2563 
2564 	if (sign)
2565 		sign = e.cte_format & CTF_INT_SIGNED;
2566 
2567 	size = e.cte_bits / NBBY;
2568 
2569 	/*
2570 	 * Check to see if our life has been complicated by the presence of
2571 	 * a bitfield.  If it has, we will print it using logic that is only
2572 	 * slightly different than that found in print_bitfield(), above.  (In
2573 	 * particular, see the comments there for an explanation of the
2574 	 * endianness differences in this code.)
2575 	 */
2576 	if (size > 8 || (e.cte_bits % NBBY) != 0 ||
2577 	    (size & (size - 1)) != 0) {
2578 		uint64_t mask = (1ULL << e.cte_bits) - 1;
2579 		uint64_t value = 0;
2580 		uint8_t *buf = (uint8_t *)&value;
2581 		uint8_t shift;
2582 
2583 		/*
2584 		 * Round our size up one byte.
2585 		 */
2586 		size = (e.cte_bits + (NBBY - 1)) / NBBY;
2587 
2588 		if (e.cte_bits > sizeof (value) * NBBY - 1) {
2589 			mdb_printf("invalid bitfield size %u", e.cte_bits);
2590 			return (DCMD_ABORT);
2591 		}
2592 
2593 #ifdef _BIG_ENDIAN
2594 		buf += sizeof (value) - size;
2595 		off += e.cte_bits;
2596 #endif
2597 
2598 		if (mdb_vread(buf, size, addr) == -1) {
2599 			mdb_warn("failed to read %lu bytes at %p", size, addr);
2600 			return (DCMD_ERR);
2601 		}
2602 
2603 		shift = off % NBBY;
2604 #ifdef _BIG_ENDIAN
2605 		shift = NBBY - shift;
2606 #endif
2607 
2608 		/*
2609 		 * If we have a bit offset within the byte, shift it down.
2610 		 */
2611 		if (off % NBBY != 0)
2612 			value >>= shift;
2613 		value &= mask;
2614 
2615 		if (sign) {
2616 			int sshift = sizeof (value) * NBBY - e.cte_bits;
2617 			value = ((int64_t)value << sshift) >> sshift;
2618 		}
2619 
2620 		mdb_printf(fmt, value);
2621 		return (0);
2622 	}
2623 
2624 	if (mdb_vread(&u.i8, size, addr) == -1) {
2625 		mdb_warn("failed to read %lu bytes at %p", (ulong_t)size, addr);
2626 		return (DCMD_ERR);
2627 	}
2628 
2629 	switch (size) {
2630 	case sizeof (uint8_t):
2631 		mdb_printf(fmt, (uint64_t)(sign ? u.i1 : u.ui1));
2632 		break;
2633 	case sizeof (uint16_t):
2634 		mdb_printf(fmt, (uint64_t)(sign ? u.i2 : u.ui2));
2635 		break;
2636 	case sizeof (uint32_t):
2637 		mdb_printf(fmt, (uint64_t)(sign ? u.i4 : u.ui4));
2638 		break;
2639 	case sizeof (uint64_t):
2640 		mdb_printf(fmt, (uint64_t)(sign ? u.i8 : u.ui8));
2641 		break;
2642 	}
2643 
2644 	return (0);
2645 }
2646 
2647 static int
2648 printf_int(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2649 {
2650 	return (printf_signed(id, addr, off, fmt, B_TRUE));
2651 }
2652 
2653 static int
2654 printf_uint(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2655 {
2656 	return (printf_signed(id, addr, off, fmt, B_FALSE));
2657 }
2658 
2659 /*ARGSUSED*/
2660 static int
2661 printf_uint32(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2662 {
2663 	mdb_ctf_id_t base;
2664 	ctf_encoding_t e;
2665 	uint32_t value;
2666 
2667 	if (mdb_ctf_type_resolve(id, &base) == -1) {
2668 		mdb_warn("could not resolve type\n");
2669 		return (DCMD_ABORT);
2670 	}
2671 
2672 	if (mdb_ctf_type_kind(base) != CTF_K_INTEGER ||
2673 	    mdb_ctf_type_encoding(base, &e) != 0 ||
2674 	    e.cte_bits / NBBY != sizeof (value)) {
2675 		mdb_warn("expected 32-bit integer type\n");
2676 		return (DCMD_ABORT);
2677 	}
2678 
2679 	if (mdb_vread(&value, sizeof (value), addr) == -1) {
2680 		mdb_warn("failed to read 32-bit value at %p", addr);
2681 		return (DCMD_ERR);
2682 	}
2683 
2684 	mdb_printf(fmt, value);
2685 
2686 	return (0);
2687 }
2688 
2689 /*ARGSUSED*/
2690 static int
2691 printf_ptr(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2692 {
2693 	uintptr_t value;
2694 	mdb_ctf_id_t base;
2695 
2696 	if (mdb_ctf_type_resolve(id, &base) == -1) {
2697 		mdb_warn("could not resolve type\n");
2698 		return (DCMD_ABORT);
2699 	}
2700 
2701 	if (mdb_ctf_type_kind(base) != CTF_K_POINTER) {
2702 		mdb_warn("expected pointer type\n");
2703 		return (DCMD_ABORT);
2704 	}
2705 
2706 	if (mdb_vread(&value, sizeof (value), addr) == -1) {
2707 		mdb_warn("failed to read pointer at %llx", addr);
2708 		return (DCMD_ERR);
2709 	}
2710 
2711 	mdb_printf(fmt, value);
2712 
2713 	return (0);
2714 }
2715 
2716 /*ARGSUSED*/
2717 static int
2718 printf_string(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2719 {
2720 	mdb_ctf_id_t base;
2721 	mdb_ctf_arinfo_t r;
2722 	char buf[1024];
2723 	ssize_t size;
2724 
2725 	if (mdb_ctf_type_resolve(id, &base) == -1) {
2726 		mdb_warn("could not resolve type");
2727 		return (DCMD_ABORT);
2728 	}
2729 
2730 	if (mdb_ctf_type_kind(base) == CTF_K_POINTER) {
2731 		uintptr_t value;
2732 
2733 		if (mdb_vread(&value, sizeof (value), addr) == -1) {
2734 			mdb_warn("failed to read pointer at %llx", addr);
2735 			return (DCMD_ERR);
2736 		}
2737 
2738 		if (mdb_readstr(buf, sizeof (buf) - 1, value) < 0) {
2739 			mdb_warn("failed to read string at %llx", value);
2740 			return (DCMD_ERR);
2741 		}
2742 
2743 		mdb_printf(fmt, buf);
2744 		return (0);
2745 	}
2746 
2747 	if (mdb_ctf_type_kind(base) != CTF_K_ARRAY) {
2748 		mdb_warn("exepected pointer or array type\n");
2749 		return (DCMD_ABORT);
2750 	}
2751 
2752 	if (mdb_ctf_array_info(base, &r) == -1 ||
2753 	    mdb_ctf_type_resolve(r.mta_contents, &base) == -1 ||
2754 	    (size = mdb_ctf_type_size(base)) == -1) {
2755 		mdb_warn("can't determine array type");
2756 		return (DCMD_ABORT);
2757 	}
2758 
2759 	if (size != 1) {
2760 		mdb_warn("string format specifier requires "
2761 		    "an array of characters\n");
2762 		return (DCMD_ABORT);
2763 	}
2764 
2765 	bzero(buf, sizeof (buf));
2766 
2767 	if (mdb_vread(buf, MIN(r.mta_nelems, sizeof (buf) - 1), addr) == -1) {
2768 		mdb_warn("failed to read array at %p", addr);
2769 		return (DCMD_ERR);
2770 	}
2771 
2772 	mdb_printf(fmt, buf);
2773 
2774 	return (0);
2775 }
2776 
2777 /*ARGSUSED*/
2778 static int
2779 printf_ipv6(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2780 {
2781 	mdb_ctf_id_t base;
2782 	mdb_ctf_id_t ipv6_type, ipv6_base;
2783 	in6_addr_t ipv6;
2784 
2785 	if (mdb_ctf_lookup_by_name("in6_addr_t", &ipv6_type) == -1) {
2786 		mdb_warn("could not resolve in6_addr_t type\n");
2787 		return (DCMD_ABORT);
2788 	}
2789 
2790 	if (mdb_ctf_type_resolve(id, &base) == -1) {
2791 		mdb_warn("could not resolve type\n");
2792 		return (DCMD_ABORT);
2793 	}
2794 
2795 	if (mdb_ctf_type_resolve(ipv6_type, &ipv6_base) == -1) {
2796 		mdb_warn("could not resolve in6_addr_t type\n");
2797 		return (DCMD_ABORT);
2798 	}
2799 
2800 	if (mdb_ctf_type_cmp(base, ipv6_base) != 0) {
2801 		mdb_warn("requires argument of type in6_addr_t\n");
2802 		return (DCMD_ABORT);
2803 	}
2804 
2805 	if (mdb_vread(&ipv6, sizeof (ipv6), addr) == -1) {
2806 		mdb_warn("couldn't read in6_addr_t at %p", addr);
2807 		return (DCMD_ERR);
2808 	}
2809 
2810 	mdb_printf(fmt, &ipv6);
2811 
2812 	return (0);
2813 }
2814 
2815 /*
2816  * To validate the format string specified to ::printf, we run the format
2817  * string through a very simple state machine that restricts us to a subset
2818  * of mdb_printf() functionality.
2819  */
2820 enum {
2821 	PRINTF_NOFMT = 1,		/* no current format specifier */
2822 	PRINTF_PERC,			/* processed '%' */
2823 	PRINTF_FMT,			/* processing format specifier */
2824 	PRINTF_LEFT,			/* processed '-', expecting width */
2825 	PRINTF_WIDTH,			/* processing width */
2826 	PRINTF_QUES			/* processed '?', expecting format */
2827 };
2828 
2829 int
2830 cmd_printf_tab(mdb_tab_cookie_t *mcp, uint_t flags, int argc,
2831     const mdb_arg_t *argv)
2832 {
2833 	int ii;
2834 	char *f;
2835 
2836 	/*
2837 	 * If argc doesn't have more than what should be the format string,
2838 	 * ignore it.
2839 	 */
2840 	if (argc <= 1)
2841 		return (0);
2842 
2843 	/*
2844 	 * Because we aren't leveraging the lex and yacc engine, we have to
2845 	 * manually walk the arguments to find both the first and last
2846 	 * open/close quote of the format string.
2847 	 */
2848 	f = strchr(argv[0].a_un.a_str, '"');
2849 	if (f == NULL)
2850 		return (0);
2851 
2852 	f = strchr(f + 1, '"');
2853 	if (f != NULL) {
2854 		ii = 0;
2855 	} else {
2856 		for (ii = 1; ii < argc; ii++) {
2857 			if (argv[ii].a_type != MDB_TYPE_STRING)
2858 				continue;
2859 			f = strchr(argv[ii].a_un.a_str, '"');
2860 			if (f != NULL)
2861 				break;
2862 		}
2863 		/* Never found */
2864 		if (ii == argc)
2865 			return (0);
2866 	}
2867 
2868 	ii++;
2869 	argc -= ii;
2870 	argv += ii;
2871 
2872 	return (cmd_print_tab_common(mcp, flags, argc, argv));
2873 }
2874 
2875 int
2876 cmd_printf(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2877 {
2878 	char type[MDB_SYM_NAMLEN];
2879 	int i, nfmts = 0, ret;
2880 	mdb_ctf_id_t id;
2881 	const char *fmt, *member;
2882 	char **fmts, *last, *dest, f;
2883 	int (**funcs)(mdb_ctf_id_t, uintptr_t, ulong_t, char *);
2884 	int state = PRINTF_NOFMT;
2885 	printarg_t pa;
2886 
2887 	if (!(flags & DCMD_ADDRSPEC))
2888 		return (DCMD_USAGE);
2889 
2890 	bzero(&pa, sizeof (pa));
2891 	pa.pa_as = MDB_TGT_AS_VIRT;
2892 	pa.pa_realtgt = pa.pa_tgt = mdb.m_target;
2893 
2894 	if (argc == 0 || argv[0].a_type != MDB_TYPE_STRING) {
2895 		mdb_warn("expected a format string\n");
2896 		return (DCMD_USAGE);
2897 	}
2898 
2899 	/*
2900 	 * Our first argument is a format string; rip it apart and run it
2901 	 * through our state machine to validate that our input is within the
2902 	 * subset of mdb_printf() format strings that we allow.
2903 	 */
2904 	fmt = argv[0].a_un.a_str;
2905 	/*
2906 	 * 'dest' must be large enough to hold a copy of the format string,
2907 	 * plus a NUL and up to 2 additional characters for each conversion
2908 	 * in the format string.  This gives us a bloat factor of 5/2 ~= 3.
2909 	 *   e.g. "%d" (strlen of 2) --> "%lld\0" (need 5 bytes)
2910 	 */
2911 	dest = mdb_zalloc(strlen(fmt) * 3, UM_SLEEP | UM_GC);
2912 	fmts = mdb_zalloc(strlen(fmt) * sizeof (char *), UM_SLEEP | UM_GC);
2913 	funcs = mdb_zalloc(strlen(fmt) * sizeof (void *), UM_SLEEP | UM_GC);
2914 	last = dest;
2915 
2916 	for (i = 0; fmt[i] != '\0'; i++) {
2917 		*dest++ = f = fmt[i];
2918 
2919 		switch (state) {
2920 		case PRINTF_NOFMT:
2921 			state = f == '%' ? PRINTF_PERC : PRINTF_NOFMT;
2922 			break;
2923 
2924 		case PRINTF_PERC:
2925 			state = f == '-' ? PRINTF_LEFT :
2926 			    f >= '0' && f <= '9' ? PRINTF_WIDTH :
2927 			    f == '?' ? PRINTF_QUES :
2928 			    f == '%' ? PRINTF_NOFMT : PRINTF_FMT;
2929 			break;
2930 
2931 		case PRINTF_LEFT:
2932 			state = f >= '0' && f <= '9' ? PRINTF_WIDTH :
2933 			    f == '?' ? PRINTF_QUES : PRINTF_FMT;
2934 			break;
2935 
2936 		case PRINTF_WIDTH:
2937 			state = f >= '0' && f <= '9' ? PRINTF_WIDTH :
2938 			    PRINTF_FMT;
2939 			break;
2940 
2941 		case PRINTF_QUES:
2942 			state = PRINTF_FMT;
2943 			break;
2944 		}
2945 
2946 		if (state != PRINTF_FMT)
2947 			continue;
2948 
2949 		dest--;
2950 
2951 		/*
2952 		 * Now check that we have one of our valid format characters.
2953 		 */
2954 		switch (f) {
2955 		case 'a':
2956 		case 'A':
2957 		case 'p':
2958 			funcs[nfmts] = printf_ptr;
2959 			break;
2960 
2961 		case 'd':
2962 		case 'q':
2963 		case 'R':
2964 			funcs[nfmts] = printf_int;
2965 			*dest++ = 'l';
2966 			*dest++ = 'l';
2967 			break;
2968 
2969 		case 'I':
2970 			funcs[nfmts] = printf_uint32;
2971 			break;
2972 
2973 		case 'N':
2974 			funcs[nfmts] = printf_ipv6;
2975 			break;
2976 
2977 		case 'H':
2978 		case 'o':
2979 		case 'r':
2980 		case 'u':
2981 		case 'x':
2982 		case 'X':
2983 			funcs[nfmts] = printf_uint;
2984 			*dest++ = 'l';
2985 			*dest++ = 'l';
2986 			break;
2987 
2988 		case 's':
2989 			funcs[nfmts] = printf_string;
2990 			break;
2991 
2992 		case 'Y':
2993 			funcs[nfmts] = sizeof (time_t) == sizeof (int) ?
2994 			    printf_uint32 : printf_uint;
2995 			break;
2996 
2997 		default:
2998 			mdb_warn("illegal format string at or near "
2999 			    "'%c' (position %d)\n", f, i + 1);
3000 			return (DCMD_ABORT);
3001 		}
3002 
3003 		*dest++ = f;
3004 		*dest++ = '\0';
3005 		fmts[nfmts++] = last;
3006 		last = dest;
3007 		state = PRINTF_NOFMT;
3008 	}
3009 
3010 	argc--;
3011 	argv++;
3012 
3013 	/*
3014 	 * Now we expect a type name.
3015 	 */
3016 	if ((ret = args_to_typename(&argc, &argv, type, sizeof (type))) != 0)
3017 		return (ret);
3018 
3019 	argv++;
3020 	argc--;
3021 
3022 	if (mdb_ctf_lookup_by_name(type, &id) != 0) {
3023 		mdb_warn("failed to look up type %s", type);
3024 		return (DCMD_ABORT);
3025 	}
3026 
3027 	if (argc == 0) {
3028 		mdb_warn("at least one member must be specified\n");
3029 		return (DCMD_USAGE);
3030 	}
3031 
3032 	if (argc != nfmts) {
3033 		mdb_warn("%s format specifiers (found %d, expected %d)\n",
3034 		    argc > nfmts ? "missing" : "extra", nfmts, argc);
3035 		return (DCMD_ABORT);
3036 	}
3037 
3038 	for (i = 0; i < argc; i++) {
3039 		mdb_ctf_id_t mid;
3040 		ulong_t off;
3041 		int ignored;
3042 
3043 		if (argv[i].a_type != MDB_TYPE_STRING) {
3044 			mdb_warn("expected only type member arguments\n");
3045 			return (DCMD_ABORT);
3046 		}
3047 
3048 		if (strcmp((member = argv[i].a_un.a_str), ".") == 0) {
3049 			/*
3050 			 * We allow "." to be specified to denote the current
3051 			 * value of dot.
3052 			 */
3053 			if (funcs[i] != printf_ptr && funcs[i] != printf_uint &&
3054 			    funcs[i] != printf_int) {
3055 				mdb_warn("expected integer or pointer format "
3056 				    "specifier for '.'\n");
3057 				return (DCMD_ABORT);
3058 			}
3059 
3060 			mdb_printf(fmts[i], mdb_get_dot());
3061 			continue;
3062 		}
3063 
3064 		pa.pa_addr = addr;
3065 
3066 		if (parse_member(&pa, member, id, &mid, &off, &ignored) != 0)
3067 			return (DCMD_ABORT);
3068 
3069 		if ((ret = funcs[i](mid, pa.pa_addr, off, fmts[i])) != 0) {
3070 			mdb_warn("failed to print member '%s'\n", member);
3071 			return (ret);
3072 		}
3073 	}
3074 
3075 	mdb_printf("%s", last);
3076 
3077 	return (DCMD_OK);
3078 }
3079 
3080 static char _mdb_printf_help[] =
3081 "The format string argument is a printf(3C)-like format string that is a\n"
3082 "subset of the format strings supported by mdb_printf().  The type argument\n"
3083 "is the name of a type to be used to interpret the memory referenced by dot.\n"
3084 "The member should either be a field in the specified structure, or the\n"
3085 "special member '.', denoting the value of dot (and treated as a pointer).\n"
3086 "The number of members must match the number of format specifiers in the\n"
3087 "format string.\n"
3088 "\n"
3089 "The following format specifiers are recognized by ::printf:\n"
3090 "\n"
3091 "  %%    Prints the '%' symbol.\n"
3092 "  %a    Prints the member in symbolic form.\n"
3093 "  %d    Prints the member as a decimal integer.  If the member is a signed\n"
3094 "        integer type, the output will be signed.\n"
3095 "  %H    Prints the member as a human-readable size.\n"
3096 "  %I    Prints the member as an IPv4 address (must be 32-bit integer type).\n"
3097 "  %N    Prints the member as an IPv6 address (must be of type in6_addr_t).\n"
3098 "  %o    Prints the member as an unsigned octal integer.\n"
3099 "  %p    Prints the member as a pointer, in hexadecimal.\n"
3100 "  %q    Prints the member in signed octal.  Honk if you ever use this!\n"
3101 "  %r    Prints the member as an unsigned value in the current output radix.\n"
3102 "  %R    Prints the member as a signed value in the current output radix.\n"
3103 "  %s    Prints the member as a string (requires a pointer or an array of\n"
3104 "        characters).\n"
3105 "  %u    Prints the member as an unsigned decimal integer.\n"
3106 "  %x    Prints the member in hexadecimal.\n"
3107 "  %X    Prints the member in hexadecimal, using the characters A-F as the\n"
3108 "        digits for the values 10-15.\n"
3109 "  %Y    Prints the member as a time_t as the string "
3110 	    "'year month day HH:MM:SS'.\n"
3111 "\n"
3112 "The following field width specifiers are recognized by ::printf:\n"
3113 "\n"
3114 "  %n    Field width is set to the specified decimal value.\n"
3115 "  %?    Field width is set to the maximum width of a hexadecimal pointer\n"
3116 "        value.  This is 8 in an ILP32 environment, and 16 in an LP64\n"
3117 "        environment.\n"
3118 "\n"
3119 "The following flag specifers are recognized by ::printf:\n"
3120 "\n"
3121 "  %-    Left-justify the output within the specified field width.  If the\n"
3122 "        width of the output is less than the specified field width, the\n"
3123 "        output will be padded with blanks on the right-hand side.  Without\n"
3124 "        %-, values are right-justified by default.\n"
3125 "\n"
3126 "  %0    Zero-fill the output field if the output is right-justified and the\n"
3127 "        width of the output is less than the specified field width.  Without\n"
3128 "        %0, right-justified values are prepended with blanks in order to\n"
3129 "        fill the field.\n"
3130 "\n"
3131 "Examples: \n"
3132 "\n"
3133 "  ::walk proc | "
3134 	"::printf \"%-6d %s\\n\" proc_t p_pidp->pid_id p_user.u_psargs\n"
3135 "  ::walk thread | "
3136 	"::printf \"%?p %3d %a\\n\" kthread_t . t_pri t_startpc\n"
3137 "  ::walk zone | "
3138 	"::printf \"%-40s %20s\\n\" zone_t zone_name zone_nodename\n"
3139 "  ::walk ire | "
3140 	"::printf \"%Y %I\\n\" ire_t ire_create_time ire_u.ire4_u.ire4_addr\n"
3141 "\n";
3142 
3143 void
3144 printf_help(void)
3145 {
3146 	mdb_printf("%s", _mdb_printf_help);
3147 }
3148