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