ofpbuf: Enable ofpbuf_push() to expand headroom.
[cascardo/ovs.git] / lib / ofpbuf.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofpbuf.h"
19 #include <assert.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include "dynamic-string.h"
23 #include "util.h"
24
25 static void
26 ofpbuf_use__(struct ofpbuf *b, void *base, size_t allocated,
27              enum ofpbuf_source source)
28 {
29     b->base = b->data = base;
30     b->allocated = allocated;
31     b->source = source;
32     b->size = 0;
33     b->l2 = b->l3 = b->l4 = b->l7 = NULL;
34     list_poison(&b->list_node);
35     b->private_p = NULL;
36 }
37
38 /* Initializes 'b' as an empty ofpbuf that contains the 'allocated' bytes of
39  * memory starting at 'base'.  'base' should be the first byte of a region
40  * obtained from malloc().  It will be freed (with free()) if 'b' is resized or
41  * freed. */
42 void
43 ofpbuf_use(struct ofpbuf *b, void *base, size_t allocated)
44 {
45     ofpbuf_use__(b, base, allocated, OFPBUF_MALLOC);
46 }
47
48 /* Initializes 'b' as an empty ofpbuf that contains the 'allocated' bytes of
49  * memory starting at 'base'.  'base' should point to a buffer on the stack.
50  * If 'b' is resized, new memory will be allocated with malloc() and 'base'
51  * will not be freed.  This is useful when a small stack-allocated buffer is
52  * normally appropriate but sometimes it must be expanded.
53  *
54  * 'base' should be appropriately aligned.  Using an array of uint32_t or
55  * uint64_t for the buffer is a reasonable way to ensure appropriate alignment
56  * for 32- or 64-bit data.
57  *
58  * (Nothing actually relies on 'base' being allocated on the stack.  It could
59  * be static or malloc()'d memory.  But stack space is the most common use
60  * case.) */
61 void
62 ofpbuf_use_stack(struct ofpbuf *b, void *base, size_t allocated)
63 {
64     ofpbuf_use__(b, base, allocated, OFPBUF_STACK);
65 }
66
67 /* Initializes 'b' as an ofpbuf whose data starts at 'data' and continues for
68  * 'size' bytes.  This is appropriate for an ofpbuf that will be used to
69  * inspect existing data, without moving it around or reallocating it, and
70  * generally without modifying it at all.
71  *
72  * An ofpbuf operation that requires reallocating data will assert-fail if this
73  * function was used to initialize it. */
74 void
75 ofpbuf_use_const(struct ofpbuf *b, const void *data, size_t size)
76 {
77     ofpbuf_use__(b, (void *) data, size, OFPBUF_CONST);
78     b->size = size;
79 }
80
81 /* Initializes 'b' as an empty ofpbuf with an initial capacity of 'size'
82  * bytes. */
83 void
84 ofpbuf_init(struct ofpbuf *b, size_t size)
85 {
86     ofpbuf_use(b, size ? xmalloc(size) : NULL, size);
87 }
88
89 /* Frees memory that 'b' points to. */
90 void
91 ofpbuf_uninit(struct ofpbuf *b)
92 {
93     if (b && b->source == OFPBUF_MALLOC) {
94         free(b->base);
95     }
96 }
97
98 /* Frees memory that 'b' points to and allocates a new ofpbuf */
99 void
100 ofpbuf_reinit(struct ofpbuf *b, size_t size)
101 {
102     ofpbuf_uninit(b);
103     ofpbuf_init(b, size);
104 }
105
106 /* Creates and returns a new ofpbuf with an initial capacity of 'size'
107  * bytes. */
108 struct ofpbuf *
109 ofpbuf_new(size_t size)
110 {
111     struct ofpbuf *b = xmalloc(sizeof *b);
112     ofpbuf_init(b, size);
113     return b;
114 }
115
116 /* Creates and returns a new ofpbuf with an initial capacity of 'size +
117  * headroom' bytes, reserving the first 'headroom' bytes as headroom. */
118 struct ofpbuf *
119 ofpbuf_new_with_headroom(size_t size, size_t headroom)
120 {
121     struct ofpbuf *b = ofpbuf_new(size + headroom);
122     ofpbuf_reserve(b, headroom);
123     return b;
124 }
125
126 struct ofpbuf *
127 ofpbuf_clone(const struct ofpbuf *buffer)
128 {
129     return ofpbuf_clone_data(buffer->data, buffer->size);
130 }
131
132 /* Creates and returns a new ofpbuf whose data are copied from 'buffer'.   The
133  * returned ofpbuf will additionally have 'headroom' bytes of headroom. */
134 struct ofpbuf *
135 ofpbuf_clone_with_headroom(const struct ofpbuf *buffer, size_t headroom)
136 {
137     struct ofpbuf *b = ofpbuf_new_with_headroom(buffer->size, headroom);
138     ofpbuf_put(b, buffer->data, buffer->size);
139     return b;
140 }
141
142 struct ofpbuf *
143 ofpbuf_clone_data(const void *data, size_t size)
144 {
145     struct ofpbuf *b = ofpbuf_new(size);
146     ofpbuf_put(b, data, size);
147     return b;
148 }
149
150 /* Frees memory that 'b' points to, as well as 'b' itself. */
151 void
152 ofpbuf_delete(struct ofpbuf *b)
153 {
154     if (b) {
155         ofpbuf_uninit(b);
156         free(b);
157     }
158 }
159
160 /* Returns the number of bytes of headroom in 'b', that is, the number of bytes
161  * of unused space in ofpbuf 'b' before the data that is in use.  (Most
162  * commonly, the data in a ofpbuf is at its beginning, and thus the ofpbuf's
163  * headroom is 0.) */
164 size_t
165 ofpbuf_headroom(const struct ofpbuf *b)
166 {
167     return (char*)b->data - (char*)b->base;
168 }
169
170 /* Returns the number of bytes that may be appended to the tail end of ofpbuf
171  * 'b' before the ofpbuf must be reallocated. */
172 size_t
173 ofpbuf_tailroom(const struct ofpbuf *b)
174 {
175     return (char*)ofpbuf_end(b) - (char*)ofpbuf_tail(b);
176 }
177
178 static void
179 ofpbuf_copy__(struct ofpbuf *b, uint8_t *new_base,
180               size_t new_headroom, size_t new_tailroom)
181 {
182     const uint8_t *old_base = b->base;
183     size_t old_headroom = ofpbuf_headroom(b);
184     size_t old_tailroom = ofpbuf_tailroom(b);
185     size_t copy_headroom = MIN(old_headroom, new_headroom);
186     size_t copy_tailroom = MIN(old_tailroom, new_tailroom);
187
188     memcpy(&new_base[new_headroom - copy_headroom],
189            &old_base[old_headroom - copy_headroom],
190            copy_headroom + b->size + copy_tailroom);
191 }
192
193 /* Reallocates 'b' so that it has exactly 'new_headroom' and 'new_tailroom'
194  * bytes of headroom and tailroom, respectively. */
195 static void
196 ofpbuf_resize__(struct ofpbuf *b, size_t new_headroom, size_t new_tailroom)
197 {
198     void *new_base, *new_data;
199     size_t new_allocated;
200
201     new_allocated = new_headroom + b->size + new_tailroom;
202
203     switch (b->source) {
204     case OFPBUF_MALLOC:
205         if (new_headroom == ofpbuf_headroom(b)) {
206             new_base = xrealloc(b->base, new_allocated);
207         } else {
208             new_base = xmalloc(new_allocated);
209             ofpbuf_copy__(b, new_base, new_headroom, new_tailroom);
210             free(b->base);
211         }
212         break;
213
214     case OFPBUF_STACK:
215         new_base = xmalloc(new_allocated);
216         ofpbuf_copy__(b, new_base, new_headroom, new_tailroom);
217         b->source = OFPBUF_MALLOC;
218         break;
219
220     case OFPBUF_CONST:
221         NOT_REACHED();
222
223     default:
224         NOT_REACHED();
225     }
226
227     b->allocated = new_allocated;
228     b->base = new_base;
229
230     new_data = (char *) new_base + new_headroom;
231     if (b->data != new_data) {
232         uintptr_t data_delta = (char *) new_data - (char *) b->data;
233         b->data = new_data;
234         if (b->l2) {
235             b->l2 = (char *) b->l2 + data_delta;
236         }
237         if (b->l3) {
238             b->l3 = (char *) b->l3 + data_delta;
239         }
240         if (b->l4) {
241             b->l4 = (char *) b->l4 + data_delta;
242         }
243         if (b->l7) {
244             b->l7 = (char *) b->l7 + data_delta;
245         }
246     }
247 }
248
249 /* Ensures that 'b' has room for at least 'size' bytes at its tail end,
250  * reallocating and copying its data if necessary.  Its headroom, if any, is
251  * preserved. */
252 void
253 ofpbuf_prealloc_tailroom(struct ofpbuf *b, size_t size)
254 {
255     if (size > ofpbuf_tailroom(b)) {
256         ofpbuf_resize__(b, ofpbuf_headroom(b), MAX(size, 64));
257     }
258 }
259
260 /* Ensures that 'b' has room for at least 'size' bytes at its head,
261  * reallocating and copying its data if necessary.  Its tailroom, if any, is
262  * preserved. */
263 void
264 ofpbuf_prealloc_headroom(struct ofpbuf *b, size_t size)
265 {
266     if (size > ofpbuf_headroom(b)) {
267         ofpbuf_resize__(b, MAX(size, 64), ofpbuf_tailroom(b));
268     }
269 }
270
271 /* Trims the size of 'b' to fit its actual content, reducing its tailroom to
272  * 0.  Its headroom, if any, is preserved.
273  *
274  * Buffers not obtained from malloc() are not resized, since that wouldn't save
275  * any memory. */
276 void
277 ofpbuf_trim(struct ofpbuf *b)
278 {
279     if (b->source == OFPBUF_MALLOC
280         && (ofpbuf_headroom(b) || ofpbuf_tailroom(b))) {
281         ofpbuf_resize__(b, 0, 0);
282     }
283 }
284
285 /* Appends 'size' bytes of data to the tail end of 'b', reallocating and
286  * copying its data if necessary.  Returns a pointer to the first byte of the
287  * new data, which is left uninitialized. */
288 void *
289 ofpbuf_put_uninit(struct ofpbuf *b, size_t size)
290 {
291     void *p;
292     ofpbuf_prealloc_tailroom(b, size);
293     p = ofpbuf_tail(b);
294     b->size += size;
295     return p;
296 }
297
298 /* Appends 'size' zeroed bytes to the tail end of 'b'.  Data in 'b' is
299  * reallocated and copied if necessary.  Returns a pointer to the first byte of
300  * the data's location in the ofpbuf. */
301 void *
302 ofpbuf_put_zeros(struct ofpbuf *b, size_t size)
303 {
304     void *dst = ofpbuf_put_uninit(b, size);
305     memset(dst, 0, size);
306     return dst;
307 }
308
309 /* Appends the 'size' bytes of data in 'p' to the tail end of 'b'.  Data in 'b'
310  * is reallocated and copied if necessary.  Returns a pointer to the first
311  * byte of the data's location in the ofpbuf. */
312 void *
313 ofpbuf_put(struct ofpbuf *b, const void *p, size_t size)
314 {
315     void *dst = ofpbuf_put_uninit(b, size);
316     memcpy(dst, p, size);
317     return dst;
318 }
319
320 /* Parses as many pairs of hex digits as possible (possibly separated by
321  * spaces) from the beginning of 's', appending bytes for their values to 'b'.
322  * Returns the first character of 's' that is not the first of a pair of hex
323  * digits.  If 'n' is nonnull, stores the number of bytes added to 'b' in
324  * '*n'. */
325 char *
326 ofpbuf_put_hex(struct ofpbuf *b, const char *s, size_t *n)
327 {
328     size_t initial_size = b->size;
329     for (;;) {
330         uint8_t byte;
331         bool ok;
332
333         s += strspn(s, " ");
334         byte = hexits_value(s, 2, &ok);
335         if (!ok) {
336             if (n) {
337                 *n = b->size - initial_size;
338             }
339             return (char *) s;
340         }
341
342         ofpbuf_put(b, &byte, 1);
343         s += 2;
344     }
345 }
346
347 /* Reserves 'size' bytes of headroom so that they can be later allocated with
348  * ofpbuf_push_uninit() without reallocating the ofpbuf. */
349 void
350 ofpbuf_reserve(struct ofpbuf *b, size_t size)
351 {
352     assert(!b->size);
353     ofpbuf_prealloc_tailroom(b, size);
354     b->data = (char*)b->data + size;
355 }
356
357 /* Prefixes 'size' bytes to the head end of 'b', reallocating and copying its
358  * data if necessary.  Returns a pointer to the first byte of the data's
359  * location in the ofpbuf.  The new data is left uninitialized. */
360 void *
361 ofpbuf_push_uninit(struct ofpbuf *b, size_t size)
362 {
363     ofpbuf_prealloc_headroom(b, size);
364     b->data = (char*)b->data - size;
365     b->size += size;
366     return b->data;
367 }
368
369 /* Prefixes 'size' zeroed bytes to the head end of 'b', reallocating and
370  * copying its data if necessary.  Returns a pointer to the first byte of the
371  * data's location in the ofpbuf. */
372 void *
373 ofpbuf_push_zeros(struct ofpbuf *b, size_t size)
374 {
375     void *dst = ofpbuf_push_uninit(b, size);
376     memset(dst, 0, size);
377     return dst;
378 }
379
380 /* Copies the 'size' bytes starting at 'p' to the head end of 'b', reallocating
381  * and copying its data if necessary.  Returns a pointer to the first byte of
382  * the data's location in the ofpbuf. */
383 void *
384 ofpbuf_push(struct ofpbuf *b, const void *p, size_t size)
385 {
386     void *dst = ofpbuf_push_uninit(b, size);
387     memcpy(dst, p, size);
388     return dst;
389 }
390
391 /* If 'b' contains at least 'offset + size' bytes of data, returns a pointer to
392  * byte 'offset'.  Otherwise, returns a null pointer. */
393 void *
394 ofpbuf_at(const struct ofpbuf *b, size_t offset, size_t size)
395 {
396     return offset + size <= b->size ? (char *) b->data + offset : NULL;
397 }
398
399 /* Returns a pointer to byte 'offset' in 'b', which must contain at least
400  * 'offset + size' bytes of data. */
401 void *
402 ofpbuf_at_assert(const struct ofpbuf *b, size_t offset, size_t size)
403 {
404     assert(offset + size <= b->size);
405     return ((char *) b->data) + offset;
406 }
407
408 /* Returns the byte following the last byte of data in use in 'b'. */
409 void *
410 ofpbuf_tail(const struct ofpbuf *b)
411 {
412     return (char *) b->data + b->size;
413 }
414
415 /* Returns the byte following the last byte allocated for use (but not
416  * necessarily in use) by 'b'. */
417 void *
418 ofpbuf_end(const struct ofpbuf *b)
419 {
420     return (char *) b->base + b->allocated;
421 }
422
423 /* Clears any data from 'b'. */
424 void
425 ofpbuf_clear(struct ofpbuf *b)
426 {
427     b->data = b->base;
428     b->size = 0;
429 }
430
431 /* Removes 'size' bytes from the head end of 'b', which must contain at least
432  * 'size' bytes of data.  Returns the first byte of data removed. */
433 void *
434 ofpbuf_pull(struct ofpbuf *b, size_t size)
435 {
436     void *data = b->data;
437     assert(b->size >= size);
438     b->data = (char*)b->data + size;
439     b->size -= size;
440     return data;
441 }
442
443 /* If 'b' has at least 'size' bytes of data, removes that many bytes from the
444  * head end of 'b' and returns the first byte removed.  Otherwise, returns a
445  * null pointer without modifying 'b'. */
446 void *
447 ofpbuf_try_pull(struct ofpbuf *b, size_t size)
448 {
449     return b->size >= size ? ofpbuf_pull(b, size) : NULL;
450 }
451
452 /* Returns a string that describes some of 'b''s metadata plus a hex dump of up
453  * to 'maxbytes' from the start of the buffer. */
454 char *
455 ofpbuf_to_string(const struct ofpbuf *b, size_t maxbytes)
456 {
457     struct ds s;
458
459     ds_init(&s);
460     ds_put_format(&s, "size=%zu, allocated=%zu, head=%zu, tail=%zu\n",
461                   b->size, b->allocated,
462                   ofpbuf_headroom(b), ofpbuf_tailroom(b));
463     ds_put_hex_dump(&s, b->data, MIN(b->size, maxbytes), 0, false);
464     return ds_cstr(&s);
465 }
466
467 /* Removes each of the "struct ofpbuf"s on 'list' from the list and frees
468  * them.  */
469 void
470 ofpbuf_list_delete(struct list *list)
471 {
472     struct ofpbuf *b, *next;
473
474     LIST_FOR_EACH_SAFE (b, next, list_node, list) {
475         list_remove(&b->list_node);
476         ofpbuf_delete(b);
477     }
478 }