xref: /illumos-gate/usr/src/cmd/mdb/common/mdb/mdb_io.c (revision 4a04e8db7f069cc2eb910470e630778f35ef3c44)
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 		break;
908 
909 	default:
910 		n = (uint_t)VA_ARG(ap, uint_t);
911 	}
912 
913 #ifndef _KMDB
914 	orig = n;
915 #endif
916 
917 	while (n >= 1024) {
918 		n /= 1024;
919 		index++;
920 	}
921 
922 	u = " KMGTPE"[index];
923 	buf[0] = '\0';
924 
925 	if (index == 0) {
926 		return (numtostr(n, 10, 0));
927 #ifndef _KMDB
928 	} else if ((orig & ((1ULL << 10 * index) - 1)) == 0) {
929 #else
930 	} else {
931 #endif
932 		/*
933 		 * If this is an even multiple of the base or we are in an
934 		 * environment where floating point is verboten (i.e., kmdb),
935 		 * always display without any decimal precision.
936 		 */
937 		(void) strcat(buf, numtostr(n, 10, 0));
938 #ifndef _KMDB
939 	} else {
940 		/*
941 		 * We want to choose a precision that results in the specified
942 		 * number of significant figures (by default, 3).  This is
943 		 * similar to the output that one would get specifying the %.*g
944 		 * format specifier (where the asterisk denotes the number of
945 		 * significant digits), but (1) we include trailing zeros if
946 		 * the there are non-zero digits beyond the number of
947 		 * significant digits (that is, 10241 is '10.0K', not the
948 		 * '10K' that it would be with %.3g) and (2) we never resort
949 		 * to %e notation when the number of digits exceeds the
950 		 * number of significant figures (that is, 1043968 is '1020K',
951 		 * not '1.02e+03K').  This is also made somewhat complicated
952 		 * by the fact that we need to deal with rounding (10239 is
953 		 * '10.0K', not '9.99K'), for which we perform nearest-even
954 		 * rounding.
955 		 */
956 		double val = (double)orig / (1ULL << 10 * index);
957 		int i, mag = 1, thresh;
958 
959 		for (i = 0; i < sigfig - 1; i++)
960 			mag *= 10;
961 
962 		for (thresh = mag * 10; mag >= 1; mag /= 10, i--) {
963 			double mult = val * (double)mag;
964 			uint32_t v;
965 
966 			/*
967 			 * Note that we cast mult to a 32-bit value.  We know
968 			 * that val is less than 1024 due to the logic above,
969 			 * and that mag is at most 10^(sigfig - 1).  This means
970 			 * that as long as sigfig is 9 or lower, this will not
971 			 * overflow.  (We perform this cast because it assures
972 			 * that we are never converting a double to a uint64_t,
973 			 * which for some compilers requires a call to a
974 			 * function not guaranteed to be in libstand.)
975 			 */
976 			if (mult - (double)(uint32_t)mult != 0.5) {
977 				v = (uint32_t)(mult + 0.5);
978 			} else {
979 				/*
980 				 * We are exactly between integer multiples
981 				 * of units; perform nearest-even rounding
982 				 * to be consistent with the behavior of
983 				 * printf().
984 				 */
985 				if ((v = (uint32_t)mult) & 1)
986 					v++;
987 			}
988 
989 			if (mag == 1) {
990 				(void) strcat(buf, numtostr(v, 10, 0));
991 				break;
992 			}
993 
994 			if (v < thresh) {
995 				(void) strcat(buf, numtostr(v / mag, 10, 0));
996 				(void) strcat(buf, ".");
997 
998 				c = (char *)numtostr(v % mag, 10, 0);
999 				i -= strlen(c);
1000 
1001 				/*
1002 				 * We need to zero-fill from the right of the
1003 				 * decimal point to the first significant digit
1004 				 * of the fractional component.
1005 				 */
1006 				while (i--)
1007 					(void) strcat(buf, "0");
1008 
1009 				(void) strcat(buf, c);
1010 				break;
1011 			}
1012 		}
1013 #endif
1014 	}
1015 
1016 	c = &buf[strlen(buf)];
1017 	*c++ = u;
1018 	*c++ = '\0';
1019 
1020 	return (buf);
1021 }
1022 
1023 static int
1024 iob_setattr(mdb_iob_t *iob, const char *s, size_t nbytes)
1025 {
1026 	uint_t attr;
1027 	int req;
1028 
1029 	if (iob->iob_pgp == NULL)
1030 		return (set_errno(ENOTTY));
1031 
1032 	if (nbytes != 0 && *s == '/') {
1033 		req = ATT_OFF;
1034 		nbytes--;
1035 		s++;
1036 	} else
1037 		req = ATT_ON;
1038 
1039 	if (nbytes != 1)
1040 		return (set_errno(EINVAL));
1041 
1042 	switch (*s) {
1043 	case 's':
1044 		attr = ATT_STANDOUT;
1045 		break;
1046 	case 'u':
1047 		attr = ATT_UNDERLINE;
1048 		break;
1049 	case 'r':
1050 		attr = ATT_REVERSE;
1051 		break;
1052 	case 'b':
1053 		attr = ATT_BOLD;
1054 		break;
1055 	case 'd':
1056 		attr = ATT_DIM;
1057 		break;
1058 	case 'a':
1059 		attr = ATT_ALTCHARSET;
1060 		break;
1061 	default:
1062 		return (set_errno(EINVAL));
1063 	}
1064 
1065 	/*
1066 	 * We need to flush the current buffer contents before calling
1067 	 * IOP_SETATTR because IOP_SETATTR may need to synchronously output
1068 	 * terminal escape sequences directly to the underlying device.
1069 	 */
1070 	(void) iob_write(iob, iob->iob_iop, iob->iob_buf, iob->iob_nbytes);
1071 	iob->iob_bufp = &iob->iob_buf[0];
1072 	iob->iob_nbytes = 0;
1073 
1074 	return (IOP_SETATTR(iob->iob_pgp, req, attr));
1075 }
1076 
1077 static void
1078 iob_bits2str(mdb_iob_t *iob, u_longlong_t value, const mdb_bitmask_t *bmp,
1079     mdb_bool_t altflag)
1080 {
1081 	mdb_bool_t delim = FALSE;
1082 	const char *str;
1083 	size_t width;
1084 
1085 	if (bmp == NULL)
1086 		goto out;
1087 
1088 	for (; bmp->bm_name != NULL; bmp++) {
1089 		if ((value & bmp->bm_mask) == bmp->bm_bits) {
1090 			width = strlen(bmp->bm_name) + delim;
1091 
1092 			if (IOB_WRAPNOW(iob, width))
1093 				mdb_iob_nl(iob);
1094 
1095 			if (delim)
1096 				mdb_iob_putc(iob, ',');
1097 			else
1098 				delim = TRUE;
1099 
1100 			mdb_iob_puts(iob, bmp->bm_name);
1101 			value &= ~bmp->bm_bits;
1102 		}
1103 	}
1104 
1105 out:
1106 	if (altflag == TRUE && (delim == FALSE || value != 0)) {
1107 		str = numtostr(value, 16, NTOS_UNSIGNED | NTOS_SHOWBASE);
1108 		width = strlen(str) + delim;
1109 
1110 		if (IOB_WRAPNOW(iob, width))
1111 			mdb_iob_nl(iob);
1112 		if (delim)
1113 			mdb_iob_putc(iob, ',');
1114 		mdb_iob_puts(iob, str);
1115 	}
1116 }
1117 
1118 static const char *
1119 iob_inaddr2str(uint32_t addr)
1120 {
1121 	static char buf[INET_ADDRSTRLEN];
1122 
1123 	(void) mdb_inet_ntop(AF_INET, &addr, buf, sizeof (buf));
1124 
1125 	return (buf);
1126 }
1127 
1128 static const char *
1129 iob_ipv6addr2str(void *addr)
1130 {
1131 	static char buf[INET6_ADDRSTRLEN];
1132 
1133 	(void) mdb_inet_ntop(AF_INET6, addr, buf, sizeof (buf));
1134 
1135 	return (buf);
1136 }
1137 
1138 static const char *
1139 iob_getvar(const char *s, size_t len)
1140 {
1141 	mdb_var_t *val;
1142 	char *var;
1143 
1144 	if (len == 0) {
1145 		(void) set_errno(EINVAL);
1146 		return (NULL);
1147 	}
1148 
1149 	var = strndup(s, len);
1150 	val = mdb_nv_lookup(&mdb.m_nv, var);
1151 	strfree(var);
1152 
1153 	if (val == NULL) {
1154 		(void) set_errno(EINVAL);
1155 		return (NULL);
1156 	}
1157 
1158 	return (numtostr(mdb_nv_get_value(val), 10, 0));
1159 }
1160 
1161 /*
1162  * The iob_doprnt function forms the main engine of the debugger's output
1163  * formatting capabilities.  Note that this is NOT exactly compatible with
1164  * the printf(3S) family, nor is it intended to be so.  We support some
1165  * extensions and format characters not supported by printf(3S), and we
1166  * explicitly do NOT provide support for %C, %S, %ws (wide-character strings),
1167  * do NOT provide for the complete functionality of %f, %e, %E, %g, %G
1168  * (alternate double formats), and do NOT support %.x (precision specification).
1169  * Note that iob_doprnt consumes varargs off the original va_list.
1170  */
1171 static void
1172 iob_doprnt(mdb_iob_t *iob, const char *format, varglist_t *ap)
1173 {
1174 	char c[2] = { 0, 0 };	/* Buffer for single character output */
1175 	const char *p;		/* Current position in format string */
1176 	size_t len;		/* Length of format string to copy verbatim */
1177 	size_t altlen;		/* Length of alternate print format prefix */
1178 	const char *altstr;	/* Alternate print format prefix */
1179 	const char *symstr;	/* Symbol + offset string */
1180 
1181 	u_longlong_t val;	/* Current integer value */
1182 	intsize_t size;		/* Current integer value size */
1183 	uint_t flags;		/* Current flags to pass to iob_int2str */
1184 	size_t width;		/* Current field width */
1185 	int zero;		/* If != 0, then integer value == 0 */
1186 
1187 	mdb_bool_t f_alt;	/* Use alternate print format (%#) */
1188 	mdb_bool_t f_altsuff;	/* Alternate print format is a suffix */
1189 	mdb_bool_t f_zfill;	/* Zero-fill field (%0) */
1190 	mdb_bool_t f_left;	/* Left-adjust field (%-) */
1191 	mdb_bool_t f_digits;	/* Explicit digits used to set field width */
1192 
1193 	union {
1194 		const char *str;
1195 		uint32_t ui32;
1196 		void *ptr;
1197 		time_t tm;
1198 		char c;
1199 		double d;
1200 		long double ld;
1201 	} u;
1202 
1203 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1204 
1205 	while ((p = strchr(format, '%')) != NULL) {
1206 		/*
1207 		 * Output the format string verbatim up to the next '%' char
1208 		 */
1209 		if (p != format) {
1210 			len = p - format;
1211 			if (IOB_WRAPNOW(iob, len) && *format != '\n')
1212 				mdb_iob_nl(iob);
1213 			mdb_iob_nputs(iob, format, len);
1214 		}
1215 
1216 		/*
1217 		 * Now we need to parse the sequence of format characters
1218 		 * following the % marker and do the appropriate thing.
1219 		 */
1220 		size = SZ_INT;		/* Use normal-sized int by default */
1221 		flags = 0;		/* Clear numtostr() format flags */
1222 		width = 0;		/* No field width limit by default */
1223 		altlen = 0;		/* No alternate format string yet */
1224 		altstr = NULL;		/* No alternate format string yet */
1225 
1226 		f_alt = FALSE;		/* Alternate format off by default */
1227 		f_altsuff = FALSE;	/* Alternate format is a prefix */
1228 		f_zfill = FALSE;	/* Zero-fill off by default */
1229 		f_left = FALSE;		/* Left-adjust off by default */
1230 		f_digits = FALSE;	/* No digits for width specified yet */
1231 
1232 		fmt_switch:
1233 		switch (*++p) {
1234 		case '0': case '1': case '2': case '3': case '4':
1235 		case '5': case '6': case '7': case '8': case '9':
1236 			if (f_digits == FALSE && *p == '0') {
1237 				f_zfill = TRUE;
1238 				goto fmt_switch;
1239 			}
1240 
1241 			if (f_digits == FALSE)
1242 				width = 0; /* clear any other width specifier */
1243 
1244 			for (u.c = *p; u.c >= '0' && u.c <= '9'; u.c = *++p)
1245 				width = width * 10 + u.c - '0';
1246 
1247 			p--;
1248 			f_digits = TRUE;
1249 			goto fmt_switch;
1250 
1251 		case 'a':
1252 			if (size < SZ_LONG)
1253 				size = SZ_LONG;	/* Bump to size of uintptr_t */
1254 
1255 			u.str = iob_int2str(ap, size, 16,
1256 			    NTOS_UNSIGNED | NTOS_SHOWBASE, &zero, &val);
1257 
1258 			if ((symstr = iob_addr2str(val)) != NULL)
1259 				u.str = symstr;
1260 
1261 			if (f_alt == TRUE) {
1262 				f_altsuff = TRUE;
1263 				altstr = ":";
1264 				altlen = 1;
1265 			}
1266 			break;
1267 
1268 		case 'A':
1269 			if (size < SZ_LONG)
1270 				size = SZ_LONG;	/* Bump to size of uintptr_t */
1271 
1272 			(void) iob_int2str(ap, size, 16,
1273 			    NTOS_UNSIGNED, &zero, &val);
1274 
1275 			u.str = iob_addr2str(val);
1276 
1277 			if (f_alt == TRUE && u.str == NULL)
1278 				u.str = "?";
1279 			break;
1280 
1281 		case 'b':
1282 			u.str = iob_int2str(ap, size, 16,
1283 			    NTOS_UNSIGNED | NTOS_SHOWBASE, &zero, &val);
1284 
1285 			iob_bits2str(iob, val, VA_PTRARG(ap), f_alt);
1286 
1287 			format = ++p;
1288 			continue;
1289 
1290 		case 'c':
1291 			c[0] = (char)VA_ARG(ap, int);
1292 			u.str = c;
1293 			break;
1294 
1295 		case 'd':
1296 		case 'i':
1297 			if (f_alt)
1298 				flags |= NTOS_SHOWBASE;
1299 			u.str = iob_int2str(ap, size, 10, flags, &zero, &val);
1300 			break;
1301 
1302 		/* No floating point in kmdb */
1303 #ifndef _KMDB
1304 		case 'e':
1305 		case 'E':
1306 			u.d = VA_ARG(ap, double);
1307 			u.str = doubletos(u.d, 7, *p);
1308 			break;
1309 
1310 		case 'g':
1311 		case 'G':
1312 			if (size >= SZ_LONG) {
1313 				u.ld = VA_ARG(ap, long double);
1314 				u.str = longdoubletos(&u.ld, 16,
1315 				    (*p == 'g') ? 'e' : 'E');
1316 			} else {
1317 				u.d = VA_ARG(ap, double);
1318 				u.str = doubletos(u.d, 16,
1319 				    (*p == 'g') ? 'e' : 'E');
1320 			}
1321 			break;
1322 #endif
1323 
1324 		case 'h':
1325 			size = SZ_SHORT;
1326 			goto fmt_switch;
1327 
1328 		case 'H':
1329 			u.str = iob_bytes2str(ap, size);
1330 			break;
1331 
1332 		case 'I':
1333 			u.ui32 = VA_ARG(ap, uint32_t);
1334 			u.str = iob_inaddr2str(u.ui32);
1335 			break;
1336 
1337 		case 'l':
1338 			if (size >= SZ_LONG)
1339 				size = SZ_LONGLONG;
1340 			else
1341 				size = SZ_LONG;
1342 			goto fmt_switch;
1343 
1344 		case 'm':
1345 			if (iob->iob_nbytes == 0) {
1346 				mdb_iob_ws(iob, (width != 0) ? width :
1347 				    iob->iob_margin);
1348 			}
1349 			format = ++p;
1350 			continue;
1351 
1352 		case 'N':
1353 			u.ptr = VA_PTRARG(ap);
1354 			u.str = iob_ipv6addr2str(u.ptr);
1355 			break;
1356 
1357 		case 'o':
1358 			u.str = iob_int2str(ap, size, 8, NTOS_UNSIGNED,
1359 			    &zero, &val);
1360 
1361 			if (f_alt && !zero) {
1362 				altstr = "0";
1363 				altlen = 1;
1364 			}
1365 			break;
1366 
1367 		case 'p':
1368 			u.ptr = VA_PTRARG(ap);
1369 			u.str = numtostr((uintptr_t)u.ptr, 16, NTOS_UNSIGNED);
1370 			break;
1371 
1372 		case 'q':
1373 			u.str = iob_int2str(ap, size, 8, flags, &zero, &val);
1374 
1375 			if (f_alt && !zero) {
1376 				altstr = "0";
1377 				altlen = 1;
1378 			}
1379 			break;
1380 
1381 		case 'r':
1382 			if (f_alt)
1383 				flags |= NTOS_SHOWBASE;
1384 			u.str = iob_int2str(ap, size, mdb.m_radix,
1385 			    NTOS_UNSIGNED | flags, &zero, &val);
1386 			break;
1387 
1388 		case 'R':
1389 			if (f_alt)
1390 				flags |= NTOS_SHOWBASE;
1391 			u.str = iob_int2str(ap, size, mdb.m_radix, flags,
1392 			    &zero, &val);
1393 			break;
1394 
1395 		case 's':
1396 			u.str = VA_PTRARG(ap);
1397 			if (u.str == NULL)
1398 				u.str = "<NULL>"; /* Be forgiving of NULL */
1399 			break;
1400 
1401 		case 't':
1402 			if (width != 0) {
1403 				while (width-- > 0)
1404 					mdb_iob_tab(iob);
1405 			} else
1406 				mdb_iob_tab(iob);
1407 
1408 			format = ++p;
1409 			continue;
1410 
1411 		case 'T':
1412 			if (width != 0 && (iob->iob_nbytes % width) != 0) {
1413 				size_t ots = iob->iob_tabstop;
1414 				iob->iob_tabstop = width;
1415 				mdb_iob_tab(iob);
1416 				iob->iob_tabstop = ots;
1417 			}
1418 			format = ++p;
1419 			continue;
1420 
1421 		case 'u':
1422 			if (f_alt)
1423 				flags |= NTOS_SHOWBASE;
1424 			u.str = iob_int2str(ap, size, 10,
1425 			    flags | NTOS_UNSIGNED, &zero, &val);
1426 			break;
1427 
1428 		case 'x':
1429 			u.str = iob_int2str(ap, size, 16, NTOS_UNSIGNED,
1430 			    &zero, &val);
1431 
1432 			if (f_alt && !zero) {
1433 				altstr = "0x";
1434 				altlen = 2;
1435 			}
1436 			break;
1437 
1438 		case 'X':
1439 			u.str = iob_int2str(ap, size, 16,
1440 			    NTOS_UNSIGNED | NTOS_UPCASE, &zero, &val);
1441 
1442 			if (f_alt && !zero) {
1443 				altstr = "0X";
1444 				altlen = 2;
1445 			}
1446 			break;
1447 
1448 		case 'Y':
1449 			u.tm = VA_ARG(ap, time_t);
1450 			u.str = iob_time2str(&u.tm);
1451 			break;
1452 
1453 		case '<':
1454 			/*
1455 			 * Used to turn attributes on (<b>), to turn them
1456 			 * off (</b>), or to print variables (<_var>).
1457 			 */
1458 			for (u.str = ++p; *p != '\0' && *p != '>'; p++)
1459 				continue;
1460 
1461 			if (*p == '>') {
1462 				size_t paramlen = p - u.str;
1463 
1464 				if (paramlen > 0) {
1465 					if (*u.str == '_') {
1466 						u.str = iob_getvar(u.str + 1,
1467 						    paramlen - 1);
1468 						break;
1469 					} else {
1470 						(void) iob_setattr(iob, u.str,
1471 						    paramlen);
1472 					}
1473 				}
1474 
1475 				p++;
1476 			}
1477 
1478 			format = p;
1479 			continue;
1480 
1481 		case '*':
1482 			width = (size_t)(uint_t)VA_ARG(ap, int);
1483 			goto fmt_switch;
1484 
1485 		case '%':
1486 			u.str = "%";
1487 			break;
1488 
1489 		case '?':
1490 			width = sizeof (uintptr_t) * 2;
1491 			goto fmt_switch;
1492 
1493 		case '#':
1494 			f_alt = TRUE;
1495 			goto fmt_switch;
1496 
1497 		case '+':
1498 			flags |= NTOS_SIGNPOS;
1499 			goto fmt_switch;
1500 
1501 		case '-':
1502 			f_left = TRUE;
1503 			goto fmt_switch;
1504 
1505 		default:
1506 			c[0] = p[0];
1507 			u.str = c;
1508 		}
1509 
1510 		len = u.str != NULL ? strlen(u.str) : 0;
1511 
1512 		if (len + altlen > width)
1513 			width = len + altlen;
1514 
1515 		/*
1516 		 * If the string and the option altstr won't fit on this line
1517 		 * and auto-wrap is set (default), skip to the next line.
1518 		 * If the string contains \n, and the \n terminated substring
1519 		 * + altstr is shorter than the above, use the shorter lf_len.
1520 		 */
1521 		if (u.str != NULL) {
1522 			char *np = strchr(u.str, '\n');
1523 			if (np != NULL) {
1524 				int lf_len = (np - u.str) + altlen;
1525 				if (lf_len < width)
1526 					width = lf_len;
1527 			}
1528 		}
1529 		if (IOB_WRAPNOW(iob, width))
1530 			mdb_iob_nl(iob);
1531 
1532 		/*
1533 		 * Optionally add whitespace or zeroes prefixing the value if
1534 		 * we haven't filled the minimum width and we're right-aligned.
1535 		 */
1536 		if (len < (width - altlen) && f_left == FALSE) {
1537 			mdb_iob_fill(iob, f_zfill ? '0' : ' ',
1538 			    width - altlen - len);
1539 		}
1540 
1541 		/*
1542 		 * Print the alternate string if it's a prefix, and then
1543 		 * print the value string itself.
1544 		 */
1545 		if (altstr != NULL && f_altsuff == FALSE)
1546 			mdb_iob_nputs(iob, altstr, altlen);
1547 		if (len != 0)
1548 			mdb_iob_nputs(iob, u.str, len);
1549 
1550 		/*
1551 		 * If we have an alternate string and it's a suffix, print it.
1552 		 */
1553 		if (altstr != NULL && f_altsuff == TRUE)
1554 			mdb_iob_nputs(iob, altstr, altlen);
1555 
1556 		/*
1557 		 * Finally, if we haven't filled the field width and we're
1558 		 * left-aligned, pad out the rest with whitespace.
1559 		 */
1560 		if ((len + altlen) < width && f_left == TRUE)
1561 			mdb_iob_ws(iob, width - altlen - len);
1562 
1563 		format = (*p != '\0') ? ++p : p;
1564 	}
1565 
1566 	/*
1567 	 * If there's anything left in the format string, output it now
1568 	 */
1569 	if (*format != '\0') {
1570 		len = strlen(format);
1571 		if (IOB_WRAPNOW(iob, len) && *format != '\n')
1572 			mdb_iob_nl(iob);
1573 		mdb_iob_nputs(iob, format, len);
1574 	}
1575 }
1576 
1577 void
1578 mdb_iob_vprintf(mdb_iob_t *iob, const char *format, va_list alist)
1579 {
1580 	varglist_t ap = { VAT_VARARGS };
1581 	va_copy(ap.val_valist, alist);
1582 	iob_doprnt(iob, format, &ap);
1583 }
1584 
1585 void
1586 mdb_iob_aprintf(mdb_iob_t *iob, const char *format, const mdb_arg_t *argv)
1587 {
1588 	varglist_t ap = { VAT_ARGVEC };
1589 	ap.val_argv = argv;
1590 	iob_doprnt(iob, format, &ap);
1591 }
1592 
1593 void
1594 mdb_iob_printf(mdb_iob_t *iob, const char *format, ...)
1595 {
1596 	va_list alist;
1597 
1598 	va_start(alist, format);
1599 	mdb_iob_vprintf(iob, format, alist);
1600 	va_end(alist);
1601 }
1602 
1603 /*
1604  * In order to handle the sprintf family of functions, we define a special
1605  * i/o backend known as a "sprintf buf" (or spbuf for short).  This back end
1606  * provides an IOP_WRITE entry point that concatenates each buffer sent from
1607  * mdb_iob_flush() onto the caller's buffer until the caller's buffer is
1608  * exhausted.  We also keep an absolute count of how many bytes were sent to
1609  * this function during the lifetime of the snprintf call.  This allows us
1610  * to provide the ability to (1) return the total size required for the given
1611  * format string and argument list, and (2) support a call to snprintf with a
1612  * NULL buffer argument with no special case code elsewhere.
1613  */
1614 static ssize_t
1615 spbuf_write(mdb_io_t *io, const void *buf, size_t buflen)
1616 {
1617 	spbuf_t *spb = io->io_data;
1618 
1619 	if (spb->spb_bufsiz != 0) {
1620 		size_t n = MIN(spb->spb_bufsiz, buflen);
1621 		bcopy(buf, spb->spb_buf, n);
1622 		spb->spb_buf += n;
1623 		spb->spb_bufsiz -= n;
1624 	}
1625 
1626 	spb->spb_total += buflen;
1627 	return (buflen);
1628 }
1629 
1630 static const mdb_io_ops_t spbuf_ops = {
1631 	no_io_read,
1632 	spbuf_write,
1633 	no_io_seek,
1634 	no_io_ctl,
1635 	no_io_close,
1636 	no_io_name,
1637 	no_io_link,
1638 	no_io_unlink,
1639 	no_io_setattr,
1640 	no_io_suspend,
1641 	no_io_resume
1642 };
1643 
1644 /*
1645  * The iob_spb_create function initializes an iob suitable for snprintf calls,
1646  * a spbuf i/o backend, and the spbuf private data, and then glues these
1647  * objects together.  The caller (either vsnprintf or asnprintf below) is
1648  * expected to have allocated the various structures on their stack.
1649  */
1650 static void
1651 iob_spb_create(mdb_iob_t *iob, char *iob_buf, size_t iob_len,
1652     mdb_io_t *io, spbuf_t *spb, char *spb_buf, size_t spb_len)
1653 {
1654 	spb->spb_buf = spb_buf;
1655 	spb->spb_bufsiz = spb_len;
1656 	spb->spb_total = 0;
1657 
1658 	io->io_ops = &spbuf_ops;
1659 	io->io_data = spb;
1660 	io->io_next = NULL;
1661 	io->io_refcnt = 1;
1662 
1663 	iob->iob_buf = iob_buf;
1664 	iob->iob_bufsiz = iob_len;
1665 	iob->iob_bufp = iob_buf;
1666 	iob->iob_nbytes = 0;
1667 	iob->iob_nlines = 0;
1668 	iob->iob_lineno = 1;
1669 	iob->iob_rows = MDB_IOB_DEFROWS;
1670 	iob->iob_cols = iob_len;
1671 	iob->iob_tabstop = MDB_IOB_DEFTAB;
1672 	iob->iob_margin = MDB_IOB_DEFMARGIN;
1673 	iob->iob_flags = MDB_IOB_WRONLY;
1674 	iob->iob_iop = io;
1675 	iob->iob_pgp = NULL;
1676 	iob->iob_next = NULL;
1677 }
1678 
1679 /*ARGSUSED*/
1680 ssize_t
1681 null_io_write(mdb_io_t *io, const void *buf, size_t nbytes)
1682 {
1683 	return (nbytes);
1684 }
1685 
1686 static const mdb_io_ops_t null_ops = {
1687 	no_io_read,
1688 	null_io_write,
1689 	no_io_seek,
1690 	no_io_ctl,
1691 	no_io_close,
1692 	no_io_name,
1693 	no_io_link,
1694 	no_io_unlink,
1695 	no_io_setattr,
1696 	no_io_suspend,
1697 	no_io_resume
1698 };
1699 
1700 mdb_io_t *
1701 mdb_nullio_create(void)
1702 {
1703 	static mdb_io_t null_io = {
1704 		&null_ops,
1705 		NULL,
1706 		NULL,
1707 		1
1708 	};
1709 
1710 	return (&null_io);
1711 }
1712 
1713 size_t
1714 mdb_iob_vsnprintf(char *buf, size_t nbytes, const char *format, va_list alist)
1715 {
1716 	varglist_t ap = { VAT_VARARGS };
1717 	char iob_buf[64];
1718 	mdb_iob_t iob;
1719 	mdb_io_t io;
1720 	spbuf_t spb;
1721 
1722 	ASSERT(buf != NULL || nbytes == 0);
1723 	iob_spb_create(&iob, iob_buf, sizeof (iob_buf), &io, &spb, buf, nbytes);
1724 	va_copy(ap.val_valist, alist);
1725 	iob_doprnt(&iob, format, &ap);
1726 	mdb_iob_flush(&iob);
1727 
1728 	if (spb.spb_bufsiz != 0)
1729 		*spb.spb_buf = '\0';
1730 	else if (buf != NULL && nbytes > 0)
1731 		*--spb.spb_buf = '\0';
1732 
1733 	return (spb.spb_total);
1734 }
1735 
1736 size_t
1737 mdb_iob_asnprintf(char *buf, size_t nbytes, const char *format,
1738     const mdb_arg_t *argv)
1739 {
1740 	varglist_t ap = { VAT_ARGVEC };
1741 	char iob_buf[64];
1742 	mdb_iob_t iob;
1743 	mdb_io_t io;
1744 	spbuf_t spb;
1745 
1746 	ASSERT(buf != NULL || nbytes == 0);
1747 	iob_spb_create(&iob, iob_buf, sizeof (iob_buf), &io, &spb, buf, nbytes);
1748 	ap.val_argv = argv;
1749 	iob_doprnt(&iob, format, &ap);
1750 	mdb_iob_flush(&iob);
1751 
1752 	if (spb.spb_bufsiz != 0)
1753 		*spb.spb_buf = '\0';
1754 	else if (buf != NULL && nbytes > 0)
1755 		*--spb.spb_buf = '\0';
1756 
1757 	return (spb.spb_total);
1758 }
1759 
1760 /*PRINTFLIKE3*/
1761 size_t
1762 mdb_iob_snprintf(char *buf, size_t nbytes, const char *format, ...)
1763 {
1764 	va_list alist;
1765 
1766 	va_start(alist, format);
1767 	nbytes = mdb_iob_vsnprintf(buf, nbytes, format, alist);
1768 	va_end(alist);
1769 
1770 	return (nbytes);
1771 }
1772 
1773 void
1774 mdb_iob_nputs(mdb_iob_t *iob, const char *s, size_t nbytes)
1775 {
1776 	size_t m, n, nleft = nbytes;
1777 	const char *p, *q = s;
1778 
1779 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1780 
1781 	if (nbytes == 0)
1782 		return; /* Return immediately if there is no work to do */
1783 
1784 	/*
1785 	 * If the string contains embedded newlines or tabs, invoke ourself
1786 	 * recursively for each string component, followed by a call to the
1787 	 * newline or tab routine.  This insures that strings with these
1788 	 * characters obey our wrapping and indenting rules, and that strings
1789 	 * with embedded newlines are flushed after each newline, allowing
1790 	 * the output pager to take over if it is enabled.
1791 	 */
1792 	while ((p = strnpbrk(q, "\t\n", nleft)) != NULL) {
1793 		if (p > q)
1794 			mdb_iob_nputs(iob, q, (size_t)(p - q));
1795 
1796 		if (*p == '\t')
1797 			mdb_iob_tab(iob);
1798 		else
1799 			mdb_iob_nl(iob);
1800 
1801 		nleft -= (size_t)(p - q) + 1;	/* Update byte count */
1802 		q = p + 1;			/* Advance past delimiter */
1803 	}
1804 
1805 	/*
1806 	 * For a given string component, we determine how many bytes (n) we can
1807 	 * copy into our buffer (limited by either cols or bufsiz depending
1808 	 * on whether AUTOWRAP is on), copy a chunk into the buffer, and
1809 	 * flush the buffer if we reach the end of a line.
1810 	 */
1811 	while (nleft != 0) {
1812 		if (iob->iob_flags & MDB_IOB_AUTOWRAP) {
1813 			ASSERT(iob->iob_cols >= iob->iob_nbytes);
1814 			n = iob->iob_cols - iob->iob_nbytes;
1815 		} else {
1816 			ASSERT(iob->iob_bufsiz >= iob->iob_nbytes);
1817 			n = iob->iob_bufsiz - iob->iob_nbytes;
1818 		}
1819 
1820 		m = MIN(nleft, n); /* copy at most n bytes in this pass */
1821 
1822 		bcopy(q, iob->iob_bufp, m);
1823 		nleft -= m;
1824 		q += m;
1825 
1826 		iob->iob_bufp += m;
1827 		iob->iob_nbytes += m;
1828 
1829 		if (m == n && nleft != 0) {
1830 			if (iob->iob_flags & MDB_IOB_AUTOWRAP)
1831 				mdb_iob_nl(iob);
1832 			else
1833 				mdb_iob_flush(iob);
1834 		}
1835 	}
1836 }
1837 
1838 void
1839 mdb_iob_puts(mdb_iob_t *iob, const char *s)
1840 {
1841 	mdb_iob_nputs(iob, s, strlen(s));
1842 }
1843 
1844 void
1845 mdb_iob_putc(mdb_iob_t *iob, int c)
1846 {
1847 	mdb_iob_fill(iob, c, 1);
1848 }
1849 
1850 void
1851 mdb_iob_tab(mdb_iob_t *iob)
1852 {
1853 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1854 
1855 	if (iob->iob_tabstop != 0) {
1856 		/*
1857 		 * Round up to the next multiple of the tabstop.  If this puts
1858 		 * us off the end of the line, just insert a newline; otherwise
1859 		 * insert sufficient whitespace to reach position n.
1860 		 */
1861 		size_t n = (iob->iob_nbytes + iob->iob_tabstop) /
1862 		    iob->iob_tabstop * iob->iob_tabstop;
1863 
1864 		if (n < iob->iob_cols)
1865 			mdb_iob_fill(iob, ' ', n - iob->iob_nbytes);
1866 		else
1867 			mdb_iob_nl(iob);
1868 	}
1869 }
1870 
1871 void
1872 mdb_iob_fill(mdb_iob_t *iob, int c, size_t nfill)
1873 {
1874 	size_t i, m, n;
1875 
1876 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1877 
1878 	while (nfill != 0) {
1879 		if (iob->iob_flags & MDB_IOB_AUTOWRAP) {
1880 			ASSERT(iob->iob_cols >= iob->iob_nbytes);
1881 			n = iob->iob_cols - iob->iob_nbytes;
1882 		} else {
1883 			ASSERT(iob->iob_bufsiz >= iob->iob_nbytes);
1884 			n = iob->iob_bufsiz - iob->iob_nbytes;
1885 		}
1886 
1887 		m = MIN(nfill, n); /* fill at most n bytes in this pass */
1888 
1889 		for (i = 0; i < m; i++)
1890 			*iob->iob_bufp++ = (char)c;
1891 
1892 		iob->iob_nbytes += m;
1893 		nfill -= m;
1894 
1895 		if (m == n && nfill != 0) {
1896 			if (iob->iob_flags & MDB_IOB_AUTOWRAP)
1897 				mdb_iob_nl(iob);
1898 			else
1899 				mdb_iob_flush(iob);
1900 		}
1901 	}
1902 }
1903 
1904 void
1905 mdb_iob_ws(mdb_iob_t *iob, size_t n)
1906 {
1907 	if (iob->iob_nbytes + n < iob->iob_cols)
1908 		mdb_iob_fill(iob, ' ', n);
1909 	else
1910 		mdb_iob_nl(iob);
1911 }
1912 
1913 void
1914 mdb_iob_nl(mdb_iob_t *iob)
1915 {
1916 	ASSERT(iob->iob_flags & MDB_IOB_WRONLY);
1917 
1918 	if (iob->iob_nbytes == iob->iob_bufsiz)
1919 		mdb_iob_flush(iob);
1920 
1921 	*iob->iob_bufp++ = '\n';
1922 	iob->iob_nbytes++;
1923 
1924 	mdb_iob_flush(iob);
1925 }
1926 
1927 ssize_t
1928 mdb_iob_ngets(mdb_iob_t *iob, char *buf, size_t n)
1929 {
1930 	ssize_t resid = n - 1;
1931 	ssize_t len;
1932 	int c;
1933 
1934 	if (iob->iob_flags & (MDB_IOB_WRONLY | MDB_IOB_EOF))
1935 		return (EOF); /* can't gets a write buf or a read buf at EOF */
1936 
1937 	if (n == 0)
1938 		return (0);   /* we need room for a terminating \0 */
1939 
1940 	while (resid != 0) {
1941 		if (iob->iob_nbytes == 0 && iob_read(iob, iob->iob_iop) <= 0)
1942 			goto done; /* failed to refill buffer */
1943 
1944 		for (len = MIN(iob->iob_nbytes, resid); len != 0; len--) {
1945 			c = *iob->iob_bufp++;
1946 			iob->iob_nbytes--;
1947 
1948 			if (c == EOF || c == '\n')
1949 				goto done;
1950 
1951 			*buf++ = (char)c;
1952 			resid--;
1953 		}
1954 	}
1955 done:
1956 	*buf = '\0';
1957 	return (n - resid - 1);
1958 }
1959 
1960 int
1961 mdb_iob_getc(mdb_iob_t *iob)
1962 {
1963 	int c;
1964 
1965 	if (iob->iob_flags & (MDB_IOB_WRONLY | MDB_IOB_EOF | MDB_IOB_ERR))
1966 		return (EOF); /* can't getc if write-only, EOF, or error bit */
1967 
1968 	if (iob->iob_nbytes == 0 && iob_read(iob, iob->iob_iop) <= 0)
1969 		return (EOF); /* failed to refill buffer */
1970 
1971 	c = (uchar_t)*iob->iob_bufp++;
1972 	iob->iob_nbytes--;
1973 
1974 	return (c);
1975 }
1976 
1977 int
1978 mdb_iob_ungetc(mdb_iob_t *iob, int c)
1979 {
1980 	if (iob->iob_flags & (MDB_IOB_WRONLY | MDB_IOB_ERR))
1981 		return (EOF); /* can't ungetc if write-only or error bit set */
1982 
1983 	if (c == EOF || iob->iob_nbytes == iob->iob_bufsiz)
1984 		return (EOF); /* can't ungetc EOF, or ungetc if buffer full */
1985 
1986 	*--iob->iob_bufp = (char)c;
1987 	iob->iob_nbytes++;
1988 	iob->iob_flags &= ~MDB_IOB_EOF;
1989 
1990 	return (c);
1991 }
1992 
1993 int
1994 mdb_iob_eof(mdb_iob_t *iob)
1995 {
1996 	return ((iob->iob_flags & (MDB_IOB_RDONLY | MDB_IOB_EOF)) ==
1997 	    (MDB_IOB_RDONLY | MDB_IOB_EOF));
1998 }
1999 
2000 int
2001 mdb_iob_err(mdb_iob_t *iob)
2002 {
2003 	return ((iob->iob_flags & MDB_IOB_ERR) == MDB_IOB_ERR);
2004 }
2005 
2006 ssize_t
2007 mdb_iob_read(mdb_iob_t *iob, void *buf, size_t n)
2008 {
2009 	ssize_t resid = n;
2010 	ssize_t len;
2011 
2012 	if (iob->iob_flags & (MDB_IOB_WRONLY | MDB_IOB_EOF | MDB_IOB_ERR))
2013 		return (0); /* can't read if write-only, eof, or error */
2014 
2015 	while (resid != 0) {
2016 		if (iob->iob_nbytes == 0 && iob_read(iob, iob->iob_iop) <= 0)
2017 			break; /* failed to refill buffer */
2018 
2019 		len = MIN(resid, iob->iob_nbytes);
2020 		bcopy(iob->iob_bufp, buf, len);
2021 
2022 		iob->iob_bufp += len;
2023 		iob->iob_nbytes -= len;
2024 
2025 		buf = (char *)buf + len;
2026 		resid -= len;
2027 	}
2028 
2029 	return (n - resid);
2030 }
2031 
2032 /*
2033  * For now, all binary writes are performed unbuffered.  This has the
2034  * side effect that the pager will not be triggered by mdb_iob_write.
2035  */
2036 ssize_t
2037 mdb_iob_write(mdb_iob_t *iob, const void *buf, size_t n)
2038 {
2039 	ssize_t ret;
2040 
2041 	if (iob->iob_flags & MDB_IOB_ERR)
2042 		return (set_errno(EIO));
2043 	if (iob->iob_flags & MDB_IOB_RDONLY)
2044 		return (set_errno(EMDB_IORO));
2045 
2046 	mdb_iob_flush(iob);
2047 	ret = iob_write(iob, iob->iob_iop, buf, n);
2048 
2049 	if (ret < 0 && iob == mdb.m_out)
2050 		longjmp(mdb.m_frame->f_pcb, MDB_ERR_OUTPUT);
2051 
2052 	return (ret);
2053 }
2054 
2055 int
2056 mdb_iob_ctl(mdb_iob_t *iob, int req, void *arg)
2057 {
2058 	return (IOP_CTL(iob->iob_iop, req, arg));
2059 }
2060 
2061 const char *
2062 mdb_iob_name(mdb_iob_t *iob)
2063 {
2064 	if (iob == NULL)
2065 		return ("<NULL>");
2066 
2067 	return (IOP_NAME(iob->iob_iop));
2068 }
2069 
2070 size_t
2071 mdb_iob_lineno(mdb_iob_t *iob)
2072 {
2073 	return (iob->iob_lineno);
2074 }
2075 
2076 size_t
2077 mdb_iob_gettabstop(mdb_iob_t *iob)
2078 {
2079 	return (iob->iob_tabstop);
2080 }
2081 
2082 size_t
2083 mdb_iob_getmargin(mdb_iob_t *iob)
2084 {
2085 	return (iob->iob_margin);
2086 }
2087 
2088 mdb_io_t *
2089 mdb_io_hold(mdb_io_t *io)
2090 {
2091 	io->io_refcnt++;
2092 	return (io);
2093 }
2094 
2095 void
2096 mdb_io_rele(mdb_io_t *io)
2097 {
2098 	ASSERT(io->io_refcnt != 0);
2099 
2100 	if (--io->io_refcnt == 0) {
2101 		IOP_CLOSE(io);
2102 		mdb_free(io, sizeof (mdb_io_t));
2103 	}
2104 }
2105 
2106 void
2107 mdb_io_destroy(mdb_io_t *io)
2108 {
2109 	ASSERT(io->io_refcnt == 0);
2110 	IOP_CLOSE(io);
2111 	mdb_free(io, sizeof (mdb_io_t));
2112 }
2113 
2114 void
2115 mdb_iob_stack_create(mdb_iob_stack_t *stk)
2116 {
2117 	stk->stk_top = NULL;
2118 	stk->stk_size = 0;
2119 }
2120 
2121 void
2122 mdb_iob_stack_destroy(mdb_iob_stack_t *stk)
2123 {
2124 	mdb_iob_t *top, *ntop;
2125 
2126 	for (top = stk->stk_top; top != NULL; top = ntop) {
2127 		ntop = top->iob_next;
2128 		mdb_iob_destroy(top);
2129 	}
2130 }
2131 
2132 void
2133 mdb_iob_stack_push(mdb_iob_stack_t *stk, mdb_iob_t *iob, size_t lineno)
2134 {
2135 	iob->iob_lineno = lineno;
2136 	iob->iob_next = stk->stk_top;
2137 	stk->stk_top = iob;
2138 	stk->stk_size++;
2139 	yylineno = 1;
2140 }
2141 
2142 mdb_iob_t *
2143 mdb_iob_stack_pop(mdb_iob_stack_t *stk)
2144 {
2145 	mdb_iob_t *top = stk->stk_top;
2146 
2147 	ASSERT(top != NULL);
2148 
2149 	stk->stk_top = top->iob_next;
2150 	top->iob_next = NULL;
2151 	stk->stk_size--;
2152 
2153 	return (top);
2154 }
2155 
2156 size_t
2157 mdb_iob_stack_size(mdb_iob_stack_t *stk)
2158 {
2159 	return (stk->stk_size);
2160 }
2161 
2162 /*
2163  * Stub functions for i/o backend implementors: these stubs either act as
2164  * pass-through no-ops or return ENOTSUP as appropriate.
2165  */
2166 ssize_t
2167 no_io_read(mdb_io_t *io, void *buf, size_t nbytes)
2168 {
2169 	if (io->io_next != NULL)
2170 		return (IOP_READ(io->io_next, buf, nbytes));
2171 
2172 	return (set_errno(EMDB_IOWO));
2173 }
2174 
2175 ssize_t
2176 no_io_write(mdb_io_t *io, const void *buf, size_t nbytes)
2177 {
2178 	if (io->io_next != NULL)
2179 		return (IOP_WRITE(io->io_next, buf, nbytes));
2180 
2181 	return (set_errno(EMDB_IORO));
2182 }
2183 
2184 off64_t
2185 no_io_seek(mdb_io_t *io, off64_t offset, int whence)
2186 {
2187 	if (io->io_next != NULL)
2188 		return (IOP_SEEK(io->io_next, offset, whence));
2189 
2190 	return (set_errno(ENOTSUP));
2191 }
2192 
2193 int
2194 no_io_ctl(mdb_io_t *io, int req, void *arg)
2195 {
2196 	if (io->io_next != NULL)
2197 		return (IOP_CTL(io->io_next, req, arg));
2198 
2199 	return (set_errno(ENOTSUP));
2200 }
2201 
2202 /*ARGSUSED*/
2203 void
2204 no_io_close(mdb_io_t *io)
2205 {
2206 /*
2207  * Note that we do not propagate IOP_CLOSE down the io stack.  IOP_CLOSE should
2208  * only be called by mdb_io_rele when an io's reference count has gone to zero.
2209  */
2210 }
2211 
2212 const char *
2213 no_io_name(mdb_io_t *io)
2214 {
2215 	if (io->io_next != NULL)
2216 		return (IOP_NAME(io->io_next));
2217 
2218 	return ("(anonymous)");
2219 }
2220 
2221 void
2222 no_io_link(mdb_io_t *io, mdb_iob_t *iob)
2223 {
2224 	if (io->io_next != NULL)
2225 		IOP_LINK(io->io_next, iob);
2226 }
2227 
2228 void
2229 no_io_unlink(mdb_io_t *io, mdb_iob_t *iob)
2230 {
2231 	if (io->io_next != NULL)
2232 		IOP_UNLINK(io->io_next, iob);
2233 }
2234 
2235 int
2236 no_io_setattr(mdb_io_t *io, int req, uint_t attrs)
2237 {
2238 	if (io->io_next != NULL)
2239 		return (IOP_SETATTR(io->io_next, req, attrs));
2240 
2241 	return (set_errno(ENOTSUP));
2242 }
2243 
2244 void
2245 no_io_suspend(mdb_io_t *io)
2246 {
2247 	if (io->io_next != NULL)
2248 		IOP_SUSPEND(io->io_next);
2249 }
2250 
2251 void
2252 no_io_resume(mdb_io_t *io)
2253 {
2254 	if (io->io_next != NULL)
2255 		IOP_RESUME(io->io_next);
2256 }
2257 
2258 /*
2259  * Iterate over the varargs. The first item indicates the mode:
2260  * MDB_TBL_PRNT
2261  * 	pull out the next vararg as a const char * and pass it and the
2262  * 	remaining varargs to iob_doprnt; if we want to print the column,
2263  * 	direct the output to mdb.m_out otherwise direct it to mdb.m_null
2264  *
2265  * MDB_TBL_FUNC
2266  * 	pull out the next vararg as type mdb_table_print_f and the
2267  * 	following one as a void * argument to the function; call the
2268  * 	function with the given argument if we want to print the column
2269  *
2270  * The second item indicates the flag; if the flag is set in the flags
2271  * argument, then the column is printed. A flag value of 0 indicates
2272  * that the column should always be printed.
2273  */
2274 void
2275 mdb_table_print(uint_t flags, const char *delimeter, ...)
2276 {
2277 	va_list alist;
2278 	uint_t flg;
2279 	uint_t type;
2280 	const char *fmt;
2281 	mdb_table_print_f *func;
2282 	void *arg;
2283 	mdb_iob_t *out;
2284 	mdb_bool_t first = TRUE;
2285 	mdb_bool_t print;
2286 
2287 	va_start(alist, delimeter);
2288 
2289 	while ((type = va_arg(alist, uint_t)) != MDB_TBL_DONE) {
2290 		flg = va_arg(alist, uint_t);
2291 
2292 		print = flg == 0 || (flg & flags) != 0;
2293 
2294 		if (print) {
2295 			if (first)
2296 				first = FALSE;
2297 			else
2298 				mdb_printf("%s", delimeter);
2299 		}
2300 
2301 		switch (type) {
2302 		case MDB_TBL_PRNT: {
2303 			varglist_t ap = { VAT_VARARGS };
2304 			fmt = va_arg(alist, const char *);
2305 			out = print ? mdb.m_out : mdb.m_null;
2306 			va_copy(ap.val_valist, alist);
2307 			iob_doprnt(out, fmt, &ap);
2308 			va_end(alist);
2309 			va_copy(alist, ap.val_valist);
2310 			break;
2311 		}
2312 
2313 		case MDB_TBL_FUNC:
2314 			func = va_arg(alist, mdb_table_print_f *);
2315 			arg = va_arg(alist, void *);
2316 
2317 			if (print)
2318 				func(arg);
2319 
2320 			break;
2321 
2322 		default:
2323 			warn("bad format type %x\n", type);
2324 			break;
2325 		}
2326 	}
2327 
2328 	va_end(alist);
2329 }
2330