1 /* malloc.c - Dumb memory allocation routines
3 * Copyright (C) 1997 Paul Mackerras
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 /* Copied from asm-generic/errno-base.h */
27 #define ENOMEM 12 /* Out of memory */
28 #define EINVAL 22 /* Invalid argument */
30 /* Imported functions */
31 extern void prom_printf (char *fmt, ...);
33 static char *malloc_ptr = 0;
34 static char *malloc_top = 0;
35 static char *last_alloc = 0;
37 void malloc_init(void *bottom, unsigned long size)
40 malloc_top = bottom + size;
43 void malloc_dispose(void)
49 void *malloc (unsigned int size)
55 if ((malloc_ptr + size + sizeof(int)) > malloc_top) {
56 prom_printf("malloc failed\n");
59 *(int *)malloc_ptr = size;
60 caddr = malloc_ptr + sizeof(int);
61 malloc_ptr += size + sizeof(int);
63 malloc_ptr = (char *) ((((unsigned int) malloc_ptr) + 3) & (~3));
67 /* Do not fall back to the malloc above as posix_memalign is needed by
68 * external libraries not yaboot */
69 int posix_memalign(void **memptr, size_t alignment, size_t size)
72 /* size of allocation including the alignment */
78 /* Minimal aligment is sizeof(void *) */
79 if (alignment < sizeof(void*))
80 alignment = sizeof(void*);
82 /* Check for valid alignment and power of 2 */
83 if ((alignment % sizeof(void*) != 0) || ((alignment-1)&alignment))
92 (size_t)((malloc_ptr + sizeof(int))+(alignment-1)) &
96 alloc_size = size + (caddr - (malloc_ptr+sizeof(int)));
98 if ((malloc_ptr + alloc_size + sizeof(int)) > malloc_top)
101 *(int *)(caddr - sizeof(int)) = size;
102 malloc_ptr += alloc_size + sizeof(int);
104 malloc_ptr = (char *) ((((unsigned int) malloc_ptr) + 3) & (~3));
105 *memptr=(void*)caddr;
110 void *realloc(void *ptr, unsigned int size)
112 char *caddr, *oaddr = ptr;
116 if (oaddr == last_alloc) {
117 if (oaddr + size > malloc_top) {
118 prom_printf("realloc failed\n");
121 *(int *)(oaddr - sizeof(int)) = size;
122 malloc_ptr = oaddr + size;
125 caddr = malloc(size);
126 if (caddr != 0 && oaddr != 0)
127 memcpy(caddr, oaddr, *(int *)(oaddr - sizeof(int)));
136 malloc_ptr = (char *) last_alloc - sizeof(int);
139 void mark (void **ptr)
143 *ptr = (void *) malloc_ptr;
146 void release (void *ptr)
150 malloc_ptr = (char *) ptr;
153 char *strdup(char const *str)
155 char *p = malloc(strlen(str) + 1);