diff options
| author | Patrick Steinhardt <ps@pks.im> | 2018-03-14 10:34:59 +0000 |
|---|---|---|
| committer | Patrick Steinhardt <ps@pks.im> | 2018-06-07 12:57:39 +0200 |
| commit | c47f71551714006ee1aba26c49fdd1f187251da2 (patch) | |
| tree | 11f42083246877bac56fa1ccc37811f9ac0767cc /src/stdalloc.c | |
| parent | 496b0df2ca2a115d2e5a7099f2b8fd6d7409fcb2 (diff) | |
| download | libgit2-c47f71551714006ee1aba26c49fdd1f187251da2.tar.gz | |
util: extract `stdalloc` allocator into its own module
Right now, the standard allocator is being declared as part of the
"util.h" header as a set of inline functions. As with the crtdbg
allocator functions, these inline functions make it hard to convert to
function pointers for our allocators.
Create a new "stdalloc" module containing our standard allocations
functions to split these out. Convert the existing allocators to macros
which make use of the stdalloc functions.
Diffstat (limited to 'src/stdalloc.c')
| -rw-r--r-- | src/stdalloc.c | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/src/stdalloc.c b/src/stdalloc.c new file mode 100644 index 000000000..1735be7e3 --- /dev/null +++ b/src/stdalloc.c @@ -0,0 +1,86 @@ +/* + * Copyright (C) the libgit2 contributors. All rights reserved. + * + * This file is part of libgit2, distributed under the GNU GPL v2 with + * a Linking Exception. For full terms see the included COPYING file. + */ + +#include "stdalloc.h" + +void *git__stdalloc__malloc(size_t len) +{ + void *ptr = malloc(len); + if (!ptr) giterr_set_oom(); + return ptr; +} + +void *git__stdalloc__calloc(size_t nelem, size_t elsize) +{ + void *ptr = calloc(nelem, elsize); + if (!ptr) giterr_set_oom(); + return ptr; +} + +char *git__stdalloc__strdup(const char *str) +{ + char *ptr = strdup(str); + if (!ptr) giterr_set_oom(); + return ptr; +} + +char *git__stdalloc__strndup(const char *str, size_t n) +{ + size_t length = 0, alloclength; + char *ptr; + + length = p_strnlen(str, n); + + if (GIT_ADD_SIZET_OVERFLOW(&alloclength, length, 1) || + !(ptr = git__stdalloc__malloc(alloclength))) + return NULL; + + if (length) + memcpy(ptr, str, length); + + ptr[length] = '\0'; + + return ptr; +} + +char *git__stdalloc__substrdup(const char *start, size_t n) +{ + char *ptr; + size_t alloclen; + + if (GIT_ADD_SIZET_OVERFLOW(&alloclen, n, 1) || + !(ptr = git__stdalloc__malloc(alloclen))) + return NULL; + + memcpy(ptr, start, n); + ptr[n] = '\0'; + return ptr; +} + +void *git__stdalloc__realloc(void *ptr, size_t size) +{ + void *new_ptr = realloc(ptr, size); + if (!new_ptr) giterr_set_oom(); + return new_ptr; +} + +void *git__stdalloc__reallocarray(void *ptr, size_t nelem, size_t elsize) +{ + size_t newsize; + return GIT_MULTIPLY_SIZET_OVERFLOW(&newsize, nelem, elsize) ? + NULL : realloc(ptr, newsize); +} + +void *git__stdalloc__mallocarray(size_t nelem, size_t elsize) +{ + return git__stdalloc__reallocarray(NULL, nelem, elsize); +} + +void git__stdalloc__free(void *ptr) +{ + free(ptr); +} |
