Cosmetics, fix typos (trivial).
[coreboot.git] / payloads / libpayload / libc / malloc.c
1 /*
2  * This file is part of the libpayload project.
3  *
4  * Copyright (C) 2008 Advanced Micro Devices, Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 /*
31  * This is a classically weak malloc() implementation. We have a relatively
32  * small and static heap, so we take the easy route with an O(N) loop
33  * through the tree for every malloc() and free(). Obviously, this doesn't
34  * scale past a few hundred KB (if that).
35  *
36  * We're also susceptible to the usual buffer overrun poisoning, though the
37  * risk is within acceptable ranges for this implementation (don't overrun
38  * your buffers, kids!).
39  */
40
41 #include <libpayload.h>
42
43 extern char _heap, _eheap;      /* Defined in the ldscript. */
44
45 static void *hstart = (void *)&_heap;
46 static void *hend = (void *)&_eheap;
47
48 typedef unsigned int hdrtype_t;
49
50 #define MAGIC     (0x2a << 26)
51 #define FLAG_FREE (1 << 25)
52 #define FLAG_USED (1 << 24)
53
54 #define SIZE(_h) ((_h) & 0xFFFFFF)
55
56 #define _HEADER(_s, _f) ((hdrtype_t) (MAGIC | (_f) | ((_s) & 0xFFFFFF)))
57
58 #define FREE_BLOCK(_s) _HEADER(_s, FLAG_FREE)
59 #define USED_BLOCK(_s) _HEADER(_s, FLAG_USED)
60
61 #define HDRSIZE (sizeof(hdrtype_t))
62
63 #define IS_FREE(_h) (((_h) & (MAGIC | FLAG_FREE)) == (MAGIC | FLAG_FREE))
64 #define HAS_MAGIC(_h) (((_h) & MAGIC) == MAGIC)
65
66 void print_malloc_map(void);
67
68 static void setup(void)
69 {
70         int size = (unsigned int)(_heap - _eheap) - HDRSIZE;
71         *((hdrtype_t *) hstart) = FREE_BLOCK(size);
72 }
73
74 static void *alloc(int len)
75 {
76         hdrtype_t header;
77         void *ptr = hstart;
78
79         /* Align the size. */
80         len = (len + 3) & ~3;
81
82         if (!len || len > 0xffffff)
83                 return (void *)NULL;
84
85         /* Make sure the region is setup correctly. */
86         if (!HAS_MAGIC(*((hdrtype_t *) ptr)))
87                 setup();
88
89         /* Find some free space. */
90         do {
91                 header = *((hdrtype_t *) ptr);
92                 int size = SIZE(header);
93
94                 if (header & FLAG_FREE) {
95                         if (len <= size) {
96                                 void *nptr = ptr + HDRSIZE + len;
97                                 int nsize = size - (len + 8);
98
99                                 /* Mark the block as used. */
100                                 *((hdrtype_t *) ptr) = USED_BLOCK(len);
101
102                                 /* If there is still room in this block,
103                                  * then mark it as such.
104                                  */
105                                 if (nsize > 0)
106                                         *((hdrtype_t *) nptr) =
107                                             FREE_BLOCK(nsize - 4);
108
109                                 return (void *)(ptr + HDRSIZE);
110                         }
111                 }
112
113                 ptr += HDRSIZE + size;
114
115         } while (ptr < hend);
116
117         /* Nothing available. */
118         return (void *)NULL;
119 }
120
121 static void _consolidate(void)
122 {
123         void *ptr = hstart;
124
125         while (ptr < hend) {
126                 void *nptr;
127                 hdrtype_t hdr = *((hdrtype_t *) ptr);
128                 unsigned int size = 0;
129
130                 if (!IS_FREE(hdr)) {
131                         ptr += HDRSIZE + SIZE(hdr);
132                         continue;
133                 }
134
135                 size = SIZE(hdr);
136                 nptr = ptr + HDRSIZE + SIZE(hdr);
137
138                 while (nptr < hend) {
139                         hdrtype_t nhdr = *((hdrtype_t *) nptr);
140
141                         if (!(IS_FREE(nhdr)))
142                                 break;
143
144                         size += SIZE(nhdr) + HDRSIZE;
145
146                         *((hdrtype_t *) nptr) = 0;
147
148                         nptr += (HDRSIZE + SIZE(nhdr));
149                 }
150
151                 *((hdrtype_t *) ptr) = FREE_BLOCK(size);
152                 ptr = nptr;
153         }
154 }
155
156 void free(void *ptr)
157 {
158         hdrtype_t hdr;
159
160         ptr -= HDRSIZE;
161
162         /* Sanity check. */
163         if (ptr < hstart || ptr >= hend)
164                 return;
165
166         hdr = *((hdrtype_t *) ptr);
167
168         /* Not our header (we're probably poisoned). */
169         if (!HAS_MAGIC(hdr))
170                 return;
171
172         /* Double free. */
173         if (hdr & FLAG_FREE)
174                 return;
175
176         *((hdrtype_t *) ptr) = FREE_BLOCK(SIZE(hdr));
177         _consolidate();
178 }
179
180 void *malloc(size_t size)
181 {
182         return alloc(size);
183 }
184
185 void *calloc(size_t nmemb, size_t size)
186 {
187         unsigned int total = (nmemb * size);
188         void *ptr = alloc(size);
189
190         if (ptr)
191                 memset(ptr, 0, total);
192
193         return ptr;
194 }
195
196 void *realloc(void *ptr, size_t size)
197 {
198         void *ret, *pptr;
199         unsigned int osize;
200
201         if (ptr == NULL)
202                 return alloc(size);
203
204         pptr = ptr - HDRSIZE;
205
206         if (!HAS_MAGIC(*((hdrtype_t *) pptr)))
207                 return NULL;
208
209         /* Get the original size of the block. */
210         osize = SIZE(*((hdrtype_t *) pptr));
211
212         /*
213          * Free the memory to update the tables - this won't touch the actual
214          * memory, so we can still use it for the copy after we have
215          * reallocated the new space.
216          */
217         free(ptr);
218         ret = alloc(size);
219
220         /*
221          * if ret == NULL, then doh - failure.
222          * if ret == ptr then woo-hoo! no copy needed.
223          */
224         if (ret == NULL || ret == ptr)
225                 return ret;
226
227         /* Copy the memory to the new location. */
228         memcpy(ret, ptr, osize > size ? size : osize);
229
230         return ret;
231 }
232
233 /* This is for debugging purposes. */
234 #ifdef TEST
235 void print_malloc_map(void)
236 {
237         void *ptr = hstart;
238
239         while (ptr < hend) {
240                 hdrtype_t hdr = *((hdrtype_t *) ptr);
241
242                 if (!HAS_MAGIC(hdr)) {
243                         printf("Poisoned magic - we're toast\n");
244                         break;
245                 }
246
247                 /* FIXME: Verify the size of the block. */
248
249                 printf("%x: %s (%x bytes)\n",
250                        (unsigned int)(ptr - hstart),
251                        hdr & FLAG_FREE ? "FREE" : "USED", SIZE(hdr));
252
253                 ptr += HDRSIZE + SIZE(hdr);
254         }
255 }
256 #endif