subr_sbuf.c revision 212478
1/*-
2 * Copyright (c) 2000-2008 Poul-Henning Kamp
3 * Copyright (c) 2000-2008 Dag-Erling Co��dan Sm��rgrav
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
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.
15 *
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
26 * SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/sys/kern/subr_sbuf.c 212478 2010-09-11 19:42:50Z kan $");
31
32#include <sys/param.h>
33
34#ifdef _KERNEL
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>
40#include <sys/uio.h>
41#include <machine/stdarg.h>
42#else /* _KERNEL */
43#include <ctype.h>
44#include <errno.h>
45#include <stdarg.h>
46#include <stdio.h>
47#include <stdlib.h>
48#include <string.h>
49#endif /* _KERNEL */
50
51#include <sys/sbuf.h>
52
53#ifdef _KERNEL
54static 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)
57#else /* _KERNEL */
58#define	KASSERT(e, m)
59#define	SBMALLOC(size)		malloc(size)
60#define	SBFREE(buf)		free(buf)
61#endif /* _KERNEL */
62
63/*
64 * Predicates
65 */
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
73/*
74 * Set / clear flags
75 */
76#define	SBUF_SETFLAG(s, f)	do { (s)->s_flags |= (f); } while (0)
77#define	SBUF_CLEARFLAG(s, f)	do { (s)->s_flags &= ~(f); } while (0)
78
79#define	SBUF_MINEXTENDSIZE	16		/* Should be power of 2. */
80#define	SBUF_MAXEXTENDSIZE	PAGE_SIZE
81#define	SBUF_MAXEXTENDINCR	PAGE_SIZE
82
83/*
84 * Debugging support
85 */
86#if defined(_KERNEL) && defined(INVARIANTS)
87
88static void
89_assert_sbuf_integrity(const char *fun, struct sbuf *s)
90{
91
92	KASSERT(s != NULL,
93	    ("%s called with a NULL sbuf pointer", fun));
94	KASSERT(s->s_buf != NULL,
95	    ("%s called with uninitialized or corrupt sbuf", fun));
96	KASSERT(s->s_len < s->s_size,
97	    ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
98}
99
100static void
101_assert_sbuf_state(const char *fun, struct sbuf *s, int state)
102{
103
104	KASSERT((s->s_flags & SBUF_FINISHED) == state,
105	    ("%s called with %sfinished or corrupt sbuf", fun,
106	    (state ? "un" : "")));
107}
108
109#define	assert_sbuf_integrity(s) _assert_sbuf_integrity(__func__, (s))
110#define	assert_sbuf_state(s, i)	 _assert_sbuf_state(__func__, (s), (i))
111
112#else /* _KERNEL && INVARIANTS */
113
114#define	assert_sbuf_integrity(s) do { } while (0)
115#define	assert_sbuf_state(s, i)	 do { } while (0)
116
117#endif /* _KERNEL && INVARIANTS */
118
119#ifdef CTASSERT
120CTASSERT(powerof2(SBUF_MAXEXTENDSIZE));
121CTASSERT(powerof2(SBUF_MAXEXTENDINCR));
122#endif
123
124static int
125sbuf_extendsize(int size)
126{
127	int newsize;
128
129	if (size < (int)SBUF_MAXEXTENDSIZE) {
130		newsize = SBUF_MINEXTENDSIZE;
131		while (newsize < size)
132			newsize *= 2;
133	} else {
134		newsize = roundup2(size, SBUF_MAXEXTENDINCR);
135	}
136	KASSERT(newsize >= size, ("%s: %d < %d\n", __func__, newsize, size));
137	return (newsize);
138}
139
140
141/*
142 * Extend an sbuf.
143 */
144static int
145sbuf_extend(struct sbuf *s, int addlen)
146{
147	char *newbuf;
148	int newsize;
149
150	if (!SBUF_CANEXTEND(s))
151		return (-1);
152	newsize = sbuf_extendsize(s->s_size + addlen);
153	newbuf = SBMALLOC(newsize);
154	if (newbuf == NULL)
155		return (-1);
156	bcopy(s->s_buf, newbuf, s->s_size);
157	if (SBUF_ISDYNAMIC(s))
158		SBFREE(s->s_buf);
159	else
160		SBUF_SETFLAG(s, SBUF_DYNAMIC);
161	s->s_buf = newbuf;
162	s->s_size = newsize;
163	return (0);
164}
165
166/*
167 * Initialize an sbuf.
168 * If buf is non-NULL, it points to a static or already-allocated string
169 * big enough to hold at least length characters.
170 */
171struct sbuf *
172sbuf_new(struct sbuf *s, char *buf, int length, int flags)
173{
174
175	KASSERT(length >= 0,
176	    ("attempt to create an sbuf of negative length (%d)", length));
177	KASSERT((flags & ~SBUF_USRFLAGMSK) == 0,
178	    ("%s called with invalid flags", __func__));
179
180	flags &= SBUF_USRFLAGMSK;
181	if (s == NULL) {
182		s = SBMALLOC(sizeof(*s));
183		if (s == NULL)
184			return (NULL);
185		bzero(s, sizeof(*s));
186		s->s_flags = flags;
187		SBUF_SETFLAG(s, SBUF_DYNSTRUCT);
188	} else {
189		bzero(s, sizeof(*s));
190		s->s_flags = flags;
191	}
192	s->s_size = length;
193	if (buf != NULL) {
194		s->s_buf = buf;
195		return (s);
196	}
197	if ((flags & SBUF_AUTOEXTEND) != 0)
198		s->s_size = sbuf_extendsize(s->s_size);
199	s->s_buf = SBMALLOC(s->s_size);
200	if (s->s_buf == NULL) {
201		if (SBUF_ISDYNSTRUCT(s))
202			SBFREE(s);
203		return (NULL);
204	}
205	SBUF_SETFLAG(s, SBUF_DYNAMIC);
206	return (s);
207}
208
209#ifdef _KERNEL
210/*
211 * Create an sbuf with uio data
212 */
213struct sbuf *
214sbuf_uionew(struct sbuf *s, struct uio *uio, int *error)
215{
216
217	KASSERT(uio != NULL,
218	    ("%s called with NULL uio pointer", __func__));
219	KASSERT(error != NULL,
220	    ("%s called with NULL error pointer", __func__));
221
222	s = sbuf_new(s, NULL, uio->uio_resid + 1, 0);
223	if (s == NULL) {
224		*error = ENOMEM;
225		return (NULL);
226	}
227	*error = uiomove(s->s_buf, uio->uio_resid, uio);
228	if (*error != 0) {
229		sbuf_delete(s);
230		return (NULL);
231	}
232	s->s_len = s->s_size - 1;
233	*error = 0;
234	return (s);
235}
236#endif
237
238/*
239 * Clear an sbuf and reset its position.
240 */
241void
242sbuf_clear(struct sbuf *s)
243{
244
245	assert_sbuf_integrity(s);
246	/* don't care if it's finished or not */
247
248	SBUF_CLEARFLAG(s, SBUF_FINISHED);
249	s->s_error = 0;
250	s->s_len = 0;
251}
252
253/*
254 * Set the sbuf's end position to an arbitrary value.
255 * Effectively truncates the sbuf at the new position.
256 */
257int
258sbuf_setpos(struct sbuf *s, int pos)
259{
260
261	assert_sbuf_integrity(s);
262	assert_sbuf_state(s, 0);
263
264	KASSERT(pos >= 0,
265	    ("attempt to seek to a negative position (%d)", pos));
266	KASSERT(pos < s->s_size,
267	    ("attempt to seek past end of sbuf (%d >= %d)", pos, s->s_size));
268
269	if (pos < 0 || pos > s->s_len)
270		return (-1);
271	s->s_len = pos;
272	return (0);
273}
274
275/*
276 * Set up a drain function and argument on an sbuf to flush data to
277 * when the sbuf buffer overflows.
278 */
279void
280sbuf_set_drain(struct sbuf *s, sbuf_drain_func *func, void *ctx)
281{
282
283	assert_sbuf_state(s, 0);
284	assert_sbuf_integrity(s);
285	KASSERT(func == s->s_drain_func || s->s_len == 0,
286	    ("Cannot change drain to %p on non-empty sbuf %p", func, s));
287	s->s_drain_func = func;
288	s->s_drain_arg = ctx;
289}
290
291/*
292 * Call the drain and process the return.
293 */
294static int
295sbuf_drain(struct sbuf *s)
296{
297	int len;
298
299	KASSERT(s->s_len > 0, ("Shouldn't drain empty sbuf %p", s));
300	KASSERT(s->s_error == 0, ("Called %s with error on %p", __func__, s));
301	len = s->s_drain_func(s->s_drain_arg, s->s_buf, s->s_len);
302	if (len < 0) {
303		s->s_error = -len;
304		return (s->s_error);
305	}
306	KASSERT(len > 0 && len <= s->s_len,
307	    ("Bad drain amount %d for sbuf %p", len, s));
308	s->s_len -= len;
309	/*
310	 * Fast path for the expected case where all the data was
311	 * drained.
312	 */
313	if (s->s_len == 0)
314		return (0);
315	/*
316	 * Move the remaining characters to the beginning of the
317	 * string.
318	 */
319	memmove(s->s_buf, s->s_buf + len, s->s_len);
320	return (0);
321}
322
323/*
324 * Append a byte to an sbuf.  This is the core function for appending
325 * to an sbuf and is the main place that deals with extending the
326 * buffer and marking overflow.
327 */
328static void
329sbuf_put_byte(int c, struct sbuf *s)
330{
331
332	assert_sbuf_integrity(s);
333	assert_sbuf_state(s, 0);
334
335	if (s->s_error != 0)
336		return;
337	if (SBUF_FREESPACE(s) <= 0) {
338		/*
339		 * If there is a drain, use it, otherwise extend the
340		 * buffer.
341		 */
342		if (s->s_drain_func != NULL)
343			(void)sbuf_drain(s);
344		else if (sbuf_extend(s, 1) < 0)
345			s->s_error = ENOMEM;
346		if (s->s_error != 0)
347			return;
348	}
349	s->s_buf[s->s_len++] = c;
350}
351
352/*
353 * Append a non-NUL character to an sbuf.  This prototype signature is
354 * suitable for use with kvprintf(9).
355 */
356static void
357sbuf_putc_func(int c, void *arg)
358{
359
360	if (c != '\0')
361		sbuf_put_byte(c, arg);
362}
363
364/*
365 * Append a byte string to an sbuf.
366 */
367int
368sbuf_bcat(struct sbuf *s, const void *buf, size_t len)
369{
370	const char *str = buf;
371	const char *end = str + len;
372
373	assert_sbuf_integrity(s);
374	assert_sbuf_state(s, 0);
375
376	if (s->s_error != 0)
377		return (-1);
378	for (; str < end; str++) {
379		sbuf_put_byte(*str, s);
380		if (s->s_error != 0)
381			return (-1);
382 	}
383	return (0);
384}
385
386#ifdef _KERNEL
387/*
388 * Copy a byte string from userland into an sbuf.
389 */
390int
391sbuf_bcopyin(struct sbuf *s, const void *uaddr, size_t len)
392{
393
394	assert_sbuf_integrity(s);
395	assert_sbuf_state(s, 0);
396	KASSERT(s->s_drain_func == NULL,
397	    ("Nonsensical copyin to sbuf %p with a drain", s));
398
399	if (s->s_error != 0)
400		return (-1);
401	if (len == 0)
402		return (0);
403	if (len > SBUF_FREESPACE(s)) {
404		sbuf_extend(s, len - SBUF_FREESPACE(s));
405		if (SBUF_FREESPACE(s) < len)
406			len = SBUF_FREESPACE(s);
407	}
408	if (copyin(uaddr, s->s_buf + s->s_len, len) != 0)
409		return (-1);
410	s->s_len += len;
411
412	return (0);
413}
414#endif
415
416/*
417 * Copy a byte string into an sbuf.
418 */
419int
420sbuf_bcpy(struct sbuf *s, const void *buf, size_t len)
421{
422
423	assert_sbuf_integrity(s);
424	assert_sbuf_state(s, 0);
425
426	sbuf_clear(s);
427	return (sbuf_bcat(s, buf, len));
428}
429
430/*
431 * Append a string to an sbuf.
432 */
433int
434sbuf_cat(struct sbuf *s, const char *str)
435{
436
437	assert_sbuf_integrity(s);
438	assert_sbuf_state(s, 0);
439
440	if (s->s_error != 0)
441		return (-1);
442
443	while (*str != '\0') {
444		sbuf_put_byte(*str++, s);
445		if (s->s_error != 0)
446			return (-1);
447	}
448	return (0);
449}
450
451#ifdef _KERNEL
452/*
453 * Append a string from userland to an sbuf.
454 */
455int
456sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
457{
458	size_t done;
459
460	assert_sbuf_integrity(s);
461	assert_sbuf_state(s, 0);
462	KASSERT(s->s_drain_func == NULL,
463	    ("Nonsensical copyin to sbuf %p with a drain", s));
464
465	if (s->s_error != 0)
466		return (-1);
467
468	if (len == 0)
469		len = SBUF_FREESPACE(s);	/* XXX return 0? */
470	if (len > SBUF_FREESPACE(s)) {
471		sbuf_extend(s, len);
472		if (SBUF_FREESPACE(s) < len)
473			len = SBUF_FREESPACE(s);
474	}
475	switch (copyinstr(uaddr, s->s_buf + s->s_len, len + 1, &done)) {
476	case ENAMETOOLONG:
477		s->s_error = ENOMEM;
478		/* fall through */
479	case 0:
480		s->s_len += done - 1;
481		break;
482	default:
483		return (-1);	/* XXX */
484	}
485
486	return (done);
487}
488#endif
489
490/*
491 * Copy a string into an sbuf.
492 */
493int
494sbuf_cpy(struct sbuf *s, const char *str)
495{
496
497	assert_sbuf_integrity(s);
498	assert_sbuf_state(s, 0);
499
500	sbuf_clear(s);
501	return (sbuf_cat(s, str));
502}
503
504/*
505 * Format the given argument list and append the resulting string to an sbuf.
506 */
507#ifdef _KERNEL
508int
509sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
510{
511
512	assert_sbuf_integrity(s);
513	assert_sbuf_state(s, 0);
514
515	KASSERT(fmt != NULL,
516	    ("%s called with a NULL format string", __func__));
517
518	(void)kvprintf(fmt, sbuf_putc_func, s, 10, ap);
519	if (s->s_error != 0)
520		return (-1);
521	return (0);
522}
523#else /* !_KERNEL */
524int
525sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
526{
527	va_list ap_copy;
528	int error, len;
529
530	assert_sbuf_integrity(s);
531	assert_sbuf_state(s, 0);
532
533	KASSERT(fmt != NULL,
534	    ("%s called with a NULL format string", __func__));
535
536	if (s->s_error != 0)
537		return (-1);
538
539	/*
540	 * For the moment, there is no way to get vsnprintf(3) to hand
541	 * back a character at a time, to push everything into
542	 * sbuf_putc_func() as was done for the kernel.
543	 *
544	 * In userspace, while drains are useful, there's generally
545	 * not a problem attempting to malloc(3) on out of space.  So
546	 * expand a userland sbuf if there is not enough room for the
547	 * data produced by sbuf_[v]printf(3).
548	 */
549
550	error = 0;
551	do {
552		va_copy(ap_copy, ap);
553		len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1,
554		    fmt, ap_copy);
555		va_end(ap_copy);
556
557		if (SBUF_FREESPACE(s) >= len)
558			break;
559		/* Cannot print with the current available space. */
560		if (s->s_drain_func != NULL && s->s_len > 0)
561			error = sbuf_drain(s);
562		else
563			error = sbuf_extend(s, len - SBUF_FREESPACE(s));
564	} while (error == 0);
565
566	/*
567	 * s->s_len is the length of the string, without the terminating nul.
568	 * When updating s->s_len, we must subtract 1 from the length that
569	 * we passed into vsnprintf() because that length includes the
570	 * terminating nul.
571	 *
572	 * vsnprintf() returns the amount that would have been copied,
573	 * given sufficient space, so don't over-increment s_len.
574	 */
575	if (SBUF_FREESPACE(s) < len)
576		len = SBUF_FREESPACE(s);
577	s->s_len += len;
578	if (!SBUF_HASROOM(s) && !SBUF_CANEXTEND(s))
579		s->s_error = ENOMEM;
580
581	KASSERT(s->s_len < s->s_size,
582	    ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
583
584	if (s->s_error != 0)
585		return (-1);
586	return (0);
587}
588#endif /* _KERNEL */
589
590/*
591 * Format the given arguments and append the resulting string to an sbuf.
592 */
593int
594sbuf_printf(struct sbuf *s, const char *fmt, ...)
595{
596	va_list ap;
597	int result;
598
599	va_start(ap, fmt);
600	result = sbuf_vprintf(s, fmt, ap);
601	va_end(ap);
602	return (result);
603}
604
605/*
606 * Append a character to an sbuf.
607 */
608int
609sbuf_putc(struct sbuf *s, int c)
610{
611
612	sbuf_putc_func(c, s);
613	if (s->s_error != 0)
614		return (-1);
615	return (0);
616}
617
618/*
619 * Trim whitespace characters from end of an sbuf.
620 */
621int
622sbuf_trim(struct sbuf *s)
623{
624
625	assert_sbuf_integrity(s);
626	assert_sbuf_state(s, 0);
627	KASSERT(s->s_drain_func == NULL,
628	    ("%s makes no sense on sbuf %p with drain", __func__, s));
629
630	if (s->s_error != 0)
631		return (-1);
632
633	while (s->s_len > 0 && isspace(s->s_buf[s->s_len-1]))
634		--s->s_len;
635
636	return (0);
637}
638
639/*
640 * Check if an sbuf has an error.
641 */
642int
643sbuf_error(struct sbuf *s)
644{
645
646	return (s->s_error);
647}
648
649/*
650 * Finish off an sbuf.
651 */
652int
653sbuf_finish(struct sbuf *s)
654{
655	int error;
656
657	assert_sbuf_integrity(s);
658	assert_sbuf_state(s, 0);
659
660	error = s->s_error;
661	if (s->s_drain_func != NULL) {
662		while (s->s_len > 0 && error == 0)
663			error = sbuf_drain(s);
664	}
665	s->s_buf[s->s_len] = '\0';
666	s->s_error = 0;
667	SBUF_SETFLAG(s, SBUF_FINISHED);
668#ifdef _KERNEL
669	return (error);
670#else
671	errno = error;
672	return (-1);
673#endif
674}
675
676/*
677 * Return a pointer to the sbuf data.
678 */
679char *
680sbuf_data(struct sbuf *s)
681{
682
683	assert_sbuf_integrity(s);
684	assert_sbuf_state(s, SBUF_FINISHED);
685	KASSERT(s->s_drain_func == NULL,
686	    ("%s makes no sense on sbuf %p with drain", __func__, s));
687
688	return (s->s_buf);
689}
690
691/*
692 * Return the length of the sbuf data.
693 */
694int
695sbuf_len(struct sbuf *s)
696{
697
698	assert_sbuf_integrity(s);
699	/* don't care if it's finished or not */
700	KASSERT(s->s_drain_func == NULL,
701	    ("%s makes no sense on sbuf %p with drain", __func__, s));
702
703	if (s->s_error != 0)
704		return (-1);
705	return (s->s_len);
706}
707
708/*
709 * Clear an sbuf, free its buffer if necessary.
710 */
711void
712sbuf_delete(struct sbuf *s)
713{
714	int isdyn;
715
716	assert_sbuf_integrity(s);
717	/* don't care if it's finished or not */
718
719	if (SBUF_ISDYNAMIC(s))
720		SBFREE(s->s_buf);
721	isdyn = SBUF_ISDYNSTRUCT(s);
722	bzero(s, sizeof(*s));
723	if (isdyn)
724		SBFREE(s);
725}
726
727/*
728 * Check if an sbuf has been finished.
729 */
730int
731sbuf_done(struct sbuf *s)
732{
733
734	return (SBUF_ISFINISHED(s));
735}
736