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