2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2000-2008 Poul-Henning Kamp
5 * Copyright (c) 2000-2008 Dag-Erling Coïdan Smørgrav
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer
13 * in this position and unchanged.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/param.h>
37 #include <sys/ctype.h>
38 #include <sys/errno.h>
39 #include <sys/kernel.h>
40 #include <sys/limits.h>
41 #include <sys/malloc.h>
42 #include <sys/systm.h>
44 #include <machine/stdarg.h>
58 static MALLOC_DEFINE(M_SBUF, "sbuf", "string buffers");
59 #define SBMALLOC(size, flags) malloc(size, M_SBUF, (flags) | M_ZERO)
60 #define SBFREE(buf) free(buf, M_SBUF)
63 #define SBMALLOC(size, flags) calloc(1, size)
64 #define SBFREE(buf) free(buf)
70 #define SBUF_ISDYNAMIC(s) ((s)->s_flags & SBUF_DYNAMIC)
71 #define SBUF_ISDYNSTRUCT(s) ((s)->s_flags & SBUF_DYNSTRUCT)
72 #define SBUF_ISFINISHED(s) ((s)->s_flags & SBUF_FINISHED)
73 #define SBUF_ISDRAINATEOL(s) ((s)->s_flags & SBUF_DRAINATEOL)
74 #define SBUF_HASROOM(s) ((s)->s_len < (s)->s_size - 1)
75 #define SBUF_FREESPACE(s) ((s)->s_size - ((s)->s_len + 1))
76 #define SBUF_CANEXTEND(s) ((s)->s_flags & SBUF_AUTOEXTEND)
77 #define SBUF_ISSECTION(s) ((s)->s_flags & SBUF_INSECTION)
78 #define SBUF_NULINCLUDED(s) ((s)->s_flags & SBUF_INCLUDENUL)
79 #define SBUF_ISDRAINTOEOR(s) ((s)->s_flags & SBUF_DRAINTOEOR)
80 #define SBUF_DODRAINTOEOR(s) (SBUF_ISSECTION(s) && SBUF_ISDRAINTOEOR(s))
81 #define SBUF_MALLOCFLAG(s) \
82 (((s)->s_flags & SBUF_NOWAIT) ? M_NOWAIT : M_WAITOK)
87 #define SBUF_SETFLAG(s, f) do { (s)->s_flags |= (f); } while (0)
88 #define SBUF_CLEARFLAG(s, f) do { (s)->s_flags &= ~(f); } while (0)
90 #define SBUF_MINSIZE 2 /* Min is 1 byte + nulterm. */
91 #define SBUF_MINEXTENDSIZE 16 /* Should be power of 2. */
94 #define SBUF_MAXEXTENDSIZE PAGE_SIZE
95 #define SBUF_MAXEXTENDINCR PAGE_SIZE
97 #define SBUF_MAXEXTENDSIZE 4096
98 #define SBUF_MAXEXTENDINCR 4096
104 #if defined(_KERNEL) && defined(INVARIANTS)
107 _assert_sbuf_integrity(const char *fun, struct sbuf *s)
111 ("%s called with a NULL sbuf pointer", fun));
112 KASSERT(s->s_buf != NULL,
113 ("%s called with uninitialized or corrupt sbuf", fun));
114 if (SBUF_ISFINISHED(s) && SBUF_NULINCLUDED(s)) {
115 KASSERT(s->s_len <= s->s_size,
116 ("wrote past end of sbuf (%jd >= %jd)",
117 (intmax_t)s->s_len, (intmax_t)s->s_size));
119 KASSERT(s->s_len < s->s_size,
120 ("wrote past end of sbuf (%jd >= %jd)",
121 (intmax_t)s->s_len, (intmax_t)s->s_size));
126 _assert_sbuf_state(const char *fun, struct sbuf *s, int state)
129 KASSERT((s->s_flags & SBUF_FINISHED) == state,
130 ("%s called with %sfinished or corrupt sbuf", fun,
131 (state ? "un" : "")));
134 #define assert_sbuf_integrity(s) _assert_sbuf_integrity(__func__, (s))
135 #define assert_sbuf_state(s, i) _assert_sbuf_state(__func__, (s), (i))
137 #else /* _KERNEL && INVARIANTS */
139 #define assert_sbuf_integrity(s) do { } while (0)
140 #define assert_sbuf_state(s, i) do { } while (0)
142 #endif /* _KERNEL && INVARIANTS */
145 CTASSERT(powerof2(SBUF_MAXEXTENDSIZE));
146 CTASSERT(powerof2(SBUF_MAXEXTENDINCR));
150 sbuf_extendsize(int size)
154 if (size < (int)SBUF_MAXEXTENDSIZE) {
155 newsize = SBUF_MINEXTENDSIZE;
156 while (newsize < size)
159 newsize = roundup2(size, SBUF_MAXEXTENDINCR);
161 KASSERT(newsize >= size, ("%s: %d < %d\n", __func__, newsize, size));
169 sbuf_extend(struct sbuf *s, int addlen)
174 if (!SBUF_CANEXTEND(s))
176 newsize = sbuf_extendsize(s->s_size + addlen);
177 newbuf = SBMALLOC(newsize, SBUF_MALLOCFLAG(s));
180 memcpy(newbuf, s->s_buf, s->s_size);
181 if (SBUF_ISDYNAMIC(s))
184 SBUF_SETFLAG(s, SBUF_DYNAMIC);
191 * Initialize an sbuf.
192 * If buf is non-NULL, it points to a static or already-allocated string
193 * big enough to hold at least length characters.
196 sbuf_new(struct sbuf *s, char *buf, int length, int flags)
200 ("attempt to create an sbuf of negative length (%d)", length));
201 KASSERT((flags & ~SBUF_USRFLAGMSK) == 0,
202 ("%s called with invalid flags", __func__));
203 KASSERT((flags & SBUF_AUTOEXTEND) || length >= SBUF_MINSIZE,
204 ("sbuf buffer %d smaller than minimum %d bytes", length,
207 flags &= SBUF_USRFLAGMSK;
210 * Allocate 'DYNSTRUCT' sbuf from the heap, if NULL 's' was provided.
213 s = SBMALLOC(sizeof(*s),
214 (flags & SBUF_NOWAIT) ? M_NOWAIT : M_WAITOK);
217 SBUF_SETFLAG(s, SBUF_DYNSTRUCT);
220 * DYNSTRUCT SBMALLOC sbufs are allocated with M_ZERO, but
221 * user-provided sbuf objects must be initialized.
223 memset(s, 0, sizeof(*s));
230 * Never-written sbufs do not need \n termination.
232 SBUF_SETFLAG(s, SBUF_DRAINATEOL);
235 * Allocate DYNAMIC, i.e., heap data buffer backing the sbuf, if no
236 * buffer was provided.
238 if (s->s_buf == NULL) {
239 if (SBUF_CANEXTEND(s))
240 s->s_size = sbuf_extendsize(s->s_size);
241 s->s_buf = SBMALLOC(s->s_size, SBUF_MALLOCFLAG(s));
242 if (s->s_buf == NULL)
244 SBUF_SETFLAG(s, SBUF_DYNAMIC);
248 if (s != NULL && s->s_buf == NULL) {
249 if (SBUF_ISDYNSTRUCT(s))
258 * Create an sbuf with uio data
261 sbuf_uionew(struct sbuf *s, struct uio *uio, int *error)
265 ("%s called with NULL uio pointer", __func__));
266 KASSERT(error != NULL,
267 ("%s called with NULL error pointer", __func__));
269 if (uio->uio_resid >= INT_MAX || uio->uio_resid < SBUF_MINSIZE - 1) {
273 s = sbuf_new(s, NULL, uio->uio_resid + 1, 0);
278 *error = uiomove(s->s_buf, uio->uio_resid, uio);
283 s->s_len = s->s_size - 1;
284 if (SBUF_ISSECTION(s))
285 s->s_sect_len = s->s_size - 1;
292 sbuf_get_flags(struct sbuf *s)
295 return (s->s_flags & SBUF_USRFLAGMSK);
299 sbuf_clear_flags(struct sbuf *s, int flags)
302 s->s_flags &= ~(flags & SBUF_USRFLAGMSK);
306 sbuf_set_flags(struct sbuf *s, int flags)
309 s->s_flags |= (flags & SBUF_USRFLAGMSK);
313 * Clear an sbuf and reset its position.
316 sbuf_clear(struct sbuf *s)
319 assert_sbuf_integrity(s);
320 /* don't care if it's finished or not */
321 KASSERT(s->s_drain_func == NULL,
322 ("%s makes no sense on sbuf %p with drain", __func__, s));
324 SBUF_CLEARFLAG(s, SBUF_FINISHED);
332 * Set the sbuf's end position to an arbitrary value.
333 * Effectively truncates the sbuf at the new position.
336 sbuf_setpos(struct sbuf *s, ssize_t pos)
339 assert_sbuf_integrity(s);
340 assert_sbuf_state(s, 0);
343 ("attempt to seek to a negative position (%jd)", (intmax_t)pos));
344 KASSERT(pos < s->s_size,
345 ("attempt to seek past end of sbuf (%jd >= %jd)",
346 (intmax_t)pos, (intmax_t)s->s_size));
347 KASSERT(!SBUF_ISSECTION(s),
348 ("attempt to seek when in a section"));
350 if (pos < 0 || pos > s->s_len)
357 * Drain into a counter. Counts amount of data without producing output.
358 * Useful for cases like sysctl, where user may first request only size.
359 * This allows to avoid pointless allocation/freeing of large buffers.
362 sbuf_count_drain(void *arg, const char *data __unused, int len)
366 sizep = (size_t *)arg;
372 * Set up a drain function and argument on an sbuf to flush data to
373 * when the sbuf buffer overflows.
376 sbuf_set_drain(struct sbuf *s, sbuf_drain_func *func, void *ctx)
379 assert_sbuf_state(s, 0);
380 assert_sbuf_integrity(s);
381 KASSERT(func == s->s_drain_func || s->s_len == 0,
382 ("Cannot change drain to %p on non-empty sbuf %p", func, s));
383 s->s_drain_func = func;
384 s->s_drain_arg = ctx;
388 * Call the drain and process the return.
391 sbuf_drain(struct sbuf *s)
396 * Immediately return when no work to do,
397 * or an error has already been accumulated.
399 if ((s->s_len == 0) || (s->s_error != 0))
402 if (SBUF_DODRAINTOEOR(s) && s->s_rec_off == 0)
403 return (s->s_error = EDEADLK);
404 len = s->s_drain_func(s->s_drain_arg, s->s_buf,
405 SBUF_DODRAINTOEOR(s) ? s->s_rec_off : s->s_len);
407 s->s_error = len ? -len : EDEADLK;
410 KASSERT(len > 0 && len <= s->s_len,
411 ("Bad drain amount %d for sbuf %p", len, s));
415 * Fast path for the expected case where all the data was
420 * When the s_buf is entirely drained, we need to remember if
421 * the last character was a '\n' or not for
422 * sbuf_nl_terminate().
424 if (s->s_buf[len - 1] == '\n')
425 SBUF_SETFLAG(s, SBUF_DRAINATEOL);
427 SBUF_CLEARFLAG(s, SBUF_DRAINATEOL);
431 * Move the remaining characters to the beginning of the
434 memmove(s->s_buf, s->s_buf + len, s->s_len);
439 * Append bytes to an sbuf. This is the core function for appending
440 * to an sbuf and is the main place that deals with extending the
441 * buffer and marking overflow.
444 sbuf_put_bytes(struct sbuf *s, const char *buf, size_t len)
448 assert_sbuf_integrity(s);
449 assert_sbuf_state(s, 0);
454 if (SBUF_FREESPACE(s) <= 0) {
456 * If there is a drain, use it, otherwise extend the
459 if (s->s_drain_func != NULL)
461 else if (sbuf_extend(s, len > INT_MAX ? INT_MAX : len)
467 n = SBUF_FREESPACE(s);
470 memcpy(&s->s_buf[s->s_len], buf, n);
472 if (SBUF_ISSECTION(s))
480 sbuf_put_byte(struct sbuf *s, char c)
483 assert_sbuf_integrity(s);
484 assert_sbuf_state(s, 0);
486 if (__predict_false(s->s_error != 0))
488 if (__predict_false(SBUF_FREESPACE(s) <= 0)) {
490 * If there is a drain, use it, otherwise extend the
493 if (s->s_drain_func != NULL)
495 else if (sbuf_extend(s, 1) < 0)
500 s->s_buf[s->s_len++] = c;
501 if (SBUF_ISSECTION(s))
506 * Append a byte string to an sbuf.
509 sbuf_bcat(struct sbuf *s, const void *buf, size_t len)
512 sbuf_put_bytes(s, buf, len);
520 * Copy a byte string from userland into an sbuf.
523 sbuf_bcopyin(struct sbuf *s, const void *uaddr, size_t len)
526 assert_sbuf_integrity(s);
527 assert_sbuf_state(s, 0);
528 KASSERT(s->s_drain_func == NULL,
529 ("Nonsensical copyin to sbuf %p with a drain", s));
535 if (len > SBUF_FREESPACE(s)) {
536 sbuf_extend(s, len - SBUF_FREESPACE(s));
537 if (SBUF_FREESPACE(s) < len)
538 len = SBUF_FREESPACE(s);
540 if (copyin(uaddr, s->s_buf + s->s_len, len) != 0)
549 * Copy a byte string into an sbuf.
552 sbuf_bcpy(struct sbuf *s, const void *buf, size_t len)
555 assert_sbuf_integrity(s);
556 assert_sbuf_state(s, 0);
559 return (sbuf_bcat(s, buf, len));
563 * Append a string to an sbuf.
566 sbuf_cat(struct sbuf *s, const char *str)
571 sbuf_put_bytes(s, str, n);
579 * Append a string from userland to an sbuf.
582 sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
586 assert_sbuf_integrity(s);
587 assert_sbuf_state(s, 0);
588 KASSERT(s->s_drain_func == NULL,
589 ("Nonsensical copyin to sbuf %p with a drain", s));
595 len = SBUF_FREESPACE(s); /* XXX return 0? */
596 if (len > SBUF_FREESPACE(s)) {
598 if (SBUF_FREESPACE(s) < len)
599 len = SBUF_FREESPACE(s);
601 switch (copyinstr(uaddr, s->s_buf + s->s_len, len + 1, &done)) {
606 s->s_len += done - 1;
607 if (SBUF_ISSECTION(s))
608 s->s_sect_len += done - 1;
611 return (-1); /* XXX */
619 * Copy a string into an sbuf.
622 sbuf_cpy(struct sbuf *s, const char *str)
625 assert_sbuf_integrity(s);
626 assert_sbuf_state(s, 0);
629 return (sbuf_cat(s, str));
633 * Format the given argument list and append the resulting string to an sbuf.
638 * Append a non-NUL character to an sbuf. This prototype signature is
639 * suitable for use with kvprintf(9).
642 sbuf_putc_func(int c, void *arg)
645 if (__predict_true(c != '\0'))
646 sbuf_put_byte(arg, c);
650 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
653 assert_sbuf_integrity(s);
654 assert_sbuf_state(s, 0);
657 ("%s called with a NULL format string", __func__));
659 (void)kvprintf(fmt, sbuf_putc_func, s, 10, ap);
666 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
671 assert_sbuf_integrity(s);
672 assert_sbuf_state(s, 0);
675 ("%s called with a NULL format string", __func__));
681 * For the moment, there is no way to get vsnprintf(3) to hand
682 * back a character at a time, to push everything into
683 * sbuf_putc_func() as was done for the kernel.
685 * In userspace, while drains are useful, there's generally
686 * not a problem attempting to malloc(3) on out of space. So
687 * expand a userland sbuf if there is not enough room for the
688 * data produced by sbuf_[v]printf(3).
693 va_copy(ap_copy, ap);
694 len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1,
702 if (SBUF_FREESPACE(s) >= len)
704 /* Cannot print with the current available space. */
705 if (s->s_drain_func != NULL && s->s_len > 0)
706 error = sbuf_drain(s); /* sbuf_drain() sets s_error. */
707 else if (sbuf_extend(s, len - SBUF_FREESPACE(s)) != 0)
708 s->s_error = error = ENOMEM;
709 } while (error == 0);
712 * s->s_len is the length of the string, without the terminating nul.
713 * When updating s->s_len, we must subtract 1 from the length that
714 * we passed into vsnprintf() because that length includes the
717 * vsnprintf() returns the amount that would have been copied,
718 * given sufficient space, so don't over-increment s_len.
720 if (SBUF_FREESPACE(s) < len)
721 len = SBUF_FREESPACE(s);
723 if (SBUF_ISSECTION(s))
724 s->s_sect_len += len;
726 KASSERT(s->s_len < s->s_size,
727 ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
736 * Format the given arguments and append the resulting string to an sbuf.
739 sbuf_printf(struct sbuf *s, const char *fmt, ...)
745 result = sbuf_vprintf(s, fmt, ap);
751 * Append a character to an sbuf.
754 sbuf_putc(struct sbuf *s, int c)
764 * Append a trailing newline to a non-empty sbuf, if one is not already
765 * present. Handles sbufs with drain functions correctly.
768 sbuf_nl_terminate(struct sbuf *s)
771 assert_sbuf_integrity(s);
772 assert_sbuf_state(s, 0);
775 * If the s_buf isn't empty, the last byte is simply s_buf[s_len - 1].
777 * If the s_buf is empty because a drain function drained it, we
778 * remember if the last byte was a \n with the SBUF_DRAINATEOL flag in
781 * In either case, we only append a \n if the previous character was
785 if (!SBUF_ISDRAINATEOL(s))
786 sbuf_put_byte(s, '\n');
787 } else if (s->s_buf[s->s_len - 1] != '\n')
788 sbuf_put_byte(s, '\n');
796 * Trim whitespace characters from end of an sbuf.
799 sbuf_trim(struct sbuf *s)
802 assert_sbuf_integrity(s);
803 assert_sbuf_state(s, 0);
804 KASSERT(s->s_drain_func == NULL,
805 ("%s makes no sense on sbuf %p with drain", __func__, s));
810 while (s->s_len > 0 && isspace(s->s_buf[s->s_len-1])) {
812 if (SBUF_ISSECTION(s))
820 * Check if an sbuf has an error.
823 sbuf_error(const struct sbuf *s)
830 * Finish off an sbuf.
833 sbuf_finish(struct sbuf *s)
836 assert_sbuf_integrity(s);
837 assert_sbuf_state(s, 0);
839 s->s_buf[s->s_len] = '\0';
840 if (SBUF_NULINCLUDED(s))
842 if (s->s_drain_func != NULL) {
843 while (s->s_len > 0 && s->s_error == 0)
844 s->s_error = sbuf_drain(s);
846 SBUF_SETFLAG(s, SBUF_FINISHED);
850 if (s->s_error != 0) {
859 * Return a pointer to the sbuf data.
862 sbuf_data(struct sbuf *s)
865 assert_sbuf_integrity(s);
866 assert_sbuf_state(s, SBUF_FINISHED);
867 KASSERT(s->s_drain_func == NULL,
868 ("%s makes no sense on sbuf %p with drain", __func__, s));
874 * Return the length of the sbuf data.
877 sbuf_len(struct sbuf *s)
880 assert_sbuf_integrity(s);
881 /* don't care if it's finished or not */
882 KASSERT(s->s_drain_func == NULL,
883 ("%s makes no sense on sbuf %p with drain", __func__, s));
888 /* If finished, nulterm is already in len, else add one. */
889 if (SBUF_NULINCLUDED(s) && !SBUF_ISFINISHED(s))
890 return (s->s_len + 1);
895 * Clear an sbuf, free its buffer if necessary.
898 sbuf_delete(struct sbuf *s)
902 assert_sbuf_integrity(s);
903 /* don't care if it's finished or not */
905 if (SBUF_ISDYNAMIC(s))
907 isdyn = SBUF_ISDYNSTRUCT(s);
908 memset(s, 0, sizeof(*s));
914 * Check if an sbuf has been finished.
917 sbuf_done(const struct sbuf *s)
920 return (SBUF_ISFINISHED(s));
927 sbuf_start_section(struct sbuf *s, ssize_t *old_lenp)
930 assert_sbuf_integrity(s);
931 assert_sbuf_state(s, 0);
933 if (!SBUF_ISSECTION(s)) {
934 KASSERT(s->s_sect_len == 0,
935 ("s_sect_len != 0 when starting a section"));
936 if (old_lenp != NULL)
938 s->s_rec_off = s->s_len;
939 SBUF_SETFLAG(s, SBUF_INSECTION);
941 KASSERT(old_lenp != NULL,
942 ("s_sect_len should be saved when starting a subsection"));
943 *old_lenp = s->s_sect_len;
949 * End the section padding to the specified length with the specified
953 sbuf_end_section(struct sbuf *s, ssize_t old_len, size_t pad, int c)
957 assert_sbuf_integrity(s);
958 assert_sbuf_state(s, 0);
959 KASSERT(SBUF_ISSECTION(s),
960 ("attempt to end a section when not in a section"));
963 len = roundup(s->s_sect_len, pad) - s->s_sect_len;
964 for (; s->s_error == 0 && len > 0; len--)
969 s->s_rec_off = s->s_sect_len = 0;
970 SBUF_CLEARFLAG(s, SBUF_INSECTION);
972 s->s_sect_len += old_len;