changelog for 0.9.1
[posh.git] / alloc.c
blob7b29cc003f6fb4c417540995d71c6920e9f554b3
1 /*-
2 * Copyright © 2009
3 * Thorsten Glaser <tg@mirbsd.org>
5 * Provided that these terms and disclaimer and all copyright notices
6 * are retained or reproduced in an accompanying document, permission
7 * is granted to deal in this work without restriction, including un‐
8 * limited rights to use, publicly perform, distribute, sell, modify,
9 * merge, give away, or sublicence.
11 * This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
12 * the utmost extent permitted by applicable law, neither express nor
13 * implied; without malicious intent or gross negligence. In no event
14 * may a licensor, author or contributor be held liable for indirect,
15 * direct, other damage, loss, or other issues arising in any way out
16 * of dealing in the work, even if advised of the possibility of such
17 * damage or existence of a defect, except proven that it results out
18 * of said person’s immediate fault when using the work as intended.
21 #include "sh.h"
23 #define remalloc(p,n) realloc((p), (n))
25 #define ALLOC_ISUNALIGNED(p) (((ptrdiff_t)(p)) % ALLOC_SIZE)
27 static ALLOC_ITEM *findptr(ALLOC_ITEM **, char *, Area *);
29 void
30 ainit(Area *ap)
32 /* area pointer is an ALLOC_ITEM, just the head of the list */
33 ap->next = NULL;
36 static ALLOC_ITEM *
37 findptr(ALLOC_ITEM **lpp, char *ptr, Area *ap)
39 void *lp;
41 #ifndef MKSH_SMALL
42 if (ALLOC_ISUNALIGNED(ptr))
43 goto fail;
44 #endif
45 /* get address of ALLOC_ITEM from user item */
47 * note: the alignment of "ptr" to ALLOC_SIZE is checked
48 * above; the "void *" gets us rid of a gcc 2.95 warning
50 *lpp = (lp = ptr - ALLOC_SIZE);
51 /* search for allocation item in group list */
52 while (ap->next != lp)
53 if ((ap = ap->next) == NULL) {
54 #ifndef MKSH_SMALL
55 fail:
56 #endif
57 internal_errorf(1, "rogue pointer %p", ptr);
59 return (ap);
62 void *
63 aresize(void *ptr, size_t numb, Area *ap)
65 ALLOC_ITEM *lp = NULL;
67 /* resizing (true) or newly allocating? */
68 if (ptr != NULL) {
69 ALLOC_ITEM *pp;
71 pp = findptr(&lp, ptr, ap);
72 pp->next = lp->next;
75 if ((numb >= SIZE_MAX - ALLOC_SIZE) ||
76 (lp = remalloc(lp, numb + ALLOC_SIZE)) == NULL
77 #ifndef MKSH_SMALL
78 || ALLOC_ISUNALIGNED(lp)
79 #endif
81 internal_errorf(1, "cannot allocate %lu data bytes",
82 (unsigned long)numb);
83 /* this only works because Area is an ALLOC_ITEM */
84 lp->next = ap->next;
85 ap->next = lp;
86 /* return user item address */
87 return ((char *)lp + ALLOC_SIZE);
90 void
91 afree(void *ptr, Area *ap)
93 if (ptr != NULL) {
94 ALLOC_ITEM *lp, *pp;
96 pp = findptr(&lp, ptr, ap);
97 /* unhook */
98 pp->next = lp->next;
99 /* now free ALLOC_ITEM */
100 free(lp);
104 void
105 afreeall(Area *ap)
107 ALLOC_ITEM *lp;
109 /* traverse group (linked list) */
110 while ((lp = ap->next) != NULL) {
111 /* make next ALLOC_ITEM head of list */
112 ap->next = lp->next;
113 /* free old head */
114 free(lp);