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) 2012 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 arguments.
 711                  */
 712                 if (argv->a_type != MDB_TYPE_IMMEDIATE)
 713                         return (DCMD_USAGE);
 714 
 715                 offset = argv->a_un.a_val;
 716 
 717                 argv++;
 718                 argc--;
 719 
 720                 if (offset % sizeof (uintptr_t)) {
 721                         mdb_warn("offset must fall on a word boundary\n");
 722                         return (DCMD_ABORT);
 723                 }
 724         } else {
 725                 const char *member;
 726                 char buf[MDB_SYM_NAMLEN];
 727                 int ret;
 728 
 729                 ret = args_to_typename(&argc, &argv, buf, sizeof (buf));
 730                 if (ret != 0)
 731                         return (ret);
 732 
 733                 argv++;
 734                 argc--;
 735 
 736                 member = argv->a_un.a_str;
 737                 offset = mdb_ctf_offsetof_by_name(buf, member);
 738                 if (offset == -1)
 739                         return (DCMD_ABORT);
 740 
 741                 argv++;
 742                 argc--;
 743 
 744                 if (offset % (sizeof (uintptr_t)) != 0) {
 745                         mdb_warn("%s is not a word-aligned member\n", member);
 746                         return (DCMD_ABORT);
 747                 }
 748         }
 749 
 750         /*
 751          * If we have any unchewed arguments, a variable name must be present.
 752          */
 753         if (argc == 1) {
 754                 if (argv->a_type != MDB_TYPE_STRING)
 755                         return (DCMD_USAGE);
 756 
 757                 if ((ret = setup_vcb(argv->a_un.a_str, addr)) != 0)
 758                         return (ret);
 759 
 760         } else if (argc != 0) {
 761                 return (DCMD_USAGE);
 762         }
 763 
 764         a = addr;
 765 
 766         do {
 767                 mdb_printf("%lr\n", a);
 768 
 769                 if (mdb_vread(&tmp, sizeof (tmp), a + offset) == -1) {
 770                         mdb_warn("failed to read next pointer from object %p",
 771                             a);
 772                         return (DCMD_ERR);
 773                 }
 774 
 775                 a = tmp;
 776         } while (a != addr && a != NULL);
 777 
 778         return (DCMD_OK);
 779 }
 780 
 781 int
 782 cmd_array(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
 783 {
 784         mdb_ctf_id_t id;
 785         ssize_t elemsize = 0;
 786         char tn[MDB_SYM_NAMLEN];
 787         int ret, nelem = -1;
 788 
 789         mdb_tgt_t *t = mdb.m_target;
 790         GElf_Sym sym;
 791         mdb_ctf_arinfo_t ar;
 792         mdb_syminfo_t s_info;
 793 
 794         if (!(flags & DCMD_ADDRSPEC))
 795                 return (DCMD_USAGE);
 796 
 797         if (argc >= 2) {
 798                 ret = args_to_typename(&argc, &argv, tn, sizeof (tn));
 799                 if (ret != 0)
 800                         return (ret);
 801 
 802                 if (argc == 1)  /* unquoted compound type without count */
 803                         return (DCMD_USAGE);
 804 
 805                 if (mdb_ctf_lookup_by_name(tn, &id) != 0) {
 806                         mdb_warn("failed to look up type %s", tn);
 807                         return (DCMD_ABORT);
 808                 }
 809 
 810                 if (argv[1].a_type == MDB_TYPE_IMMEDIATE)
 811                         nelem = argv[1].a_un.a_val;
 812                 else
 813                         nelem = mdb_strtoull(argv[1].a_un.a_str);
 814 
 815                 elemsize = mdb_ctf_type_size(id);
 816         } else if (addr_to_sym(t, addr, tn, sizeof (tn), &sym, &s_info)
 817             != NULL && mdb_ctf_lookup_by_symbol(&sym, &s_info, &id)
 818             == 0 && mdb_ctf_type_kind(id) == CTF_K_ARRAY &&
 819             mdb_ctf_array_info(id, &ar) != -1) {
 820                 elemsize = mdb_ctf_type_size(id) / ar.mta_nelems;
 821                 nelem = ar.mta_nelems;
 822         } else {
 823                 mdb_warn("no symbol information for %a", addr);
 824                 return (DCMD_ERR);
 825         }
 826 
 827         if (argc == 3 || argc == 1) {
 828                 if (argv[argc - 1].a_type != MDB_TYPE_STRING)
 829                         return (DCMD_USAGE);
 830 
 831                 if ((ret = setup_vcb(argv[argc - 1].a_un.a_str, addr)) != 0)
 832                         return (ret);
 833 
 834         } else if (argc > 3) {
 835                 return (DCMD_USAGE);
 836         }
 837 
 838         for (; nelem > 0; nelem--) {
 839                 mdb_printf("%lr\n", addr);
 840                 addr = addr + elemsize;
 841         }
 842 
 843         return (DCMD_OK);
 844 }
 845 
 846 /*
 847  * Print an integer bitfield in hexadecimal by reading the enclosing byte(s)
 848  * and then shifting and masking the data in the lower bits of a uint64_t.
 849  */
 850 static int
 851 print_bitfield(ulong_t off, printarg_t *pap, ctf_encoding_t *ep)
 852 {
 853         mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
 854         size_t size = (ep->cte_bits + (NBBY - 1)) / NBBY;
 855         uint64_t mask = (1ULL << ep->cte_bits) - 1;
 856         uint64_t value = 0;
 857         uint8_t *buf = (uint8_t *)&value;
 858         uint8_t shift;
 859 
 860         const char *format;
 861 
 862         if (!(pap->pa_flags & PA_SHOWVAL))
 863                 return (0);
 864 
 865         if (ep->cte_bits > sizeof (value) * NBBY - 1) {
 866                 mdb_printf("??? (invalid bitfield size %u)", ep->cte_bits);
 867                 return (0);
 868         }
 869 
 870         /*
 871          * On big-endian machines, we need to adjust the buf pointer to refer
 872          * to the lowest 'size' bytes in 'value', and we need shift based on
 873          * the offset from the end of the data, not the offset of the start.
 874          */
 875 #ifdef _BIG_ENDIAN
 876         buf += sizeof (value) - size;
 877         off += ep->cte_bits;
 878 #endif
 879         if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, buf, size, addr) != size) {
 880                 mdb_warn("failed to read %lu bytes at %llx",
 881                     (ulong_t)size, addr);
 882                 return (1);
 883         }
 884 
 885         shift = off % NBBY;
 886 
 887         /*
 888          * Offsets are counted from opposite ends on little- and
 889          * big-endian machines.
 890          */
 891 #ifdef _BIG_ENDIAN
 892         shift = NBBY - shift;
 893 #endif
 894 
 895         /*
 896          * If the bits we want do not begin on a byte boundary, shift the data
 897          * right so that the value is in the lowest 'cte_bits' of 'value'.
 898          */
 899         if (off % NBBY != 0)
 900                 value >>= shift;
 901         value &= mask;
 902 
 903         /*
 904          * We default to printing signed bitfields as decimals,
 905          * and unsigned bitfields in hexadecimal.  If they specify
 906          * hexadecimal, we treat the field as unsigned.
 907          */
 908         if ((pap->pa_flags & PA_INTHEX) ||
 909             !(ep->cte_format & CTF_INT_SIGNED)) {
 910                 format = (pap->pa_flags & PA_INTDEC)? "%#llu" : "%#llx";
 911         } else {
 912                 int sshift = sizeof (value) * NBBY - ep->cte_bits;
 913 
 914                 /* sign-extend value, and print as a signed decimal */
 915                 value = ((int64_t)value << sshift) >> sshift;
 916                 format = "%#lld";
 917         }
 918         mdb_printf(format, value);
 919 
 920         return (0);
 921 }
 922 
 923 /*
 924  * Print out a character or integer value.  We use some simple heuristics,
 925  * described below, to determine the appropriate radix to use for output.
 926  */
 927 static int
 928 print_int_val(const char *type, ctf_encoding_t *ep, ulong_t off,
 929     printarg_t *pap)
 930 {
 931         static const char *const sformat[] = { "%#d", "%#d", "%#d", "%#lld" };
 932         static const char *const uformat[] = { "%#u", "%#u", "%#u", "%#llu" };
 933         static const char *const xformat[] = { "%#x", "%#x", "%#x", "%#llx" };
 934 
 935         mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
 936         const char *const *fsp;
 937         size_t size;
 938 
 939         union {
 940                 uint64_t i8;
 941                 uint32_t i4;
 942                 uint16_t i2;
 943                 uint8_t i1;
 944                 time_t t;
 945                 ipaddr_t I;
 946         } u;
 947 
 948         if (!(pap->pa_flags & PA_SHOWVAL))
 949                 return (0);
 950 
 951         if (ep->cte_format & CTF_INT_VARARGS) {
 952                 mdb_printf("...\n");
 953                 return (0);
 954         }
 955 
 956         /*
 957          * If the size is not a power-of-two number of bytes in the range 1-8
 958          * then we assume it is a bitfield and print it as such.
 959          */
 960         size = ep->cte_bits / NBBY;
 961         if (size > 8 || (ep->cte_bits % NBBY) != 0 || (size & (size - 1)) != 0)
 962                 return (print_bitfield(off, pap, ep));
 963 
 964         if (IS_CHAR(*ep)) {
 965                 mdb_printf("'");
 966                 if (mdb_fmt_print(pap->pa_tgt, pap->pa_as,
 967                     addr, 1, 'C') == addr)
 968                         return (1);
 969                 mdb_printf("'");
 970                 return (0);
 971         }
 972 
 973         if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.i8, size, addr) != size) {
 974                 mdb_warn("failed to read %lu bytes at %llx",
 975                     (ulong_t)size, addr);
 976                 return (1);
 977         }
 978 
 979         /*
 980          * We pretty-print some integer based types.  time_t values are
 981          * printed as a calendar date and time, and IPv4 addresses as human
 982          * readable dotted quads.
 983          */
 984         if (!(pap->pa_flags & (PA_INTHEX | PA_INTDEC))) {
 985                 if (strcmp(type, "time_t") == 0 && u.t != 0) {
 986                         mdb_printf("%Y", u.t);
 987                         return (0);
 988                 }
 989                 if (strcmp(type, "ipaddr_t") == 0 ||
 990                     strcmp(type, "in_addr_t") == 0) {
 991                         mdb_printf("%I", u.I);
 992                         return (0);
 993                 }
 994         }
 995 
 996         /*
 997          * The default format is hexadecimal.
 998          */
 999         if (!(pap->pa_flags & PA_INTDEC))
1000                 fsp = xformat;
1001         else if (ep->cte_format & CTF_INT_SIGNED)
1002                 fsp = sformat;
1003         else
1004                 fsp = uformat;
1005 
1006         switch (size) {
1007         case sizeof (uint8_t):
1008                 mdb_printf(fsp[0], u.i1);
1009                 break;
1010         case sizeof (uint16_t):
1011                 mdb_printf(fsp[1], u.i2);
1012                 break;
1013         case sizeof (uint32_t):
1014                 mdb_printf(fsp[2], u.i4);
1015                 break;
1016         case sizeof (uint64_t):
1017                 mdb_printf(fsp[3], u.i8);
1018                 break;
1019         }
1020         return (0);
1021 }
1022 
1023 /*ARGSUSED*/
1024 static int
1025 print_int(const char *type, const char *name, mdb_ctf_id_t id,
1026     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1027 {
1028         ctf_encoding_t e;
1029 
1030         if (!(pap->pa_flags & PA_SHOWVAL))
1031                 return (0);
1032 
1033         if (mdb_ctf_type_encoding(base, &e) != 0) {
1034                 mdb_printf("??? (%s)", mdb_strerror(errno));
1035                 return (0);
1036         }
1037 
1038         return (print_int_val(type, &e, off, pap));
1039 }
1040 
1041 /*
1042  * Print out a floating point value.  We only provide support for floats in
1043  * the ANSI-C float, double, and long double formats.
1044  */
1045 /*ARGSUSED*/
1046 static int
1047 print_float(const char *type, const char *name, mdb_ctf_id_t id,
1048     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1049 {
1050 #ifndef _KMDB
1051         mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1052         ctf_encoding_t e;
1053 
1054         union {
1055                 float f;
1056                 double d;
1057                 long double ld;
1058         } u;
1059 
1060         if (!(pap->pa_flags & PA_SHOWVAL))
1061                 return (0);
1062 
1063         if (mdb_ctf_type_encoding(base, &e) == 0) {
1064                 if (e.cte_format == CTF_FP_SINGLE &&
1065                     e.cte_bits == sizeof (float) * NBBY) {
1066                         if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.f,
1067                             sizeof (u.f), addr) != sizeof (u.f)) {
1068                                 mdb_warn("failed to read float at %llx", addr);
1069                                 return (1);
1070                         }
1071                         mdb_printf("%s", doubletos(u.f, 7, 'e'));
1072 
1073                 } else if (e.cte_format == CTF_FP_DOUBLE &&
1074                     e.cte_bits == sizeof (double) * NBBY) {
1075                         if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.d,
1076                             sizeof (u.d), addr) != sizeof (u.d)) {
1077                                 mdb_warn("failed to read float at %llx", addr);
1078                                 return (1);
1079                         }
1080                         mdb_printf("%s", doubletos(u.d, 7, 'e'));
1081 
1082                 } else if (e.cte_format == CTF_FP_LDOUBLE &&
1083                     e.cte_bits == sizeof (long double) * NBBY) {
1084                         if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.ld,
1085                             sizeof (u.ld), addr) != sizeof (u.ld)) {
1086                                 mdb_warn("failed to read float at %llx", addr);
1087                                 return (1);
1088                         }
1089                         mdb_printf("%s", longdoubletos(&u.ld, 16, 'e'));
1090 
1091                 } else {
1092                         mdb_printf("??? (unsupported FP format %u / %u bits\n",
1093                             e.cte_format, e.cte_bits);
1094                 }
1095         } else
1096                 mdb_printf("??? (%s)", mdb_strerror(errno));
1097 #else
1098         mdb_printf("<FLOAT>");
1099 #endif
1100         return (0);
1101 }
1102 
1103 
1104 /*
1105  * Print out a pointer value as a symbol name + offset or a hexadecimal value.
1106  * If the pointer itself is a char *, we attempt to read a bit of the data
1107  * referenced by the pointer and display it if it is a printable ASCII string.
1108  */
1109 /*ARGSUSED*/
1110 static int
1111 print_ptr(const char *type, const char *name, mdb_ctf_id_t id,
1112     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1113 {
1114         mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1115         ctf_encoding_t e;
1116         uintptr_t value;
1117         char buf[256];
1118         ssize_t len;
1119 
1120         if (!(pap->pa_flags & PA_SHOWVAL))
1121                 return (0);
1122 
1123         if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as,
1124             &value, sizeof (value), addr) != sizeof (value)) {
1125                 mdb_warn("failed to read %s pointer at %llx", name, addr);
1126                 return (1);
1127         }
1128 
1129         if (pap->pa_flags & PA_NOSYMBOLIC) {
1130                 mdb_printf("%#lx", value);
1131                 return (0);
1132         }
1133 
1134         mdb_printf("%a", value);
1135 
1136         if (value == NULL || strcmp(type, "caddr_t") == 0)
1137                 return (0);
1138 
1139         if (mdb_ctf_type_kind(base) == CTF_K_POINTER &&
1140             mdb_ctf_type_reference(base, &base) != -1 &&
1141             mdb_ctf_type_resolve(base, &base) != -1 &&
1142             mdb_ctf_type_encoding(base, &e) == 0 && IS_CHAR(e)) {
1143                 if ((len = mdb_tgt_readstr(pap->pa_realtgt, pap->pa_as,
1144                     buf, sizeof (buf), value)) >= 0 && strisprint(buf)) {
1145                         if (len == sizeof (buf))
1146                                 (void) strabbr(buf, sizeof (buf));
1147                         mdb_printf(" \"%s\"", buf);
1148                 }
1149         }
1150 
1151         return (0);
1152 }
1153 
1154 
1155 /*
1156  * Print out a fixed-size array.  We special-case arrays of characters
1157  * and attempt to print them out as ASCII strings if possible.  For other
1158  * arrays, we iterate over a maximum of pa_armemlim members and call
1159  * mdb_ctf_type_visit() again on each element to print its value.
1160  */
1161 /*ARGSUSED*/
1162 static int
1163 print_array(const char *type, const char *name, mdb_ctf_id_t id,
1164     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1165 {
1166         mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1167         printarg_t pa = *pap;
1168         ssize_t eltsize;
1169         mdb_ctf_arinfo_t r;
1170         ctf_encoding_t e;
1171         uint_t i, kind, limit;
1172         int d, sou;
1173         char buf[8];
1174         char *str;
1175 
1176         if (!(pap->pa_flags & PA_SHOWVAL))
1177                 return (0);
1178 
1179         if (pap->pa_depth == pap->pa_maxdepth) {
1180                 mdb_printf("[ ... ]");
1181                 return (0);
1182         }
1183 
1184         /*
1185          * Determine the base type and size of the array's content.  If this
1186          * fails, we cannot print anything and just give up.
1187          */
1188         if (mdb_ctf_array_info(base, &r) == -1 ||
1189             mdb_ctf_type_resolve(r.mta_contents, &base) == -1 ||
1190             (eltsize = mdb_ctf_type_size(base)) == -1) {
1191                 mdb_printf("[ ??? ] (%s)", mdb_strerror(errno));
1192                 return (0);
1193         }
1194 
1195         /*
1196          * Read a few bytes and determine if the content appears to be
1197          * printable ASCII characters.  If so, read the entire array and
1198          * attempt to display it as a string if it is printable.
1199          */
1200         if ((pap->pa_arstrlim == MDB_ARR_NOLIMIT ||
1201             r.mta_nelems <= pap->pa_arstrlim) &&
1202             mdb_ctf_type_encoding(base, &e) == 0 && IS_CHAR(e) &&
1203             mdb_tgt_readstr(pap->pa_tgt, pap->pa_as, buf,
1204             MIN(sizeof (buf), r.mta_nelems), addr) > 0 && strisprint(buf)) {
1205 
1206                 str = mdb_alloc(r.mta_nelems + 1, UM_SLEEP | UM_GC);
1207                 str[r.mta_nelems] = '\0';
1208 
1209                 if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, str,
1210                     r.mta_nelems, addr) != r.mta_nelems) {
1211                         mdb_warn("failed to read char array at %llx", addr);
1212                         return (1);
1213                 }
1214 
1215                 if (strisprint(str)) {
1216                         mdb_printf("[ \"%s\" ]", str);
1217                         return (0);
1218                 }
1219         }
1220 
1221         if (pap->pa_armemlim != MDB_ARR_NOLIMIT)
1222                 limit = MIN(r.mta_nelems, pap->pa_armemlim);
1223         else
1224                 limit = r.mta_nelems;
1225 
1226         if (limit == 0) {
1227                 mdb_printf("[ ... ]");
1228                 return (0);
1229         }
1230 
1231         kind = mdb_ctf_type_kind(base);
1232         sou = IS_COMPOSITE(kind);
1233 
1234         pa.pa_addr = addr;              /* set base address to start of array */
1235         pa.pa_maxdepth = pa.pa_maxdepth - pa.pa_depth - 1;
1236         pa.pa_nest += pa.pa_depth + 1;  /* nesting level is current depth + 1 */
1237         pa.pa_depth = 0;                /* reset depth to 0 for new scope */
1238         pa.pa_prefix = NULL;
1239 
1240         if (sou) {
1241                 pa.pa_delim = "\n";
1242                 mdb_printf("[\n");
1243         } else {
1244                 pa.pa_flags &= ~(PA_SHOWTYPE | PA_SHOWNAME | PA_SHOWADDR);
1245                 pa.pa_delim = ", ";
1246                 mdb_printf("[ ");
1247         }
1248 
1249         for (i = 0; i < limit; i++, pa.pa_addr += eltsize) {
1250                 if (i == limit - 1 && !sou) {
1251                         if (limit < r.mta_nelems)
1252                                 pa.pa_delim = ", ... ]";
1253                         else
1254                                 pa.pa_delim = " ]";
1255                 }
1256 
1257                 if (mdb_ctf_type_visit(r.mta_contents, elt_print, &pa) == -1) {
1258                         mdb_warn("failed to print array data");
1259                         return (1);
1260                 }
1261         }
1262 
1263         if (sou) {
1264                 for (d = pa.pa_depth - 1; d >= 0; d--)
1265                         print_close_sou(&pa, d);
1266 
1267                 if (limit < r.mta_nelems) {
1268                         mdb_printf("%*s... ]",
1269                             (pap->pa_depth + pap->pa_nest) * pap->pa_tab, "");
1270                 } else {
1271                         mdb_printf("%*s]",
1272                             (pap->pa_depth + pap->pa_nest) * pap->pa_tab, "");
1273                 }
1274         }
1275 
1276         /* copy the hole array info, since it may have been grown */
1277         pap->pa_holes = pa.pa_holes;
1278         pap->pa_nholes = pa.pa_nholes;
1279 
1280         return (0);
1281 }
1282 
1283 /*
1284  * Print out a struct or union header.  We need only print the open brace
1285  * because mdb_ctf_type_visit() itself will automatically recurse through
1286  * all members of the given struct or union.
1287  */
1288 /*ARGSUSED*/
1289 static int
1290 print_sou(const char *type, const char *name, mdb_ctf_id_t id,
1291     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1292 {
1293         mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1294 
1295         /*
1296          * We have pretty-printing for some structures where displaying
1297          * structure contents has no value.
1298          */
1299         if (pap->pa_flags & PA_SHOWVAL) {
1300                 if (strcmp(type, "in6_addr_t") == 0 ||
1301                     strcmp(type, "struct in6_addr") == 0) {
1302                         in6_addr_t in6addr;
1303 
1304                         if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &in6addr,
1305                             sizeof (in6addr), addr) != sizeof (in6addr)) {
1306                                 mdb_warn("failed to read %s pointer at %llx",
1307                                     name, addr);
1308                                 return (1);
1309                         }
1310                         mdb_printf("%N", &in6addr);
1311                         /*
1312                          * Don't print anything further down in the
1313                          * structure.
1314                          */
1315                         pap->pa_nooutdepth = pap->pa_depth;
1316                         return (0);
1317                 }
1318                 if (strcmp(type, "struct in_addr") == 0) {
1319                         in_addr_t inaddr;
1320 
1321                         if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &inaddr,
1322                             sizeof (inaddr), addr) != sizeof (inaddr)) {
1323                                 mdb_warn("failed to read %s pointer at %llx",
1324                                     name, addr);
1325                                 return (1);
1326                         }
1327                         mdb_printf("%I", inaddr);
1328                         pap->pa_nooutdepth = pap->pa_depth;
1329                         return (0);
1330                 }
1331         }
1332 
1333         if (pap->pa_depth == pap->pa_maxdepth)
1334                 mdb_printf("{ ... }");
1335         else
1336                 mdb_printf("{");
1337         pap->pa_delim = "\n";
1338         return (0);
1339 }
1340 
1341 /*
1342  * Print an enum value.  We attempt to convert the value to the corresponding
1343  * enum name and print that if possible.
1344  */
1345 /*ARGSUSED*/
1346 static int
1347 print_enum(const char *type, const char *name, mdb_ctf_id_t id,
1348     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1349 {
1350         mdb_tgt_addr_t addr = pap->pa_addr + off / NBBY;
1351         const char *ename;
1352         int value;
1353         int isp2 = enum_is_p2(base);
1354         int flags = pap->pa_flags | (isp2 ? PA_INTHEX : 0);
1355 
1356         if (!(flags & PA_SHOWVAL))
1357                 return (0);
1358 
1359         if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as,
1360             &value, sizeof (value), addr) != sizeof (value)) {
1361                 mdb_warn("failed to read %s integer at %llx", name, addr);
1362                 return (1);
1363         }
1364 
1365         if (flags & PA_INTHEX)
1366                 mdb_printf("%#x", value);
1367         else
1368                 mdb_printf("%#d", value);
1369 
1370         (void) mdb_inc_indent(8);
1371         mdb_printf(" (");
1372 
1373         if (!isp2 || enum_value_print_p2(base, value, 0) != 0) {
1374                 ename = mdb_ctf_enum_name(base, value);
1375                 if (ename == NULL) {
1376                         ename = "???";
1377                 }
1378                 mdb_printf("%s", ename);
1379         }
1380         mdb_printf(")");
1381         (void) mdb_dec_indent(8);
1382 
1383         return (0);
1384 }
1385 
1386 /*
1387  * This will only get called if the structure isn't found in any available CTF
1388  * data.
1389  */
1390 /*ARGSUSED*/
1391 static int
1392 print_tag(const char *type, const char *name, mdb_ctf_id_t id,
1393     mdb_ctf_id_t base, ulong_t off, printarg_t *pap)
1394 {
1395         char basename[MDB_SYM_NAMLEN];
1396 
1397         if (pap->pa_flags & PA_SHOWVAL)
1398                 mdb_printf("; ");
1399 
1400         if (mdb_ctf_type_name(base, basename, sizeof (basename)) != NULL)
1401                 mdb_printf("<forward declaration of %s>", basename);
1402         else
1403                 mdb_printf("<forward declaration of unknown type>");
1404 
1405         return (0);
1406 }
1407 
1408 static void
1409 print_hole(printarg_t *pap, int depth, ulong_t off, ulong_t endoff)
1410 {
1411         ulong_t bits = endoff - off;
1412         ulong_t size = bits / NBBY;
1413         ctf_encoding_t e;
1414 
1415         static const char *const name = "<<HOLE>>";
1416         char type[MDB_SYM_NAMLEN];
1417 
1418         int bitfield =
1419             (off % NBBY != 0 ||
1420             bits % NBBY != 0 ||
1421             size > 8 ||
1422             (size & (size - 1)) != 0);
1423 
1424         ASSERT(off < endoff);
1425 
1426         if (bits > NBBY * sizeof (uint64_t)) {
1427                 ulong_t end;
1428 
1429                 /*
1430                  * The hole is larger than the largest integer type.  To
1431                  * handle this, we split up the hole at 8-byte-aligned
1432                  * boundaries, recursing to print each subsection.  For
1433                  * normal C structures, we'll loop at most twice.
1434                  */
1435                 for (; off < endoff; off = end) {
1436                         end = P2END(off, NBBY * sizeof (uint64_t));
1437                         if (end > endoff)
1438                                 end = endoff;
1439 
1440                         ASSERT((end - off) <= NBBY * sizeof (uint64_t));
1441                         print_hole(pap, depth, off, end);
1442                 }
1443                 ASSERT(end == endoff);
1444 
1445                 return;
1446         }
1447 
1448         if (bitfield)
1449                 (void) mdb_snprintf(type, sizeof (type), "unsigned");
1450         else
1451                 (void) mdb_snprintf(type, sizeof (type), "uint%d_t", bits);
1452 
1453         if (pap->pa_flags & (PA_SHOWTYPE | PA_SHOWNAME | PA_SHOWADDR))
1454                 mdb_printf("%*s", (depth + pap->pa_nest) * pap->pa_tab, "");
1455 
1456         if (pap->pa_flags & PA_SHOWADDR) {
1457                 if (off % NBBY == 0)
1458                         mdb_printf("%llx ", pap->pa_addr + off / NBBY);
1459                 else
1460                         mdb_printf("%llx.%lx ",
1461                             pap->pa_addr + off / NBBY, off % NBBY);
1462         }
1463 
1464         if (pap->pa_flags & PA_SHOWTYPE)
1465                 mdb_printf("%s ", type);
1466 
1467         if (pap->pa_flags & PA_SHOWNAME)
1468                 mdb_printf("%s", name);
1469 
1470         if (bitfield && (pap->pa_flags & PA_SHOWTYPE))
1471                 mdb_printf(" :%d", bits);
1472 
1473         mdb_printf("%s ", (pap->pa_flags & PA_SHOWVAL)? " =" : "");
1474 
1475         /*
1476          * We fake up a ctf_encoding_t, and use print_int_val() to print
1477          * the value.  Holes are always processed as unsigned integers.
1478          */
1479         bzero(&e, sizeof (e));
1480         e.cte_format = 0;
1481         e.cte_offset = 0;
1482         e.cte_bits = bits;
1483 
1484         if (print_int_val(type, &e, off, pap) != 0)
1485                 mdb_iob_discard(mdb.m_out);
1486         else
1487                 mdb_iob_puts(mdb.m_out, pap->pa_delim);
1488 }
1489 
1490 /*
1491  * The print_close_sou() function is called for each structure or union
1492  * which has been completed.  For structures, we detect and print any holes
1493  * before printing the closing brace.
1494  */
1495 static void
1496 print_close_sou(printarg_t *pap, int newdepth)
1497 {
1498         int d = newdepth + pap->pa_nest;
1499 
1500         if ((pap->pa_flags & PA_SHOWHOLES) && !pap->pa_holes[d].hi_isunion) {
1501                 ulong_t end = pap->pa_holes[d + 1].hi_offset;
1502                 ulong_t expected = pap->pa_holes[d].hi_offset;
1503 
1504                 if (end < expected)
1505                         print_hole(pap, newdepth + 1, end, expected);
1506         }
1507         /* if the struct is an array element, print a comma after the } */
1508         mdb_printf("%*s}%s\n", d * pap->pa_tab, "",
1509             (newdepth == 0 && pap->pa_nest > 0)? "," : "");
1510 }
1511 
1512 static printarg_f *const printfuncs[] = {
1513         print_int,      /* CTF_K_INTEGER */
1514         print_float,    /* CTF_K_FLOAT */
1515         print_ptr,      /* CTF_K_POINTER */
1516         print_array,    /* CTF_K_ARRAY */
1517         print_ptr,      /* CTF_K_FUNCTION */
1518         print_sou,      /* CTF_K_STRUCT */
1519         print_sou,      /* CTF_K_UNION */
1520         print_enum,     /* CTF_K_ENUM */
1521         print_tag       /* CTF_K_FORWARD */
1522 };
1523 
1524 /*
1525  * The elt_print function is used as the mdb_ctf_type_visit callback.  For
1526  * each element, we print an appropriate name prefix and then call the
1527  * print subroutine for this type class in the array above.
1528  */
1529 static int
1530 elt_print(const char *name, mdb_ctf_id_t id, mdb_ctf_id_t base,
1531     ulong_t off, int depth, void *data)
1532 {
1533         char type[MDB_SYM_NAMLEN + sizeof (" <<12345678...>>")];
1534         int kind, rc, d;
1535         printarg_t *pap = data;
1536 
1537         for (d = pap->pa_depth - 1; d >= depth; d--) {
1538                 if (d < pap->pa_nooutdepth)
1539                         print_close_sou(pap, d);
1540         }
1541 
1542         /*
1543          * Reset pa_nooutdepth if we've come back out of the structure we
1544          * didn't want to print.
1545          */
1546         if (depth <= pap->pa_nooutdepth)
1547                 pap->pa_nooutdepth = (uint_t)-1;
1548 
1549         if (depth > pap->pa_maxdepth || depth > pap->pa_nooutdepth)
1550                 return (0);
1551 
1552         if (!mdb_ctf_type_valid(base) ||
1553             (kind = mdb_ctf_type_kind(base)) == -1)
1554                 return (-1); /* errno is set for us */
1555 
1556         if (mdb_ctf_type_name(id, type, MDB_SYM_NAMLEN) == NULL)
1557                 (void) strcpy(type, "(?)");
1558 
1559         if (pap->pa_flags & PA_SHOWBASETYPE) {
1560                 /*
1561                  * If basetype is different and informative, concatenate
1562                  * <<basetype>> (or <<baset...>> if it doesn't fit)
1563                  *
1564                  * We just use the end of the buffer to store the type name, and
1565                  * only connect it up if that's necessary.
1566                  */
1567 
1568                 char *type_end = type + strlen(type);
1569                 char *basetype;
1570                 size_t sz;
1571 
1572                 (void) strlcat(type, " <<", sizeof (type));
1573 
1574                 basetype = type + strlen(type);
1575                 sz = sizeof (type) - (basetype - type);
1576 
1577                 *type_end = '\0'; /* restore the end of type for strcmp() */
1578 
1579                 if (mdb_ctf_type_name(base, basetype, sz) != NULL &&
1580                     strcmp(basetype, type) != 0 &&
1581                     strcmp(basetype, "struct ") != 0 &&
1582                     strcmp(basetype, "enum ") != 0 &&
1583                     strcmp(basetype, "union ") != 0) {
1584                         type_end[0] = ' ';      /* reconnect */
1585                         if (strlcat(type, ">>", sizeof (type)) >= sizeof (type))
1586                                 (void) strlcpy(
1587                                     type + sizeof (type) - 6, "...>>", 6);
1588                 }
1589         }
1590 
1591         if (pap->pa_flags & PA_SHOWHOLES) {
1592                 ctf_encoding_t e;
1593                 ssize_t nsize;
1594                 ulong_t newoff;
1595                 holeinfo_t *hole;
1596                 int extra = IS_COMPOSITE(kind)? 1 : 0;
1597 
1598                 /*
1599                  * grow the hole array, if necessary
1600                  */
1601                 if (pap->pa_nest + depth + extra >= pap->pa_nholes) {
1602                         int new = MAX(MAX(8, pap->pa_nholes * 2),
1603                             pap->pa_nest + depth + extra + 1);
1604 
1605                         holeinfo_t *nhi = mdb_zalloc(
1606                             sizeof (*nhi) * new, UM_NOSLEEP | UM_GC);
1607 
1608                         bcopy(pap->pa_holes, nhi,
1609                             pap->pa_nholes * sizeof (*nhi));
1610 
1611                         pap->pa_holes = nhi;
1612                         pap->pa_nholes = new;
1613                 }
1614 
1615                 hole = &pap->pa_holes[depth + pap->pa_nest];
1616 
1617                 if (depth != 0 && off > hole->hi_offset)
1618                         print_hole(pap, depth, hole->hi_offset, off);
1619 
1620                 /* compute the next expected offset */
1621                 if (kind == CTF_K_INTEGER &&
1622                     mdb_ctf_type_encoding(base, &e) == 0)
1623                         newoff = off + e.cte_bits;
1624                 else if ((nsize = mdb_ctf_type_size(base)) >= 0)
1625                         newoff = off + nsize * NBBY;
1626                 else {
1627                         /* something bad happened, disable hole checking */
1628                         newoff = -1UL;          /* ULONG_MAX */
1629                 }
1630 
1631                 hole->hi_offset = newoff;
1632 
1633                 if (IS_COMPOSITE(kind)) {
1634                         hole->hi_isunion = (kind == CTF_K_UNION);
1635                         hole++;
1636                         hole->hi_offset = off;
1637                 }
1638         }
1639 
1640         if (pap->pa_flags & (PA_SHOWTYPE | PA_SHOWNAME | PA_SHOWADDR))
1641                 mdb_printf("%*s", (depth + pap->pa_nest) * pap->pa_tab, "");
1642 
1643         if (pap->pa_flags & PA_SHOWADDR) {
1644                 if (off % NBBY == 0)
1645                         mdb_printf("%llx ", pap->pa_addr + off / NBBY);
1646                 else
1647                         mdb_printf("%llx.%lx ",
1648                             pap->pa_addr + off / NBBY, off % NBBY);
1649         }
1650 
1651         if ((pap->pa_flags & PA_SHOWTYPE)) {
1652                 mdb_printf("%s", type);
1653                 /*
1654                  * We want to avoid printing a trailing space when
1655                  * dealing with pointers in a structure, so we end
1656                  * up with:
1657                  *
1658                  *      label_t *t_onfault = 0
1659                  *
1660                  * If depth is zero, always print the trailing space unless
1661                  * we also have a prefix.
1662                  */
1663                 if (type[strlen(type) - 1] != '*' ||
1664                     (depth == 0 && (!(pap->pa_flags & PA_SHOWNAME) ||
1665                     pap->pa_prefix == NULL)))
1666                         mdb_printf(" ");
1667         }
1668 
1669         if (pap->pa_flags & PA_SHOWNAME) {
1670                 if (pap->pa_prefix != NULL && depth <= 1)
1671                         mdb_printf("%s%s", pap->pa_prefix,
1672                             (depth == 0) ? "" : pap->pa_suffix);
1673                 mdb_printf("%s", name);
1674         }
1675 
1676         if ((pap->pa_flags & PA_SHOWTYPE) && kind == CTF_K_INTEGER) {
1677                 ctf_encoding_t e;
1678 
1679                 if (mdb_ctf_type_encoding(base, &e) == 0) {
1680                         ulong_t bits = e.cte_bits;
1681                         ulong_t size = bits / NBBY;
1682 
1683                         if (bits % NBBY != 0 ||
1684                             off % NBBY != 0 ||
1685                             size > 8 ||
1686                             size != mdb_ctf_type_size(base))
1687                                 mdb_printf(" :%d", bits);
1688                 }
1689         }
1690 
1691         if (depth != 0 ||
1692             ((pap->pa_flags & PA_SHOWNAME) && pap->pa_prefix != NULL))
1693                 mdb_printf("%s ", pap->pa_flags & PA_SHOWVAL ? " =" : "");
1694 
1695         if (depth == 0 && pap->pa_prefix != NULL)
1696                 name = pap->pa_prefix;
1697 
1698         pap->pa_depth = depth;
1699         if (kind <= CTF_K_UNKNOWN || kind >= CTF_K_TYPEDEF) {
1700                 mdb_warn("unknown ctf for %s type %s kind %d\n",
1701                     name, type, kind);
1702                 return (-1);
1703         }
1704         rc = printfuncs[kind - 1](type, name, id, base, off, pap);
1705 
1706         if (rc != 0)
1707                 mdb_iob_discard(mdb.m_out);
1708         else
1709                 mdb_iob_puts(mdb.m_out, pap->pa_delim);
1710 
1711         return (rc);
1712 }
1713 
1714 /*
1715  * Special semantics for pipelines.
1716  */
1717 static int
1718 pipe_print(mdb_ctf_id_t id, ulong_t off, void *data)
1719 {
1720         printarg_t *pap = data;
1721         ssize_t size;
1722         static const char *const fsp[] = { "%#r", "%#r", "%#r", "%#llr" };
1723         uintptr_t value;
1724         uintptr_t addr = pap->pa_addr + off / NBBY;
1725         mdb_ctf_id_t base;
1726         ctf_encoding_t e;
1727 
1728         union {
1729                 uint64_t i8;
1730                 uint32_t i4;
1731                 uint16_t i2;
1732                 uint8_t i1;
1733         } u;
1734 
1735         if (mdb_ctf_type_resolve(id, &base) == -1) {
1736                 mdb_warn("could not resolve type");
1737                 return (-1);
1738         }
1739 
1740         /*
1741          * If the user gives -a, then always print out the address of the
1742          * member.
1743          */
1744         if ((pap->pa_flags & PA_SHOWADDR)) {
1745                 mdb_printf("%#lr\n", addr);
1746                 return (0);
1747         }
1748 
1749 again:
1750         switch (mdb_ctf_type_kind(base)) {
1751         case CTF_K_POINTER:
1752                 if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as,
1753                     &value, sizeof (value), addr) != sizeof (value)) {
1754                         mdb_warn("failed to read pointer at %p", addr);
1755                         return (-1);
1756                 }
1757                 mdb_printf("%#lr\n", value);
1758                 break;
1759 
1760         case CTF_K_INTEGER:
1761         case CTF_K_ENUM:
1762                 if (mdb_ctf_type_encoding(base, &e) != 0) {
1763                         mdb_printf("could not get type encoding\n");
1764                         return (-1);
1765                 }
1766 
1767                 /*
1768                  * For immediate values, we just print out the value.
1769                  */
1770                 size = e.cte_bits / NBBY;
1771                 if (size > 8 || (e.cte_bits % NBBY) != 0 ||
1772                     (size & (size - 1)) != 0) {
1773                         return (print_bitfield(off, pap, &e));
1774                 }
1775 
1776                 if (mdb_tgt_aread(pap->pa_tgt, pap->pa_as, &u.i8, size,
1777                     addr) != size) {
1778                         mdb_warn("failed to read %lu bytes at %p",
1779                             (ulong_t)size, pap->pa_addr);
1780                         return (-1);
1781                 }
1782 
1783                 switch (size) {
1784                 case sizeof (uint8_t):
1785                         mdb_printf(fsp[0], u.i1);
1786                         break;
1787                 case sizeof (uint16_t):
1788                         mdb_printf(fsp[1], u.i2);
1789                         break;
1790                 case sizeof (uint32_t):
1791                         mdb_printf(fsp[2], u.i4);
1792                         break;
1793                 case sizeof (uint64_t):
1794                         mdb_printf(fsp[3], u.i8);
1795                         break;
1796                 }
1797                 mdb_printf("\n");
1798                 break;
1799 
1800         case CTF_K_FUNCTION:
1801         case CTF_K_FLOAT:
1802         case CTF_K_ARRAY:
1803         case CTF_K_UNKNOWN:
1804         case CTF_K_STRUCT:
1805         case CTF_K_UNION:
1806         case CTF_K_FORWARD:
1807                 /*
1808                  * For these types, always print the address of the member
1809                  */
1810                 mdb_printf("%#lr\n", addr);
1811                 break;
1812 
1813         default:
1814                 mdb_warn("unknown type %d", mdb_ctf_type_kind(base));
1815                 break;
1816         }
1817 
1818         return (0);
1819 }
1820 
1821 static int
1822 parse_delimiter(char **strp)
1823 {
1824         switch (**strp) {
1825         case '\0':
1826                 return (MEMBER_DELIM_DONE);
1827 
1828         case '.':
1829                 *strp = *strp + 1;
1830                 return (MEMBER_DELIM_DOT);
1831 
1832         case '[':
1833                 *strp = *strp + 1;
1834                 return (MEMBER_DELIM_LBR);
1835 
1836         case '-':
1837                 *strp = *strp + 1;
1838                 if (**strp == '>') {
1839                         *strp = *strp + 1;
1840                         return (MEMBER_DELIM_PTR);
1841                 }
1842                 *strp = *strp - 1;
1843                 /*FALLTHROUGH*/
1844         default:
1845                 return (MEMBER_DELIM_ERR);
1846         }
1847 }
1848 
1849 static int
1850 deref(printarg_t *pap, size_t size)
1851 {
1852         uint32_t a32;
1853         mdb_tgt_as_t as = pap->pa_as;
1854         mdb_tgt_addr_t *ap = &pap->pa_addr;
1855 
1856         if (size == sizeof (mdb_tgt_addr_t)) {
1857                 if (mdb_tgt_aread(mdb.m_target, as, ap, size, *ap) == -1) {
1858                         mdb_warn("could not dereference pointer %llx\n", *ap);
1859                         return (-1);
1860                 }
1861         } else {
1862                 if (mdb_tgt_aread(mdb.m_target, as, &a32, size, *ap) == -1) {
1863                         mdb_warn("could not dereference pointer %x\n", *ap);
1864                         return (-1);
1865                 }
1866 
1867                 *ap = (mdb_tgt_addr_t)a32;
1868         }
1869 
1870         /*
1871          * We've dereferenced at least once, we must be on the real
1872          * target. If we were in the immediate target, reset to the real
1873          * target; it's reset as needed when we return to the print
1874          * routines.
1875          */
1876         if (pap->pa_tgt == pap->pa_immtgt)
1877                 pap->pa_tgt = pap->pa_realtgt;
1878 
1879         return (0);
1880 }
1881 
1882 static int
1883 parse_member(printarg_t *pap, const char *str, mdb_ctf_id_t id,
1884     mdb_ctf_id_t *idp, ulong_t *offp, int *last_deref)
1885 {
1886         int delim;
1887         char member[64];
1888         char buf[128];
1889         uint_t index;
1890         char *start = (char *)str;
1891         char *end;
1892         ulong_t off = 0;
1893         mdb_ctf_arinfo_t ar;
1894         mdb_ctf_id_t rid;
1895         int kind;
1896         ssize_t size;
1897         int non_array = FALSE;
1898 
1899         /*
1900          * id always has the unresolved type for printing error messages
1901          * that include the type; rid always has the resolved type for
1902          * use in mdb_ctf_* calls.  It is possible for this command to fail,
1903          * however, if the resolved type is in the parent and it is currently
1904          * unavailable.  Note that we also can't print out the name of the
1905          * type, since that would also rely on looking up the resolved name.
1906          */
1907         if (mdb_ctf_type_resolve(id, &rid) != 0) {
1908                 mdb_warn("failed to resolve type");
1909                 return (-1);
1910         }
1911 
1912         delim = parse_delimiter(&start);
1913         /*
1914          * If the user fails to specify an initial delimiter, guess -> for
1915          * pointer types and . for non-pointer types.
1916          */
1917         if (delim == MEMBER_DELIM_ERR)
1918                 delim = (mdb_ctf_type_kind(rid) == CTF_K_POINTER) ?
1919                     MEMBER_DELIM_PTR : MEMBER_DELIM_DOT;
1920 
1921         *last_deref = FALSE;
1922 
1923         while (delim != MEMBER_DELIM_DONE) {
1924                 switch (delim) {
1925                 case MEMBER_DELIM_PTR:
1926                         kind = mdb_ctf_type_kind(rid);
1927                         if (kind != CTF_K_POINTER) {
1928                                 mdb_warn("%s is not a pointer type\n",
1929                                     mdb_ctf_type_name(id, buf, sizeof (buf)));
1930                                 return (-1);
1931                         }
1932 
1933                         size = mdb_ctf_type_size(id);
1934                         if (deref(pap, size) != 0)
1935                                 return (-1);
1936 
1937                         (void) mdb_ctf_type_reference(rid, &id);
1938                         (void) mdb_ctf_type_resolve(id, &rid);
1939 
1940                         off = 0;
1941                         break;
1942 
1943                 case MEMBER_DELIM_DOT:
1944                         kind = mdb_ctf_type_kind(rid);
1945                         if (kind != CTF_K_STRUCT && kind != CTF_K_UNION) {
1946                                 mdb_warn("%s is not a struct or union type\n",
1947                                     mdb_ctf_type_name(id, buf, sizeof (buf)));
1948                                 return (-1);
1949                         }
1950                         break;
1951 
1952                 case MEMBER_DELIM_LBR:
1953                         end = strchr(start, ']');
1954                         if (end == NULL) {
1955                                 mdb_warn("no trailing ']'\n");
1956                                 return (-1);
1957                         }
1958 
1959                         (void) mdb_snprintf(member, end - start + 1, "%s",
1960                             start);
1961 
1962                         index = mdb_strtoull(member);
1963 
1964                         switch (mdb_ctf_type_kind(rid)) {
1965                         case CTF_K_POINTER:
1966                                 size = mdb_ctf_type_size(rid);
1967 
1968                                 if (deref(pap, size) != 0)
1969                                         return (-1);
1970 
1971                                 (void) mdb_ctf_type_reference(rid, &id);
1972                                 (void) mdb_ctf_type_resolve(id, &rid);
1973 
1974                                 size = mdb_ctf_type_size(id);
1975                                 if (size <= 0) {
1976                                         mdb_warn("cannot dereference void "
1977                                             "type\n");
1978                                         return (-1);
1979                                 }
1980 
1981                                 pap->pa_addr += index * size;
1982                                 off = 0;
1983 
1984                                 if (index == 0 && non_array)
1985                                         *last_deref = TRUE;
1986                                 break;
1987 
1988                         case CTF_K_ARRAY:
1989                                 (void) mdb_ctf_array_info(rid, &ar);
1990 
1991                                 if (index >= ar.mta_nelems) {
1992                                         mdb_warn("index %r is outside of "
1993                                             "array bounds [0 .. %r]\n",
1994                                             index, ar.mta_nelems - 1);
1995                                 }
1996 
1997                                 id = ar.mta_contents;
1998                                 (void) mdb_ctf_type_resolve(id, &rid);
1999 
2000                                 size = mdb_ctf_type_size(id);
2001                                 if (size <= 0) {
2002                                         mdb_warn("cannot dereference void "
2003                                             "type\n");
2004                                         return (-1);
2005                                 }
2006 
2007                                 pap->pa_addr += index * size;
2008                                 off = 0;
2009                                 break;
2010 
2011                         default:
2012                                 mdb_warn("cannot index into non-array, "
2013                                     "non-pointer type\n");
2014                                 return (-1);
2015                         }
2016 
2017                         start = end + 1;
2018                         delim = parse_delimiter(&start);
2019                         continue;
2020 
2021                 case MEMBER_DELIM_ERR:
2022                 default:
2023                         mdb_warn("'%c' is not a valid delimiter\n", *start);
2024                         return (-1);
2025                 }
2026 
2027                 *last_deref = FALSE;
2028                 non_array = TRUE;
2029 
2030                 /*
2031                  * Find the end of the member name; assume that a member
2032                  * name is at least one character long.
2033                  */
2034                 for (end = start + 1; isalnum(*end) || *end == '_'; end++)
2035                         continue;
2036 
2037                 (void) mdb_snprintf(member, end - start + 1, "%s", start);
2038 
2039                 if (mdb_ctf_member_info(rid, member, &off, &id) != 0) {
2040                         mdb_warn("failed to find member %s of %s", member,
2041                             mdb_ctf_type_name(id, buf, sizeof (buf)));
2042                         return (-1);
2043                 }
2044                 (void) mdb_ctf_type_resolve(id, &rid);
2045 
2046                 pap->pa_addr += off / NBBY;
2047 
2048                 start = end;
2049                 delim = parse_delimiter(&start);
2050         }
2051 
2052         *idp = id;
2053         *offp = off;
2054 
2055         return (0);
2056 }
2057 
2058 int
2059 cmd_print_tab(mdb_tab_cookie_t *mcp, uint_t flags, int argc,
2060     const mdb_arg_t *argv)
2061 {
2062         char tn[MDB_SYM_NAMLEN];
2063         char member[64];
2064         int i, dummy, delim, kind;
2065         int ret = 0;
2066         mdb_ctf_id_t id, rid;
2067         mdb_ctf_arinfo_t ar;
2068         char *start, *end;
2069         ulong_t dul;
2070 
2071         /*
2072          * This getopts is only here to make the tab completion work better when
2073          * including options in the ::print arguments. None of the values should
2074          * be used. This should only be updated with additional arguments, if
2075          * they are added to cmd_print.
2076          */
2077         i = mdb_getopts(argc, argv,
2078             'a', MDB_OPT_SETBITS, PA_SHOWADDR, &dummy,
2079             'C', MDB_OPT_SETBITS, TRUE, &dummy,
2080             'c', MDB_OPT_UINTPTR, &dummy,
2081             'd', MDB_OPT_SETBITS, PA_INTDEC, &dummy,
2082             'h', MDB_OPT_SETBITS, PA_SHOWHOLES, &dummy,
2083             'i', MDB_OPT_SETBITS, TRUE, &dummy,
2084             'L', MDB_OPT_SETBITS, TRUE, &dummy,
2085             'l', MDB_OPT_UINTPTR, &dummy,
2086             'n', MDB_OPT_SETBITS, PA_NOSYMBOLIC, &dummy,
2087             'p', MDB_OPT_SETBITS, TRUE, &dummy,
2088             's', MDB_OPT_UINTPTR, &dummy,
2089             'T', MDB_OPT_SETBITS, PA_SHOWTYPE | PA_SHOWBASETYPE, &dummy,
2090             't', MDB_OPT_SETBITS, PA_SHOWTYPE, &dummy,
2091             'x', MDB_OPT_SETBITS, PA_INTHEX, &dummy,
2092             NULL);
2093 
2094         argc -= i;
2095         argv += i;
2096 
2097         if (argc == 0 && !(flags & DCMD_TAB_SPACE))
2098                 return (0);
2099 
2100         if (argc == 0 && (flags & DCMD_TAB_SPACE))
2101                 return (mdb_tab_complete_type(mcp, NULL, MDB_TABC_NOPOINT |
2102                     MDB_TABC_NOARRAY));
2103 
2104         if ((ret = mdb_tab_typename(&argc, &argv, tn, sizeof (tn))) < 0)
2105                 return (ret);
2106 
2107         if (argc == 1 && (!(flags & DCMD_TAB_SPACE) || ret == 1))
2108                 return (mdb_tab_complete_type(mcp, tn, MDB_TABC_NOPOINT |
2109                     MDB_TABC_NOARRAY));
2110 
2111         if (argc == 1 && (flags & DCMD_TAB_SPACE))
2112                 return (mdb_tab_complete_member(mcp, tn, NULL));
2113 
2114         /*
2115          * This is the reason that tab completion was created. We're going to go
2116          * along and walk the delimiters until we find something a member that
2117          * we don't recognize, at which point we'll try and tab complete it.
2118          * Note that ::print takes multiple args, so this is going to operate on
2119          * whatever the last arg that we have is.
2120          */
2121         if (mdb_ctf_lookup_by_name(tn, &id) != 0)
2122                 return (1);
2123 
2124         (void) mdb_ctf_type_resolve(id, &rid);
2125         start = (char *)argv[argc-1].a_un.a_str;
2126         delim = parse_delimiter(&start);
2127 
2128         /*
2129          * If we hit the case where we actually have no delimiters, than we need
2130          * to make sure that we properly set up the fields the loops would.
2131          */
2132         if (delim == MEMBER_DELIM_DONE)
2133                 (void) mdb_snprintf(member, sizeof (member), "%s", start);
2134 
2135         while (delim != MEMBER_DELIM_DONE) {
2136                 switch (delim) {
2137                 case MEMBER_DELIM_PTR:
2138                         kind = mdb_ctf_type_kind(rid);
2139                         if (kind != CTF_K_POINTER)
2140                                 return (1);
2141 
2142                         (void) mdb_ctf_type_reference(rid, &id);
2143                         (void) mdb_ctf_type_resolve(id, &rid);
2144                         break;
2145                 case MEMBER_DELIM_DOT:
2146                         kind = mdb_ctf_type_kind(rid);
2147                         if (kind != CTF_K_STRUCT && kind != CTF_K_UNION)
2148                                 return (1);
2149                         break;
2150                 case MEMBER_DELIM_LBR:
2151                         end = strchr(start, ']');
2152                         /*
2153                          * We're not going to try and tab complete the indexes
2154                          * here. So for now, punt on it. Also, we're not going
2155                          * to try and validate you're within the bounds, just
2156                          * that you get the type you asked for.
2157                          */
2158                         if (end == NULL)
2159                                 return (1);
2160 
2161                         switch (mdb_ctf_type_kind(rid)) {
2162                         case CTF_K_POINTER:
2163                                 (void) mdb_ctf_type_reference(rid, &id);
2164                                 (void) mdb_ctf_type_resolve(id, &rid);
2165                                 break;
2166                         case CTF_K_ARRAY:
2167                                 (void) mdb_ctf_array_info(rid, &ar);
2168                                 id = ar.mta_contents;
2169                                 (void) mdb_ctf_type_resolve(id, &rid);
2170                                 break;
2171                         default:
2172                                 return (1);
2173                         }
2174 
2175                         start = end + 1;
2176                         delim = parse_delimiter(&start);
2177                         break;
2178                 case MEMBER_DELIM_ERR:
2179                 default:
2180                         break;
2181                 }
2182 
2183                 for (end = start + 1; isalnum(*end) || *end == '_'; end++)
2184                         continue;
2185 
2186                 (void) mdb_snprintf(member, end - start + 1, start);
2187 
2188                 /*
2189                  * We are going to try to resolve this name as a member. There
2190                  * are a few two different questions that we need to answer. The
2191                  * first is do we recognize this member. The second is are we at
2192                  * the end of the string. If we encounter a member that we don't
2193                  * recognize before the end, then we have to error out and can't
2194                  * complete it. But if there are no more delimiters then we can
2195                  * try and complete it.
2196                  */
2197                 ret = mdb_ctf_member_info(rid, member, &dul, &id);
2198                 start = end;
2199                 delim = parse_delimiter(&start);
2200                 if (ret != 0 && errno == EMDB_CTFNOMEMB) {
2201                         if (delim != MEMBER_DELIM_DONE)
2202                                 return (1);
2203                         continue;
2204                 } else if (ret != 0)
2205                         return (1);
2206 
2207                 if (delim == MEMBER_DELIM_DONE)
2208                         return (mdb_tab_complete_member_by_id(mcp, rid,
2209                             member));
2210 
2211                 (void) mdb_ctf_type_resolve(id, &rid);
2212         }
2213 
2214         /*
2215          * If we've reached here, then we need to try and tab complete the last
2216          * field, which is currently member, based on the ctf type id that we
2217          * already have in rid.
2218          */
2219         return (mdb_tab_complete_member_by_id(mcp, rid, member));
2220 }
2221 
2222 /*
2223  * Recursively descend a print a given data structure.  We create a struct of
2224  * the relevant print arguments and then call mdb_ctf_type_visit() to do the
2225  * traversal, using elt_print() as the callback for each element.
2226  */
2227 /*ARGSUSED*/
2228 int
2229 cmd_print(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2230 {
2231         uintptr_t opt_c = MDB_ARR_NOLIMIT, opt_l = MDB_ARR_NOLIMIT;
2232         uint_t opt_C = FALSE, opt_L = FALSE, opt_p = FALSE, opt_i = FALSE;
2233         uintptr_t opt_s = (uintptr_t)-1ul;
2234         int uflags = (flags & DCMD_ADDRSPEC) ? PA_SHOWVAL : 0;
2235         mdb_ctf_id_t id;
2236         int err = DCMD_OK;
2237 
2238         mdb_tgt_t *t = mdb.m_target;
2239         printarg_t pa;
2240         int d, i;
2241 
2242         char s_name[MDB_SYM_NAMLEN];
2243         mdb_syminfo_t s_info;
2244         GElf_Sym sym;
2245 
2246         /*
2247          * If a new option is added, make sure the getopts above in
2248          * cmd_print_tab is also updated.
2249          */
2250         i = mdb_getopts(argc, argv,
2251             'a', MDB_OPT_SETBITS, PA_SHOWADDR, &uflags,
2252             'C', MDB_OPT_SETBITS, TRUE, &opt_C,
2253             'c', MDB_OPT_UINTPTR, &opt_c,
2254             'd', MDB_OPT_SETBITS, PA_INTDEC, &uflags,
2255             'h', MDB_OPT_SETBITS, PA_SHOWHOLES, &uflags,
2256             'i', MDB_OPT_SETBITS, TRUE, &opt_i,
2257             'L', MDB_OPT_SETBITS, TRUE, &opt_L,
2258             'l', MDB_OPT_UINTPTR, &opt_l,
2259             'n', MDB_OPT_SETBITS, PA_NOSYMBOLIC, &uflags,
2260             'p', MDB_OPT_SETBITS, TRUE, &opt_p,
2261             's', MDB_OPT_UINTPTR, &opt_s,
2262             'T', MDB_OPT_SETBITS, PA_SHOWTYPE | PA_SHOWBASETYPE, &uflags,
2263             't', MDB_OPT_SETBITS, PA_SHOWTYPE, &uflags,
2264             'x', MDB_OPT_SETBITS, PA_INTHEX, &uflags,
2265             NULL);
2266 
2267         if (uflags & PA_INTHEX)
2268                 uflags &= ~PA_INTDEC;       /* -x and -d are mutually exclusive */
2269 
2270         uflags |= PA_SHOWNAME;
2271 
2272         if (opt_p && opt_i) {
2273                 mdb_warn("-p and -i options are incompatible\n");
2274                 return (DCMD_ERR);
2275         }
2276 
2277         argc -= i;
2278         argv += i;
2279 
2280         if (argc != 0 && argv->a_type == MDB_TYPE_STRING) {
2281                 const char *t_name = s_name;
2282                 int ret;
2283 
2284                 if (strchr("+-", argv->a_un.a_str[0]) != NULL)
2285                         return (DCMD_USAGE);
2286 
2287                 if ((ret = args_to_typename(&argc, &argv, s_name,
2288                     sizeof (s_name))) != 0)
2289                         return (ret);
2290 
2291                 if (mdb_ctf_lookup_by_name(t_name, &id) != 0) {
2292                         if (!(flags & DCMD_ADDRSPEC) || opt_i ||
2293                             addr_to_sym(t, addr, s_name, sizeof (s_name),
2294                             &sym, &s_info) == NULL ||
2295                             mdb_ctf_lookup_by_symbol(&sym, &s_info, &id) != 0) {
2296 
2297                                 mdb_warn("failed to look up type %s", t_name);
2298                                 return (DCMD_ABORT);
2299                         }
2300                 } else {
2301                         argc--;
2302                         argv++;
2303                 }
2304 
2305         } else if (!(flags & DCMD_ADDRSPEC) || opt_i) {
2306                 return (DCMD_USAGE);
2307 
2308         } else if (addr_to_sym(t, addr, s_name, sizeof (s_name),
2309             &sym, &s_info) == NULL) {
2310                 mdb_warn("no symbol information for %a", addr);
2311                 return (DCMD_ERR);
2312 
2313         } else if (mdb_ctf_lookup_by_symbol(&sym, &s_info, &id) != 0) {
2314                 mdb_warn("no type data available for %a [%u]", addr,
2315                     s_info.sym_id);
2316                 return (DCMD_ERR);
2317         }
2318 
2319         pa.pa_tgt = mdb.m_target;
2320         pa.pa_realtgt = pa.pa_tgt;
2321         pa.pa_immtgt = NULL;
2322         pa.pa_as = opt_p ? MDB_TGT_AS_PHYS : MDB_TGT_AS_VIRT;
2323         pa.pa_armemlim = mdb.m_armemlim;
2324         pa.pa_arstrlim = mdb.m_arstrlim;
2325         pa.pa_delim = "\n";
2326         pa.pa_flags = uflags;
2327         pa.pa_nest = 0;
2328         pa.pa_tab = 4;
2329         pa.pa_prefix = NULL;
2330         pa.pa_suffix = NULL;
2331         pa.pa_holes = NULL;
2332         pa.pa_nholes = 0;
2333         pa.pa_depth = 0;
2334         pa.pa_maxdepth = opt_s;
2335         pa.pa_nooutdepth = (uint_t)-1;
2336 
2337         if ((flags & DCMD_ADDRSPEC) && !opt_i)
2338                 pa.pa_addr = opt_p ? mdb_get_dot() : addr;
2339         else
2340                 pa.pa_addr = NULL;
2341 
2342         if (opt_i) {
2343                 const char *vargv[2];
2344                 uintmax_t dot = mdb_get_dot();
2345                 size_t outsize = mdb_ctf_type_size(id);
2346                 vargv[0] = (const char *)&dot;
2347                 vargv[1] = (const char *)&outsize;
2348                 pa.pa_immtgt = mdb_tgt_create(mdb_value_tgt_create,
2349                     0, 2, vargv);
2350                 pa.pa_tgt = pa.pa_immtgt;
2351         }
2352 
2353         if (opt_c != MDB_ARR_NOLIMIT)
2354                 pa.pa_arstrlim = opt_c;
2355         if (opt_C)
2356                 pa.pa_arstrlim = MDB_ARR_NOLIMIT;
2357         if (opt_l != MDB_ARR_NOLIMIT)
2358                 pa.pa_armemlim = opt_l;
2359         if (opt_L)
2360                 pa.pa_armemlim = MDB_ARR_NOLIMIT;
2361 
2362         if (argc > 0) {
2363                 for (i = 0; i < argc; i++) {
2364                         mdb_ctf_id_t mid;
2365                         int last_deref;
2366                         ulong_t off;
2367                         int kind;
2368                         char buf[MDB_SYM_NAMLEN];
2369 
2370                         mdb_tgt_t *oldtgt = pa.pa_tgt;
2371                         mdb_tgt_as_t oldas = pa.pa_as;
2372                         mdb_tgt_addr_t oldaddr = pa.pa_addr;
2373 
2374                         if (argv->a_type == MDB_TYPE_STRING) {
2375                                 const char *member = argv[i].a_un.a_str;
2376                                 mdb_ctf_id_t rid;
2377 
2378                                 if (parse_member(&pa, member, id, &mid,
2379                                     &off, &last_deref) != 0) {
2380                                         err = DCMD_ABORT;
2381                                         goto out;
2382                                 }
2383 
2384                                 /*
2385                                  * If the member string ends with a "[0]"
2386                                  * (last_deref * is true) and the type is a
2387                                  * structure or union, * print "->" rather
2388                                  * than "[0]." in elt_print.
2389                                  */
2390                                 (void) mdb_ctf_type_resolve(mid, &rid);
2391                                 kind = mdb_ctf_type_kind(rid);
2392                                 if (last_deref && IS_SOU(kind)) {
2393                                         char *end;
2394                                         (void) mdb_snprintf(buf, sizeof (buf),
2395                                             "%s", member);
2396                                         end = strrchr(buf, '[');
2397                                         *end = '\0';
2398                                         pa.pa_suffix = "->";
2399                                         member = &buf[0];
2400                                 } else if (IS_SOU(kind)) {
2401                                         pa.pa_suffix = ".";
2402                                 } else {
2403                                         pa.pa_suffix = "";
2404                                 }
2405 
2406                                 pa.pa_prefix = member;
2407                         } else {
2408                                 ulong_t moff;
2409 
2410                                 moff = (ulong_t)argv[i].a_un.a_val;
2411 
2412                                 if (mdb_ctf_offset_to_name(id, moff * NBBY,
2413                                     buf, sizeof (buf), 0, &mid, &off) == -1) {
2414                                         mdb_warn("invalid offset %lx\n", moff);
2415                                         err = DCMD_ABORT;
2416                                         goto out;
2417                                 }
2418 
2419                                 pa.pa_prefix = buf;
2420                                 pa.pa_addr += moff - off / NBBY;
2421                                 pa.pa_suffix = strlen(buf) == 0 ? "" : ".";
2422                         }
2423 
2424                         off %= NBBY;
2425                         if (flags & DCMD_PIPE_OUT) {
2426                                 if (pipe_print(mid, off, &pa) != 0) {
2427                                         mdb_warn("failed to print type");
2428                                         err = DCMD_ERR;
2429                                         goto out;
2430                                 }
2431                         } else if (off != 0) {
2432                                 mdb_ctf_id_t base;
2433                                 (void) mdb_ctf_type_resolve(mid, &base);
2434 
2435                                 if (elt_print("", mid, base, off, 0,
2436                                     &pa) != 0) {
2437                                         mdb_warn("failed to print type");
2438                                         err = DCMD_ERR;
2439                                         goto out;
2440                                 }
2441                         } else {
2442                                 if (mdb_ctf_type_visit(mid, elt_print,
2443                                     &pa) == -1) {
2444                                         mdb_warn("failed to print type");
2445                                         err = DCMD_ERR;
2446                                         goto out;
2447                                 }
2448 
2449                                 for (d = pa.pa_depth - 1; d >= 0; d--)
2450                                         print_close_sou(&pa, d);
2451                         }
2452 
2453                         pa.pa_depth = 0;
2454                         pa.pa_tgt = oldtgt;
2455                         pa.pa_as = oldas;
2456                         pa.pa_addr = oldaddr;
2457                         pa.pa_delim = "\n";
2458                 }
2459 
2460         } else if (flags & DCMD_PIPE_OUT) {
2461                 if (pipe_print(id, 0, &pa) != 0) {
2462                         mdb_warn("failed to print type");
2463                         err = DCMD_ERR;
2464                         goto out;
2465                 }
2466         } else {
2467                 if (mdb_ctf_type_visit(id, elt_print, &pa) == -1) {
2468                         mdb_warn("failed to print type");
2469                         err = DCMD_ERR;
2470                         goto out;
2471                 }
2472 
2473                 for (d = pa.pa_depth - 1; d >= 0; d--)
2474                         print_close_sou(&pa, d);
2475         }
2476 
2477         mdb_set_dot(addr + mdb_ctf_type_size(id));
2478         err = DCMD_OK;
2479 out:
2480         if (pa.pa_immtgt)
2481                 mdb_tgt_destroy(pa.pa_immtgt);
2482         return (err);
2483 }
2484 
2485 void
2486 print_help(void)
2487 {
2488         mdb_printf(
2489             "-a         show address of object\n"
2490             "-C         unlimit the length of character arrays\n"
2491             "-c limit   limit the length of character arrays\n"
2492             "-d         output values in decimal\n"
2493             "-h         print holes in structures\n"
2494             "-i         interpret address as data of the given type\n"
2495             "-L         unlimit the length of standard arrays\n"
2496             "-l limit   limit the length of standard arrays\n"
2497             "-n         don't print pointers as symbol offsets\n"
2498             "-p         interpret address as a physical memory address\n"
2499             "-s depth   limit the recursion depth\n"
2500             "-T         show type and <<base type>> of object\n"
2501             "-t         show type of object\n"
2502             "-x         output values in hexadecimal\n"
2503             "\n"
2504             "type may be omitted if the C type of addr can be inferred.\n"
2505             "\n"
2506             "Members may be specified with standard C syntax using the\n"
2507             "array indexing operator \"[index]\", structure member\n"
2508             "operator \".\", or structure pointer operator \"->\".\n"
2509             "\n"
2510             "Offsets must use the $[ expression ] syntax\n");
2511 }
2512 
2513 static int
2514 printf_signed(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt,
2515     boolean_t sign)
2516 {
2517         ssize_t size;
2518         mdb_ctf_id_t base;
2519         ctf_encoding_t e;
2520 
2521         union {
2522                 uint64_t ui8;
2523                 uint32_t ui4;
2524                 uint16_t ui2;
2525                 uint8_t ui1;
2526                 int64_t i8;
2527                 int32_t i4;
2528                 int16_t i2;
2529                 int8_t i1;
2530         } u;
2531 
2532         if (mdb_ctf_type_resolve(id, &base) == -1) {
2533                 mdb_warn("could not resolve type");
2534                 return (DCMD_ABORT);
2535         }
2536 
2537         if (mdb_ctf_type_kind(base) != CTF_K_INTEGER) {
2538                 mdb_warn("expected integer type\n");
2539                 return (DCMD_ABORT);
2540         }
2541 
2542         if (mdb_ctf_type_encoding(base, &e) != 0) {
2543                 mdb_warn("could not get type encoding");
2544                 return (DCMD_ABORT);
2545         }
2546 
2547         if (sign)
2548                 sign = e.cte_format & CTF_INT_SIGNED;
2549 
2550         size = e.cte_bits / NBBY;
2551 
2552         /*
2553          * Check to see if our life has been complicated by the presence of
2554          * a bitfield.  If it has, we will print it using logic that is only
2555          * slightly different than that found in print_bitfield(), above.  (In
2556          * particular, see the comments there for an explanation of the
2557          * endianness differences in this code.)
2558          */
2559         if (size > 8 || (e.cte_bits % NBBY) != 0 ||
2560             (size & (size - 1)) != 0) {
2561                 uint64_t mask = (1ULL << e.cte_bits) - 1;
2562                 uint64_t value = 0;
2563                 uint8_t *buf = (uint8_t *)&value;
2564                 uint8_t shift;
2565 
2566                 /*
2567                  * Round our size up one byte.
2568                  */
2569                 size = (e.cte_bits + (NBBY - 1)) / NBBY;
2570 
2571                 if (e.cte_bits > sizeof (value) * NBBY - 1) {
2572                         mdb_printf("invalid bitfield size %u", e.cte_bits);
2573                         return (DCMD_ABORT);
2574                 }
2575 
2576 #ifdef _BIG_ENDIAN
2577                 buf += sizeof (value) - size;
2578                 off += e.cte_bits;
2579 #endif
2580 
2581                 if (mdb_vread(buf, size, addr) == -1) {
2582                         mdb_warn("failed to read %lu bytes at %p", size, addr);
2583                         return (DCMD_ERR);
2584                 }
2585 
2586                 shift = off % NBBY;
2587 #ifdef _BIG_ENDIAN
2588                 shift = NBBY - shift;
2589 #endif
2590 
2591                 /*
2592                  * If we have a bit offset within the byte, shift it down.
2593                  */
2594                 if (off % NBBY != 0)
2595                         value >>= shift;
2596                 value &= mask;
2597 
2598                 if (sign) {
2599                         int sshift = sizeof (value) * NBBY - e.cte_bits;
2600                         value = ((int64_t)value << sshift) >> sshift;
2601                 }
2602 
2603                 mdb_printf(fmt, value);
2604                 return (0);
2605         }
2606 
2607         if (mdb_vread(&u.i8, size, addr) == -1) {
2608                 mdb_warn("failed to read %lu bytes at %p", (ulong_t)size, addr);
2609                 return (DCMD_ERR);
2610         }
2611 
2612         switch (size) {
2613         case sizeof (uint8_t):
2614                 mdb_printf(fmt, (uint64_t)(sign ? u.i1 : u.ui1));
2615                 break;
2616         case sizeof (uint16_t):
2617                 mdb_printf(fmt, (uint64_t)(sign ? u.i2 : u.ui2));
2618                 break;
2619         case sizeof (uint32_t):
2620                 mdb_printf(fmt, (uint64_t)(sign ? u.i4 : u.ui4));
2621                 break;
2622         case sizeof (uint64_t):
2623                 mdb_printf(fmt, (uint64_t)(sign ? u.i8 : u.ui8));
2624                 break;
2625         }
2626 
2627         return (0);
2628 }
2629 
2630 static int
2631 printf_int(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2632 {
2633         return (printf_signed(id, addr, off, fmt, B_TRUE));
2634 }
2635 
2636 static int
2637 printf_uint(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2638 {
2639         return (printf_signed(id, addr, off, fmt, B_FALSE));
2640 }
2641 
2642 /*ARGSUSED*/
2643 static int
2644 printf_uint32(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2645 {
2646         mdb_ctf_id_t base;
2647         ctf_encoding_t e;
2648         uint32_t value;
2649 
2650         if (mdb_ctf_type_resolve(id, &base) == -1) {
2651                 mdb_warn("could not resolve type\n");
2652                 return (DCMD_ABORT);
2653         }
2654 
2655         if (mdb_ctf_type_kind(base) != CTF_K_INTEGER ||
2656             mdb_ctf_type_encoding(base, &e) != 0 ||
2657             e.cte_bits / NBBY != sizeof (value)) {
2658                 mdb_warn("expected 32-bit integer type\n");
2659                 return (DCMD_ABORT);
2660         }
2661 
2662         if (mdb_vread(&value, sizeof (value), addr) == -1) {
2663                 mdb_warn("failed to read 32-bit value at %p", addr);
2664                 return (DCMD_ERR);
2665         }
2666 
2667         mdb_printf(fmt, value);
2668 
2669         return (0);
2670 }
2671 
2672 /*ARGSUSED*/
2673 static int
2674 printf_ptr(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2675 {
2676         uintptr_t value;
2677         mdb_ctf_id_t base;
2678 
2679         if (mdb_ctf_type_resolve(id, &base) == -1) {
2680                 mdb_warn("could not resolve type\n");
2681                 return (DCMD_ABORT);
2682         }
2683 
2684         if (mdb_ctf_type_kind(base) != CTF_K_POINTER) {
2685                 mdb_warn("expected pointer type\n");
2686                 return (DCMD_ABORT);
2687         }
2688 
2689         if (mdb_vread(&value, sizeof (value), addr) == -1) {
2690                 mdb_warn("failed to read pointer at %llx", addr);
2691                 return (DCMD_ERR);
2692         }
2693 
2694         mdb_printf(fmt, value);
2695 
2696         return (0);
2697 }
2698 
2699 /*ARGSUSED*/
2700 static int
2701 printf_string(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2702 {
2703         mdb_ctf_id_t base;
2704         mdb_ctf_arinfo_t r;
2705         char buf[1024];
2706         ssize_t size;
2707 
2708         if (mdb_ctf_type_resolve(id, &base) == -1) {
2709                 mdb_warn("could not resolve type");
2710                 return (DCMD_ABORT);
2711         }
2712 
2713         if (mdb_ctf_type_kind(base) == CTF_K_POINTER) {
2714                 uintptr_t value;
2715 
2716                 if (mdb_vread(&value, sizeof (value), addr) == -1) {
2717                         mdb_warn("failed to read pointer at %llx", addr);
2718                         return (DCMD_ERR);
2719                 }
2720 
2721                 if (mdb_readstr(buf, sizeof (buf) - 1, value) < 0) {
2722                         mdb_warn("failed to read string at %llx", value);
2723                         return (DCMD_ERR);
2724                 }
2725 
2726                 mdb_printf(fmt, buf);
2727                 return (0);
2728         }
2729 
2730         if (mdb_ctf_type_kind(base) != CTF_K_ARRAY) {
2731                 mdb_warn("exepected pointer or array type\n");
2732                 return (DCMD_ABORT);
2733         }
2734 
2735         if (mdb_ctf_array_info(base, &r) == -1 ||
2736             mdb_ctf_type_resolve(r.mta_contents, &base) == -1 ||
2737             (size = mdb_ctf_type_size(base)) == -1) {
2738                 mdb_warn("can't determine array type");
2739                 return (DCMD_ABORT);
2740         }
2741 
2742         if (size != 1) {
2743                 mdb_warn("string format specifier requires "
2744                     "an array of characters\n");
2745                 return (DCMD_ABORT);
2746         }
2747 
2748         bzero(buf, sizeof (buf));
2749 
2750         if (mdb_vread(buf, MIN(r.mta_nelems, sizeof (buf) - 1), addr) == -1) {
2751                 mdb_warn("failed to read array at %p", addr);
2752                 return (DCMD_ERR);
2753         }
2754 
2755         mdb_printf(fmt, buf);
2756 
2757         return (0);
2758 }
2759 
2760 /*ARGSUSED*/
2761 static int
2762 printf_ipv6(mdb_ctf_id_t id, uintptr_t addr, ulong_t off, char *fmt)
2763 {
2764         mdb_ctf_id_t base;
2765         mdb_ctf_id_t ipv6_type, ipv6_base;
2766         in6_addr_t ipv6;
2767 
2768         if (mdb_ctf_lookup_by_name("in6_addr_t", &ipv6_type) == -1) {
2769                 mdb_warn("could not resolve in6_addr_t type\n");
2770                 return (DCMD_ABORT);
2771         }
2772 
2773         if (mdb_ctf_type_resolve(id, &base) == -1) {
2774                 mdb_warn("could not resolve type\n");
2775                 return (DCMD_ABORT);
2776         }
2777 
2778         if (mdb_ctf_type_resolve(ipv6_type, &ipv6_base) == -1) {
2779                 mdb_warn("could not resolve in6_addr_t type\n");
2780                 return (DCMD_ABORT);
2781         }
2782 
2783         if (mdb_ctf_type_cmp(base, ipv6_base) != 0) {
2784                 mdb_warn("requires argument of type in6_addr_t\n");
2785                 return (DCMD_ABORT);
2786         }
2787 
2788         if (mdb_vread(&ipv6, sizeof (ipv6), addr) == -1) {
2789                 mdb_warn("couldn't read in6_addr_t at %p", addr);
2790                 return (DCMD_ERR);
2791         }
2792 
2793         mdb_printf(fmt, &ipv6);
2794 
2795         return (0);
2796 }
2797 
2798 /*
2799  * To validate the format string specified to ::printf, we run the format
2800  * string through a very simple state machine that restricts us to a subset
2801  * of mdb_printf() functionality.
2802  */
2803 enum {
2804         PRINTF_NOFMT = 1,               /* no current format specifier */
2805         PRINTF_PERC,                    /* processed '%' */
2806         PRINTF_FMT,                     /* processing format specifier */
2807         PRINTF_LEFT,                    /* processed '-', expecting width */
2808         PRINTF_WIDTH,                   /* processing width */
2809         PRINTF_QUES                     /* processed '?', expecting format */
2810 };
2811 
2812 int
2813 cmd_printf(uintptr_t addr, uint_t flags, int argc, const mdb_arg_t *argv)
2814 {
2815         char type[MDB_SYM_NAMLEN];
2816         int i, nfmts = 0, ret;
2817         mdb_ctf_id_t id;
2818         const char *fmt, *member;
2819         char **fmts, *last, *dest, f;
2820         int (**funcs)(mdb_ctf_id_t, uintptr_t, ulong_t, char *);
2821         int state = PRINTF_NOFMT;
2822         printarg_t pa;
2823 
2824         if (!(flags & DCMD_ADDRSPEC))
2825                 return (DCMD_USAGE);
2826 
2827         bzero(&pa, sizeof (pa));
2828         pa.pa_as = MDB_TGT_AS_VIRT;
2829         pa.pa_realtgt = pa.pa_tgt = mdb.m_target;
2830 
2831         if (argc == 0 || argv[0].a_type != MDB_TYPE_STRING) {
2832                 mdb_warn("expected a format string\n");
2833                 return (DCMD_USAGE);
2834         }
2835 
2836         /*
2837          * Our first argument is a format string; rip it apart and run it
2838          * through our state machine to validate that our input is within the
2839          * subset of mdb_printf() format strings that we allow.
2840          */
2841         fmt = argv[0].a_un.a_str;
2842         /*
2843          * 'dest' must be large enough to hold a copy of the format string,
2844          * plus a NUL and up to 2 additional characters for each conversion
2845          * in the format string.  This gives us a bloat factor of 5/2 ~= 3.
2846          *   e.g. "%d" (strlen of 2) --> "%lld\0" (need 5 bytes)
2847          */
2848         dest = mdb_zalloc(strlen(fmt) * 3, UM_SLEEP | UM_GC);
2849         fmts = mdb_zalloc(strlen(fmt) * sizeof (char *), UM_SLEEP | UM_GC);
2850         funcs = mdb_zalloc(strlen(fmt) * sizeof (void *), UM_SLEEP | UM_GC);
2851         last = dest;
2852 
2853         for (i = 0; fmt[i] != '\0'; i++) {
2854                 *dest++ = f = fmt[i];
2855 
2856                 switch (state) {
2857                 case PRINTF_NOFMT:
2858                         state = f == '%' ? PRINTF_PERC : PRINTF_NOFMT;
2859                         break;
2860 
2861                 case PRINTF_PERC:
2862                         state = f == '-' ? PRINTF_LEFT :
2863                             f >= '0' && f <= '9' ? PRINTF_WIDTH :
2864                             f == '?' ? PRINTF_QUES :
2865                             f == '%' ? PRINTF_NOFMT : PRINTF_FMT;
2866                         break;
2867 
2868                 case PRINTF_LEFT:
2869                         state = f >= '0' && f <= '9' ? PRINTF_WIDTH :
2870                             f == '?' ? PRINTF_QUES : PRINTF_FMT;
2871                         break;
2872 
2873                 case PRINTF_WIDTH:
2874                         state = f >= '0' && f <= '9' ? PRINTF_WIDTH :
2875                             PRINTF_FMT;
2876                         break;
2877 
2878                 case PRINTF_QUES:
2879                         state = PRINTF_FMT;
2880                         break;
2881                 }
2882 
2883                 if (state != PRINTF_FMT)
2884                         continue;
2885 
2886                 dest--;
2887 
2888                 /*
2889                  * Now check that we have one of our valid format characters.
2890                  */
2891                 switch (f) {
2892                 case 'a':
2893                 case 'A':
2894                 case 'p':
2895                         funcs[nfmts] = printf_ptr;
2896                         break;
2897 
2898                 case 'd':
2899                 case 'q':
2900                 case 'R':
2901                         funcs[nfmts] = printf_int;
2902                         *dest++ = 'l';
2903                         *dest++ = 'l';
2904                         break;
2905 
2906                 case 'I':
2907                         funcs[nfmts] = printf_uint32;
2908                         break;
2909 
2910                 case 'N':
2911                         funcs[nfmts] = printf_ipv6;
2912                         break;
2913 
2914                 case 'H':
2915                 case 'o':
2916                 case 'r':
2917                 case 'u':
2918                 case 'x':
2919                 case 'X':
2920                         funcs[nfmts] = printf_uint;
2921                         *dest++ = 'l';
2922                         *dest++ = 'l';
2923                         break;
2924 
2925                 case 's':
2926                         funcs[nfmts] = printf_string;
2927                         break;
2928 
2929                 case 'Y':
2930                         funcs[nfmts] = sizeof (time_t) == sizeof (int) ?
2931                             printf_uint32 : printf_uint;
2932                         break;
2933 
2934                 default:
2935                         mdb_warn("illegal format string at or near "
2936                             "'%c' (position %d)\n", f, i + 1);
2937                         return (DCMD_ABORT);
2938                 }
2939 
2940                 *dest++ = f;
2941                 *dest++ = '\0';
2942                 fmts[nfmts++] = last;
2943                 last = dest;
2944                 state = PRINTF_NOFMT;
2945         }
2946 
2947         argc--;
2948         argv++;
2949 
2950         /*
2951          * Now we expect a type name.
2952          */
2953         if ((ret = args_to_typename(&argc, &argv, type, sizeof (type))) != 0)
2954                 return (ret);
2955 
2956         argv++;
2957         argc--;
2958 
2959         if (mdb_ctf_lookup_by_name(type, &id) != 0) {
2960                 mdb_warn("failed to look up type %s", type);
2961                 return (DCMD_ABORT);
2962         }
2963 
2964         if (argc == 0) {
2965                 mdb_warn("at least one member must be specified\n");
2966                 return (DCMD_USAGE);
2967         }
2968 
2969         if (argc != nfmts) {
2970                 mdb_warn("%s format specifiers (found %d, expected %d)\n",
2971                     argc > nfmts ? "missing" : "extra", nfmts, argc);
2972                 return (DCMD_ABORT);
2973         }
2974 
2975         for (i = 0; i < argc; i++) {
2976                 mdb_ctf_id_t mid;
2977                 ulong_t off;
2978                 int ignored;
2979 
2980                 if (argv[i].a_type != MDB_TYPE_STRING) {
2981                         mdb_warn("expected only type member arguments\n");
2982                         return (DCMD_ABORT);
2983                 }
2984 
2985                 if (strcmp((member = argv[i].a_un.a_str), ".") == 0) {
2986                         /*
2987                          * We allow "." to be specified to denote the current
2988                          * value of dot.
2989                          */
2990                         if (funcs[i] != printf_ptr && funcs[i] != printf_uint &&
2991                             funcs[i] != printf_int) {
2992                                 mdb_warn("expected integer or pointer format "
2993                                     "specifier for '.'\n");
2994                                 return (DCMD_ABORT);
2995                         }
2996 
2997                         mdb_printf(fmts[i], mdb_get_dot());
2998                         continue;
2999                 }
3000 
3001                 pa.pa_addr = addr;
3002 
3003                 if (parse_member(&pa, member, id, &mid, &off, &ignored) != 0)
3004                         return (DCMD_ABORT);
3005 
3006                 if ((ret = funcs[i](mid, pa.pa_addr, off, fmts[i])) != 0) {
3007                         mdb_warn("failed to print member '%s'\n", member);
3008                         return (ret);
3009                 }
3010         }
3011 
3012         mdb_printf("%s", last);
3013 
3014         return (DCMD_OK);
3015 }
3016 
3017 static char _mdb_printf_help[] =
3018 "The format string argument is a printf(3C)-like format string that is a\n"
3019 "subset of the format strings supported by mdb_printf().  The type argument\n"
3020 "is the name of a type to be used to interpret the memory referenced by dot.\n"
3021 "The member should either be a field in the specified structure, or the\n"
3022 "special member '.', denoting the value of dot (and treated as a pointer).\n"
3023 "The number of members must match the number of format specifiers in the\n"
3024 "format string.\n"
3025 "\n"
3026 "The following format specifiers are recognized by ::printf:\n"
3027 "\n"
3028 "  %%    Prints the '%' symbol.\n"
3029 "  %a    Prints the member in symbolic form.\n"
3030 "  %d    Prints the member as a decimal integer.  If the member is a signed\n"
3031 "        integer type, the output will be signed.\n"
3032 "  %H    Prints the member as a human-readable size.\n"
3033 "  %I    Prints the member as an IPv4 address (must be 32-bit integer type).\n"
3034 "  %N    Prints the member as an IPv6 address (must be of type in6_addr_t).\n"
3035 "  %o    Prints the member as an unsigned octal integer.\n"
3036 "  %p    Prints the member as a pointer, in hexadecimal.\n"
3037 "  %q    Prints the member in signed octal.  Honk if you ever use this!\n"
3038 "  %r    Prints the member as an unsigned value in the current output radix.\n"
3039 "  %R    Prints the member as a signed value in the current output radix.\n"
3040 "  %s    Prints the member as a string (requires a pointer or an array of\n"
3041 "        characters).\n"
3042 "  %u    Prints the member as an unsigned decimal integer.\n"
3043 "  %x    Prints the member in hexadecimal.\n"
3044 "  %X    Prints the member in hexadecimal, using the characters A-F as the\n"
3045 "        digits for the values 10-15.\n"
3046 "  %Y    Prints the member as a time_t as the string "
3047             "'year month day HH:MM:SS'.\n"
3048 "\n"
3049 "The following field width specifiers are recognized by ::printf:\n"
3050 "\n"
3051 "  %n    Field width is set to the specified decimal value.\n"
3052 "  %?    Field width is set to the maximum width of a hexadecimal pointer\n"
3053 "        value.  This is 8 in an ILP32 environment, and 16 in an LP64\n"
3054 "        environment.\n"
3055 "\n"
3056 "The following flag specifers are recognized by ::printf:\n"
3057 "\n"
3058 "  %-    Left-justify the output within the specified field width.  If the\n"
3059 "        width of the output is less than the specified field width, the\n"
3060 "        output will be padded with blanks on the right-hand side.  Without\n"
3061 "        %-, values are right-justified by default.\n"
3062 "\n"
3063 "  %0    Zero-fill the output field if the output is right-justified and the\n"
3064 "        width of the output is less than the specified field width.  Without\n"
3065 "        %0, right-justified values are prepended with blanks in order to\n"
3066 "        fill the field.\n"
3067 "\n"
3068 "Examples: \n"
3069 "\n"
3070 "  ::walk proc | "
3071         "::printf \"%-6d %s\\n\" proc_t p_pidp->pid_id p_user.u_psargs\n"
3072 "  ::walk thread | "
3073         "::printf \"%?p %3d %a\\n\" kthread_t . t_pri t_startpc\n"
3074 "  ::walk zone | "
3075         "::printf \"%-40s %20s\\n\" zone_t zone_name zone_nodename\n"
3076 "  ::walk ire | "
3077         "::printf \"%Y %I\\n\" ire_t ire_create_time ire_u.ire4_u.ire4_addr\n"
3078 "\n";
3079 
3080 void
3081 printf_help(void)
3082 {
3083         mdb_printf("%s", _mdb_printf_help);
3084 }