diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/gen_bpf.c | 10 | ||||
-rw-r--r-- | src/helper.c | 25 | ||||
-rw-r--r-- | src/helper.h | 1 |
3 files changed, 34 insertions, 2 deletions
diff --git a/src/gen_bpf.c b/src/gen_bpf.c index 6961d09..602810c 100644 --- a/src/gen_bpf.c +++ b/src/gen_bpf.c @@ -351,6 +351,7 @@ static struct bpf_blk *_blk_resize(struct bpf_state *state, { unsigned int size_adj = (AINC_BLK > size_add ? AINC_BLK : size_add); struct bpf_instr *new; + size_t old_size, new_size; if (blk == NULL) return NULL; @@ -358,8 +359,10 @@ static struct bpf_blk *_blk_resize(struct bpf_state *state, if ((blk->blk_cnt + size_adj) <= blk->blk_alloc) return blk; + old_size = blk->blk_alloc * sizeof(*new); blk->blk_alloc += size_adj; - new = realloc(blk->blks, blk->blk_alloc * sizeof(*(blk->blks))); + new_size = blk->blk_alloc * sizeof(*new); + new = zrealloc(blk->blks, old_size, new_size); if (new == NULL) { _blk_free(state, blk); return NULL; @@ -443,10 +446,13 @@ static int _bpf_append_blk(struct bpf_program *prg, const struct bpf_blk *blk) bpf_instr_raw *i_iter; unsigned int old_cnt = prg->blk_cnt; unsigned int iter; + size_t old_size, new_size; /* (re)allocate the program memory */ + old_size = BPF_PGM_SIZE(prg); prg->blk_cnt += blk->blk_cnt; - i_new = realloc(prg->blks, BPF_PGM_SIZE(prg)); + new_size = BPF_PGM_SIZE(prg); + i_new = zrealloc(prg->blks, old_size, new_size); if (i_new == NULL) { rc = -ENOMEM; goto bpf_append_blk_failure; diff --git a/src/helper.c b/src/helper.c index c746749..1017d52 100644 --- a/src/helper.c +++ b/src/helper.c @@ -47,3 +47,28 @@ void *zmalloc(size_t size) return ptr; } + +/** + * Change the size of an allocated buffer + * @param ptr pointer to the allocated buffer. If NULL it is equivalent to zmalloc. + * @param old_size the current size of the allocated buffer + * @param size the new size of the buffer + * + * This function changes the size of an allocated memory buffer and return a pointer + * to the buffer on success, the new buffer portion is initialized to zero. NULL is + * returned on failure. The returned buffer could be different than the specified + * ptr param. + * + */ +void *zrealloc(void *ptr, size_t old_size, size_t size) +{ + /* NOTE: unlike malloc() zero size allocations always return NULL */ + if (size == 0) + return NULL; + + ptr = realloc(ptr, size); + if (!ptr) + return NULL; + memset(ptr + old_size, 0, size - old_size); + return ptr; +} diff --git a/src/helper.h b/src/helper.h index 2d610ce..5972f1a 100644 --- a/src/helper.h +++ b/src/helper.h @@ -23,5 +23,6 @@ #define _FILTER_HELPER_H void *zmalloc(size_t size); +void *zrealloc(void *ptr, size_t old_size, size_t size); #endif |