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