Usermode/libc - scanf() and many other cleanups
[tpg/acess2.git] / Usermode / Libraries / libc.so_src / heap.c
1 /*\r
2 AcessOS Basic LibC\r
3 heap.c - Heap Manager\r
4 */\r
5 #include <acess/sys.h>\r
6 #include <stdlib.h>\r
7 #include <string.h>\r
8 #include "lib.h"\r
9 \r
10 #if 0\r
11 # define DEBUGS(s...)   _SysDebug(s)\r
12 #else\r
13 # define DEBUGS(s...)   do{}while(0)\r
14 #endif\r
15 \r
16 // === Constants ===\r
17 #define MAGIC   0xACE55051      //AcessOS1\r
18 #define MAGIC_FREE      (~MAGIC)\r
19 #define BLOCK_SIZE      16      //Minimum\r
20 #define HEAP_INIT_SIZE  0x10000\r
21 \r
22 typedef unsigned int Uint;\r
23 \r
24 // === TYPES ===\r
25 typedef struct {\r
26         uint32_t        magic;\r
27         size_t  size;\r
28         char    data[];\r
29 }       heap_head;\r
30 typedef struct {\r
31         heap_head       *header;\r
32         uint32_t        magic;\r
33 }       heap_foot;\r
34 \r
35 // === LOCAL VARIABLES ===\r
36 static void     *_heap_start = NULL;\r
37 static void     *_heap_end = NULL;\r
38 \r
39 // === PROTOTYPES ===\r
40 EXPORT void     *malloc(size_t bytes);\r
41 EXPORT void     *calloc(size_t bytes, size_t count);\r
42 EXPORT void     free(void *mem);\r
43 EXPORT void     *realloc(void *mem, size_t bytes);\r
44 EXPORT void     *sbrk(int increment);\r
45 LOCAL void      *extendHeap(int bytes);\r
46 static void     *FindHeapBase();\r
47 LOCAL uint      brk(uintptr_t newpos);\r
48 LOCAL void      Heap_Dump(void);\r
49 \r
50 //Code\r
51 \r
52 /**\r
53  \fn EXPORT void *malloc(size_t bytes)\r
54  \brief Allocates memory from the heap space\r
55  \param bytes   Integer - Size of buffer to return\r
56  \return Pointer to buffer\r
57 */\r
58 EXPORT void *malloc(size_t bytes)\r
59 {\r
60         size_t  bestSize;\r
61         size_t  closestMatch = 0;\r
62         void    *bestMatchAddr = 0;\r
63         heap_head       *curBlock;\r
64 \r
65 //      _SysDebug("&_heap_start = %p, _heap_start = %p", &_heap_start, _heap_start);\r
66         // Initialise Heap\r
67         if(_heap_start == NULL)\r
68         {\r
69                 _heap_start = sbrk(0);\r
70                 _heap_end = _heap_start;\r
71                 extendHeap(HEAP_INIT_SIZE);\r
72         }\r
73         \r
74         curBlock = _heap_start;\r
75 //      _SysDebug("_heap_start = %p", _heap_start);\r
76         \r
77         bestSize = bytes + sizeof(heap_head) + sizeof(heap_foot) + BLOCK_SIZE - 1;\r
78         bestSize = (bestSize/BLOCK_SIZE)*BLOCK_SIZE;    //Round up to block size\r
79         \r
80         while( (uintptr_t)curBlock < (uintptr_t)_heap_end)\r
81         {\r
82                 //_SysDebug(" malloc: curBlock = 0x%x, curBlock->magic = 0x%x\n", curBlock, curBlock->magic);\r
83                 if(curBlock->magic == MAGIC_FREE)\r
84                 {\r
85                         if(curBlock->size == bestSize)\r
86                                 break;\r
87                         if(bestSize < curBlock->size && (curBlock->size < closestMatch || closestMatch == 0)) {\r
88                                 closestMatch = curBlock->size;\r
89                                 bestMatchAddr = curBlock;\r
90                         }\r
91                 }\r
92                 else if(curBlock->magic != MAGIC)\r
93                 {\r
94                         //Corrupt Heap\r
95                         Heap_Dump();\r
96                         _SysDebug("malloc: Corrupt Heap\n");\r
97                         return NULL;\r
98                 }\r
99                 curBlock = (heap_head*)((uintptr_t)curBlock + curBlock->size);\r
100         }\r
101         \r
102         if((uintptr_t)curBlock < (uintptr_t)_heap_start) {\r
103                 _SysDebug("malloc: Heap underrun for some reason\n");\r
104                 return NULL;\r
105         }\r
106         \r
107         //Found a perfect match\r
108         if((uintptr_t)curBlock < (uintptr_t)_heap_end) {\r
109                 curBlock->magic = MAGIC;\r
110                 return (void*)((uintptr_t)curBlock + sizeof(heap_head));\r
111         }\r
112         \r
113         //Out of Heap Space\r
114         if(!closestMatch) {\r
115                 curBlock = extendHeap(bestSize);        //Allocate more\r
116                 if(curBlock == NULL) {\r
117                         _SysDebug("malloc: Out of Heap Space\n");\r
118                         return NULL;\r
119                 }\r
120                 curBlock->magic = MAGIC;\r
121                 DEBUGS("malloc(0x%x) = %p (extend) 0x%x", bytes, curBlock->data, bestSize);\r
122                 return curBlock->data;\r
123         }\r
124         \r
125         heap_head *besthead = (void*)bestMatchAddr;\r
126         \r
127         //Split Block?\r
128         if(closestMatch - bestSize > BLOCK_SIZE) {\r
129                 heap_foot       *foot;\r
130                 curBlock = (heap_head*)bestMatchAddr;\r
131                 curBlock->magic = MAGIC;\r
132                 curBlock->size = bestSize;\r
133                 foot = (heap_foot*)(bestMatchAddr + bestSize - sizeof(heap_foot));\r
134                 foot->header = curBlock;\r
135                 foot->magic = MAGIC;\r
136 \r
137                 curBlock = (heap_head*)(bestMatchAddr + bestSize);\r
138                 curBlock->magic = MAGIC_FREE;\r
139                 curBlock->size = closestMatch - bestSize;\r
140                 \r
141                 foot = (heap_foot*)(bestMatchAddr + closestMatch - sizeof(heap_foot));\r
142                 foot->header = curBlock;\r
143                 \r
144                 besthead->magic = MAGIC;        //mark as used\r
145                 DEBUGS("malloc(0x%x) = %p (split) 0x%x", bytes, besthead->data, bestSize);\r
146                 return besthead->data;\r
147         }\r
148         \r
149         //Don't Split the block\r
150         besthead->magic = MAGIC;\r
151         DEBUGS("malloc(0x%x) = %p (reuse) 0x%x", bytes, besthead->data, besthead->size);\r
152         return besthead->data;\r
153 }\r
154 \r
155 /**\r
156  * \fn EXPORT void *calloc(size_t bytes, size_t count)\r
157  * \brief Allocate and zero a block of memory\r
158  * \param __nmemb       Number of memeber elements\r
159  * \param __size        Size of one element\r
160  */\r
161 EXPORT void *calloc(size_t __nmemb, size_t __size)\r
162 {\r
163         void    *ret = malloc(__size*__nmemb);\r
164         if(!ret)        return NULL;\r
165         memset(ret, 0, __size*__nmemb);\r
166         return ret;\r
167 }\r
168 \r
169 /**\r
170  \fn EXPORT void free(void *mem)\r
171  \brief Free previously allocated memory\r
172  \param mem     Pointer - Memory to free\r
173 */\r
174 EXPORT void free(void *mem)\r
175 {\r
176         heap_head       *head = (void*)((intptr_t)mem-sizeof(heap_head));\r
177         \r
178         // Sanity please!\r
179         if(!mem)        return;\r
180         \r
181         if(head->magic != MAGIC)        //Valid Heap Address\r
182                 return;\r
183         \r
184         head->magic = MAGIC_FREE;\r
185         DEBUGS("free(%p) : 0x%x bytes", mem, head->size);\r
186         \r
187         //Unify Right\r
188         if((uintptr_t)head + head->size < (uintptr_t)_heap_end)\r
189         {\r
190                 heap_head       *nextHead = (heap_head*)((intptr_t)head + head->size);\r
191                 if(nextHead->magic == MAGIC_FREE) {     //Is the next block free\r
192                         head->size += nextHead->size;   //Amalgamate\r
193                         nextHead->magic = 0;    //For Security\r
194                 }\r
195         }\r
196         //Unify Left\r
197         if((uintptr_t)head - sizeof(heap_foot) > (uintptr_t)_heap_start)\r
198         {\r
199                 heap_head       *prevHead;\r
200                 heap_foot       *prevFoot = (heap_foot *)((intptr_t)head - sizeof(heap_foot));\r
201                 if(prevFoot->magic == MAGIC) {\r
202                         prevHead = prevFoot->header;\r
203                         if(prevHead->magic == MAGIC_FREE) {\r
204                                 prevHead->size += head->size;   //Amalgamate\r
205                                 head->magic = 0;        //For Security\r
206                         }\r
207                 }\r
208         }\r
209 }\r
210 \r
211 /**\r
212  \fn EXPORT void *realloc(void *oldPos, size_t bytes)\r
213  \brief Reallocate a block of memory\r
214  \param bytes   Integer - Size of new buffer\r
215  \param oldPos  Pointer - Old Buffer\r
216  \return Pointer to new buffer\r
217 */\r
218 EXPORT void *realloc(void *oldPos, size_t bytes)\r
219 {\r
220         void *ret;\r
221         heap_head       *head;\r
222         \r
223         if(oldPos == NULL) {\r
224                 return malloc(bytes);\r
225         }\r
226         \r
227         //Check for free space after block\r
228         head = (heap_head*)((uintptr_t)oldPos-sizeof(heap_head));\r
229         \r
230         //Hack to used free's amagamating algorithym and malloc's splitting\r
231         free(oldPos);\r
232         \r
233         //Allocate new memory\r
234         ret = malloc(bytes);\r
235         if(ret == NULL)\r
236                 return NULL;\r
237         \r
238         //Copy Old Data\r
239         if(ret != oldPos) {\r
240                 memcpy(ret, oldPos, head->size-sizeof(heap_head)-sizeof(heap_foot));\r
241         }\r
242         \r
243         //Return\r
244         return ret;\r
245 }\r
246 \r
247 /**\r
248  * \fn LOCAL void *extendHeap(int bytes)\r
249  * \brief Create a new block at the end of the heap area\r
250  * \param bytes Integer - Size reqired\r
251  * \return Pointer to last free block\r
252  */\r
253 \r
254 LOCAL void *extendHeap(int bytes)\r
255 {\r
256         heap_head       *head = _heap_end;\r
257         heap_foot       *foot;\r
258         \r
259         //Expand Memory Space  (Use foot as a temp pointer)\r
260         foot = sbrk(bytes);\r
261         if(foot == (void*)-1)\r
262                 return NULL;\r
263         \r
264         //Create New Block\r
265         // Header\r
266         head->magic = MAGIC_FREE;       //Unallocated\r
267         head->size = bytes;\r
268         // Footer\r
269         foot = _heap_end + bytes - sizeof(heap_foot);\r
270         foot->header = head;\r
271         foot->magic = MAGIC;\r
272         \r
273         //Combine with previous block if nessasary\r
274         if(_heap_end != _heap_start && ((heap_foot*)((uintptr_t)_heap_end-sizeof(heap_foot)))->magic == MAGIC) {\r
275                 heap_head       *tmpHead = ((heap_foot*)((uintptr_t)_heap_end-sizeof(heap_foot)))->header;\r
276                 if(tmpHead->magic == MAGIC_FREE) {\r
277                         tmpHead->size += bytes;\r
278                         foot->header = tmpHead;\r
279                         head = tmpHead;\r
280                 }\r
281         }\r
282         \r
283         _heap_end = (void*) ((uintptr_t)foot+sizeof(heap_foot));\r
284         return head;\r
285 }\r
286 \r
287 /**\r
288  \fn EXPORT void *sbrk(int increment)\r
289  \brief Increases the program's memory space\r
290  \param count   Integer - Size of heap increase\r
291  \return Pointer to start of new region\r
292 */\r
293 EXPORT void *sbrk(int increment)\r
294 {\r
295         static uintptr_t oldEnd = 0;\r
296         static uintptr_t curEnd = 0;\r
297 \r
298         //_SysDebug("sbrk: (increment=%i)", increment);\r
299 \r
300         if (curEnd == 0) {\r
301                 oldEnd = curEnd = (uintptr_t)FindHeapBase();\r
302                 //_SysAllocate(curEnd); // Allocate the first page\r
303         }\r
304 \r
305         //_SysDebug(" sbrk: oldEnd = 0x%x", oldEnd);\r
306         if (increment == 0)     return (void *) curEnd;\r
307 \r
308         oldEnd = curEnd;\r
309 \r
310         // Single Page\r
311         if( (curEnd & 0xFFF) && (curEnd & 0xFFF) + increment < 0x1000 )\r
312         {\r
313                 //if( curEnd & 0xFFF == 0 )\r
314                 //{\r
315                 //      if( !_SysAllocate(curEnd) )\r
316                 //      {\r
317                 //              _SysDebug("sbrk - Error allocating memory");\r
318                 //              return (void*)-1;\r
319                 //      }\r
320                 //}\r
321                 curEnd += increment;\r
322                 //_SysDebug("sbrk: RETURN %p (single page, no alloc)", (void *) oldEnd);\r
323                 return (void *)oldEnd;\r
324         }\r
325 \r
326         increment -= curEnd & 0xFFF;\r
327         curEnd += 0xFFF;        curEnd &= ~0xFFF;\r
328         while( increment > 0 )\r
329         {\r
330                 if( !_SysAllocate(curEnd) )\r
331                 {\r
332                         // Error?\r
333                         _SysDebug("sbrk - Error allocating memory");\r
334                         return (void*)-1;\r
335                 }\r
336                 increment -= 0x1000;\r
337                 curEnd += 0x1000;\r
338         }\r
339 \r
340         //_SysDebug("sbrk: RETURN %p", (void *) oldEnd);\r
341         return (void *) oldEnd;\r
342 }\r
343 \r
344 /**\r
345  * \fn EXPORT int IsHeap(void *ptr)\r
346  */\r
347 EXPORT int IsHeap(void *ptr)\r
348 {\r
349         #if 0\r
350         heap_head       *head;\r
351         heap_foot       *foot;\r
352         #endif\r
353         if( (uintptr_t)ptr < (uintptr_t)_heap_start )   return 0;\r
354         if( (uintptr_t)ptr > (uintptr_t)_heap_end )     return 0;\r
355         \r
356         #if 0\r
357         head = (void*)((Uint)ptr - 4);\r
358         if( head->magic != MAGIC )      return 0;\r
359         foot = (void*)( (Uint)ptr + head->size - sizeof(heap_foot) );\r
360         if( foot->magic != MAGIC )      return 0;\r
361         #endif\r
362         return 1;\r
363 }\r
364 \r
365 // === STATIC FUNCTIONS ===\r
366 /**\r
367  * Does the job of brk(0)\r
368  */\r
369 static void *FindHeapBase()\r
370 {\r
371         #if 0\r
372         #define MAX             0xC0000000      // Address\r
373         #define THRESHOLD       512     // Pages\r
374         uint    addr;\r
375         uint    stretch = 0;\r
376         uint64_t        tmp;\r
377         \r
378         // Scan address space\r
379         for(addr = 0;\r
380                 addr < MAX;\r
381                 addr += 0x1000\r
382                 )\r
383         {\r
384                 tmp = _SysGetPhys(addr);\r
385                 if( tmp != 0 ) {\r
386                         stretch = 0;\r
387                 } else {\r
388                         stretch ++;\r
389                         if(stretch > THRESHOLD)\r
390                         {\r
391                                 return (void*)( addr - stretch*0x1000 );\r
392                         }\r
393                 }\r
394                 //__asm__ __volatile__ (\r
395                 //      "push %%ebx;mov %%edx,%%ebx;int $0xAC;pop %%ebx"\r
396                 //      ::"a"(256),"d"("%x"),"c"(addr));\r
397         }\r
398         \r
399         return NULL;\r
400         #else\r
401         return (void*)0x00900000;\r
402         #endif\r
403 }\r
404 \r
405 LOCAL uint brk(uintptr_t newpos)\r
406 {\r
407         static uintptr_t        curpos;\r
408         uint    pages;\r
409         uint    ret = curpos;\r
410          int    delta;\r
411         \r
412         _SysDebug("brk: (newpos=0x%x)", newpos);\r
413         \r
414         // Find initial position\r
415         if(curpos == 0) curpos = (uintptr_t)FindHeapBase();\r
416         \r
417         // Get Current Position\r
418         if(newpos == 0) return curpos;\r
419         \r
420         if(newpos < curpos)     return newpos;\r
421         \r
422         delta = newpos - curpos;\r
423         _SysDebug(" brk: delta = 0x%x", delta);\r
424         \r
425         // Do we need to add pages\r
426         if(curpos & 0xFFF && (curpos & 0xFFF) + delta < 0x1000)\r
427                 return curpos += delta;\r
428         \r
429         // Page align current position\r
430         if(curpos & 0xFFF)      delta -= 0x1000 - (curpos & 0xFFF);\r
431         curpos = (curpos + 0xFFF) & ~0xFFF;\r
432         \r
433         // Allocate Pages\r
434         pages = (delta + 0xFFF) >> 12;\r
435         while(pages--)\r
436         {\r
437                 _SysAllocate(curpos);\r
438                 curpos += 0x1000;\r
439                 delta -= 0x1000;\r
440         }\r
441         \r
442         // Bring the current position to exactly what we want\r
443         curpos -= ((delta + 0xFFF) & ~0xFFF) - delta;\r
444         \r
445         return ret;     // Return old curpos\r
446 }\r
447 \r
448 void Heap_Dump(void)\r
449 {\r
450         heap_head *cur = _heap_start;\r
451         while( cur < (heap_head*)_heap_end )\r
452         {\r
453                 switch( cur->magic )\r
454                 {\r
455                 case MAGIC:\r
456                         _SysDebug("Used block %p[0x%x] - ptr=%p", cur, cur->size, cur->data);\r
457                         break;\r
458                 case MAGIC_FREE:\r
459                         _SysDebug("Free block %p[0x%x] - ptr=%p", cur, cur->size, cur->data);\r
460                         break;\r
461                 default:\r
462                         _SysDebug("Block %p bad magic (0x%x)", cur, cur->magic);\r
463                         return ;\r
464                 }\r
465                 cur = (void*)( (char*)cur + cur->size );\r
466         }\r
467 }\r
468 \r

UCC git Repository :: git.ucc.asn.au