xref: /illumos-gate/usr/src/cmd/mdb/common/mdb/mdb_io.c (revision 3c6b90be1d51de874ba4c1f05537c85375b6ab6e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
28  * Copyright (c) 2016 by Delphix. All rights reserved.
29  */
30 
31 /*
32  * MDB uses its own enhanced standard i/o mechanism for all input and output.
33  * This file provides the underpinnings of this mechanism, including the
34  * printf-style formatting code, the output pager, and APIs for raw input
35  * and output.  This mechanism is used throughout the debugger for everything
36  * from simple sprintf and printf-style formatting, to input to the lexer
37  * and parser, to raw file i/o for reading ELF files.  In general, we divide
38  * our i/o implementation into two parts:
39  *
40  * (1) An i/o buffer (mdb_iob_t) provides buffered read or write capabilities,
41  * as well as access to formatting and the ability to invoke a pager.  The
42  * buffer is constructed explicitly for use in either reading or writing; it
43  * may not be used for both simultaneously.
44  *
45  * (2) Each i/o buffer is associated with an underlying i/o backend (mdb_io_t).
46  * The backend provides, through an ops-vector, equivalents for the standard
47  * read, write, lseek, ioctl, and close operations.  In addition, the backend
48  * can provide an IOP_NAME entry point for returning a name for the backend,
49  * IOP_LINK and IOP_UNLINK entry points that are called when the backend is
50  * connected or disconnected from an mdb_iob_t, and an IOP_SETATTR entry point
51  * for manipulating terminal attributes.
52  *
53  * The i/o objects themselves are reference counted so that more than one i/o
54  * buffer may make use of the same i/o backend.  In addition, each buffer
55  * provides the ability to push or pop backends to interpose on input or output
56  * behavior.  We make use of this, for example, to implement interactive
57  * session logging.  Normally, the stdout iob has a backend that is either
58  * file descriptor 1, or a terminal i/o backend associated with the tty.
59  * However, we can push a log i/o backend on top that multiplexes stdout to
60  * the original back-end and another backend that writes to a log file.  The
61  * use of i/o backends is also used for simplifying tasks such as making
62  * lex and yacc read from strings for mdb_eval(), and making our ELF file
63  * processing code read executable "files" from a crash dump via kvm_uread.
64  *
65  * Additionally, the formatting code provides auto-wrap and indent facilities
66  * that are necessary for compatibility with adb macro formatting.  In auto-
67  * wrap mode, the formatting code examines each new chunk of output to determine
68  * if it will fit on the current line.  If not, instead of having the chunk
69  * divided between the current line of output and the next, the auto-wrap
70  * code will automatically output a newline, auto-indent the next line,
71  * and then continue.  Auto-indent is implemented by simply prepending a number
72  * of blanks equal to iob_margin to the start of each line.  The margin is
73  * inserted when the iob is created, and following each flush of the buffer.
74  */
75 
76 #include <sys/types.h>
77 #include <sys/termios.h>
78 #include <stdarg.h>
79 #include <arpa/inet.h>
80 #include <sys/socket.h>
81 
82 #include <mdb/mdb_types.h>
83 #include <mdb/mdb_argvec.h>
84 #include <mdb/mdb_stdlib.h>
85 #include <mdb/mdb_string.h>
86 #include <mdb/mdb_target.h>
87 #include <mdb/mdb_signal.h>
88 #include <mdb/mdb_debug.h>
89 #include <mdb/mdb_io_impl.h>
90 #include <mdb/mdb_modapi.h>
91 #include <mdb/mdb_demangle.h>
92 #include <mdb/mdb_err.h>
93 #include <mdb/mdb_nv.h>
94 #include <mdb/mdb_frame.h>
95 #include <mdb/mdb_lex.h>
96 #include <mdb/mdb.h>
97 
98 /*
99  * Define list of possible integer sizes for conversion routines:
100  */
101 typedef enum {
102 	SZ_SHORT,		/* format %h? */
103 	SZ_INT,			/* format %? */
104 	SZ_LONG,		/* format %l? */
105 	SZ_LONGLONG		/* format %ll? */
106 } intsize_t;
107 
108 /*
109  * The iob snprintf family of functions makes use of a special "sprintf
110  * buffer" i/o backend in order to provide the appropriate snprintf semantics.
111  * This structure is maintained as the backend-specific private storage,
112  * and its use is described in more detail below (see spbuf_write()).
113  */
114 typedef struct {
115 	char *spb_buf;		/* pointer to underlying buffer */
116 	size_t spb_bufsiz;	/* length of underlying buffer */
117 	size_t spb_total;	/* total of all bytes passed via IOP_WRITE */
118 } spbuf_t;
119 
120 /*
121  * Define VA_ARG macro for grabbing the next datum to format for the printf
122  * family of functions.  We use VA_ARG so that we can support two kinds of
123  * argument lists: the va_list type supplied by <stdarg.h> used for printf and
124  * vprintf, and an array of mdb_arg_t structures, which we expect will be
125  * either type STRING or IMMEDIATE.  The vec_arg function takes care of
126  * handling the mdb_arg_t case.
127  */
128 
129 typedef enum {
130 	VAT_VARARGS,		/* va_list is a va_list */
131 	VAT_ARGVEC		/* va_list is a const mdb_arg_t[] in disguise */
132 } vatype_t;
133 
134 typedef struct {
135 	vatype_t val_type;
136 	union {
137 		va_list	_val_valist;
138 		const mdb_arg_t *_val_argv;
139 	} _val_u;
140 } varglist_t;
141 
142 #define	val_valist	_val_u._val_valist
143 #define	val_argv	_val_u._val_argv
144 
145 #define	VA_ARG(ap, type) ((ap->val_type == VAT_VARARGS) ? \
146 	va_arg(ap->val_valist, type) : (type)vec_arg(&ap->val_argv))
147 #define	VA_PTRARG(ap) ((ap->val_type == VAT_VARARGS) ? \
148 	(void *)va_arg(ap->val_valist, uintptr_t) : \
149 	(void *)(uintptr_t)vec_arg(&ap->val_argv))
150 
151 /*
152  * Define macro for converting char constant to Ctrl-char equivalent:
153  */
154 #ifndef CTRL
155 #define	CTRL(c)	((c) & 0x01f)
156 #endif
157 
158 /*
159  * Define macro for determining if we should automatically wrap to the next
160  * line of output, based on the amount of consumed buffer space and the
161  * specified size of the next thing to be inserted (n).
162  */
163 #define	IOB_WRAPNOW(iob, n)	\
164 	(((iob)->iob_flags & MDB_IOB_AUTOWRAP) && ((iob)->iob_nbytes != 0) && \
165 	((n) + (iob)->iob_nbytes > (iob)->iob_cols))
166 
167 /*
168  * Define prompt string and string to erase prompt string for iob_pager
169  * function, which is invoked if the pager is enabled on an i/o buffer
170  * and we're about to print a line which would be the last on the screen.
171  */
172 
173 static const char io_prompt[] = ">> More [<space>, <cr>, q, n, c, a] ? ";
174 static const char io_perase[] = "                                      ";
175 
176 static const char io_pbcksp[] =
177 /*CSTYLED*/
178 "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
179 
180 static const size_t io_promptlen = sizeof (io_prompt) - 1;
181 static const size_t io_peraselen = sizeof (io_perase) - 1;
182 static const size_t io_pbcksplen = sizeof (io_pbcksp) - 1;
183 
184 static ssize_t
185 iob_write(mdb_iob_t *iob, mdb_io_t *io, const void *buf, size_t n)
186 {
187 	ssize_t resid = n;
188 	ssize_t len;
189 
190 	while (resid != 0) {
191 		if ((len = IOP_WRITE(io, buf, resid)) <= 0)
192 			break;
193 
194 		buf = (char *)buf + len;
195 		resid -= len;
196 	}
197 
198 	/*
199 	 * Note that if we had a partial write before an error, we still want
200 	 * to return the fact something was written.  The caller will get an
201 	 * error next time it tries to write anything.
202 	 */
203 	if (resid == n && n != 0) {
204 		iob->iob_flags |= MDB_IOB_ERR;
205 		return (-1);
206 	}
207 
208 	return (n - resid);
209 }
210 
211 static ssize_t
212 iob_read(mdb_iob_t *iob, mdb_io_t *io)
213 {
214 	ssize_t len;
215 
216 	ASSERT(iob->iob_nbytes == 0);
217 	len = IOP_READ(io, iob->iob_buf, iob->iob_bufsiz);
218 	iob->iob_bufp = &iob->iob_buf[0];
219 
220 	switch (len) {
221 	case -1:
222 		iob->iob_flags |= MDB_IOB_ERR;
223 		break;
224 	case 0:
225 		iob->iob_flags |= MDB_IOB_EOF;
226 		break;
227 	default:
228 		iob->iob_nbytes = len;
229 	}
230 
231 	return (len);
232 }
233 
234 /*ARGSUSED*/
235 static void
236 iob_winch(int sig, siginfo_t *sip, ucontext_t *ucp, void *data)
237 {
238 	siglongjmp(*((sigjmp_buf *)data), sig);
239 }
240 
241 static int
242 iob_pager(mdb_iob_t *iob)
243 {
244 	int status = 0;
245 	sigjmp_buf env;
246 	uchar_t c;
247 
248 	mdb_signal_f *termio_winch;
249 	void *termio_data;
250 	size_t old_rows;
251 
252 	if (iob->iob_pgp == NULL || (iob->iob_flags & MDB_IOB_PGCONT))
253 		return (0);
254 
255 	termio_winch = mdb_signal_gethandler(SIGWINCH, &termio_data);
256 	(void) mdb_signal_sethandler(SIGWINCH, iob_winch, &env);
257 
258 	if (sigsetjmp(env, 1) != 0) {
259 		/*
260 		 * Reset the cursor back to column zero before printing a new
261 		 * prompt, since its position is unreliable after a SIGWINCH.
262 		 */
263 		(void) iob_write(iob, iob->iob_pgp, "\r", sizeof (char));
264 		old_rows = iob->iob_rows;
265 
266 		/*
267 		 * If an existing SIGWINCH handler was present, call it.  We
268 		 * expect that this will be termio: the handler will read the
269 		 * new window size, and then resize this iob appropriately.
270 		 */
271 		if (termio_winch != (mdb_signal_f *)NULL)
272 			termio_winch(SIGWINCH, NULL, NULL, termio_data);
273 
274 		/*
275 		 * If the window has increased in size, we treat this like a
276 		 * request to fill out the new remainder of the page.
277 		 */
278 		if (iob->iob_rows > old_rows) {
279 			iob->iob_flags &= ~MDB_IOB_PGSINGLE;
280 			iob->iob_nlines = old_rows;
281 			status = 0;
282 			goto winch;
283 		}
284 	}
285 
286 	(void) iob_write(iob, iob->iob_pgp, io_prompt, io_promptlen);
287 
288 	for (;;) {
289 		if (IOP_READ(iob->iob_pgp, &c, sizeof (c)) != sizeof (c)) {
290 			status = MDB_ERR_PAGER;
291 			break;
292 		}
293 
294 		switch (c) {
295 		case 'N':
296 		case 'n':
297 		case '\n':
298 		case '\r':
299 			iob->iob_flags |= MDB_IOB_PGSINGLE;
300 			goto done;
301 
302 		case CTRL('c'):
303 		case CTRL('\\'):
304 		case 'Q':
305 		case 'q':
306 			mdb_iob_discard(iob);
307 			status = MDB_ERR_PAGER;
308 			goto done;
309 
310 		case 'A':
311 		case 'a':
312 			mdb_iob_discard(iob);
313 			status = MDB_ERR_ABORT;
314 			goto done;
315 
316 		case 'C':
317 		case 'c':
318 			iob->iob_flags |= MDB_IOB_PGCONT;
319 			/*FALLTHRU*/
320 
321 		case ' ':
322 			iob->iob_flags &= ~MDB_IOB_PGSINGLE;
323 			goto done;
324 		}
325 	}
326 
327 done:
328 	(void) iob_write(iob, iob->iob_pgp, io_pbcksp, io_pbcksplen);
329 winch:
330 	(void) iob_write(iob, iob->iob_pgp, io_perase, io_peraselen);
331 	(void) iob_write(iob, iob->iob_pgp, io_pbcksp, io_pbcksplen);
332 	(void) mdb_signal_sethandler(SIGWINCH, termio_winch, termio_data);
333 
334 	if ((iob->iob_flags & MDB_IOB_ERR) && status == 0)
335 		status = MDB_ERR_OUTPUT;
336 
337 	return (status);
338 }
339 
340 static void
341 iob_indent(mdb_iob_t *iob)
342 {
343 	if (iob->iob_nbytes == 0 && iob->iob_margin != 0 &&
344 	    (iob->iob_flags & MDB_IOB_INDENT)) {
345 		size_t i;
346 
347 		ASSERT(iob->iob_margin < iob->iob_cols);
348 		ASSERT(iob->iob_bufp == iob->iob_buf);
349 
350 		for (i = 0; i < iob->iob_margin; i++)
351 			*iob->iob_bufp++ = ' ';
352 
353 		iob->iob_nbytes = iob->iob_margin;
354 	}
355 }
356 
357 static void
358 iob_unindent(mdb_iob_t *iob)
359 {
360 	if (iob->iob_nbytes != 0 && iob->iob_nbytes == iob->iob_margin) {
361 		const char *p = iob->iob_buf;
362 
363 		while (p < &iob->iob_buf[iob->iob_margin]) {
364 			if (*p++ != ' ')
365 				return;
366 		}
367 
368 		iob->iob_bufp = &iob->iob_buf[0];
369 		iob->iob_nbytes = 0;
370 	}
371 }
372 
373 mdb_iob_t *
374 mdb_iob_create(mdb_io_t *io, uint_t flags)
375 {
376 	mdb_iob_t *iob = mdb_alloc(sizeof (mdb_iob_t), UM_SLEEP);
377 
378 	iob->iob_buf = mdb_alloc(BUFSIZ, UM_SLEEP);
379 	iob->iob_bufsiz = BUFSIZ;
380 	iob->iob_bufp = &iob->iob_buf[0];
381 	iob->iob_nbytes = 0;
382 	iob->iob_nlines = 0;
383 	iob->iob_lineno = 1;
384 	iob->iob_rows = MDB_IOB_DEFROWS;
385 	iob->iob_cols = MDB_IOB_DEFCOLS;
386 	iob->iob_tabstop = MDB_IOB_DEFTAB;
387 	iob->iob_margin = MDB_IOB_DEFMARGIN;
388 	iob->iob_flags = flags & ~(MDB_IOB_EOF|MDB_IOB_ERR) | MDB_IOB_AUTOWRAP;
389 	iob->iob_iop = mdb_io_hold(io);
390 	iob->iob_pgp = NULL;
391 	iob->iob_next = NULL;
392 
393 	IOP_LINK(io, iob);
394 	iob_indent(iob);
395 	return (iob);
396 }
397 
398 void
399 mdb_iob_pipe(mdb_iob_t **iobs, mdb_iobsvc_f *rdsvc, mdb_iobsvc_f *wrsvc)
400 {
401 	mdb_io_t *pio = mdb_pipeio_create(rdsvc, wrsvc);
402 	int i;
403 
404 	iobs[0] = mdb_iob_create(pio, MDB_IOB_RDONLY);
405 	iobs[1] = mdb_iob_create(pio, MDB_IOB_WRONLY);
406 
407 	for (i = 0; i < 2; i++) {
408 		iobs[i]->iob_flags &= ~MDB_IOB_AUTOWRAP;
409 		iobs[i]->iob_cols = iobs[i]->iob_bufsiz;
410 	}
411 }
412 
413 void
414 mdb_iob_destroy(mdb_iob_t *iob)
415 {
416 	/*
417 	 * Don't flush a pipe, since it may cause a context swith when the
418 	 * other side has already been destroyed.
419 	 */
420 	if (!mdb_iob_isapipe(iob))
421 		mdb_iob_flush(iob);
422 
423 	if (iob->iob_pgp != NULL)
424 		mdb_io_rele(iob->iob_pgp);
425 
426 	while (iob->iob_iop != NULL) {
427 		IOP_UNLINK(iob->iob_iop, iob);
428 		(void) mdb_iob_pop_io(iob);
429 	}
430 
431 	mdb_free(iob->iob_buf, iob->iob_bufsiz);
432 	mdb_free(iob, sizeof (mdb_iob_t));
433 }
434 
435 void
436 mdb_iob_discard(mdb_iob_t *iob)
437 {
438 	iob->iob_bufp = &iob->iob_buf[0];
439 	iob->iob_nbytes = 0;
440 }
441 
442 void
443 mdb_iob_flush(mdb_iob_t *iob)
444 {
445 	int pgerr = 0;
446 
447 	if (iob->iob_nbytes == 0)
448 		return; /* Nothing to do if buffer is empty */
449 
450 	if (iob->iob_flags & MDB_IOB_WRONLY) {
451 		if (iob->iob_flags & MDB_IOB_PGSINGLE) {
452 			iob->iob_flags &= ~MDB_IOB_PGSINGLE;
453 			iob->iob_nlines = 0;
454 			pgerr = iob_pager(iob);
455 
456 		} else if (iob->iob_nlines >= iob->iob_rows - 1) {
457 			iob->iob_nlines = 0;
458 			if (iob->iob_flags & MDB_IOB_PGENABLE)
459 				pgerr = iob_pager(iob);
460 		}
461 
462 		if (pgerr == 0) {
463 			/*
464 			 * We only jump out of the dcmd on error if the iob is
465 			 * m_out. Presumably, if a dcmd has opened a special
466 			 * file and is writing to it, it will handle errors
467 			 * properly.
468 			 */
469 			if (iob_write(iob, iob->iob_iop, iob->iob_buf,
470 			    iob->iob_nbytes) < 0 && iob == mdb.m_out)
471 				pgerr = MDB_ERR_OUTPUT;
472 			iob->iob_nlines++;
473 		}
474 	}
475 
476 	iob->iob_bufp = &iob->iob_buf[0];
477 	iob->iob_nbytes = 0;
478 	iob_indent(iob);
479 
480 	if (pgerr)
481 		longjmp(mdb.m_frame->f_pcb, pgerr);
482 }
483 
484 void
485 mdb_iob_nlflush(mdb_iob_t *iob)
486 {
487 	iob_unindent(iob);
488 
489 	if (iob->iob_nbytes != 0)
490 		mdb_iob_nl(iob);
491 	else
492 		iob_indent(iob);
493 }
494 
495 void
496 mdb_iob_push_io(mdb_iob_t *iob, mdb_io_t *io)
497 {
498 	ASSERT(io->io_next == NULL);
499 
500 	io->io_next = iob->iob_iop;
501 	iob->iob_iop = mdb_io_hold(io);
502 }
503 
504 mdb_io_t *
505 mdb_iob_pop_io(mdb_iob_t *iob)
506 {
507 	mdb_io_t *io = iob->iob_iop;
508 
509 	if (io != NULL) {
510 		iob->iob_iop = io->io_next;
511 		io->io_next = NULL;
512 		mdb_io_rele(io);
513 	}
514 
515 	return (io);
516 }
517 
518 void
519 mdb_iob_resize(mdb_iob_t *iob, size_t rows, size_t cols)
520 {
521 	if (cols > iob->iob_bufsiz)
522 		iob->iob_cols = iob->iob_bufsiz;
523 	else
524 		iob->iob_cols = cols != 0 ? cols : MDB_IOB_DEFCOLS;
525 
526 	iob->iob_rows = rows != 0 ? rows : MDB_IOB_DEFROWS;
527 }
528 
529 void
530 mdb_iob_setpager(mdb_iob_t *iob, mdb_io_t *pgio)
531 {
532 	struct winsize winsz;
533 
534 	if (iob->iob_pgp != NULL) {
535 		IOP_UNLINK(iob->iob_pgp, iob);
536 		mdb_io_rele(iob->iob_pgp);
537 	}
538 
539 	iob->iob_flags |= MDB_IOB_PGENABLE;
540 	iob->iob_flags &= ~(MDB_IOB_PGSINGLE | MDB_IOB_PGCONT);
541 	iob->iob_pgp = mdb_io_hold(pgio);
542 
543 	IOP_LINK(iob->iob_pgp, iob);
544 
545 	if (IOP_CTL(pgio, TIOCGWINSZ, &winsz) == 0)
546 		mdb_iob_resize(iob, (size_t)winsz.ws_row, (size_t)winsz.ws_col);
547 }
548 
549 void
550 mdb_iob_tabstop(mdb_iob_t *iob, size_t tabstop)
551 {
552 	iob->iob_tabstop = MIN(tabstop, iob->iob_cols - 1);
553 }
554 
555 void
556 mdb_iob_margin(mdb_iob_t *iob, size_t margin)
557 {
558 	iob_unindent(iob);
559 	iob->iob_margin = MIN(margin, iob->iob_cols - 1);
560 	iob_indent(iob);
561 }
562 
563 void
564 mdb_iob_setbuf(mdb_iob_t *iob, void *buf, size_t bufsiz)
565 {
566 	ASSERT(buf != NULL && bufsiz != 0);
567 
568 	mdb_free(iob->iob_buf, iob->iob_bufsiz);
569 	iob->iob_buf = buf;
570 	iob->iob_bufsiz = bufsiz;
571 
572 	if (iob->iob_flags & MDB_IOB_WRONLY)
573 		iob->iob_cols = MIN(iob->iob_cols, iob->iob_bufsiz);
574 }
575 
576 void
577 mdb_iob_clearlines(mdb_iob_t *iob)
578 {
579 	iob->iob_flags &= ~(MDB_IOB_PGSINGLE | MDB_IOB_PGCONT);
580 	iob->iob_nlines = 0;
581 }
582 
583 void
584 mdb_iob_setflags(mdb_iob_t *iob, uint_t flags)
585 {
586 	iob->iob_flags |= flags;
587 	if (flags & MDB_IOB_INDENT)
588 		iob_indent(iob);
589 }
590 
591 void
592 mdb_iob_clrflags(mdb_iob_t *iob, uint_t flags)
593 {
594 	iob->iob_flags &= ~flags;
595 	if (flags & MDB_IOB_INDENT)
596 		iob_unindent(iob);
597 }
598 
599 uint_t
600 mdb_iob_getflags(mdb_iob_t *iob)
601 {
602 	return (iob->iob_flags);
603 }
604 
605 static uintmax_t
606 vec_arg(const mdb_arg_t **app)
607 {
608 	uintmax_t value;
609 
610 	if ((*app)->a_type == MDB_TYPE_STRING)
611 		value = (uintmax_t)(uintptr_t)(*app)->a_un.a_str;
612 	else
613 		value = (*app)->a_un.a_val;
614 
615 	(*app)++;
616 	return (value);
617 }
618 
619 static const char *
620 iob_size2str(intsize_t size)
621 {
622 	switch (size) {
623 	case SZ_SHORT:
624 		return ("short");
625 	case SZ_INT:
626 		return ("int");
627 	case SZ_LONG:
628 		return ("long");
629 	case SZ_LONGLONG:
630 		return ("long long");
631 	}
632 	return ("");
633 }
634 
635 /*
636  * In order to simplify maintenance of the ::formats display, we provide an
637  * unparser for mdb_printf format strings that converts a simple format
638  * string with one specifier into a descriptive representation, e.g.
639  * mdb_iob_format2str("%llx") returns "hexadecimal long long".
640  */
641 const char *
642 mdb_iob_format2str(const char *format)
643 {
644 	intsize_t size = SZ_INT;
645 	const char *p;
646 
647 	static char buf[64];
648 
649 	buf[0] = '\0';
650 
651 	if ((p = strchr(format, '%')) == NULL)
652 		goto done;
653 
654 fmt_switch:
655 	switch (*++p) {
656 	case '0': case '1': case '2': case '3': case '4':
657 	case '5': case '6': case '7': case '8': case '9':
658 		while (*p >= '0' && *p <= '9')
659 			p++;
660 		p--;
661 		goto fmt_switch;
662 
663 	case 'a':
664 	case 'A':
665 		return ("symbol");
666 
667 	case 'b':
668 		(void) strcpy(buf, "unsigned ");
669 		(void) strcat(buf, iob_size2str(size));
670 		(void) strcat(buf, " bitfield");
671 		break;
672 
673 	case 'c':
674 		return ("character");
675 
676 	case 'd':
677 	case 'i':
678 		(void) strcpy(buf, "decimal signed ");
679 		(void) strcat(buf, iob_size2str(size));
680 		break;
681 
682 	case 'e':
683 	case 'E':
684 	case 'g':
685 	case 'G':
686 		return ("double");
687 
688 	case 'h':
689 		size = SZ_SHORT;
690 		goto fmt_switch;
691 
692 	case 'H':
693 		return ("human-readable size");
694 
695 	case 'I':
696 		return ("IPv4 address");
697 
698 	case 'l':
699 		if (size >= SZ_LONG)
700 			size = SZ_LONGLONG;
701 		else
702 			size = SZ_LONG;
703 		goto fmt_switch;
704 
705 	case 'm':
706 		return ("margin");
707 
708 	case 'N':
709 		return ("IPv6 address");
710 
711 	case 'o':
712 		(void) strcpy(buf, "octal unsigned ");
713 		(void) strcat(buf, iob_size2str(size));
714 		break;
715 
716 	case 'p':
717 		return ("pointer");
718 
719 	case 'q':
720 		(void) strcpy(buf, "octal signed ");
721 		(void) strcat(buf, iob_size2str(size));
722 		break;
723 
724 	case 'r':
725 		(void) strcpy(buf, "default radix unsigned ");
726 		(void) strcat(buf, iob_size2str(size));
727 		break;
728 
729 	case 'R':
730 		(void) strcpy(buf, "default radix signed ");
731 		(void) strcat(buf, iob_size2str(size));
732 		break;
733 
734 	case 's':
735 		return ("string");
736 
737 	case 't':
738 	case 'T':
739 		return ("tab");
740 
741 	case 'u':
742 		(void) strcpy(buf, "decimal unsigned ");
743 		(void) strcat(buf, iob_size2str(size));
744 		break;
745 
746 	case 'x':
747 	case 'X':
748 		(void) strcat(buf, "hexadecimal ");
749 		(void) strcat(buf, iob_size2str(size));
750 		break;
751 
752 	case 'Y':
753 		return ("time_t");
754 
755 	case '<':
756 		return ("terminal attribute");
757 
758 	case '?':
759 	case '#':
760 	case '+':
761 	case '-':
762 		goto fmt_switch;
763 	}
764 
765 done:
766 	if (buf[0] == '\0')
767 		(void) strcpy(buf, "text");
768 
769 	return ((const char *)buf);
770 }
771 
772 static const char *
773 iob_int2str(varglist_t *ap, intsize_t size, int base, uint_t flags, int *zero,
774     u_longlong_t *value)
775 {
776 	uintmax_t i;
777 
778 	switch (size) {
779 	case SZ_LONGLONG:
780 		if (flags & NTOS_UNSIGNED)
781 			i = (u_longlong_t)VA_ARG(ap, u_longlong_t);
782 		else
783 			i = (longlong_t)VA_ARG(ap, longlong_t);
784 		break;
785 
786 	case SZ_LONG:
787 		if (flags & NTOS_UNSIGNED)
788 			i = (ulong_t)VA_ARG(ap, ulong_t);
789 		else
790 			i = (long)VA_ARG(ap, long);
791 		break;
792 
793 	case SZ_SHORT:
794 		if (flags & NTOS_UNSIGNED)
795 			i = (ushort_t)VA_ARG(ap, uint_t);
796 		else
797 			i = (short)VA_ARG(ap, int);
798 		break;
799 
800 	default:
801 		if (flags & NTOS_UNSIGNED)
802 			i = (uint_t)VA_ARG(ap, uint_t);
803 		else
804 			i = (int)VA_ARG(ap, int);
805 	}
806 
807 	*zero = i == 0;	/* Return flag indicating if result was zero */
808 	*value = i;	/* Return value retrieved from va_list */
809 
810 	return (numtostr(i, base, flags));
811 }
812 
813 static const char *
814 iob_time2str(time_t *tmp)
815 {
816 	/*
817 	 * ctime(3c) returns a string of the form
818 	 * "Fri Sep 13 00:00:00 1986\n\0".  We turn this into the canonical
819 	 * adb /y format "1986 Sep 13 00:00:00" below.
820 	 */
821 	const char *src = ctime(tmp);
822 	static char buf[32];
823 	char *dst = buf;
824 	int i;
825 
826 	if (src == NULL)
827 		return (numtostr((uintmax_t)*tmp, mdb.m_radix, 0));
828 
829 	for (i = 20; i < 24; i++)
830 		*dst++ = src[i]; /* Copy the 4-digit year */
831 
832 	for (i = 3; i < 19; i++)
833 		*dst++ = src[i]; /* Copy month, day, and h:m:s */
834 
835 	*dst = '\0';
836 	return (buf);
837 }
838 
839 static const char *
840 iob_addr2str(uintptr_t addr)
841 {
842 	static char buf[MDB_TGT_SYM_NAMLEN];
843 	char *name = buf;
844 	longlong_t offset;
845 	GElf_Sym sym;
846 
847 	if (mdb_tgt_lookup_by_addr(mdb.m_target, addr,
848 	    MDB_TGT_SYM_FUZZY, buf, sizeof (buf), &sym, NULL) == -1)
849 		return (NULL);
850 
851 	if (mdb.m_demangler != NULL && (mdb.m_flags & MDB_FL_DEMANGLE))
852 		name = (char *)mdb_dem_convert(mdb.m_demangler, buf);
853 
854 	/*
855 	 * Here we provide a little cooperation between the %a formatting code
856 	 * and the proc target: if the initial address passed to %a is in fact
857 	 * a PLT address, the proc target's lookup_by_addr code will convert
858 	 * this to the PLT destination (a different address).  We do not want
859 	 * to append a "+/-offset" suffix based on comparison with the query
860 	 * symbol in this case because the proc target has really done a hidden
861 	 * query for us with a different address.  We detect this case by
862 	 * comparing the initial characters of buf to the special PLT= string.
863 	 */
864 	if (sym.st_value != addr && strncmp(name, "PLT=", 4) != 0) {
865 		if (sym.st_value > addr)
866 			offset = -(longlong_t)(sym.st_value - addr);
867 		else
868 			offset = (longlong_t)(addr - sym.st_value);
869 
870 		(void) strcat(name, numtostr(offset, mdb.m_radix,
871 		    NTOS_SIGNPOS | NTOS_SHOWBASE));
872 	}
873 
874 	return (name);
875 }
876 
877 /*
878  * Produce human-readable size, similar in spirit (and identical in output)
879  * to libzfs's zfs_nicenum() -- but made significantly more complicated by
880  * the constraint that we cannot use snprintf() as an implementation detail.
881  * Recall, floating point is verboten in kmdb.
882  */
883 static const char *
884 iob_bytes2str(varglist_t *ap, intsize_t size)
885 {
886 #ifndef _KMDB
887 	const int sigfig = 3;
888 	uint64_t orig;
889 #endif
890 	uint64_t n;
891 
892 	static char buf[68], *c;
893 	int index = 0;
894 	char u;
895 
896 	switch (size) {
897 	case SZ_LONGLONG:
898 		n = (u_longlong_t)VA_ARG(ap, u_longlong_t);
899 		break;
900 
901 	case SZ_LONG:
902 		n = (ulong_t)VA_ARG(ap, ulong_t);
903 		break;
904 
905 	case SZ_SHORT:
906 		n = (ushort_t)VA_ARG(ap, uint_t);
907 
908 	default:
909 		n = (uint_t)VA_ARG(ap, uint_t);
910 	}
911 
912 #ifndef _KMDB
913 	orig = n;
914 #endif
915 
916 	while (n >= 1024) {
917 		n /= 1024;
918 		index++;
919 	}
920 
921 	u = " KMGTPE"[index];
922 	buf[0] = '\0';
923 
924 	if (index == 0) {
925 		return (numtostr(n, 10, 0));
926 #ifndef _KMDB
927 	} else if ((orig & ((1ULL << 10 * index) - 1)) == 0) {
928 #else
929 	} else {
930 #endif
931 		/*
932 		 * If this is an even multiple of the base or we are in an
933 		 * environment where floating point is verboten (i.e., kmdb),
934 		 * always display without any decimal precision.
935 		 */
936 		(void) strcat(buf, numtostr(n, 10, 0));
937 #ifndef _KMDB
938 	} else {
939 		/*
940 		 * We want to choose a precision that results in the specified
941 		 * number of significant figures (by default, 3).  This is
942 		 * similar to the output that one would get specifying the %.*g
943 		 * format specifier (where the asterisk denotes the number of
944 		 * significant digits), but (1) we include trailing zeros if
945 		 * the there are non-zero digits beyond the number of
946 		 * significant digits (that is, 10241 is '10.0K', not the
947 		 * '10K' that it would be with %.3g) and (2) we never resort
948 		 * to %e notation when the number of digits exceeds the
949 		 * number of significant figures (that is, 1043968 is '1020K',
950 		 * not '1.02e+03K').  This is also made somewhat complicated
951 		 * by the fact that we need to deal with rounding (10239 is
952 		 * '10.0K', not '9.99K'), for which we perform nearest-even
953 		 * rounding.
954 		 */
955 		double val = (double)orig / (1ULL << 10 * index);
956 		int i, mag = 1, thresh;
957 
958 		for (i = 0; i < sigfig - 1; i++)
959 			mag *= 10;
960 
961 		for (thresh = mag * 10; mag >= 1; mag /= 10, i--) {
962 			double mult = val * (double)mag;
963 			uint32_t v;
964 
965 			/*
966 			 * Note that we cast mult to a 32-bit value.  We know
967 			 * that val is less than 1024 due to the logic above,
968 			 * and that mag is at most 10^(sigfig - 1).  This means
969 			 * that as long as sigfig is 9 or lower, this will not
970 			 * overflow.  (We perform this cast because it assures
971 			 * that we are never converting a double to a uint64_t,
972 			 * which for some compilers requires a call to a
973 			 * function not guaranteed to be in libstand.)
974 			 */
975 			if (mult - (double)(uint32_t)mult != 0.5) {
976 				v = (uint32_t)(mult + 0.5);
977 			} else {
978 				/*
979 				 * We are exactly between integer multiples
980 				 * of units; perform nearest-even rounding
981 				 * to be consistent with the behavior of
982 				 * printf().
983 				 */
984 				if ((v = (uint32_t)mult) & 1)
985 					v++;
986 			}
987 
988 			if (mag == 1) {
989 				(void) strcat(buf, numtostr(v, 10, 0));
990 				break;
991 			}
992 
993 			if (v < thresh) {
994 				(void) strcat(buf, numtostr(v / mag, 10, 0));
995 				(void) strcat(buf, ".");
996 
997 				c = (char *)numtostr(v % mag, 10, 0);
998 				i -= strlen(c);
999 
1000 				/*
1001 				 * We need to zero-fill from the right of the
1002 				 * decimal point to the first significant digit
1003 				 * of the fractional component.
1004 				 */
1005 				while (i--)
1006 					(void) strcat(buf, "0");
1007 
1008 				(void) strcat(buf, c);
1009 				break;
1010 			}
1011 		}
1012 #endif
1013 	}
1014 
1015 	c = &buf[strlen(buf)];
1016 	*c++ = u;
1017 	*c++ = '\0';
1018 
1019 	return (buf);
1020 }
1021 
1022 static int
1023 iob_setattr(mdb_iob_t *iob, const char *s, size_t nbytes)
1024 {
1025 	uint_t attr;
1026 	int req;
1027 
1028 	if (iob->iob_pgp == NULL)
1029 		return (set_errno(ENOTTY));
1030 
1031 	if (nbytes != 0 && *s == '/') {
1032 		req = ATT_OFF;
1033 		nbytes--;
1034 		s++;
1035 	} else
1036 		req = ATT_ON;
1037 
1038 	if (nbytes != 1)
1039 		return (set_errno(EINVAL));
1040 
1041 	switch (*s) {
1042 	case 's':
1043 		attr = ATT_STANDOUT;
1044 		break;
1045 	case 'u':
1046 		attr = ATT_UNDERLINE;
1047 		break;
1048 	case 'r':
1049 		attr = ATT_REVERSE;
1050 		break;
1051 	case 'b':
1052 		attr = ATT_BOLD;
1053 		break;
1054 	case 'd':
1055 		attr = ATT_DIM;
1056 		break;
1057 	case 'a':
1058 		attr = ATT_ALTCHARSET;
1059 		break;
1060 	default:
1061 		return (set_errno(EINVAL));
1062 	}
1063 
1064 	/*
1065 	 * We need to flush the current buffer contents before calling
1066 	 * IOP_SETATTR because IOP_SETATTR may need to synchronously output
1067 	 * terminal escape sequences directly to the underlying device.
1068 	 */
1069 	(void) iob_write(iob, iob->iob_iop, iob->iob_buf, iob->iob_nbytes);
1070 	iob->iob_bufp = &iob->iob_buf[0];
1071 	iob->iob_nbytes = 0;
1072 
1073 	return (IOP_SETATTR(iob->iob_pgp, req, attr));
1074 }
1075 
1076 static void
1077 iob_bits2str(mdb_iob_t *iob, u_longlong_t value, const mdb_bitmask_t *bmp,
1078     mdb_bool_t altflag)
1079 {
1080 	mdb_bool_t delim = FALSE;
1081 	const char *str;
1082 	size_t width;
1083 
1084 	if (bmp == NULL)
1085 		goto out;
1086 
1087 	for (; bmp->bm_name != NULL; bmp++) {
1088 		if ((value & bmp->bm_mask) == bmp->bm_bits) {
1089 			width = strlen(bmp->bm_name) + delim;
1090 
1091 			if (IOB_WRAPNOW(iob, width))
1092 				mdb_iob_nl(iob);
1093 
1094 			if (delim)
1095 				mdb_iob_putc(iob, ',');
1096 			else
1097 				delim = TRUE;
1098 
1099 			mdb_iob_puts(iob, bmp->bm_name);
1100 			value &= ~bmp->bm_bits;
1101 		}
1102 	}
1103 
1104 out:
1105 	if (altflag == TRUE && (delim == FALSE || value != 0)) {
1106 		str = numtostr(value, 16, NTOS_UNSIGNED | NTOS_SHOWBASE);
1107 		width = strlen(str) + delim;
1108 
1109 		if (IOB_WRAPNOW(iob, width))
1110 			mdb_iob_nl(iob);
1111 		if (delim)
1112 			mdb_iob_putc(iob, ',');
1113 		mdb_iob_puts(iob, str);
1114 	}
1115 }
1116 
1117 static const char *
1118 iob_inaddr2str(uint32_t addr)
1119 {
1120 	static char buf[INET_ADDRSTRLEN];
1121 
1122 	(void) mdb_inet_ntop(AF_INET, &addr, buf, sizeof (buf));
1123 
1124 	return (buf);
1125 }
1126 
1127 static const char *
1128 iob_ipv6addr2str(void *addr)
1129 {
1130 	static char buf[INET6_ADDRSTRLEN];
1131 
1132 	(void) mdb_inet_ntop(AF_INET6, addr, buf, sizeof (buf));
1133 
1134 	return (buf);
1135 }
1136 
1137 static const char *
1138 iob_getvar(const char *s, size_t len)
1139 {
1140 	mdb_var_t *val;
1141 	char *var;
1142 
1143 	if (len == 0) {
1144 		(void) set_errno(EINVAL);
1145 		return (NULL);
1146 	}
1147 
1148 	var = strndup(s, len);
1149 	val = mdb_nv_lookup(&mdb.m_nv, var);
1150 	strfree(var);
1151 
1152 	if (val == NULL) {
1153 		(void) set_errno(EINVAL);
1154 		return (NULL);
1155 	}
1156 
1157 	return (numtostr(mdb_nv_get_value(val), 10, 0));
1158 }
1159 
1160 /*
1161  * The iob_doprnt function forms the main engine of the debugger's output
1162  * formatting capabilities.  Note that this is NOT exactly compatible with
1163  * the printf(3S) family, nor is it intended to be so.  We support some
1164  * extensions and format characters not supported by printf(3S), and we
1165  * explicitly do NOT provide support for %C, %S, %ws (wide-character strings),
1166  * do NOT provide for the complete functionality of %f, %e, %E, %g, %G
1167  * (alternate double formats), and do NOT support %.x (precision specification).
1168  * Note that iob_doprnt consumes varargs off the original va_list.
1169  */
1170 static void
1171 iob_doprnt(mdb_iob_t *iob, const char *format, varglist_t *ap)
1172 {
1173 	char c[2] = { 0, 0 };	/* Buffer for single character output */
1174 	const char *p;		/* Current position in format string */
1175 	size_t len;		/* Length of format string to copy verbatim */
1176 	size_t altlen;		/* Length of alternate print format prefix */
1177 	const char *altstr;	/* Alternate print format prefix */
1178 	const char *symstr;	/* Symbol + offset string */
1179 
1180 	u_longlong_t val;	/* Current integer value */
1181 	intsize_t size;		/* Current integer value size */
1182 	uint_t flags;		/* Current flags to pass to iob_int2str */
1183 	size_t width;		/* Current field width */
1184 	int zero;		/* If != 0, then integer value == 0 */
1185 
1186 	mdb_bool_t f_alt;	/* Use alternate print format (%#) */
1187 	mdb_bool_t f_altsuff;	/* Alternate print format is a suffix */
1188 	mdb_bool_t f_zfill;	/* Zero-fill field (%0) */
1189 	mdb_bool_t f_left;	/* Left-adjust field (%-) */
1190 	mdb_bool_t f_digits;	/* Explicit digits used to set field width */
1191 
1192 	union {
1193 		const char *str;
1194 		uint32_t ui32;
1195 		void *ptr;
1196 		time_t tm;
1197 		char c;
1198 		double d;
1199 		long double ld;
1200 	} u;
1201 
1202 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1203 
1204 	while ((p = strchr(format, '%')) != NULL) {
1205 		/*
1206 		 * Output the format string verbatim up to the next '%' char
1207 		 */
1208 		if (p != format) {
1209 			len = p - format;
1210 			if (IOB_WRAPNOW(iob, len) && *format != '\n')
1211 				mdb_iob_nl(iob);
1212 			mdb_iob_nputs(iob, format, len);
1213 		}
1214 
1215 		/*
1216 		 * Now we need to parse the sequence of format characters
1217 		 * following the % marker and do the appropriate thing.
1218 		 */
1219 		size = SZ_INT;		/* Use normal-sized int by default */
1220 		flags = 0;		/* Clear numtostr() format flags */
1221 		width = 0;		/* No field width limit by default */
1222 		altlen = 0;		/* No alternate format string yet */
1223 		altstr = NULL;		/* No alternate format string yet */
1224 
1225 		f_alt = FALSE;		/* Alternate format off by default */
1226 		f_altsuff = FALSE;	/* Alternate format is a prefix */
1227 		f_zfill = FALSE;	/* Zero-fill off by default */
1228 		f_left = FALSE;		/* Left-adjust off by default */
1229 		f_digits = FALSE;	/* No digits for width specified yet */
1230 
1231 		fmt_switch:
1232 		switch (*++p) {
1233 		case '0': case '1': case '2': case '3': case '4':
1234 		case '5': case '6': case '7': case '8': case '9':
1235 			if (f_digits == FALSE && *p == '0') {
1236 				f_zfill = TRUE;
1237 				goto fmt_switch;
1238 			}
1239 
1240 			if (f_digits == FALSE)
1241 				width = 0; /* clear any other width specifier */
1242 
1243 			for (u.c = *p; u.c >= '0' && u.c <= '9'; u.c = *++p)
1244 				width = width * 10 + u.c - '0';
1245 
1246 			p--;
1247 			f_digits = TRUE;
1248 			goto fmt_switch;
1249 
1250 		case 'a':
1251 			if (size < SZ_LONG)
1252 				size = SZ_LONG;	/* Bump to size of uintptr_t */
1253 
1254 			u.str = iob_int2str(ap, size, 16,
1255 			    NTOS_UNSIGNED | NTOS_SHOWBASE, &zero, &val);
1256 
1257 			if ((symstr = iob_addr2str(val)) != NULL)
1258 				u.str = symstr;
1259 
1260 			if (f_alt == TRUE) {
1261 				f_altsuff = TRUE;
1262 				altstr = ":";
1263 				altlen = 1;
1264 			}
1265 			break;
1266 
1267 		case 'A':
1268 			if (size < SZ_LONG)
1269 				size = SZ_LONG;	/* Bump to size of uintptr_t */
1270 
1271 			(void) iob_int2str(ap, size, 16,
1272 			    NTOS_UNSIGNED, &zero, &val);
1273 
1274 			u.str = iob_addr2str(val);
1275 
1276 			if (f_alt == TRUE && u.str == NULL)
1277 				u.str = "?";
1278 			break;
1279 
1280 		case 'b':
1281 			u.str = iob_int2str(ap, size, 16,
1282 			    NTOS_UNSIGNED | NTOS_SHOWBASE, &zero, &val);
1283 
1284 			iob_bits2str(iob, val, VA_PTRARG(ap), f_alt);
1285 
1286 			format = ++p;
1287 			continue;
1288 
1289 		case 'c':
1290 			c[0] = (char)VA_ARG(ap, int);
1291 			u.str = c;
1292 			break;
1293 
1294 		case 'd':
1295 		case 'i':
1296 			if (f_alt)
1297 				flags |= NTOS_SHOWBASE;
1298 			u.str = iob_int2str(ap, size, 10, flags, &zero, &val);
1299 			break;
1300 
1301 		/* No floating point in kmdb */
1302 #ifndef _KMDB
1303 		case 'e':
1304 		case 'E':
1305 			u.d = VA_ARG(ap, double);
1306 			u.str = doubletos(u.d, 7, *p);
1307 			break;
1308 
1309 		case 'g':
1310 		case 'G':
1311 			if (size >= SZ_LONG) {
1312 				u.ld = VA_ARG(ap, long double);
1313 				u.str = longdoubletos(&u.ld, 16,
1314 				    (*p == 'g') ? 'e' : 'E');
1315 			} else {
1316 				u.d = VA_ARG(ap, double);
1317 				u.str = doubletos(u.d, 16,
1318 				    (*p == 'g') ? 'e' : 'E');
1319 			}
1320 			break;
1321 #endif
1322 
1323 		case 'h':
1324 			size = SZ_SHORT;
1325 			goto fmt_switch;
1326 
1327 		case 'H':
1328 			u.str = iob_bytes2str(ap, size);
1329 			break;
1330 
1331 		case 'I':
1332 			u.ui32 = VA_ARG(ap, uint32_t);
1333 			u.str = iob_inaddr2str(u.ui32);
1334 			break;
1335 
1336 		case 'l':
1337 			if (size >= SZ_LONG)
1338 				size = SZ_LONGLONG;
1339 			else
1340 				size = SZ_LONG;
1341 			goto fmt_switch;
1342 
1343 		case 'm':
1344 			if (iob->iob_nbytes == 0) {
1345 				mdb_iob_ws(iob, (width != 0) ? width :
1346 				    iob->iob_margin);
1347 			}
1348 			format = ++p;
1349 			continue;
1350 
1351 		case 'N':
1352 			u.ptr = VA_PTRARG(ap);
1353 			u.str = iob_ipv6addr2str(u.ptr);
1354 			break;
1355 
1356 		case 'o':
1357 			u.str = iob_int2str(ap, size, 8, NTOS_UNSIGNED,
1358 			    &zero, &val);
1359 
1360 			if (f_alt && !zero) {
1361 				altstr = "0";
1362 				altlen = 1;
1363 			}
1364 			break;
1365 
1366 		case 'p':
1367 			u.ptr = VA_PTRARG(ap);
1368 			u.str = numtostr((uintptr_t)u.ptr, 16, NTOS_UNSIGNED);
1369 			break;
1370 
1371 		case 'q':
1372 			u.str = iob_int2str(ap, size, 8, flags, &zero, &val);
1373 
1374 			if (f_alt && !zero) {
1375 				altstr = "0";
1376 				altlen = 1;
1377 			}
1378 			break;
1379 
1380 		case 'r':
1381 			if (f_alt)
1382 				flags |= NTOS_SHOWBASE;
1383 			u.str = iob_int2str(ap, size, mdb.m_radix,
1384 			    NTOS_UNSIGNED | flags, &zero, &val);
1385 			break;
1386 
1387 		case 'R':
1388 			if (f_alt)
1389 				flags |= NTOS_SHOWBASE;
1390 			u.str = iob_int2str(ap, size, mdb.m_radix, flags,
1391 			    &zero, &val);
1392 			break;
1393 
1394 		case 's':
1395 			u.str = VA_PTRARG(ap);
1396 			if (u.str == NULL)
1397 				u.str = "<NULL>"; /* Be forgiving of NULL */
1398 			break;
1399 
1400 		case 't':
1401 			if (width != 0) {
1402 				while (width-- > 0)
1403 					mdb_iob_tab(iob);
1404 			} else
1405 				mdb_iob_tab(iob);
1406 
1407 			format = ++p;
1408 			continue;
1409 
1410 		case 'T':
1411 			if (width != 0 && (iob->iob_nbytes % width) != 0) {
1412 				size_t ots = iob->iob_tabstop;
1413 				iob->iob_tabstop = width;
1414 				mdb_iob_tab(iob);
1415 				iob->iob_tabstop = ots;
1416 			}
1417 			format = ++p;
1418 			continue;
1419 
1420 		case 'u':
1421 			if (f_alt)
1422 				flags |= NTOS_SHOWBASE;
1423 			u.str = iob_int2str(ap, size, 10,
1424 			    flags | NTOS_UNSIGNED, &zero, &val);
1425 			break;
1426 
1427 		case 'x':
1428 			u.str = iob_int2str(ap, size, 16, NTOS_UNSIGNED,
1429 			    &zero, &val);
1430 
1431 			if (f_alt && !zero) {
1432 				altstr = "0x";
1433 				altlen = 2;
1434 			}
1435 			break;
1436 
1437 		case 'X':
1438 			u.str = iob_int2str(ap, size, 16,
1439 			    NTOS_UNSIGNED | NTOS_UPCASE, &zero, &val);
1440 
1441 			if (f_alt && !zero) {
1442 				altstr = "0X";
1443 				altlen = 2;
1444 			}
1445 			break;
1446 
1447 		case 'Y':
1448 			u.tm = VA_ARG(ap, time_t);
1449 			u.str = iob_time2str(&u.tm);
1450 			break;
1451 
1452 		case '<':
1453 			/*
1454 			 * Used to turn attributes on (<b>), to turn them
1455 			 * off (</b>), or to print variables (<_var>).
1456 			 */
1457 			for (u.str = ++p; *p != '\0' && *p != '>'; p++)
1458 				continue;
1459 
1460 			if (*p == '>') {
1461 				size_t paramlen = p - u.str;
1462 
1463 				if (paramlen > 0) {
1464 					if (*u.str == '_') {
1465 						u.str = iob_getvar(u.str + 1,
1466 						    paramlen - 1);
1467 						break;
1468 					} else {
1469 						(void) iob_setattr(iob, u.str,
1470 						    paramlen);
1471 					}
1472 				}
1473 
1474 				p++;
1475 			}
1476 
1477 			format = p;
1478 			continue;
1479 
1480 		case '*':
1481 			width = (size_t)(uint_t)VA_ARG(ap, int);
1482 			goto fmt_switch;
1483 
1484 		case '%':
1485 			u.str = "%";
1486 			break;
1487 
1488 		case '?':
1489 			width = sizeof (uintptr_t) * 2;
1490 			goto fmt_switch;
1491 
1492 		case '#':
1493 			f_alt = TRUE;
1494 			goto fmt_switch;
1495 
1496 		case '+':
1497 			flags |= NTOS_SIGNPOS;
1498 			goto fmt_switch;
1499 
1500 		case '-':
1501 			f_left = TRUE;
1502 			goto fmt_switch;
1503 
1504 		default:
1505 			c[0] = p[0];
1506 			u.str = c;
1507 		}
1508 
1509 		len = u.str != NULL ? strlen(u.str) : 0;
1510 
1511 		if (len + altlen > width)
1512 			width = len + altlen;
1513 
1514 		/*
1515 		 * If the string and the option altstr won't fit on this line
1516 		 * and auto-wrap is set (default), skip to the next line.
1517 		 * If the string contains \n, and the \n terminated substring
1518 		 * + altstr is shorter than the above, use the shorter lf_len.
1519 		 */
1520 		if (u.str != NULL) {
1521 			char *np = strchr(u.str, '\n');
1522 			if (np != NULL) {
1523 				int lf_len = (np - u.str) + altlen;
1524 				if (lf_len < width)
1525 					width = lf_len;
1526 			}
1527 		}
1528 		if (IOB_WRAPNOW(iob, width))
1529 			mdb_iob_nl(iob);
1530 
1531 		/*
1532 		 * Optionally add whitespace or zeroes prefixing the value if
1533 		 * we haven't filled the minimum width and we're right-aligned.
1534 		 */
1535 		if (len < (width - altlen) && f_left == FALSE) {
1536 			mdb_iob_fill(iob, f_zfill ? '0' : ' ',
1537 			    width - altlen - len);
1538 		}
1539 
1540 		/*
1541 		 * Print the alternate string if it's a prefix, and then
1542 		 * print the value string itself.
1543 		 */
1544 		if (altstr != NULL && f_altsuff == FALSE)
1545 			mdb_iob_nputs(iob, altstr, altlen);
1546 		if (len != 0)
1547 			mdb_iob_nputs(iob, u.str, len);
1548 
1549 		/*
1550 		 * If we have an alternate string and it's a suffix, print it.
1551 		 */
1552 		if (altstr != NULL && f_altsuff == TRUE)
1553 			mdb_iob_nputs(iob, altstr, altlen);
1554 
1555 		/*
1556 		 * Finally, if we haven't filled the field width and we're
1557 		 * left-aligned, pad out the rest with whitespace.
1558 		 */
1559 		if ((len + altlen) < width && f_left == TRUE)
1560 			mdb_iob_ws(iob, width - altlen - len);
1561 
1562 		format = (*p != '\0') ? ++p : p;
1563 	}
1564 
1565 	/*
1566 	 * If there's anything left in the format string, output it now
1567 	 */
1568 	if (*format != '\0') {
1569 		len = strlen(format);
1570 		if (IOB_WRAPNOW(iob, len) && *format != '\n')
1571 			mdb_iob_nl(iob);
1572 		mdb_iob_nputs(iob, format, len);
1573 	}
1574 }
1575 
1576 void
1577 mdb_iob_vprintf(mdb_iob_t *iob, const char *format, va_list alist)
1578 {
1579 	varglist_t ap = { VAT_VARARGS };
1580 	va_copy(ap.val_valist, alist);
1581 	iob_doprnt(iob, format, &ap);
1582 }
1583 
1584 void
1585 mdb_iob_aprintf(mdb_iob_t *iob, const char *format, const mdb_arg_t *argv)
1586 {
1587 	varglist_t ap = { VAT_ARGVEC };
1588 	ap.val_argv = argv;
1589 	iob_doprnt(iob, format, &ap);
1590 }
1591 
1592 void
1593 mdb_iob_printf(mdb_iob_t *iob, const char *format, ...)
1594 {
1595 	va_list alist;
1596 
1597 	va_start(alist, format);
1598 	mdb_iob_vprintf(iob, format, alist);
1599 	va_end(alist);
1600 }
1601 
1602 /*
1603  * In order to handle the sprintf family of functions, we define a special
1604  * i/o backend known as a "sprintf buf" (or spbuf for short).  This back end
1605  * provides an IOP_WRITE entry point that concatenates each buffer sent from
1606  * mdb_iob_flush() onto the caller's buffer until the caller's buffer is
1607  * exhausted.  We also keep an absolute count of how many bytes were sent to
1608  * this function during the lifetime of the snprintf call.  This allows us
1609  * to provide the ability to (1) return the total size required for the given
1610  * format string and argument list, and (2) support a call to snprintf with a
1611  * NULL buffer argument with no special case code elsewhere.
1612  */
1613 static ssize_t
1614 spbuf_write(mdb_io_t *io, const void *buf, size_t buflen)
1615 {
1616 	spbuf_t *spb = io->io_data;
1617 
1618 	if (spb->spb_bufsiz != 0) {
1619 		size_t n = MIN(spb->spb_bufsiz, buflen);
1620 		bcopy(buf, spb->spb_buf, n);
1621 		spb->spb_buf += n;
1622 		spb->spb_bufsiz -= n;
1623 	}
1624 
1625 	spb->spb_total += buflen;
1626 	return (buflen);
1627 }
1628 
1629 static const mdb_io_ops_t spbuf_ops = {
1630 	no_io_read,
1631 	spbuf_write,
1632 	no_io_seek,
1633 	no_io_ctl,
1634 	no_io_close,
1635 	no_io_name,
1636 	no_io_link,
1637 	no_io_unlink,
1638 	no_io_setattr,
1639 	no_io_suspend,
1640 	no_io_resume
1641 };
1642 
1643 /*
1644  * The iob_spb_create function initializes an iob suitable for snprintf calls,
1645  * a spbuf i/o backend, and the spbuf private data, and then glues these
1646  * objects together.  The caller (either vsnprintf or asnprintf below) is
1647  * expected to have allocated the various structures on their stack.
1648  */
1649 static void
1650 iob_spb_create(mdb_iob_t *iob, char *iob_buf, size_t iob_len,
1651     mdb_io_t *io, spbuf_t *spb, char *spb_buf, size_t spb_len)
1652 {
1653 	spb->spb_buf = spb_buf;
1654 	spb->spb_bufsiz = spb_len;
1655 	spb->spb_total = 0;
1656 
1657 	io->io_ops = &spbuf_ops;
1658 	io->io_data = spb;
1659 	io->io_next = NULL;
1660 	io->io_refcnt = 1;
1661 
1662 	iob->iob_buf = iob_buf;
1663 	iob->iob_bufsiz = iob_len;
1664 	iob->iob_bufp = iob_buf;
1665 	iob->iob_nbytes = 0;
1666 	iob->iob_nlines = 0;
1667 	iob->iob_lineno = 1;
1668 	iob->iob_rows = MDB_IOB_DEFROWS;
1669 	iob->iob_cols = iob_len;
1670 	iob->iob_tabstop = MDB_IOB_DEFTAB;
1671 	iob->iob_margin = MDB_IOB_DEFMARGIN;
1672 	iob->iob_flags = MDB_IOB_WRONLY;
1673 	iob->iob_iop = io;
1674 	iob->iob_pgp = NULL;
1675 	iob->iob_next = NULL;
1676 }
1677 
1678 /*ARGSUSED*/
1679 ssize_t
1680 null_io_write(mdb_io_t *io, const void *buf, size_t nbytes)
1681 {
1682 	return (nbytes);
1683 }
1684 
1685 static const mdb_io_ops_t null_ops = {
1686 	no_io_read,
1687 	null_io_write,
1688 	no_io_seek,
1689 	no_io_ctl,
1690 	no_io_close,
1691 	no_io_name,
1692 	no_io_link,
1693 	no_io_unlink,
1694 	no_io_setattr,
1695 	no_io_suspend,
1696 	no_io_resume
1697 };
1698 
1699 mdb_io_t *
1700 mdb_nullio_create(void)
1701 {
1702 	static mdb_io_t null_io = {
1703 		&null_ops,
1704 		NULL,
1705 		NULL,
1706 		1
1707 	};
1708 
1709 	return (&null_io);
1710 }
1711 
1712 size_t
1713 mdb_iob_vsnprintf(char *buf, size_t nbytes, const char *format, va_list alist)
1714 {
1715 	varglist_t ap = { VAT_VARARGS };
1716 	char iob_buf[64];
1717 	mdb_iob_t iob;
1718 	mdb_io_t io;
1719 	spbuf_t spb;
1720 
1721 	ASSERT(buf != NULL || nbytes == 0);
1722 	iob_spb_create(&iob, iob_buf, sizeof (iob_buf), &io, &spb, buf, nbytes);
1723 	va_copy(ap.val_valist, alist);
1724 	iob_doprnt(&iob, format, &ap);
1725 	mdb_iob_flush(&iob);
1726 
1727 	if (spb.spb_bufsiz != 0)
1728 		*spb.spb_buf = '\0';
1729 	else if (buf != NULL && nbytes > 0)
1730 		*--spb.spb_buf = '\0';
1731 
1732 	return (spb.spb_total);
1733 }
1734 
1735 size_t
1736 mdb_iob_asnprintf(char *buf, size_t nbytes, const char *format,
1737     const mdb_arg_t *argv)
1738 {
1739 	varglist_t ap = { VAT_ARGVEC };
1740 	char iob_buf[64];
1741 	mdb_iob_t iob;
1742 	mdb_io_t io;
1743 	spbuf_t spb;
1744 
1745 	ASSERT(buf != NULL || nbytes == 0);
1746 	iob_spb_create(&iob, iob_buf, sizeof (iob_buf), &io, &spb, buf, nbytes);
1747 	ap.val_argv = argv;
1748 	iob_doprnt(&iob, format, &ap);
1749 	mdb_iob_flush(&iob);
1750 
1751 	if (spb.spb_bufsiz != 0)
1752 		*spb.spb_buf = '\0';
1753 	else if (buf != NULL && nbytes > 0)
1754 		*--spb.spb_buf = '\0';
1755 
1756 	return (spb.spb_total);
1757 }
1758 
1759 /*PRINTFLIKE3*/
1760 size_t
1761 mdb_iob_snprintf(char *buf, size_t nbytes, const char *format, ...)
1762 {
1763 	va_list alist;
1764 
1765 	va_start(alist, format);
1766 	nbytes = mdb_iob_vsnprintf(buf, nbytes, format, alist);
1767 	va_end(alist);
1768 
1769 	return (nbytes);
1770 }
1771 
1772 void
1773 mdb_iob_nputs(mdb_iob_t *iob, const char *s, size_t nbytes)
1774 {
1775 	size_t m, n, nleft = nbytes;
1776 	const char *p, *q = s;
1777 
1778 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1779 
1780 	if (nbytes == 0)
1781 		return; /* Return immediately if there is no work to do */
1782 
1783 	/*
1784 	 * If the string contains embedded newlines or tabs, invoke ourself
1785 	 * recursively for each string component, followed by a call to the
1786 	 * newline or tab routine.  This insures that strings with these
1787 	 * characters obey our wrapping and indenting rules, and that strings
1788 	 * with embedded newlines are flushed after each newline, allowing
1789 	 * the output pager to take over if it is enabled.
1790 	 */
1791 	while ((p = strnpbrk(q, "\t\n", nleft)) != NULL) {
1792 		if (p > q)
1793 			mdb_iob_nputs(iob, q, (size_t)(p - q));
1794 
1795 		if (*p == '\t')
1796 			mdb_iob_tab(iob);
1797 		else
1798 			mdb_iob_nl(iob);
1799 
1800 		nleft -= (size_t)(p - q) + 1;	/* Update byte count */
1801 		q = p + 1;			/* Advance past delimiter */
1802 	}
1803 
1804 	/*
1805 	 * For a given string component, we determine how many bytes (n) we can
1806 	 * copy into our buffer (limited by either cols or bufsiz depending
1807 	 * on whether AUTOWRAP is on), copy a chunk into the buffer, and
1808 	 * flush the buffer if we reach the end of a line.
1809 	 */
1810 	while (nleft != 0) {
1811 		if (iob->iob_flags & MDB_IOB_AUTOWRAP) {
1812 			ASSERT(iob->iob_cols >= iob->iob_nbytes);
1813 			n = iob->iob_cols - iob->iob_nbytes;
1814 		} else {
1815 			ASSERT(iob->iob_bufsiz >= iob->iob_nbytes);
1816 			n = iob->iob_bufsiz - iob->iob_nbytes;
1817 		}
1818 
1819 		m = MIN(nleft, n); /* copy at most n bytes in this pass */
1820 
1821 		bcopy(q, iob->iob_bufp, m);
1822 		nleft -= m;
1823 		q += m;
1824 
1825 		iob->iob_bufp += m;
1826 		iob->iob_nbytes += m;
1827 
1828 		if (m == n && nleft != 0) {
1829 			if (iob->iob_flags & MDB_IOB_AUTOWRAP)
1830 				mdb_iob_nl(iob);
1831 			else
1832 				mdb_iob_flush(iob);
1833 		}
1834 	}
1835 }
1836 
1837 void
1838 mdb_iob_puts(mdb_iob_t *iob, const char *s)
1839 {
1840 	mdb_iob_nputs(iob, s, strlen(s));
1841 }
1842 
1843 void
1844 mdb_iob_putc(mdb_iob_t *iob, int c)
1845 {
1846 	mdb_iob_fill(iob, c, 1);
1847 }
1848 
1849 void
1850 mdb_iob_tab(mdb_iob_t *iob)
1851 {
1852 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1853 
1854 	if (iob->iob_tabstop != 0) {
1855 		/*
1856 		 * Round up to the next multiple of the tabstop.  If this puts
1857 		 * us off the end of the line, just insert a newline; otherwise
1858 		 * insert sufficient whitespace to reach position n.
1859 		 */
1860 		size_t n = (iob->iob_nbytes + iob->iob_tabstop) /
1861 		    iob->iob_tabstop * iob->iob_tabstop;
1862 
1863 		if (n < iob->iob_cols)
1864 			mdb_iob_fill(iob, ' ', n - iob->iob_nbytes);
1865 		else
1866 			mdb_iob_nl(iob);
1867 	}
1868 }
1869 
1870 void
1871 mdb_iob_fill(mdb_iob_t *iob, int c, size_t nfill)
1872 {
1873 	size_t i, m, n;
1874 
1875 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1876 
1877 	while (nfill != 0) {
1878 		if (iob->iob_flags & MDB_IOB_AUTOWRAP) {
1879 			ASSERT(iob->iob_cols >= iob->iob_nbytes);
1880 			n = iob->iob_cols - iob->iob_nbytes;
1881 		} else {
1882 			ASSERT(iob->iob_bufsiz >= iob->iob_nbytes);
1883 			n = iob->iob_bufsiz - iob->iob_nbytes;
1884 		}
1885 
1886 		m = MIN(nfill, n); /* fill at most n bytes in this pass */
1887 
1888 		for (i = 0; i < m; i++)
1889 			*iob->iob_bufp++ = (char)c;
1890 
1891 		iob->iob_nbytes += m;
1892 		nfill -= m;
1893 
1894 		if (m == n && nfill != 0) {
1895 			if (iob->iob_flags & MDB_IOB_AUTOWRAP)
1896 				mdb_iob_nl(iob);
1897 			else
1898 				mdb_iob_flush(iob);
1899 		}
1900 	}
1901 }
1902 
1903 void
1904 mdb_iob_ws(mdb_iob_t *iob, size_t n)
1905 {
1906 	if (iob->iob_nbytes + n < iob->iob_cols)
1907 		mdb_iob_fill(iob, ' ', n);
1908 	else
1909 		mdb_iob_nl(iob);
1910 }
1911 
1912 void
1913 mdb_iob_nl(mdb_iob_t *iob)
1914 {
1915 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1916 
1917 	if (iob->iob_nbytes == iob->iob_bufsiz)
1918 		mdb_iob_flush(iob);
1919 
1920 	*iob->iob_bufp++ = '\n';
1921 	iob->iob_nbytes++;
1922 
1923 	mdb_iob_flush(iob);
1924 }
1925 
1926 ssize_t
1927 mdb_iob_ngets(mdb_iob_t *iob, char *buf, size_t n)
1928 {
1929 	ssize_t resid = n - 1;
1930 	ssize_t len;
1931 	int c;
1932 
1933 	if (iob->iob_flags & (MDB_IOB_WRONLY | MDB_IOB_EOF))
1934 		return (EOF); /* can't gets a write buf or a read buf at EOF */
1935 
1936 	if (n == 0)
1937 		return (0);   /* we need room for a terminating \0 */
1938 
1939 	while (resid != 0) {
1940 		if (iob->iob_nbytes == 0 && iob_read(iob, iob->iob_iop) <= 0)
1941 			goto done; /* failed to refill buffer */
1942 
1943 		for (len = MIN(iob->iob_nbytes, resid); len != 0; len--) {
1944 			c = *iob->iob_bufp++;
1945 			iob->iob_nbytes--;
1946 
1947 			if (c == EOF || c == '\n')
1948 				goto done;
1949 
1950 			*buf++ = (char)c;
1951 			resid--;
1952 		}
1953 	}
1954 done:
1955 	*buf = '\0';
1956 	return (n - resid - 1);
1957 }
1958 
1959 int
1960 mdb_iob_getc(mdb_iob_t *iob)
1961 {
1962 	int c;
1963 
1964 	if (iob->iob_flags & (MDB_IOB_WRONLY | MDB_IOB_EOF | MDB_IOB_ERR))
1965 		return (EOF); /* can't getc if write-only, EOF, or error bit */
1966 
1967 	if (iob->iob_nbytes == 0 && iob_read(iob, iob->iob_iop) <= 0)
1968 		return (EOF); /* failed to refill buffer */
1969 
1970 	c = (uchar_t)*iob->iob_bufp++;
1971 	iob->iob_nbytes--;
1972 
1973 	return (c);
1974 }
1975 
1976 int
1977 mdb_iob_ungetc(mdb_iob_t *iob, int c)
1978 {
1979 	if (iob->iob_flags & (MDB_IOB_WRONLY | MDB_IOB_ERR))
1980 		return (EOF); /* can't ungetc if write-only or error bit set */
1981 
1982 	if (c == EOF || iob->iob_nbytes == iob->iob_bufsiz)
1983 		return (EOF); /* can't ungetc EOF, or ungetc if buffer full */
1984 
1985 	*--iob->iob_bufp = (char)c;
1986 	iob->iob_nbytes++;
1987 	iob->iob_flags &= ~MDB_IOB_EOF;
1988 
1989 	return (c);
1990 }
1991 
1992 int
1993 mdb_iob_eof(mdb_iob_t *iob)
1994 {
1995 	return ((iob->iob_flags & (MDB_IOB_RDONLY | MDB_IOB_EOF)) ==
1996 	    (MDB_IOB_RDONLY | MDB_IOB_EOF));
1997 }
1998 
1999 int
2000 mdb_iob_err(mdb_iob_t *iob)
2001 {
2002 	return ((iob->iob_flags & MDB_IOB_ERR) == MDB_IOB_ERR);
2003 }
2004 
2005 ssize_t
2006 mdb_iob_read(mdb_iob_t *iob, void *buf, size_t n)
2007 {
2008 	ssize_t resid = n;
2009 	ssize_t len;
2010 
2011 	if (iob->iob_flags & (MDB_IOB_WRONLY | MDB_IOB_EOF | MDB_IOB_ERR))
2012 		return (0); /* can't read if write-only, eof, or error */
2013 
2014 	while (resid != 0) {
2015 		if (iob->iob_nbytes == 0 && iob_read(iob, iob->iob_iop) <= 0)
2016 			break; /* failed to refill buffer */
2017 
2018 		len = MIN(resid, iob->iob_nbytes);
2019 		bcopy(iob->iob_bufp, buf, len);
2020 
2021 		iob->iob_bufp += len;
2022 		iob->iob_nbytes -= len;
2023 
2024 		buf = (char *)buf + len;
2025 		resid -= len;
2026 	}
2027 
2028 	return (n - resid);
2029 }
2030 
2031 /*
2032  * For now, all binary writes are performed unbuffered.  This has the
2033  * side effect that the pager will not be triggered by mdb_iob_write.
2034  */
2035 ssize_t
2036 mdb_iob_write(mdb_iob_t *iob, const void *buf, size_t n)
2037 {
2038 	ssize_t ret;
2039 
2040 	if (iob->iob_flags & MDB_IOB_ERR)
2041 		return (set_errno(EIO));
2042 	if (iob->iob_flags & MDB_IOB_RDONLY)
2043 		return (set_errno(EMDB_IORO));
2044 
2045 	mdb_iob_flush(iob);
2046 	ret = iob_write(iob, iob->iob_iop, buf, n);
2047 
2048 	if (ret < 0 && iob == mdb.m_out)
2049 		longjmp(mdb.m_frame->f_pcb, MDB_ERR_OUTPUT);
2050 
2051 	return (ret);
2052 }
2053 
2054 int
2055 mdb_iob_ctl(mdb_iob_t *iob, int req, void *arg)
2056 {
2057 	return (IOP_CTL(iob->iob_iop, req, arg));
2058 }
2059 
2060 const char *
2061 mdb_iob_name(mdb_iob_t *iob)
2062 {
2063 	if (iob == NULL)
2064 		return ("<NULL>");
2065 
2066 	return (IOP_NAME(iob->iob_iop));
2067 }
2068 
2069 size_t
2070 mdb_iob_lineno(mdb_iob_t *iob)
2071 {
2072 	return (iob->iob_lineno);
2073 }
2074 
2075 size_t
2076 mdb_iob_gettabstop(mdb_iob_t *iob)
2077 {
2078 	return (iob->iob_tabstop);
2079 }
2080 
2081 size_t
2082 mdb_iob_getmargin(mdb_iob_t *iob)
2083 {
2084 	return (iob->iob_margin);
2085 }
2086 
2087 mdb_io_t *
2088 mdb_io_hold(mdb_io_t *io)
2089 {
2090 	io->io_refcnt++;
2091 	return (io);
2092 }
2093 
2094 void
2095 mdb_io_rele(mdb_io_t *io)
2096 {
2097 	ASSERT(io->io_refcnt != 0);
2098 
2099 	if (--io->io_refcnt == 0) {
2100 		IOP_CLOSE(io);
2101 		mdb_free(io, sizeof (mdb_io_t));
2102 	}
2103 }
2104 
2105 void
2106 mdb_io_destroy(mdb_io_t *io)
2107 {
2108 	ASSERT(io->io_refcnt == 0);
2109 	IOP_CLOSE(io);
2110 	mdb_free(io, sizeof (mdb_io_t));
2111 }
2112 
2113 void
2114 mdb_iob_stack_create(mdb_iob_stack_t *stk)
2115 {
2116 	stk->stk_top = NULL;
2117 	stk->stk_size = 0;
2118 }
2119 
2120 void
2121 mdb_iob_stack_destroy(mdb_iob_stack_t *stk)
2122 {
2123 	mdb_iob_t *top, *ntop;
2124 
2125 	for (top = stk->stk_top; top != NULL; top = ntop) {
2126 		ntop = top->iob_next;
2127 		mdb_iob_destroy(top);
2128 	}
2129 }
2130 
2131 void
2132 mdb_iob_stack_push(mdb_iob_stack_t *stk, mdb_iob_t *iob, size_t lineno)
2133 {
2134 	iob->iob_lineno = lineno;
2135 	iob->iob_next = stk->stk_top;
2136 	stk->stk_top = iob;
2137 	stk->stk_size++;
2138 	yylineno = 1;
2139 }
2140 
2141 mdb_iob_t *
2142 mdb_iob_stack_pop(mdb_iob_stack_t *stk)
2143 {
2144 	mdb_iob_t *top = stk->stk_top;
2145 
2146 	ASSERT(top != NULL);
2147 
2148 	stk->stk_top = top->iob_next;
2149 	top->iob_next = NULL;
2150 	stk->stk_size--;
2151 
2152 	return (top);
2153 }
2154 
2155 size_t
2156 mdb_iob_stack_size(mdb_iob_stack_t *stk)
2157 {
2158 	return (stk->stk_size);
2159 }
2160 
2161 /*
2162  * Stub functions for i/o backend implementors: these stubs either act as
2163  * pass-through no-ops or return ENOTSUP as appropriate.
2164  */
2165 ssize_t
2166 no_io_read(mdb_io_t *io, void *buf, size_t nbytes)
2167 {
2168 	if (io->io_next != NULL)
2169 		return (IOP_READ(io->io_next, buf, nbytes));
2170 
2171 	return (set_errno(EMDB_IOWO));
2172 }
2173 
2174 ssize_t
2175 no_io_write(mdb_io_t *io, const void *buf, size_t nbytes)
2176 {
2177 	if (io->io_next != NULL)
2178 		return (IOP_WRITE(io->io_next, buf, nbytes));
2179 
2180 	return (set_errno(EMDB_IORO));
2181 }
2182 
2183 off64_t
2184 no_io_seek(mdb_io_t *io, off64_t offset, int whence)
2185 {
2186 	if (io->io_next != NULL)
2187 		return (IOP_SEEK(io->io_next, offset, whence));
2188 
2189 	return (set_errno(ENOTSUP));
2190 }
2191 
2192 int
2193 no_io_ctl(mdb_io_t *io, int req, void *arg)
2194 {
2195 	if (io->io_next != NULL)
2196 		return (IOP_CTL(io->io_next, req, arg));
2197 
2198 	return (set_errno(ENOTSUP));
2199 }
2200 
2201 /*ARGSUSED*/
2202 void
2203 no_io_close(mdb_io_t *io)
2204 {
2205 /*
2206  * Note that we do not propagate IOP_CLOSE down the io stack.  IOP_CLOSE should
2207  * only be called by mdb_io_rele when an io's reference count has gone to zero.
2208  */
2209 }
2210 
2211 const char *
2212 no_io_name(mdb_io_t *io)
2213 {
2214 	if (io->io_next != NULL)
2215 		return (IOP_NAME(io->io_next));
2216 
2217 	return ("(anonymous)");
2218 }
2219 
2220 void
2221 no_io_link(mdb_io_t *io, mdb_iob_t *iob)
2222 {
2223 	if (io->io_next != NULL)
2224 		IOP_LINK(io->io_next, iob);
2225 }
2226 
2227 void
2228 no_io_unlink(mdb_io_t *io, mdb_iob_t *iob)
2229 {
2230 	if (io->io_next != NULL)
2231 		IOP_UNLINK(io->io_next, iob);
2232 }
2233 
2234 int
2235 no_io_setattr(mdb_io_t *io, int req, uint_t attrs)
2236 {
2237 	if (io->io_next != NULL)
2238 		return (IOP_SETATTR(io->io_next, req, attrs));
2239 
2240 	return (set_errno(ENOTSUP));
2241 }
2242 
2243 void
2244 no_io_suspend(mdb_io_t *io)
2245 {
2246 	if (io->io_next != NULL)
2247 		IOP_SUSPEND(io->io_next);
2248 }
2249 
2250 void
2251 no_io_resume(mdb_io_t *io)
2252 {
2253 	if (io->io_next != NULL)
2254 		IOP_RESUME(io->io_next);
2255 }
2256 
2257 /*
2258  * Iterate over the varargs. The first item indicates the mode:
2259  * MDB_TBL_PRNT
2260  * 	pull out the next vararg as a const char * and pass it and the
2261  * 	remaining varargs to iob_doprnt; if we want to print the column,
2262  * 	direct the output to mdb.m_out otherwise direct it to mdb.m_null
2263  *
2264  * MDB_TBL_FUNC
2265  * 	pull out the next vararg as type mdb_table_print_f and the
2266  * 	following one as a void * argument to the function; call the
2267  * 	function with the given argument if we want to print the column
2268  *
2269  * The second item indicates the flag; if the flag is set in the flags
2270  * argument, then the column is printed. A flag value of 0 indicates
2271  * that the column should always be printed.
2272  */
2273 void
2274 mdb_table_print(uint_t flags, const char *delimeter, ...)
2275 {
2276 	va_list alist;
2277 	uint_t flg;
2278 	uint_t type;
2279 	const char *fmt;
2280 	mdb_table_print_f *func;
2281 	void *arg;
2282 	mdb_iob_t *out;
2283 	mdb_bool_t first = TRUE;
2284 	mdb_bool_t print;
2285 
2286 	va_start(alist, delimeter);
2287 
2288 	while ((type = va_arg(alist, uint_t)) != MDB_TBL_DONE) {
2289 		flg = va_arg(alist, uint_t);
2290 
2291 		print = flg == 0 || (flg & flags) != 0;
2292 
2293 		if (print) {
2294 			if (first)
2295 				first = FALSE;
2296 			else
2297 				mdb_printf("%s", delimeter);
2298 		}
2299 
2300 		switch (type) {
2301 		case MDB_TBL_PRNT: {
2302 			varglist_t ap = { VAT_VARARGS };
2303 			fmt = va_arg(alist, const char *);
2304 			out = print ? mdb.m_out : mdb.m_null;
2305 			va_copy(ap.val_valist, alist);
2306 			iob_doprnt(out, fmt, &ap);
2307 			va_end(alist);
2308 			va_copy(alist, ap.val_valist);
2309 			break;
2310 		}
2311 
2312 		case MDB_TBL_FUNC:
2313 			func = va_arg(alist, mdb_table_print_f *);
2314 			arg = va_arg(alist, void *);
2315 
2316 			if (print)
2317 				func(arg);
2318 
2319 			break;
2320 
2321 		default:
2322 			warn("bad format type %x\n", type);
2323 			break;
2324 		}
2325 	}
2326 
2327 	va_end(alist);
2328 }
2329