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)
56 #define SBFREE(buf) free(buf, M_SBUF)
59 #define SBMALLOC(size) malloc(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_HASOVERFLOWED(s) ((s)->s_flags & SBUF_OVERFLOWED)
70 #define SBUF_HASROOM(s) ((s)->s_len < (s)->s_size - 1)
71 #define SBUF_FREESPACE(s) ((s)->s_size - (s)->s_len - 1)
72 #define SBUF_CANEXTEND(s) ((s)->s_flags & SBUF_AUTOEXTEND)
77 #define SBUF_SETFLAG(s, f) do { (s)->s_flags |= (f); } while (0)
78 #define SBUF_CLEARFLAG(s, f) do { (s)->s_flags &= ~(f); } while (0)
80 #define SBUF_MINEXTENDSIZE 16 /* Should be power of 2. */
81 #define SBUF_MAXEXTENDSIZE PAGE_SIZE
82 #define SBUF_MAXEXTENDINCR PAGE_SIZE
87 #if defined(_KERNEL) && defined(INVARIANTS)
90 _assert_sbuf_integrity(const char *fun, struct sbuf *s)
94 ("%s called with a NULL sbuf pointer", fun));
95 KASSERT(s->s_buf != NULL,
96 ("%s called with uninitialized or corrupt sbuf", fun));
97 KASSERT(s->s_len < s->s_size,
98 ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
102 _assert_sbuf_state(const char *fun, struct sbuf *s, int state)
105 KASSERT((s->s_flags & SBUF_FINISHED) == state,
106 ("%s called with %sfinished or corrupt sbuf", fun,
107 (state ? "un" : "")));
110 #define assert_sbuf_integrity(s) _assert_sbuf_integrity(__func__, (s))
111 #define assert_sbuf_state(s, i) _assert_sbuf_state(__func__, (s), (i))
113 #else /* _KERNEL && INVARIANTS */
115 #define assert_sbuf_integrity(s) do { } while (0)
116 #define assert_sbuf_state(s, i) do { } while (0)
118 #endif /* _KERNEL && INVARIANTS */
121 CTASSERT(powerof2(SBUF_MAXEXTENDSIZE));
122 CTASSERT(powerof2(SBUF_MAXEXTENDINCR));
126 sbuf_extendsize(int size)
130 if (size < (int)SBUF_MAXEXTENDSIZE) {
131 newsize = SBUF_MINEXTENDSIZE;
132 while (newsize < size)
135 newsize = roundup2(size, SBUF_MAXEXTENDINCR);
137 KASSERT(newsize >= size, ("%s: %d < %d\n", __func__, newsize, size));
146 sbuf_extend(struct sbuf *s, int addlen)
151 if (!SBUF_CANEXTEND(s))
153 newsize = sbuf_extendsize(s->s_size + addlen);
154 newbuf = SBMALLOC(newsize);
157 bcopy(s->s_buf, newbuf, s->s_size);
158 if (SBUF_ISDYNAMIC(s))
161 SBUF_SETFLAG(s, SBUF_DYNAMIC);
168 * Initialize an sbuf.
169 * If buf is non-NULL, it points to a static or already-allocated string
170 * big enough to hold at least length characters.
173 sbuf_new(struct sbuf *s, char *buf, int length, int flags)
177 ("attempt to create an sbuf of negative length (%d)", length));
178 KASSERT((flags & ~SBUF_USRFLAGMSK) == 0,
179 ("%s called with invalid flags", __func__));
181 flags &= SBUF_USRFLAGMSK;
183 s = SBMALLOC(sizeof(*s));
186 bzero(s, sizeof(*s));
188 SBUF_SETFLAG(s, SBUF_DYNSTRUCT);
190 bzero(s, sizeof(*s));
198 if ((flags & SBUF_AUTOEXTEND) != 0)
199 s->s_size = sbuf_extendsize(s->s_size);
200 s->s_buf = SBMALLOC(s->s_size);
201 if (s->s_buf == NULL) {
202 if (SBUF_ISDYNSTRUCT(s))
206 SBUF_SETFLAG(s, SBUF_DYNAMIC);
212 * Create an sbuf with uio data
215 sbuf_uionew(struct sbuf *s, struct uio *uio, int *error)
219 ("%s called with NULL uio pointer", __func__));
220 KASSERT(error != NULL,
221 ("%s called with NULL error pointer", __func__));
223 s = sbuf_new(s, NULL, uio->uio_resid + 1, 0);
228 *error = uiomove(s->s_buf, uio->uio_resid, uio);
233 s->s_len = s->s_size - 1;
240 * Clear an sbuf and reset its position.
243 sbuf_clear(struct sbuf *s)
246 assert_sbuf_integrity(s);
247 /* don't care if it's finished or not */
249 SBUF_CLEARFLAG(s, SBUF_FINISHED);
250 SBUF_CLEARFLAG(s, SBUF_OVERFLOWED);
256 * Set the sbuf's end position to an arbitrary value.
257 * Effectively truncates the sbuf at the new position.
260 sbuf_setpos(struct sbuf *s, int pos)
263 assert_sbuf_integrity(s);
264 assert_sbuf_state(s, 0);
267 ("attempt to seek to a negative position (%d)", pos));
268 KASSERT(pos < s->s_size,
269 ("attempt to seek past end of sbuf (%d >= %d)", pos, s->s_size));
271 if (pos < 0 || pos > s->s_len)
278 * Set up a drain function and argument on an sbuf to flush data to
279 * when the sbuf buffer overflows.
282 sbuf_set_drain(struct sbuf *s, sbuf_drain_func *func, void *ctx)
285 assert_sbuf_state(s, 0);
286 assert_sbuf_integrity(s);
287 KASSERT(func == s->s_drain_func || s->s_len == 0,
288 ("Cannot change drain to %p on non-empty sbuf %p", func, s));
289 s->s_drain_func = func;
290 s->s_drain_arg = ctx;
294 * Call the drain and process the return.
297 sbuf_drain(struct sbuf *s)
301 KASSERT(s->s_len > 0, ("Shouldn't drain empty sbuf %p", s));
302 len = s->s_drain_func(s->s_drain_arg, s->s_buf, s->s_len);
305 SBUF_SETFLAG(s, SBUF_OVERFLOWED);
309 KASSERT(len > 0, ("Drain must either error or work!"));
312 * Fast path for the expected case where all the data was
318 * Move the remaining characters to the beginning of the
321 memmove(s->s_buf, s->s_buf + len, s->s_len);
326 * Append a byte to an sbuf. This is the core function for appending
327 * to an sbuf and is the main place that deals with extending the
328 * buffer and marking overflow.
331 sbuf_put_byte(int c, struct sbuf *s)
334 assert_sbuf_integrity(s);
335 assert_sbuf_state(s, 0);
337 if (SBUF_HASOVERFLOWED(s))
339 if (SBUF_FREESPACE(s) <= 0) {
341 * If there is a drain, use it, otherwise extend the
344 if (s->s_drain_func != NULL)
346 else if (sbuf_extend(s, 1) < 0)
347 SBUF_SETFLAG(s, SBUF_OVERFLOWED);
348 if (SBUF_HASOVERFLOWED(s))
351 s->s_buf[s->s_len++] = c;
355 * Append a non-NUL character to an sbuf. This prototype signature is
356 * suitable for use with kvprintf(9).
359 sbuf_putc_func(int c, void *arg)
363 sbuf_put_byte(c, arg);
367 * Append a byte string to an sbuf.
370 sbuf_bcat(struct sbuf *s, const void *buf, size_t len)
372 const char *str = buf;
373 const char *end = str + len;
375 assert_sbuf_integrity(s);
376 assert_sbuf_state(s, 0);
378 if (SBUF_HASOVERFLOWED(s))
380 for (; str < end; str++) {
381 sbuf_put_byte(*str, s);
382 if (SBUF_HASOVERFLOWED(s))
390 * Copy a byte string from userland into an sbuf.
393 sbuf_bcopyin(struct sbuf *s, const void *uaddr, size_t len)
396 assert_sbuf_integrity(s);
397 assert_sbuf_state(s, 0);
398 KASSERT(s->s_drain_func == NULL,
399 ("Nonsensical copyin to sbuf %p with a drain", s));
401 if (SBUF_HASOVERFLOWED(s))
405 if (len > SBUF_FREESPACE(s)) {
406 sbuf_extend(s, len - SBUF_FREESPACE(s));
407 if (SBUF_FREESPACE(s) < len)
408 len = SBUF_FREESPACE(s);
410 if (copyin(uaddr, s->s_buf + s->s_len, len) != 0)
419 * Copy a byte string into an sbuf.
422 sbuf_bcpy(struct sbuf *s, const void *buf, size_t len)
425 assert_sbuf_integrity(s);
426 assert_sbuf_state(s, 0);
429 return (sbuf_bcat(s, buf, len));
433 * Append a string to an sbuf.
436 sbuf_cat(struct sbuf *s, const char *str)
439 assert_sbuf_integrity(s);
440 assert_sbuf_state(s, 0);
442 if (SBUF_HASOVERFLOWED(s))
445 while (*str != '\0') {
446 sbuf_put_byte(*str, s);
447 if (SBUF_HASOVERFLOWED(s))
455 * Append a string from userland to an sbuf.
458 sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
462 assert_sbuf_integrity(s);
463 assert_sbuf_state(s, 0);
464 KASSERT(s->s_drain_func == NULL,
465 ("Nonsensical copyin to sbuf %p with a drain", s));
467 if (SBUF_HASOVERFLOWED(s))
471 len = SBUF_FREESPACE(s); /* XXX return 0? */
472 if (len > SBUF_FREESPACE(s)) {
474 if (SBUF_FREESPACE(s) < len)
475 len = SBUF_FREESPACE(s);
477 switch (copyinstr(uaddr, s->s_buf + s->s_len, len + 1, &done)) {
479 SBUF_SETFLAG(s, SBUF_OVERFLOWED);
482 s->s_len += done - 1;
485 return (-1); /* XXX */
493 * Copy a string into an sbuf.
496 sbuf_cpy(struct sbuf *s, const char *str)
499 assert_sbuf_integrity(s);
500 assert_sbuf_state(s, 0);
503 return (sbuf_cat(s, str));
507 * Format the given argument list and append the resulting string to an sbuf.
511 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
514 assert_sbuf_integrity(s);
515 assert_sbuf_state(s, 0);
518 ("%s called with a NULL format string", __func__));
520 (void)kvprintf(fmt, sbuf_putc_func, s, 10, ap);
521 if (SBUF_HASOVERFLOWED(s))
527 sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
532 assert_sbuf_integrity(s);
533 assert_sbuf_state(s, 0);
536 ("%s called with a NULL format string", __func__));
538 if (SBUF_HASOVERFLOWED(s))
542 * For the moment, there is no way to get vsnprintf(3) to hand
543 * back a character at a time, to push everything into
544 * sbuf_putc_func() as was done for the kernel.
546 * In userspace, while drains are useful, there's generally
547 * not a problem attempting to malloc(3) on out of space. So
548 * expand a userland sbuf if there is not enough room for the
549 * data produced by sbuf_[v]printf(3).
554 va_copy(ap_copy, ap);
555 len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1,
559 if (SBUF_FREESPACE(s) >= len)
561 /* Cannot print with the current available space. */
562 if (s->s_drain_func != NULL && s->s_len > 0)
563 error = sbuf_drain(s);
565 error = sbuf_extend(s, len - SBUF_FREESPACE(s));
566 } while (error == 0);
569 * s->s_len is the length of the string, without the terminating nul.
570 * When updating s->s_len, we must subtract 1 from the length that
571 * we passed into vsnprintf() because that length includes the
574 * vsnprintf() returns the amount that would have been copied,
575 * given sufficient space, so don't over-increment s_len.
577 if (SBUF_FREESPACE(s) < len)
578 len = SBUF_FREESPACE(s);
580 if (!SBUF_HASROOM(s) && !SBUF_CANEXTEND(s))
581 SBUF_SETFLAG(s, SBUF_OVERFLOWED);
583 KASSERT(s->s_len < s->s_size,
584 ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
586 if (SBUF_HASOVERFLOWED(s))
593 * Format the given arguments and append the resulting string to an sbuf.
596 sbuf_printf(struct sbuf *s, const char *fmt, ...)
602 result = sbuf_vprintf(s, fmt, ap);
608 * Append a character to an sbuf.
611 sbuf_putc(struct sbuf *s, int c)
614 sbuf_putc_func(c, s);
615 if (SBUF_HASOVERFLOWED(s))
621 * Trim whitespace characters from end of an sbuf.
624 sbuf_trim(struct sbuf *s)
627 assert_sbuf_integrity(s);
628 assert_sbuf_state(s, 0);
629 KASSERT(s->s_drain_func == NULL,
630 ("%s makes no sense on sbuf %p with drain", __func__, s));
632 if (SBUF_HASOVERFLOWED(s))
635 while (s->s_len > 0 && isspace(s->s_buf[s->s_len-1]))
642 * Check if an sbuf overflowed
645 sbuf_overflowed(struct sbuf *s)
648 return (SBUF_HASOVERFLOWED(s));
652 * Finish off an sbuf.
655 sbuf_finish(struct sbuf *s)
659 assert_sbuf_integrity(s);
660 assert_sbuf_state(s, 0);
662 if (s->s_drain_func != NULL) {
664 while (s->s_len > 0 && error == 0)
665 error = sbuf_drain(s);
666 } else if (SBUF_HASOVERFLOWED(s))
668 s->s_buf[s->s_len] = '\0';
669 SBUF_CLEARFLAG(s, SBUF_OVERFLOWED);
670 SBUF_SETFLAG(s, SBUF_FINISHED);
680 * Return a pointer to the sbuf data.
683 sbuf_data(struct sbuf *s)
686 assert_sbuf_integrity(s);
687 assert_sbuf_state(s, SBUF_FINISHED);
688 KASSERT(s->s_drain_func == NULL,
689 ("%s makes no sense on sbuf %p with drain", __func__, s));
695 * Return the length of the sbuf data.
698 sbuf_len(struct sbuf *s)
701 assert_sbuf_integrity(s);
702 /* don't care if it's finished or not */
703 KASSERT(s->s_drain_func == NULL,
704 ("%s makes no sense on sbuf %p with drain", __func__, s));
706 if (SBUF_HASOVERFLOWED(s))
712 * Clear an sbuf, free its buffer if necessary.
715 sbuf_delete(struct sbuf *s)
719 assert_sbuf_integrity(s);
720 /* don't care if it's finished or not */
722 if (SBUF_ISDYNAMIC(s))
724 isdyn = SBUF_ISDYNSTRUCT(s);
725 bzero(s, sizeof(*s));
731 * Check if an sbuf has been finished.
734 sbuf_done(struct sbuf *s)
737 return (SBUF_ISFINISHED(s));