util.c revision 1.1
1/* $OpenBSD: util.c,v 1.1 2002/02/21 23:17:53 drahn Exp $ */ 2 3#include <sys/types.h> 4#include <sys/mman.h> 5#include <string.h> 6#include "archdep.h" 7 8/* 9 * Static vars usable after bootsrapping. 10 */ 11static void *_dl_malloc_base; 12static void *_dl_malloc_pool = 0; 13static long *_dl_malloc_free = 0; 14 15char * 16_dl_strdup(const char *orig) 17{ 18 char *newstr; 19 newstr = _dl_malloc(_dl_strlen(orig)+1); 20 _dl_strcpy(newstr, orig); 21 return (newstr); 22} 23 24/* 25 * The following malloc/free code is a very simplified implementation 26 * of a malloc function. However, we do not need to be very complex here 27 * because we only free memory when 'dlclose()' is called and we can 28 * reuse at least the memory allocated for the object descriptor. We have 29 * one dynamic string allocated, the library name and it is likely that 30 * we can reuse that one to without a lot of complex colapsing code. 31 */ 32 33void * 34_dl_malloc(int size) 35{ 36 long *p; 37 long *t, *n; 38 39 size = (size + 8 + DL_MALLOC_ALIGN - 1) & ~(DL_MALLOC_ALIGN - 1); 40 41 if ((t = _dl_malloc_free) != 0) { /* Try free list first */ 42 n = (long *)&_dl_malloc_free; 43 while (t && t[-1] < size) { 44 n = t; 45 t = (long *)*t; 46 } 47 if (t) { 48 *n = *t; 49 _dl_memset(t, 0, t[-1] - 4); 50 return((void *)t); 51 } 52 } 53 if ((_dl_malloc_pool == 0) || 54 (_dl_malloc_pool + size > _dl_malloc_base + 4096)) { 55 _dl_malloc_pool = (void *)_dl_mmap((void *)0, 4096, 56 PROT_READ|PROT_WRITE, 57 MAP_ANON|MAP_PRIVATE, -1, 0); 58 if (_dl_malloc_pool == 0 || _dl_malloc_pool == MAP_FAILED ) { 59 _dl_printf("Dynamic loader failure: malloc.\n"); 60 _dl_exit(7); 61 } 62 _dl_malloc_base = _dl_malloc_pool; 63 } 64 p = _dl_malloc_pool; 65 _dl_malloc_pool += size; 66 _dl_memset(p, 0, size); 67 *p = size; 68 return((void *)(p + 1)); 69} 70 71void 72_dl_free(void *p) 73{ 74 long *t = (long *)p; 75 76 *t = (long)_dl_malloc_free; 77 _dl_malloc_free = p; 78} 79