2 * Copyright (c) 2009, 2010, 2011
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.
23 __RCSID("$MirOS: src/bin/mksh/lalloc.c,v 1.19 2011/09/07 15:24:16 tg Exp $");
25 /* build with CPPFLAGS+= -DUSE_REALLOC_MALLOC=0 on ancient systems */
26 #if defined(USE_REALLOC_MALLOC) && (USE_REALLOC_MALLOC == 0)
27 #define remalloc(p,n) ((p) == NULL ? malloc_osi(n) : realloc_osi((p), (n)))
29 #define remalloc(p,n) realloc_osi((p), (n))
32 #define ALLOC_ISUNALIGNED(p) (((ptrdiff_t)(p)) % ALLOC_SIZE)
34 static ALLOC_ITEM *findptr(ALLOC_ITEM **, char *, Area *);
39 /* area pointer is an ALLOC_ITEM, just the head of the list */
44 findptr(ALLOC_ITEM **lpp, char *ptr, Area *ap)
49 if (ALLOC_ISUNALIGNED(ptr))
52 /* get address of ALLOC_ITEM from user item */
54 * note: the alignment of "ptr" to ALLOC_SIZE is checked
55 * above; the "void *" gets us rid of a gcc 2.95 warning
57 *lpp = (lp = ptr - ALLOC_SIZE);
58 /* search for allocation item in group list */
59 while (ap->next != lp)
60 if ((ap = ap->next) == NULL) {
65 internal_warningf("rogue pointer %zX in ap %zX",
66 (size_t)ptr, (size_t)ap);
67 /* try to get a coredump */
70 internal_errorf("rogue pointer %zX", (size_t)ptr);
77 aresize2(void *ptr, size_t fac1, size_t fac2, Area *ap)
79 if (notoktomul(fac1, fac2))
80 internal_errorf(Tintovfl, fac1, '*', fac2);
81 return (aresize(ptr, fac1 * fac2, ap));
85 aresize(void *ptr, size_t numb, Area *ap)
87 ALLOC_ITEM *lp = NULL;
89 /* resizing (true) or newly allocating? */
93 pp = findptr(&lp, ptr, ap);
97 if (notoktoadd(numb, ALLOC_SIZE) ||
98 (lp = remalloc(lp, numb + ALLOC_SIZE)) == NULL
100 || ALLOC_ISUNALIGNED(lp)
103 internal_errorf(Toomem, (unsigned long)numb);
104 /* this only works because Area is an ALLOC_ITEM */
107 /* return user item address */
108 return ((char *)lp + ALLOC_SIZE);
112 afree(void *ptr, Area *ap)
117 pp = findptr(&lp, ptr, ap);
120 /* now free ALLOC_ITEM */
130 /* traverse group (linked list) */
131 while ((lp = ap->next) != NULL) {
132 /* make next ALLOC_ITEM head of list */