Debian Codegraph @

src/util/allocators/debugalloc.c

raw
1 /*
2 * Copyright (C) the libgit2 contributors. All rights reserved.
3 *
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
6 */
7
8 #include "debugalloc.h"
9
10 static void *debugalloc__malloc(size_t len, const char *file, int line)
11 {
12 unsigned char *ptr;
13 size_t total = len + sizeof(size_t);
14
15 GIT_UNUSED(file);
16 GIT_UNUSED(line);
17
18 if (!len || (ptr = malloc(total)) == NULL)
19 return NULL;
20
21 memcpy(ptr, &len, sizeof(size_t));
22 return ptr + sizeof(size_t);
23 }
24
25 static void *debugalloc__realloc(void *_ptr, size_t len, const char *file, int line)
26 {
27 unsigned char *ptr = _ptr, *newptr;
28 size_t original_len;
29 size_t total = len + sizeof(size_t);
30
31 GIT_UNUSED(file);
32 GIT_UNUSED(line);
33
34 if (!len && !ptr)
35 return NULL;
36
37 if (!len) {
38 free(ptr - sizeof(size_t));
39 return NULL;
40 }
41
42 if ((newptr = malloc(total)) == NULL)
43 return NULL;
44
45 if (ptr) {
46 memcpy(&original_len, ptr - sizeof(size_t), sizeof(size_t));
47 memcpy(newptr + sizeof(size_t), ptr, min(len, original_len));
48
49 memset(ptr - sizeof(size_t), 0xfd, original_len + sizeof(size_t));
50 free(ptr - sizeof(size_t));
51 }
52
53 memcpy(newptr, &len, sizeof(size_t));
54 return newptr + sizeof(size_t);
55 }
56
57 static void debugalloc__free(void *_ptr)
58 {
59 unsigned char *ptr = _ptr;
60
61 if (!ptr)
62 return;
63
64 free(ptr - sizeof(size_t));
65 }
66
67 int git_debugalloc_init_allocator(git_allocator *allocator)
68 {
69 allocator->gmalloc = debugalloc__malloc;
70 allocator->grealloc = debugalloc__realloc;
71 allocator->gfree = debugalloc__free;
72 return 0;
73 }