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/malloc.h>
39 #include <sys/systm.h>
41 #include <machine/stdarg.h>
54 static MALLOC_DEFINE(M_SBUF, "sbuf", "string buffers");
55 #define SBMALLOC(size) malloc(size, M_SBUF, M_WAITOK|M_ZERO)
56 #define SBFREE(buf) free(buf, M_SBUF)
59 #define SBMALLOC(size) calloc(1, size)
60 #define SBFREE(buf) free(buf)
66 #define SBUF_ISDYNAMIC(s) ((s)->s_flags & SBUF_DYNAMIC)
67 #define SBUF_ISDYNSTRUCT(s) ((s)->s_flags & SBUF_DYNSTRUCT)
68 #define SBUF_ISFINISHED(s) ((s)->s_flags & SBUF_FINISHED)
69 #define SBUF_HASROOM(s) ((s)->s_len < (s)->s_size - 1)
70 #define SBUF_FREESPACE(s) ((s)->s_size - ((s)->s_len + 1))
71 #define SBUF_CANEXTEND(s) ((s)->s_flags & SBUF_AUTOEXTEND)
72 #define SBUF_ISSECTION(s) ((s)->s_flags & SBUF_INSECTION)
73 #define SBUF_NULINCLUDED(s) ((s)->s_flags & SBUF_INCLUDENUL)
78 #define SBUF_SETFLAG(s, f) do { (s)->s_flags |= (f); } while (0)
79 #define SBUF_CLEARFLAG(s, f) do { (s)->s_flags &= ~(f); } while (0)
81 #define SBUF_MINSIZE 2 /* Min is 1 byte + nulterm. */
82 #define SBUF_MINEXTENDSIZE 16 /* Should be power of 2. */
85 #define SBUF_MAXEXTENDSIZE PAGE_SIZE
86 #define SBUF_MAXEXTENDINCR PAGE_SIZE
88 #define SBUF_MAXEXTENDSIZE 4096
89 #define SBUF_MAXEXTENDINCR 4096
95 #if defined(_KERNEL) && defined(INVARIANTS)
98 _assert_sbuf_integrity(const char *fun, struct sbuf *s)
102 ("%s called with a NULL sbuf pointer", fun));
103 KASSERT(s->s_buf != NULL,
104 ("%s called with uninitialized or corrupt sbuf", fun));
105 if (SBUF_ISFINISHED(s) && SBUF_NULINCLUDED(s)) {
106 KASSERT(s->s_len <= s->s_size,
107 ("wrote past end of sbuf (%jd >= %jd)",
108 (intmax_t)s->s_len, (intmax_t)s->s_size));
110 KASSERT(s->s_len < s->s_size,
111 ("wrote past end of sbuf (%jd >= %jd)",
112 (intmax_t)s->s_len, (intmax_t)s->s_size));
117 _assert_sbuf_state(const char *fun, struct sbuf *s, int state)
120 KASSERT((s->s_flags & SBUF_FINISHED) == state,
121 ("%s called with %sfinished or corrupt sbuf", fun,
122 (state ? "un" : "")));
125 #define assert_sbuf_integrity(s) _assert_sbuf_integrity(__func__, (s))
126 #define assert_sbuf_state(s, i) _assert_sbuf_state(__func__, (s), (i))
128 #else /* _KERNEL && INVARIANTS */
130 #define assert_sbuf_integrity(s) do { } while (0)
131 #define assert_sbuf_state(s, i) do { } while (0)
133 #endif /* _KERNEL && INVARIANTS */
136 CTASSERT(powerof2(SBUF_MAXEXTENDSIZE));
137 CTASSERT(powerof2(SBUF_MAXEXTENDINCR));
141 sbuf_extendsize(int size)
145 if (size < (int)SBUF_MAXEXTENDSIZE) {
146 newsize = SBUF_MINEXTENDSIZE;
147 while (newsize < size)
150 newsize = roundup2(size, SBUF_MAXEXTENDINCR);
152 KASSERT(newsize >= size, ("%s: %d < %d\n", __func__, newsize, size));
160 sbuf_extend(struct sbuf *s, int addlen)
165 if (!SBUF_CANEXTEND(s))
167 newsize = sbuf_extendsize(s->s_size + addlen);
168 newbuf = SBMALLOC(newsize);
171 memcpy(newbuf, s->s_buf, s->s_size);
172 if (SBUF_ISDYNAMIC(s))
175 SBUF_SETFLAG(s, SBUF_DYNAMIC);
182 * Initialize the internals of an sbuf.
183 * If buf is non-NULL, it points to a static or already-allocated string
184 * big enough to hold at least length characters.
187 sbuf_newbuf(struct sbuf *s, char *buf, int length, int flags)
190 memset(s, 0, sizeof(*s));
195 if ((s->s_flags & SBUF_AUTOEXTEND) == 0) {
196 KASSERT(s->s_size >= SBUF_MINSIZE,
197 ("attempt to create an sbuf smaller than %d bytes",
201 if (s->s_buf != NULL)
204 if ((flags & SBUF_AUTOEXTEND) != 0)
205 s->s_size = sbuf_extendsize(s->s_size);
207 s->s_buf = SBMALLOC(s->s_size);
208 if (s->s_buf == NULL)
210 SBUF_SETFLAG(s, SBUF_DYNAMIC);
215 * Initialize an sbuf.
216 * If buf is non-NULL, it points to a static or already-allocated string
217 * big enough to hold at least length characters.
220 sbuf_new(struct sbuf *s, char *buf, int length, int flags)
224 ("attempt to create an sbuf of negative length (%d)", length));
225 KASSERT((flags & ~SBUF_USRFLAGMSK) == 0,
226 ("%s called with invalid flags", __func__));
228 flags &= SBUF_USRFLAGMSK;
230 return (sbuf_newbuf(s, buf, length, flags));
232 s = SBMALLOC(sizeof(*s));
235 if (sbuf_newbuf(s, buf, length, flags) == NULL) {
239 SBUF_SETFLAG(s, SBUF_DYNSTRUCT);
245 * Create an sbuf with uio data
248 sbuf_uionew(struct sbuf *s, struct uio *uio, int *error)
252 ("%s called with NULL uio pointer", __func__));
253 KASSERT(error != NULL,
254 ("%s called with NULL error pointer", __func__));
256 s = sbuf_new(s, NULL, uio->uio_resid + 1, 0);
261 *error = uiomove(s->s_buf, uio->uio_resid, uio);
266 s->s_len = s->s_size - 1;
267 if (SBUF_ISSECTION(s))
268 s->s_sect_len = s->s_size - 1;
275 sbuf_get_flags(struct sbuf *s)
278 return (s->s_flags & SBUF_USRFLAGMSK);
282 sbuf_clear_flags(struct sbuf *s, int flags)
285 s->s_flags &= ~(flags & SBUF_USRFLAGMSK);
289 sbuf_set_flags(struct sbuf *s, int flags)
293 s->s_flags |= (flags & SBUF_USRFLAGMSK);
297 * Clear an sbuf and reset its position.
300 sbuf_clear(struct sbuf *s)
303 assert_sbuf_integrity(s);
304 /* don't care if it's finished or not */
306 SBUF_CLEARFLAG(s, SBUF_FINISHED);
313 * Set the sbuf's end position to an arbitrary value.
314 * Effectively truncates the sbuf at the new position.
317 sbuf_setpos(struct sbuf *s, ssize_t pos)
320 assert_sbuf_integrity(s);
321 assert_sbuf_state(s, 0);
324 ("attempt to seek to a negative position (%jd)", (intmax_t)pos));
325 KASSERT(pos < s->s_size,
326 ("attempt to seek past end of sbuf (%jd >= %jd)",
327 (intmax_t)pos, (intmax_t)s->s_size));
328 KASSERT(!SBUF_ISSECTION(s),
329 ("attempt to seek when in a section"));
331 if (pos < 0 || pos > s->s_len)
338 * Set up a drain function and argument on an sbuf to flush data to
339 * when the sbuf buffer overflows.
342 sbuf_set_drain(struct sbuf *s, sbuf_drain_func *func, void *ctx)
345 assert_sbuf_state(s, 0);
346 assert_sbuf_integrity(s);
347 KASSERT(func == s->s_drain_func || s->s_len == 0,
348 ("Cannot change drain to %p on non-empty sbuf %p", func, s));
349 s->s_drain_func = func;
350 s->s_drain_arg = ctx;
354 * Call the drain and process the return.
357 sbuf_drain(struct sbuf *s)
361 KASSERT(s->s_len > 0, ("Shouldn't drain empty sbuf %p", s));
362 KASSERT(s->s_error == 0, ("Called %s with error on %p", __func__, s));
363 len = s->s_drain_func(s->s_drain_arg, s->s_buf, s->s_len);
368 KASSERT(len > 0 && len <= s->s_len,
369 ("Bad drain amount %d for sbuf %p", len, s));
372 * Fast path for the expected case where all the data was
378 * Move the remaining characters to the beginning of the
381 memmove(s->s_buf, s->s_buf + len, s->s_len);
386 * Append a byte to an sbuf. This is the core function for appending
387 * to an sbuf and is the main place that deals with extending the
388 * buffer and marking overflow.
391 sbuf_put_byte(struct sbuf *s, int c)
394 assert_sbuf_integrity(s);
395 assert_sbuf_state(s, 0);
399 if (SBUF_FREESPACE(s) <= 0) {
401 * If there is a drain, use it, otherwise extend the
404 if (s->s_drain_func != NULL)
406 else if (sbuf_extend(s, 1) < 0)
411 s->s_buf[s->s_len++] = c;
412 if (SBUF_ISSECTION(s))
417 * Append a byte string to an sbuf.
420 sbuf_bcat(struct sbuf *s, const void *buf, size_t len)
422 const char *str = buf;
423 const char *end = str + len;
425 assert_sbuf_integrity(s);
426 assert_sbuf_state(s, 0);
430 for (; str < end; str++) {
431 sbuf_put_byte(s, *str);
440 * Copy a byte string from userland into an sbuf.
443 sbuf_bcopyin(struct sbuf *s, const void *uaddr, size_t len)
446 assert_sbuf_integrity(s);
447 assert_sbuf_state(s, 0);
448 KASSERT(s->s_drain_func == NULL,
449 ("Nonsensical copyin to sbuf %p with a drain", s));
455 if (len > SBUF_FREESPACE(s)) {
456 sbuf_extend(s, len - SBUF_FREESPACE(s));
457 if (SBUF_FREESPACE(s) < len)
458 len = SBUF_FREESPACE(s);
460 if (copyin(uaddr, s->s_buf + s->s_len, len) != 0)
469 * Copy a byte string into an sbuf.
472 sbuf_bcpy(struct sbuf *s, const void *buf, size_t len)
475 assert_sbuf_integrity(s);
476 assert_sbuf_state(s, 0);
479 return (sbuf_bcat(s, buf, len));
483 * Append a string to an sbuf.
486 sbuf_cat(struct sbuf *s, const char *str)
489 assert_sbuf_integrity(s);
490 assert_sbuf_state(s, 0);
495 while (*str != '\0') {
496 sbuf_put_byte(s, *str++);
505 * Append a string from userland to an sbuf.
508 sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
512 assert_sbuf_integrity(s);
513 assert_sbuf_state(s, 0);
514 KASSERT(s->s_drain_func == NULL,
515 ("Nonsensical copyin to sbuf %p with a drain", s));
521 len = SBUF_FREESPACE(s); /* XXX return 0? */
522 if (len > SBUF_FREESPACE(s)) {
524 if (SBUF_FREESPACE(s) < len)
525 len = SBUF_FREESPACE(s);
527 switch (copyinstr(uaddr, s->s_buf + s->s_len, len + 1, &done)) {
532 s->s_len += done - 1;
533 if (SBUF_ISSECTION(s))
534 s->s_sect_len += done - 1;
537 return (-1); /* XXX */
545 * Copy a string into an sbuf.
548 sbuf_cpy(struct sbuf *s, const char *str)
551 assert_sbuf_integrity(s);
552 assert_sbuf_state(s, 0);
555 return (sbuf_cat(s, str));
559 * Format the given argument list and append the resulting string to an sbuf.
564 * Append a non-NUL character to an sbuf. This prototype signature is
565 * suitable for use with kvprintf(9).
568 sbuf_putc_func(int c, void *arg)
572 sbuf_put_byte(arg, c);
576 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
579 assert_sbuf_integrity(s);
580 assert_sbuf_state(s, 0);
583 ("%s called with a NULL format string", __func__));
585 (void)kvprintf(fmt, sbuf_putc_func, s, 10, ap);
592 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
597 assert_sbuf_integrity(s);
598 assert_sbuf_state(s, 0);
601 ("%s called with a NULL format string", __func__));
607 * For the moment, there is no way to get vsnprintf(3) to hand
608 * back a character at a time, to push everything into
609 * sbuf_putc_func() as was done for the kernel.
611 * In userspace, while drains are useful, there's generally
612 * not a problem attempting to malloc(3) on out of space. So
613 * expand a userland sbuf if there is not enough room for the
614 * data produced by sbuf_[v]printf(3).
619 va_copy(ap_copy, ap);
620 len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1,
624 if (SBUF_FREESPACE(s) >= len)
626 /* Cannot print with the current available space. */
627 if (s->s_drain_func != NULL && s->s_len > 0)
628 error = sbuf_drain(s);
630 error = sbuf_extend(s, len - SBUF_FREESPACE(s));
631 } while (error == 0);
634 * s->s_len is the length of the string, without the terminating nul.
635 * When updating s->s_len, we must subtract 1 from the length that
636 * we passed into vsnprintf() because that length includes the
639 * vsnprintf() returns the amount that would have been copied,
640 * given sufficient space, so don't over-increment s_len.
642 if (SBUF_FREESPACE(s) < len)
643 len = SBUF_FREESPACE(s);
645 if (SBUF_ISSECTION(s))
646 s->s_sect_len += len;
647 if (!SBUF_HASROOM(s) && !SBUF_CANEXTEND(s))
650 KASSERT(s->s_len < s->s_size,
651 ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
660 * Format the given arguments and append the resulting string to an sbuf.
663 sbuf_printf(struct sbuf *s, const char *fmt, ...)
669 result = sbuf_vprintf(s, fmt, ap);
675 * Append a character to an sbuf.
678 sbuf_putc(struct sbuf *s, int c)
688 * Trim whitespace characters from end of an sbuf.
691 sbuf_trim(struct sbuf *s)
694 assert_sbuf_integrity(s);
695 assert_sbuf_state(s, 0);
696 KASSERT(s->s_drain_func == NULL,
697 ("%s makes no sense on sbuf %p with drain", __func__, s));
702 while (s->s_len > 0 && isspace(s->s_buf[s->s_len-1])) {
704 if (SBUF_ISSECTION(s))
712 * Check if an sbuf has an error.
715 sbuf_error(const struct sbuf *s)
722 * Finish off an sbuf.
725 sbuf_finish(struct sbuf *s)
728 assert_sbuf_integrity(s);
729 assert_sbuf_state(s, 0);
731 s->s_buf[s->s_len] = '\0';
732 if (SBUF_NULINCLUDED(s))
734 if (s->s_drain_func != NULL) {
735 while (s->s_len > 0 && s->s_error == 0)
736 s->s_error = sbuf_drain(s);
738 SBUF_SETFLAG(s, SBUF_FINISHED);
742 if (s->s_error != 0) {
751 * Return a pointer to the sbuf data.
754 sbuf_data(struct sbuf *s)
757 assert_sbuf_integrity(s);
758 assert_sbuf_state(s, SBUF_FINISHED);
759 KASSERT(s->s_drain_func == NULL,
760 ("%s makes no sense on sbuf %p with drain", __func__, s));
766 * Return the length of the sbuf data.
769 sbuf_len(struct sbuf *s)
772 assert_sbuf_integrity(s);
773 /* don't care if it's finished or not */
774 KASSERT(s->s_drain_func == NULL,
775 ("%s makes no sense on sbuf %p with drain", __func__, s));
780 /* If finished, nulterm is already in len, else add one. */
781 if (SBUF_NULINCLUDED(s) && !SBUF_ISFINISHED(s))
782 return (s->s_len + 1);
787 * Clear an sbuf, free its buffer if necessary.
790 sbuf_delete(struct sbuf *s)
794 assert_sbuf_integrity(s);
795 /* don't care if it's finished or not */
797 if (SBUF_ISDYNAMIC(s))
799 isdyn = SBUF_ISDYNSTRUCT(s);
800 memset(s, 0, sizeof(*s));
806 * Check if an sbuf has been finished.
809 sbuf_done(const struct sbuf *s)
812 return (SBUF_ISFINISHED(s));
819 sbuf_start_section(struct sbuf *s, ssize_t *old_lenp)
822 assert_sbuf_integrity(s);
823 assert_sbuf_state(s, 0);
825 if (!SBUF_ISSECTION(s)) {
826 KASSERT(s->s_sect_len == 0,
827 ("s_sect_len != 0 when starting a section"));
828 if (old_lenp != NULL)
830 SBUF_SETFLAG(s, SBUF_INSECTION);
832 KASSERT(old_lenp != NULL,
833 ("s_sect_len should be saved when starting a subsection"));
834 *old_lenp = s->s_sect_len;
840 * End the section padding to the specified length with the specified
844 sbuf_end_section(struct sbuf *s, ssize_t old_len, size_t pad, int c)
848 assert_sbuf_integrity(s);
849 assert_sbuf_state(s, 0);
850 KASSERT(SBUF_ISSECTION(s),
851 ("attempt to end a section when not in a section"));
854 len = roundup(s->s_sect_len, pad) - s->s_sect_len;
855 for (; s->s_error == 0 && len > 0; len--)
861 SBUF_CLEARFLAG(s, SBUF_INSECTION);
863 s->s_sect_len += old_len;