subr_sbuf.c revision 116182
1/*-
2 * Copyright (c) 2000 Poul-Henning Kamp and Dag-Erling Co�dan Sm�rgrav
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/sys/kern/subr_sbuf.c 116182 2003-06-11 00:56:59Z obrien $");
31
32#include <sys/param.h>
33
34#ifdef _KERNEL
35#include <sys/ctype.h>
36#include <sys/kernel.h>
37#include <sys/malloc.h>
38#include <sys/systm.h>
39#include <sys/uio.h>
40#include <machine/stdarg.h>
41#else /* _KERNEL */
42#include <ctype.h>
43#include <stdarg.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <string.h>
47#endif /* _KERNEL */
48
49#include <sys/sbuf.h>
50
51#ifdef _KERNEL
52MALLOC_DEFINE(M_SBUF, "sbuf", "string buffers");
53#define	SBMALLOC(size)		malloc(size, M_SBUF, M_WAITOK)
54#define	SBFREE(buf)		free(buf, M_SBUF)
55#else /* _KERNEL */
56#define	KASSERT(e, m)
57#define	SBMALLOC(size)		malloc(size)
58#define	SBFREE(buf)		free(buf)
59#define	min(x,y)		MIN(x,y)
60#endif /* _KERNEL */
61
62/*
63 * Predicates
64 */
65#define	SBUF_ISDYNAMIC(s)	((s)->s_flags & SBUF_DYNAMIC)
66#define	SBUF_ISDYNSTRUCT(s)	((s)->s_flags & SBUF_DYNSTRUCT)
67#define	SBUF_ISFINISHED(s)	((s)->s_flags & SBUF_FINISHED)
68#define	SBUF_HASOVERFLOWED(s)	((s)->s_flags & SBUF_OVERFLOWED)
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)
87static void
88_assert_sbuf_integrity(const char *fun, struct sbuf *s)
89{
90	KASSERT(s != NULL,
91	    ("%s called with a NULL sbuf pointer", fun));
92	KASSERT(s->s_buf != NULL,
93	    ("%s called with uninitialized or corrupt sbuf", fun));
94	KASSERT(s->s_len < s->s_size,
95	    ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
96}
97
98static void
99_assert_sbuf_state(const char *fun, struct sbuf *s, int state)
100{
101	KASSERT((s->s_flags & SBUF_FINISHED) == state,
102	    ("%s called with %sfinished or corrupt sbuf", fun,
103	    (state ? "un" : "")));
104}
105#define	assert_sbuf_integrity(s) _assert_sbuf_integrity(__func__, (s))
106#define	assert_sbuf_state(s, i)	 _assert_sbuf_state(__func__, (s), (i))
107#else /* _KERNEL && INVARIANTS */
108#define	assert_sbuf_integrity(s) do { } while (0)
109#define	assert_sbuf_state(s, i)	 do { } while (0)
110#endif /* _KERNEL && INVARIANTS */
111
112static int
113sbuf_extendsize(int size)
114{
115	int newsize;
116
117	newsize = SBUF_MINEXTENDSIZE;
118	while (newsize < size) {
119		if (newsize < (int)SBUF_MAXEXTENDSIZE)
120			newsize *= 2;
121		else
122			newsize += SBUF_MAXEXTENDINCR;
123	}
124
125	return (newsize);
126}
127
128
129/*
130 * Extend an sbuf.
131 */
132static int
133sbuf_extend(struct sbuf *s, int addlen)
134{
135	char *newbuf;
136	int newsize;
137
138	if (!SBUF_CANEXTEND(s))
139		return (-1);
140
141	newsize = sbuf_extendsize(s->s_size + addlen);
142	newbuf = (char *)SBMALLOC(newsize);
143	if (newbuf == NULL)
144		return (-1);
145	bcopy(s->s_buf, newbuf, s->s_size);
146	if (SBUF_ISDYNAMIC(s))
147		SBFREE(s->s_buf);
148	else
149		SBUF_SETFLAG(s, SBUF_DYNAMIC);
150	s->s_buf = newbuf;
151	s->s_size = newsize;
152	return (0);
153}
154
155/*
156 * Initialize an sbuf.
157 * If buf is non-NULL, it points to a static or already-allocated string
158 * big enough to hold at least length characters.
159 */
160struct sbuf *
161sbuf_new(struct sbuf *s, char *buf, int length, int flags)
162{
163	KASSERT(length >= 0,
164	    ("attempt to create an sbuf of negative length (%d)", length));
165	KASSERT((flags & ~SBUF_USRFLAGMSK) == 0,
166	    ("%s called with invalid flags", __func__));
167
168	flags &= SBUF_USRFLAGMSK;
169	if (s == NULL) {
170		s = (struct sbuf *)SBMALLOC(sizeof *s);
171		if (s == NULL)
172			return (NULL);
173		bzero(s, sizeof *s);
174		s->s_flags = flags;
175		SBUF_SETFLAG(s, SBUF_DYNSTRUCT);
176	} else {
177		bzero(s, sizeof *s);
178		s->s_flags = flags;
179	}
180	s->s_size = length;
181	if (buf) {
182		s->s_buf = buf;
183		return (s);
184	}
185	if (flags & SBUF_AUTOEXTEND)
186		s->s_size = sbuf_extendsize(s->s_size);
187	s->s_buf = (char *)SBMALLOC(s->s_size);
188	if (s->s_buf == NULL) {
189		if (SBUF_ISDYNSTRUCT(s))
190			SBFREE(s);
191		return (NULL);
192	}
193	SBUF_SETFLAG(s, SBUF_DYNAMIC);
194	return (s);
195}
196
197#ifdef _KERNEL
198/*
199 * Create an sbuf with uio data
200 */
201struct sbuf *
202sbuf_uionew(struct sbuf *s, struct uio *uio, int *error)
203{
204	KASSERT(uio != NULL,
205	    ("%s called with NULL uio pointer", __func__));
206	KASSERT(error != NULL,
207	    ("%s called with NULL error pointer", __func__));
208
209	s = sbuf_new(s, NULL, uio->uio_resid + 1, 0);
210	if (s == NULL) {
211		*error = ENOMEM;
212		return (NULL);
213	}
214	*error = uiomove(s->s_buf, uio->uio_resid, uio);
215	if (*error != 0) {
216		sbuf_delete(s);
217		return (NULL);
218	}
219	s->s_len = s->s_size - 1;
220	*error = 0;
221	return (s);
222}
223#endif
224
225/*
226 * Clear an sbuf and reset its position.
227 */
228void
229sbuf_clear(struct sbuf *s)
230{
231	assert_sbuf_integrity(s);
232	/* don't care if it's finished or not */
233
234	SBUF_CLEARFLAG(s, SBUF_FINISHED);
235	SBUF_CLEARFLAG(s, SBUF_OVERFLOWED);
236	s->s_len = 0;
237}
238
239/*
240 * Set the sbuf's end position to an arbitrary value.
241 * Effectively truncates the sbuf at the new position.
242 */
243int
244sbuf_setpos(struct sbuf *s, int pos)
245{
246	assert_sbuf_integrity(s);
247	assert_sbuf_state(s, 0);
248
249	KASSERT(pos >= 0,
250	    ("attempt to seek to a negative position (%d)", pos));
251	KASSERT(pos < s->s_size,
252	    ("attempt to seek past end of sbuf (%d >= %d)", pos, s->s_size));
253
254	if (pos < 0 || pos > s->s_len)
255		return (-1);
256	s->s_len = pos;
257	return (0);
258}
259
260/*
261 * Append a byte string to an sbuf.
262 */
263int
264sbuf_bcat(struct sbuf *s, const char *str, size_t len)
265{
266	assert_sbuf_integrity(s);
267	assert_sbuf_state(s, 0);
268
269	if (SBUF_HASOVERFLOWED(s))
270		return (-1);
271
272	for (; len; len--) {
273		if (!SBUF_HASROOM(s) && sbuf_extend(s, len) < 0)
274			break;
275		s->s_buf[s->s_len++] = *str++;
276	}
277	if (len) {
278		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
279		return (-1);
280	}
281	return (0);
282}
283
284#ifdef _KERNEL
285/*
286 * Copy a byte string from userland into an sbuf.
287 */
288int
289sbuf_bcopyin(struct sbuf *s, const void *uaddr, size_t len)
290{
291	assert_sbuf_integrity(s);
292	assert_sbuf_state(s, 0);
293
294	if (SBUF_HASOVERFLOWED(s))
295		return (-1);
296
297	if (len == 0)
298		return (0);
299	if (len > SBUF_FREESPACE(s)) {
300		sbuf_extend(s, len - SBUF_FREESPACE(s));
301		len = min(len, SBUF_FREESPACE(s));
302	}
303	if (copyin(uaddr, s->s_buf + s->s_len, len) != 0)
304		return (-1);
305	s->s_len += len;
306
307	return (0);
308}
309#endif
310
311/*
312 * Copy a byte string into an sbuf.
313 */
314int
315sbuf_bcpy(struct sbuf *s, const char *str, size_t len)
316{
317	assert_sbuf_integrity(s);
318	assert_sbuf_state(s, 0);
319
320	sbuf_clear(s);
321	return (sbuf_bcat(s, str, len));
322}
323
324/*
325 * Append a string to an sbuf.
326 */
327int
328sbuf_cat(struct sbuf *s, const char *str)
329{
330	assert_sbuf_integrity(s);
331	assert_sbuf_state(s, 0);
332
333	if (SBUF_HASOVERFLOWED(s))
334		return (-1);
335
336	while (*str) {
337		if (!SBUF_HASROOM(s) && sbuf_extend(s, strlen(str)) < 0)
338			break;
339		s->s_buf[s->s_len++] = *str++;
340	}
341	if (*str) {
342		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
343		return (-1);
344	}
345	return (0);
346}
347
348#ifdef _KERNEL
349/*
350 * Append a string from userland to an sbuf.
351 */
352int
353sbuf_copyin(struct sbuf *s, const void *uaddr, size_t len)
354{
355	size_t done;
356
357	assert_sbuf_integrity(s);
358	assert_sbuf_state(s, 0);
359
360	if (SBUF_HASOVERFLOWED(s))
361		return (-1);
362
363	if (len == 0)
364		len = SBUF_FREESPACE(s);	/* XXX return 0? */
365	if (len > SBUF_FREESPACE(s)) {
366		sbuf_extend(s, len);
367		len = min(len, SBUF_FREESPACE(s));
368	}
369	switch (copyinstr(uaddr, s->s_buf + s->s_len, len + 1, &done)) {
370	case ENAMETOOLONG:
371		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
372		/* fall through */
373	case 0:
374		s->s_len += done - 1;
375		break;
376	default:
377		return (-1);	/* XXX */
378	}
379
380	return (0);
381}
382#endif
383
384/*
385 * Copy a string into an sbuf.
386 */
387int
388sbuf_cpy(struct sbuf *s, const char *str)
389{
390	assert_sbuf_integrity(s);
391	assert_sbuf_state(s, 0);
392
393	sbuf_clear(s);
394	return (sbuf_cat(s, str));
395}
396
397/*
398 * Format the given argument list and append the resulting string to an sbuf.
399 */
400int
401sbuf_vprintf(struct sbuf *s, const char *fmt, va_list ap)
402{
403	va_list ap_copy;
404	int len;
405
406	assert_sbuf_integrity(s);
407	assert_sbuf_state(s, 0);
408
409	KASSERT(fmt != NULL,
410	    ("%s called with a NULL format string", __func__));
411
412	if (SBUF_HASOVERFLOWED(s))
413		return (-1);
414
415	do {
416		va_copy(ap_copy, ap);
417		len = vsnprintf(&s->s_buf[s->s_len], SBUF_FREESPACE(s) + 1,
418		    fmt, ap_copy);
419		va_end(ap_copy);
420	} while (len > SBUF_FREESPACE(s) &&
421	    sbuf_extend(s, len - SBUF_FREESPACE(s)) == 0);
422
423	/*
424	 * s->s_len is the length of the string, without the terminating nul.
425	 * When updating s->s_len, we must subtract 1 from the length that
426	 * we passed into vsnprintf() because that length includes the
427	 * terminating nul.
428	 *
429	 * vsnprintf() returns the amount that would have been copied,
430	 * given sufficient space, hence the min() calculation below.
431	 */
432	s->s_len += min(len, SBUF_FREESPACE(s));
433	if (!SBUF_HASROOM(s) && !SBUF_CANEXTEND(s))
434		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
435
436	KASSERT(s->s_len < s->s_size,
437	    ("wrote past end of sbuf (%d >= %d)", s->s_len, s->s_size));
438
439	if (SBUF_HASOVERFLOWED(s))
440		return (-1);
441	return (0);
442}
443
444/*
445 * Format the given arguments and append the resulting string to an sbuf.
446 */
447int
448sbuf_printf(struct sbuf *s, const char *fmt, ...)
449{
450	va_list ap;
451	int result;
452
453	va_start(ap, fmt);
454	result = sbuf_vprintf(s, fmt, ap);
455	va_end(ap);
456	return(result);
457}
458
459/*
460 * Append a character to an sbuf.
461 */
462int
463sbuf_putc(struct sbuf *s, int c)
464{
465	assert_sbuf_integrity(s);
466	assert_sbuf_state(s, 0);
467
468	if (SBUF_HASOVERFLOWED(s))
469		return (-1);
470
471	if (!SBUF_HASROOM(s) && sbuf_extend(s, 1) < 0) {
472		SBUF_SETFLAG(s, SBUF_OVERFLOWED);
473		return (-1);
474	}
475	if (c != '\0')
476	    s->s_buf[s->s_len++] = c;
477	return (0);
478}
479
480/*
481 * Trim whitespace characters from end of an sbuf.
482 */
483int
484sbuf_trim(struct sbuf *s)
485{
486	assert_sbuf_integrity(s);
487	assert_sbuf_state(s, 0);
488
489	if (SBUF_HASOVERFLOWED(s))
490		return (-1);
491
492	while (s->s_len && isspace(s->s_buf[s->s_len-1]))
493		--s->s_len;
494
495	return (0);
496}
497
498/*
499 * Check if an sbuf overflowed
500 */
501int
502sbuf_overflowed(struct sbuf *s)
503{
504    return SBUF_HASOVERFLOWED(s);
505}
506
507/*
508 * Finish off an sbuf.
509 */
510void
511sbuf_finish(struct sbuf *s)
512{
513	assert_sbuf_integrity(s);
514	assert_sbuf_state(s, 0);
515
516	s->s_buf[s->s_len] = '\0';
517	SBUF_CLEARFLAG(s, SBUF_OVERFLOWED);
518	SBUF_SETFLAG(s, SBUF_FINISHED);
519}
520
521/*
522 * Return a pointer to the sbuf data.
523 */
524char *
525sbuf_data(struct sbuf *s)
526{
527	assert_sbuf_integrity(s);
528	assert_sbuf_state(s, SBUF_FINISHED);
529
530	return s->s_buf;
531}
532
533/*
534 * Return the length of the sbuf data.
535 */
536int
537sbuf_len(struct sbuf *s)
538{
539	assert_sbuf_integrity(s);
540	/* don't care if it's finished or not */
541
542	if (SBUF_HASOVERFLOWED(s))
543		return (-1);
544	return s->s_len;
545}
546
547/*
548 * Clear an sbuf, free its buffer if necessary.
549 */
550void
551sbuf_delete(struct sbuf *s)
552{
553	int isdyn;
554
555	assert_sbuf_integrity(s);
556	/* don't care if it's finished or not */
557
558	if (SBUF_ISDYNAMIC(s))
559		SBFREE(s->s_buf);
560	isdyn = SBUF_ISDYNSTRUCT(s);
561	bzero(s, sizeof *s);
562	if (isdyn)
563		SBFREE(s);
564}
565
566/*
567 * Check if an sbuf has been finished.
568 */
569int
570sbuf_done(struct sbuf *s)
571{
572
573	return(SBUF_ISFINISHED(s));
574}
575