Added state-handle and some support for asynchronous activities.
[yaz-moved-to-github.git] / util / dmalloc.c
1 /*
2  * Copyright (C) 1994, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: dmalloc.c,v $
7  * Revision 1.1  1995-03-27 08:35:17  quinn
8  * Created util library
9  * Added memory debugging module. Imported options-manager
10  *
11  *
12  */
13
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <string.h>
17
18 static const unsigned long head = 0xaabbccdd;
19 static const unsigned long tail = 0x11223344;
20 static const unsigned long freed = 0xffeeffee;
21
22 void *d_malloc(char *file, int line, int nbytes)
23 {
24     char *res;
25     int long len;
26
27     if (!(res = malloc(nbytes + 3 * sizeof(long))))
28         return 0;
29     fprintf(stderr, "---d_malloc, '%s':%d, %d->0x%p\n",
30         file, line, nbytes, res + 2 * sizeof(long));
31     len = nbytes;
32     memcpy(res, &head, sizeof(long));
33     memcpy(res + sizeof(long), &len, sizeof(long));
34     res += 2 * sizeof(long);
35     memcpy(res + nbytes, &tail, sizeof(long));
36     return res;
37 }
38
39 void d_free(char *file, int line, char *ptr)
40 {
41     long len;
42
43     if (memcmp(&head, ptr - 2 * sizeof(long), sizeof(long)))
44         abort();
45     memcpy(ptr, &freed, sizeof(long));
46     memcpy(&len, ptr - sizeof(long), sizeof(long));
47     if (memcmp(ptr + len, &tail, sizeof(long)))
48         abort();
49     fprintf(stderr, "---d_free, '%s':%d, 0x%p (%d)\n",
50         file, line, ptr, len);
51     free(ptr - 2 * sizeof(long));
52     return;
53 }
54
55 void *d_realloc(char *file, int line, char *ptr, int nbytes)
56 {
57     long len, nlen = nbytes;
58     char *p = ptr;
59     char *r;
60
61     if (memcmp(&head, ptr - 2 * sizeof(long), sizeof(long)))
62         abort();
63     memcpy(&len, ptr - sizeof(long), sizeof(long));
64     if (memcmp(ptr + len, &tail, sizeof(long)))
65         abort();
66     if (!(r = realloc(ptr, nbytes + 3 * sizeof(long))))
67         return 0;
68     fprintf(stderr, "---d_realloc, '%s':%d, %d->%d, 0x%p->0x%p\n",
69         file, line, len, nbytes, p, r + 2 * sizeof(long));
70     memcpy(r, &head, sizeof(long));
71     memcpy(r + sizeof(long), &nlen, sizeof(long));
72     if (r != ptr - 2 * sizeof(long))
73     {
74         memcpy(r + 2 * sizeof(long), ptr, len);
75         memcpy(ptr - 2 * sizeof(long), &freed, sizeof(long));
76     }
77     r += 2 * sizeof(long);
78     memcpy(r + nbytes, &tail, sizeof(long));
79     return r;
80 }