2 * Copyright (c) 2000-2008 Poul-Henning Kamp
3 * Copyright (c) 2000-2008 Dag-Erling Coïdan Smørgrav
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer
11 * in this position and unchanged.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
35 #include <sys/ctype.h>
36 #include <sys/errno.h>
37 #include <sys/kernel.h>
38 #include <sys/limits.h>
39 #include <sys/malloc.h>
40 #include <sys/systm.h>
42 #include <machine/stdarg.h>
56 static MALLOC_DEFINE(M_SBUF, "sbuf", "string buffers");
57 #define SBMALLOC(size) malloc(size, M_SBUF, M_WAITOK|M_ZERO)
58 #define SBFREE(buf) free(buf, M_SBUF)
61 #define SBMALLOC(size) calloc(1, size)
62 #define SBFREE(buf) free(buf)
68 #define SBUF_ISDYNAMIC(s) ((s)->s_flags & SBUF_DYNAMIC)
69 #define SBUF_ISDYNSTRUCT(s) ((s)->s_flags & SBUF_DYNSTRUCT)
70 #define SBUF_ISFINISHED(s) ((s)->s_flags & SBUF_FINISHED)
71 #define SBUF_HASROOM(s) ((s)->s_len < (s)->s_size - 1)
72 #define SBUF_FREESPACE(s) ((s)->s_size - ((s)->s_len + 1))
73 #define SBUF_CANEXTEND(s) ((s)->s_flags & SBUF_AUTOEXTEND)
74 #define SBUF_ISSECTION(s) ((s)->s_flags & SBUF_INSECTION)
75 #define SBUF_NULINCLUDED(s) ((s)->s_flags & SBUF_INCLUDENUL)
80 #define SBUF_SETFLAG(s, f) do { (s)->s_flags |= (f); } while (0)
81 #define SBUF_CLEARFLAG(s, f) do { (s)->s_flags &= ~(f); } while (0)
83 #define SBUF_MINSIZE 2 /* Min is 1 byte + nulterm. */
84 #define SBUF_MINEXTENDSIZE 16 /* Should be power of 2. */
87 #define SBUF_MAXEXTENDSIZE PAGE_SIZE
88 #define SBUF_MAXEXTENDINCR PAGE_SIZE
90 #define SBUF_MAXEXTENDSIZE 4096
91 #define SBUF_MAXEXTENDINCR 4096
97 #if defined(_KERNEL) && defined(INVARIANTS)
100 _assert_sbuf_integrity(const char *fun, struct sbuf *s)
104 ("%s called with a NULL sbuf pointer", fun));
105 KASSERT(s->s_buf != NULL,
106 ("%s called with uninitialized or corrupt sbuf", fun));
107 if (SBUF_ISFINISHED(s) && SBUF_NULINCLUDED(s)) {
108 KASSERT(s->s_len <= s->s_size,
109 ("wrote past end of sbuf (%jd >= %jd)",
110 (intmax_t)s->s_len, (intmax_t)s->s_size));
112 KASSERT(s->s_len < s->s_size,
113 ("wrote past end of sbuf (%jd >= %jd)",
114 (intmax_t)s->s_len, (intmax_t)s->s_size));
119 _assert_sbuf_state(const char *fun, struct sbuf *s, int state)
122 KASSERT((s->s_flags & SBUF_FINISHED) == state,
123 ("%s called with %sfinished or corrupt sbuf", fun,
124 (state ? "un" : "")));
127 #define assert_sbuf_integrity(s) _assert_sbuf_integrity(__func__, (s))
128 #define assert_sbuf_state(s, i) _assert_sbuf_state(__func__, (s), (i))
130 #else /* _KERNEL && INVARIANTS */
132 #define assert_sbuf_integrity(s) do { } while (0)
133 #define assert_sbuf_state(s, i) do { } while (0)
135 #endif /* _KERNEL && INVARIANTS */
138 CTASSERT(powerof2(SBUF_MAXEXTENDSIZE));
139 CTASSERT(powerof2(SBUF_MAXEXTENDINCR));
143 sbuf_extendsize(int size)
147 if (size < (int)SBUF_MAXEXTENDSIZE) {
148 newsize = SBUF_MINEXTENDSIZE;
149 while (newsize < size)
152 newsize = roundup2(size, SBUF_MAXEXTENDINCR);
154 KASSERT(newsize >= size, ("%s: %d < %d\n", __func__, newsize, size));
162 sbuf_extend(struct sbuf *s, int addlen)
167 if (!SBUF_CANEXTEND(s))
169 newsize = sbuf_extendsize(s->s_size + addlen);
170 newbuf = SBMALLOC(newsize);
173 memcpy(newbuf, s->s_buf, s->s_size);
174 if (SBUF_ISDYNAMIC(s))
177 SBUF_SETFLAG(s, SBUF_DYNAMIC);
184 * Initialize the internals of an sbuf.
185 * If buf is non-NULL, it points to a static or already-allocated string
186 * big enough to hold at least length characters.
189 sbuf_newbuf(struct sbuf *s, char *buf, int length, int flags)
192 memset(s, 0, sizeof(*s));
197 if ((s->s_flags & SBUF_AUTOEXTEND) == 0) {
198 KASSERT(s->s_size >= SBUF_MINSIZE,
199 ("attempt to create an sbuf smaller than %d bytes",
203 if (s->s_buf != NULL)
206 if ((flags & SBUF_AUTOEXTEND) != 0)
207 s->s_size = sbuf_extendsize(s->s_size);
209 s->s_buf = SBMALLOC(s->s_size);
210 if (s->s_buf == NULL)
212 SBUF_SETFLAG(s, SBUF_DYNAMIC);
217 * Initialize an sbuf.
218 * If buf is non-NULL, it points to a static or already-allocated string
219 * big enough to hold at least length characters.
222 sbuf_new(struct sbuf *s, char *buf, int length, int flags)
226 ("attempt to create an sbuf of negative length (%d)", length));
227 KASSERT((flags & ~SBUF_USRFLAGMSK) == 0,
228 ("%s called with invalid flags", __func__));
230 flags &= SBUF_USRFLAGMSK;
232 return (sbuf_newbuf(s, buf, length, flags));
234 s = SBMALLOC(sizeof(*s));
237 if (sbuf_newbuf(s, buf, length, flags) == NULL) {
241 SBUF_SETFLAG(s, SBUF_DYNSTRUCT);
247 * Create an sbuf with uio data
250 sbuf_uionew(struct sbuf *s, struct uio *uio, int *error)
254 ("%s called with NULL uio pointer", __func__));
255 KASSERT(error != NULL,
256 ("%s called with NULL error pointer", __func__));
258 s = sbuf_new(s, NULL, uio->uio_resid + 1, 0);
263 *error = uiomove(s->s_buf, uio->uio_resid, uio);
268 s->s_len = s->s_size - 1;
269 if (SBUF_ISSECTION(s))
270 s->s_sect_len = s->s_size - 1;
277 sbuf_get_flags(struct sbuf *s)
280 return (s->s_flags & SBUF_USRFLAGMSK);
284 sbuf_clear_flags(struct sbuf *s, int flags)
287 s->s_flags &= ~(flags & SBUF_USRFLAGMSK);
291 sbuf_set_flags(struct sbuf *s, int flags)
295 s->s_flags |= (flags & SBUF_USRFLAGMSK);
299 * Clear an sbuf and reset its position.
302 sbuf_clear(struct sbuf *s)
305 assert_sbuf_integrity(s);
306 /* don't care if it's finished or not */
308 SBUF_CLEARFLAG(s, SBUF_FINISHED);
315 * Set the sbuf's end position to an arbitrary value.
316 * Effectively truncates the sbuf at the new position.
319 sbuf_setpos(struct sbuf *s, ssize_t pos)
322 assert_sbuf_integrity(s);
323 assert_sbuf_state(s, 0);
326 ("attempt to seek to a negative position (%jd)", (intmax_t)pos));
327 KASSERT(pos < s->s_size,
328 ("attempt to seek past end of sbuf (%jd >= %jd)",
329 (intmax_t)pos, (intmax_t)s->s_size));
330 KASSERT(!SBUF_ISSECTION(s),
331 ("attempt to seek when in a section"));
333 if (pos < 0 || pos > s->s_len)
340 * Set up a drain function and argument on an sbuf to flush data to
341 * when the sbuf buffer overflows.
344 sbuf_set_drain(struct sbuf *s, sbuf_drain_func *func, void *ctx)
347 assert_sbuf_state(s, 0);
348 assert_sbuf_integrity(s);
349 KASSERT(func == s->s_drain_func || s->s_len == 0,
350 ("Cannot change drain to %p on non-empty sbuf %p", func, s));
351 s->s_drain_func = func;
352 s->s_drain_arg = ctx;
356 * Call the drain and process the return.
359 sbuf_drain(struct sbuf *s)
363 KASSERT(s->s_len > 0, ("Shouldn't drain empty sbuf %p", s));
364 KASSERT(s->s_error == 0, ("Called %s with error on %p", __func__, s));
365 len = s->s_drain_func(s->s_drain_arg, s->s_buf, s->s_len);
370 KASSERT(len > 0 && len <= s->s_len,
371 ("Bad drain amount %d for sbuf %p", len, s));
374 * Fast path for the expected case where all the data was
380 * Move the remaining characters to the beginning of the
383 memmove(s->s_buf, s->s_buf + len, s->s_len);
388 * Append bytes to an sbuf. This is the core function for appending
389 * to an sbuf and is the main place that deals with extending the
390 * buffer and marking overflow.
393 sbuf_put_bytes(struct sbuf *s, const char *buf, size_t len)
397 assert_sbuf_integrity(s);
398 assert_sbuf_state(s, 0);
403 if (SBUF_FREESPACE(s) <= 0) {
405 * If there is a drain, use it, otherwise extend the
408 if (s->s_drain_func != NULL)
410 else if (sbuf_extend(s, len > INT_MAX ? INT_MAX : len)
416 n = SBUF_FREESPACE(s);
419 memcpy(&s->s_buf[s->s_len], buf, n);
421 if (SBUF_ISSECTION(s))
429 sbuf_put_byte(struct sbuf *s, char c)
432 sbuf_put_bytes(s, &c, 1);
436 * Append a byte string to an sbuf.
439 sbuf_bcat(struct sbuf *s, const void *buf, size_t len)
442 sbuf_put_bytes(s, buf, len);
450 * Copy a byte string from userland into an sbuf.
453 sbuf_bcopyin(struct sbuf *s, const void *uaddr, size_t len)
456 assert_sbuf_integrity(s);
457 assert_sbuf_state(s, 0);
458 KASSERT(s->s_drain_func == NULL,
459 ("Nonsensical copyin to sbuf %p with a drain", s));
465 if (len > SBUF_FREESPACE(s)) {
466 sbuf_extend(s, len - SBUF_FREESPACE(s));
467 if (SBUF_FREESPACE(s) < len)
468 len = SBUF_FREESPACE(s);
470 if (copyin(uaddr, s->s_buf + s->s_len, len) != 0)
479 * Copy a byte string into an sbuf.
482 sbuf_bcpy(struct sbuf *s, const void *buf, size_t len)
485 assert_sbuf_integrity(s);
486 assert_sbuf_state(s, 0);
489 return (sbuf_bcat(s, buf, len));
493 * Append a string to an sbuf.
496 sbuf_cat(struct sbuf *s, const char *str)
501 sbuf_put_bytes(s, str, n);
509 * Append a string from userland to an sbuf.
512 sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
516 assert_sbuf_integrity(s);
517 assert_sbuf_state(s, 0);
518 KASSERT(s->s_drain_func == NULL,
519 ("Nonsensical copyin to sbuf %p with a drain", s));
525 len = SBUF_FREESPACE(s); /* XXX return 0? */
526 if (len > SBUF_FREESPACE(s)) {
528 if (SBUF_FREESPACE(s) < len)
529 len = SBUF_FREESPACE(s);
531 switch (copyinstr(uaddr, s->s_buf + s->s_len, len + 1, &done)) {
536 s->s_len += done - 1;
537 if (SBUF_ISSECTION(s))
538 s->s_sect_len += done - 1;
541 return (-1); /* XXX */
549 * Copy a string into an sbuf.
552 sbuf_cpy(struct sbuf *s, const char *str)
555 assert_sbuf_integrity(s);
556 assert_sbuf_state(s, 0);
559 return (sbuf_cat(s, str));
563 * Format the given argument list and append the resulting string to an sbuf.
568 * Append a non-NUL character to an sbuf. This prototype signature is
569 * suitable for use with kvprintf(9).
572 sbuf_putc_func(int c, void *arg)
576 sbuf_put_byte(arg, c);
580 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
583 assert_sbuf_integrity(s);
584 assert_sbuf_state(s, 0);
587 ("%s called with a NULL format string", __func__));
589 (void)kvprintf(fmt, sbuf_putc_func, s, 10, ap);
596 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
601 assert_sbuf_integrity(s);
602 assert_sbuf_state(s, 0);
605 ("%s called with a NULL format string", __func__));
611 * For the moment, there is no way to get vsnprintf(3) to hand
612 * back a character at a time, to push everything into
613 * sbuf_putc_func() as was done for the kernel.
615 * In userspace, while drains are useful, there's generally
616 * not a problem attempting to malloc(3) on out of space. So
617 * expand a userland sbuf if there is not enough room for the
618 * data produced by sbuf_[v]printf(3).
623 va_copy(ap_copy, ap);
624 len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1,
632 if (SBUF_FREESPACE(s) >= len)
634 /* Cannot print with the current available space. */
635 if (s->s_drain_func != NULL && s->s_len > 0)
636 error = sbuf_drain(s);
638 error = sbuf_extend(s, len - SBUF_FREESPACE(s));
639 } while (error == 0);
642 * s->s_len is the length of the string, without the terminating nul.
643 * When updating s->s_len, we must subtract 1 from the length that
644 * we passed into vsnprintf() because that length includes the
647 * vsnprintf() returns the amount that would have been copied,
648 * given sufficient space, so don't over-increment s_len.
650 if (SBUF_FREESPACE(s) < len)
651 len = SBUF_FREESPACE(s);
653 if (SBUF_ISSECTION(s))
654 s->s_sect_len += len;
655 if (!SBUF_HASROOM(s) && !SBUF_CANEXTEND(s))
658 KASSERT(s->s_len < s->s_size,
659 ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
668 * Format the given arguments and append the resulting string to an sbuf.
671 sbuf_printf(struct sbuf *s, const char *fmt, ...)
677 result = sbuf_vprintf(s, fmt, ap);
683 * Append a character to an sbuf.
686 sbuf_putc(struct sbuf *s, int c)
696 * Trim whitespace characters from end of an sbuf.
699 sbuf_trim(struct sbuf *s)
702 assert_sbuf_integrity(s);
703 assert_sbuf_state(s, 0);
704 KASSERT(s->s_drain_func == NULL,
705 ("%s makes no sense on sbuf %p with drain", __func__, s));
710 while (s->s_len > 0 && isspace(s->s_buf[s->s_len-1])) {
712 if (SBUF_ISSECTION(s))
720 * Check if an sbuf has an error.
723 sbuf_error(const struct sbuf *s)
730 * Finish off an sbuf.
733 sbuf_finish(struct sbuf *s)
736 assert_sbuf_integrity(s);
737 assert_sbuf_state(s, 0);
739 s->s_buf[s->s_len] = '\0';
740 if (SBUF_NULINCLUDED(s))
742 if (s->s_drain_func != NULL) {
743 while (s->s_len > 0 && s->s_error == 0)
744 s->s_error = sbuf_drain(s);
746 SBUF_SETFLAG(s, SBUF_FINISHED);
750 if (s->s_error != 0) {
759 * Return a pointer to the sbuf data.
762 sbuf_data(struct sbuf *s)
765 assert_sbuf_integrity(s);
766 assert_sbuf_state(s, SBUF_FINISHED);
767 KASSERT(s->s_drain_func == NULL,
768 ("%s makes no sense on sbuf %p with drain", __func__, s));
774 * Return the length of the sbuf data.
777 sbuf_len(struct sbuf *s)
780 assert_sbuf_integrity(s);
781 /* don't care if it's finished or not */
782 KASSERT(s->s_drain_func == NULL,
783 ("%s makes no sense on sbuf %p with drain", __func__, s));
788 /* If finished, nulterm is already in len, else add one. */
789 if (SBUF_NULINCLUDED(s) && !SBUF_ISFINISHED(s))
790 return (s->s_len + 1);
795 * Clear an sbuf, free its buffer if necessary.
798 sbuf_delete(struct sbuf *s)
802 assert_sbuf_integrity(s);
803 /* don't care if it's finished or not */
805 if (SBUF_ISDYNAMIC(s))
807 isdyn = SBUF_ISDYNSTRUCT(s);
808 memset(s, 0, sizeof(*s));
814 * Check if an sbuf has been finished.
817 sbuf_done(const struct sbuf *s)
820 return (SBUF_ISFINISHED(s));
827 sbuf_start_section(struct sbuf *s, ssize_t *old_lenp)
830 assert_sbuf_integrity(s);
831 assert_sbuf_state(s, 0);
833 if (!SBUF_ISSECTION(s)) {
834 KASSERT(s->s_sect_len == 0,
835 ("s_sect_len != 0 when starting a section"));
836 if (old_lenp != NULL)
838 SBUF_SETFLAG(s, SBUF_INSECTION);
840 KASSERT(old_lenp != NULL,
841 ("s_sect_len should be saved when starting a subsection"));
842 *old_lenp = s->s_sect_len;
848 * End the section padding to the specified length with the specified
852 sbuf_end_section(struct sbuf *s, ssize_t old_len, size_t pad, int c)
856 assert_sbuf_integrity(s);
857 assert_sbuf_state(s, 0);
858 KASSERT(SBUF_ISSECTION(s),
859 ("attempt to end a section when not in a section"));
862 len = roundup(s->s_sect_len, pad) - s->s_sect_len;
863 for (; s->s_error == 0 && len > 0; len--)
869 SBUF_CLEARFLAG(s, SBUF_INSECTION);
871 s->s_sect_len += old_len;