1 /* alloc-srvx.c - Debug allocation wrapper
2 * Copyright 2005 srvx Development Team
4 * This file is part of srvx.
6 * srvx is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
22 /* cookies for anybody who recognizes these bytes without help :) */
23 #define ALLOC_MAGIC 0x1acf
24 #define FREE_MAGIC 0xfc1d
27 unsigned int file_id : 8;
28 unsigned int size : 24;
29 unsigned int line : 16;
30 unsigned int magic : 16;
33 static char file_id_map[256][32];
34 static unsigned int file_ids_used;
37 file_id_cmp(const void *a_, const void *b_)
39 return strcmp(a_, b_);
43 get_file_id(const char *fname)
47 entry = bsearch(fname, file_id_map, file_ids_used, sizeof(file_id_map[0]), file_id_cmp);
49 return ((char*)entry - file_id_map[0]) / sizeof(file_id_map[0]);
50 strcpy(file_id_map[file_ids_used++], fname);
51 qsort(file_id_map, file_ids_used, sizeof(file_id_map[0]), file_id_cmp);
52 return file_ids_used - 1;
56 srvx_malloc(const char *file, unsigned int line, size_t size)
58 struct alloc_header *block;
60 block = malloc(sizeof(*block) + size);
61 assert(block != NULL);
62 memset(block, 0, sizeof(*block) + size);
63 block->file_id = get_file_id(file);
66 block->magic = ALLOC_MAGIC;
71 srvx_realloc(const char *file, unsigned int line, void *ptr, size_t size)
73 struct alloc_header *block = NULL, *newblock;
76 block = (struct alloc_header *)ptr - 1;
77 assert(block->magic == ALLOC_MAGIC);
78 if (block->size >= size)
82 newblock = malloc(sizeof(*newblock) + size);
83 assert(newblock != NULL);
84 memset(newblock, 0, sizeof(*newblock) + size);
85 newblock->file_id = get_file_id(file);
86 newblock->line = line;
87 newblock->size = size;
88 newblock->magic = ALLOC_MAGIC;
91 memcpy(newblock + 1, block + 1, block->size);
92 size = block->size + sizeof(*block);
93 memset(block, 0, size);
94 block->magic = FREE_MAGIC;
102 srvx_strdup(const char *file, unsigned int line, const char *src)
107 len = strlen(src) + 1;
108 target = srvx_malloc(file, line, len);
109 memcpy(target, src, len);
114 srvx_free(const char *file, unsigned int line, void *ptr)
116 struct alloc_header *block;
121 block = (struct alloc_header *)ptr - 1;
122 assert(block->magic == ALLOC_MAGIC);
123 size = block->size + sizeof(*block);
124 memset(block, 0, size);
125 block->magic = FREE_MAGIC;
127 (void)file; (void)line;