malloc.c
来自「基于组件方式开发操作系统的OSKIT源代码」· C语言 代码 · 共 1,161 行 · 第 1/2 页
C
1,161 行
#ifndef OSKIT/* * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <phk@FreeBSD.ORG> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp * ---------------------------------------------------------------------------- * * $\Id: malloc.c,v 1.18.2.2 1997/03/18 16:18:24 phk Exp $ * *//* * Defining EXTRA_SANITY will enable extra checks which are related * to internal conditions and consistency in malloc.c. This has a * noticeable runtime performance hit, and generally will not do you * any good unless you fiddle with the internals of malloc or want * to catch random pointer corruption as early as possible. */#ifndef MALLOC_EXTRA_SANITY#undef MALLOC_EXTRA_SANITY#endif/* * Defining MALLOC_STATS will enable you to call malloc_dump() and set * the [dD] options in the MALLOC_OPTIONS environment variable. * It has no run-time performance hit. */#ifndef MALLOC_STATS#undef MALLOC_STATS#endif/* * What to use for Junk. This is the byte value we use to fill with * when the 'J' option is enabled. */#define SOME_JUNK 0xd0 /* as in "Duh" :-) *//* * The basic parameters you can tweak. * * malloc_pageshift pagesize = 1 << malloc_pageshift * It's probably best if this is the native * page size, but it shouldn't have to be. * * malloc_minsize minimum size of an allocation in bytes. * If this is too small it's too much work * to manage them. This is also the smallest * unit of alignment used for the storage * returned by malloc/realloc. * */#if defined(__i386__) && defined(__FreeBSD__)# define malloc_pageshift 12U# define malloc_minsize 16U#endif /* __i386__ && __FreeBSD__ *//* Insert your combination here... */#if defined(__FOOCPU__) && defined(__BAROS__)# define malloc_pageshift 12U# define malloc_minsize 16U#endif /* __i386__ && __FreeBSD__ *//* * No user serviceable parts behind this point. */#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <errno.h>#include <sys/types.h>#include <sys/mman.h>/* * This structure describes a page worth of chunks. */struct pginfo { struct pginfo *next; /* next on the free list */ void *page; /* Pointer to the page */ u_short size; /* size of this page's chunks */ u_short shift; /* How far to shift for this size chunks */ u_short free; /* How many free chunks */ u_short total; /* How many chunk */ u_int bits[1]; /* Which chunks are free */};/* * This structure describes a number of free pages. */struct pgfree { struct pgfree *next; /* next run of free pages */ struct pgfree *prev; /* prev run of free pages */ void *page; /* pointer to free pages */ void *end; /* pointer to end of free pages */ u_long size; /* number of bytes free */};/* * How many bits per u_int in the bitmap. * Change only if not 8 bits/byte */#define MALLOC_BITS (8*sizeof(u_int))/* * Magic values to put in the page_directory */#define MALLOC_NOT_MINE ((struct pginfo*) 0)#define MALLOC_FREE ((struct pginfo*) 1)#define MALLOC_FIRST ((struct pginfo*) 2)#define MALLOC_FOLLOW ((struct pginfo*) 3)#define MALLOC_MAGIC ((struct pginfo*) 4)#ifndef malloc_pageshift#define malloc_pageshift 12U#endif#ifndef malloc_minsize#define malloc_minsize 16U#endif#ifndef malloc_pageshift#error "malloc_pageshift undefined"#endif#if !defined(malloc_pagesize)#define malloc_pagesize (1U<<malloc_pageshift)#endif#if ((1<<malloc_pageshift) != malloc_pagesize)#error "(1<<malloc_pageshift) != malloc_pagesize"#endif#ifndef malloc_maxsize#define malloc_maxsize ((malloc_pagesize)>>1)#endif/* A mask for the offset inside a page. */#define malloc_pagemask ((malloc_pagesize)-1)#define pageround(foo) (((foo) + (malloc_pagemask))&(~(malloc_pagemask)))#define ptr2index(foo) (((u_long)(foo) >> malloc_pageshift)-malloc_origo)/* Set when initialization has been done */static unsigned malloc_started; /* Number of free pages we cache */static unsigned malloc_cache = 16;/* The offset from pagenumber to index into the page directory */static u_long malloc_origo;/* The last index in the page directory we care about */static u_long last_index;/* Pointer to page directory. Allocated "as if with" malloc */static struct pginfo **page_dir;/* How many slots in the page directory */static unsigned malloc_ninfo;/* Free pages line up here */static struct pgfree free_list;/* Abort(), user doesn't handle problems. */static int malloc_abort;/* Are we trying to die ? */static int suicide;/* dump statistics */static int malloc_stats;/* always realloc ? */static int malloc_realloc;/* pass the kernel a hint on free pages ? */static int malloc_hint;/* zero fill ? */static int malloc_zero;/* junk fill ? */static int malloc_junk;/* utrace ? */static int malloc_utrace;#ifdef __FreeBSD__struct ut { void *p; size_t s; void *r; };void utrace __P((struct ut *, int));#define UTRACE(a, b, c) \ if (malloc_utrace) \ {struct ut u; u.p=a; u.s = b; u.r=c; utrace(&u, sizeof u);}#else /* !__FreeBSD__ */#define UTRACE(a,b,c)#endif/* my last break. */static void *malloc_brk;/* one location cache for free-list holders */static struct pgfree *px;/* compile-time options */char *malloc_options;/* Name of the current public function */static char *malloc_func;/* * Necessary function declarations */static int extend_pgdir(u_long index);static void *imalloc(size_t size);static void ifree(void *ptr);static void *irealloc(void *ptr, size_t size);#ifdef MALLOC_STATSvoidmalloc_dump(FILE *fd){ struct pginfo **pd; struct pgfree *pf; int j; pd = page_dir; /* print out all the pages */ for(j=0;j<=last_index;j++) { fprintf(fd, "%08lx %5d ", (j+malloc_origo) << malloc_pageshift, j); if (pd[j] == MALLOC_NOT_MINE) { for(j++;j<=last_index && pd[j] == MALLOC_NOT_MINE;j++) ; j--; fprintf(fd, ".. %5d not mine\n", j); } else if (pd[j] == MALLOC_FREE) { for(j++;j<=last_index && pd[j] == MALLOC_FREE;j++) ; j--; fprintf(fd, ".. %5d free\n", j); } else if (pd[j] == MALLOC_FIRST) { for(j++;j<=last_index && pd[j] == MALLOC_FOLLOW;j++) ; j--; fprintf(fd, ".. %5d in use\n", j); } else if (pd[j] < MALLOC_MAGIC) { fprintf(fd, "(%p)\n", pd[j]); } else { fprintf(fd, "%p %d (of %d) x %d @ %p --> %p\n", pd[j], pd[j]->free, pd[j]->total, pd[j]->size, pd[j]->page, pd[j]->next); } } for(pf=free_list.next; pf; pf=pf->next) { fprintf(fd, "Free: @%p [%p...%p[ %ld ->%p <-%p\n", pf, pf->page, pf->end, pf->size, pf->prev, pf->next); if (pf == pf->next) { fprintf(fd, "Free_list loops.\n"); break; } } /* print out various info */ fprintf(fd, "Minsize\t%d\n", malloc_minsize); fprintf(fd, "Maxsize\t%d\n", malloc_maxsize); fprintf(fd, "Pagesize\t%d\n", malloc_pagesize); fprintf(fd, "Pageshift\t%d\n", malloc_pageshift); fprintf(fd, "FirstPage\t%ld\n", malloc_origo); fprintf(fd, "LastPage\t%ld %lx\n", last_index+malloc_pageshift, (last_index + malloc_pageshift) << malloc_pageshift); fprintf(fd, "Break\t%ld\n", (u_long)sbrk(0) >> malloc_pageshift);}#endif /* MALLOC_STATS */extern char *__progname;static voidwrterror(char *p){ char *q = " error: "; suicide = 1; write(2, __progname, strlen(__progname)); write(2, malloc_func, strlen(malloc_func)); write(2, q, strlen(q)); write(2, p, strlen(p));#ifdef MALLOC_STATS if (malloc_stats) malloc_dump(stderr);#endif /* MALLOC_STATS */ abort();}static voidwrtwarning(char *p){ char *q = " warning: "; if (malloc_abort) wrterror(p); write(2, __progname, strlen(__progname)); write(2, malloc_func, strlen(malloc_func)); write(2, q, strlen(q)); write(2, p, strlen(p));}#ifdef MALLOC_STATSstatic voidmalloc_exit(){ FILE *fd = fopen("malloc.out", "a"); char *q = "malloc() warning: Couldn't dump stats.\n"; if (fd) { malloc_dump(fd); fclose(fd); } else write(2, q, strlen(q));}#endif /* MALLOC_STATS *//* * Allocate a number of pages from the OS */static caddr_tmap_pages(int pages){ caddr_t result, tail; result = (caddr_t)pageround((u_long)sbrk(0)); tail = result + (pages << malloc_pageshift); if (brk(tail)) {#ifdef EXTRA_SANITY wrterror("(ES): map_pages fails\n");#endif /* EXTRA_SANITY */ return 0; } last_index = ptr2index(tail) - 1; malloc_brk = tail; if ((last_index+1) >= malloc_ninfo && !extend_pgdir(last_index)) return 0;; return result;}/* * Extend page directory */static intextend_pgdir(u_long index){ struct pginfo **new, **old; int i, oldlen; /* Make it this many pages */ i = index * sizeof *page_dir; i /= malloc_pagesize; i += 2; /* remember the old mapping size */ oldlen = malloc_ninfo * sizeof *page_dir; /* * NOTE: we allocate new pages and copy the directory rather than tempt * fate by trying to "grow" the region.. There is nothing to prevent * us from accidently re-mapping space that's been allocated by our caller * via dlopen() or other mmap(). * * The copy problem is not too bad, as there is 4K of page index per * 4MB of malloc arena. * * We can totally avoid the copy if we open a file descriptor to associate * the anon mappings with. Then, when we remap the pages at the new * address, the old pages will be "magically" remapped.. But this means * keeping open a "secret" file descriptor..... */ /* Get new pages */ new = (struct pginfo**) mmap(0, i * malloc_pagesize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0); if (new == (struct pginfo **)-1) return 0; /* Copy the old stuff */ memcpy(new, page_dir, malloc_ninfo * sizeof *page_dir); /* register the new size */ malloc_ninfo = i * malloc_pagesize / sizeof *page_dir; /* swap the pointers */ old = page_dir; page_dir = new; /* Now free the old stuff */ munmap((caddr_t)old, oldlen); return 1;}/* * Initialize the world */static voidmalloc_init (){ char *p, b[64]; int i, j;#ifdef EXTRA_SANITY malloc_junk = 1;#endif /* EXTRA_SANITY */ for (i = 0; i < 3; i++) { if (i == 0) { j = readlink("/etc/malloc.conf", b, sizeof b - 1); if (j <= 0) continue; b[j] = '\0'; p = b; } else if (i == 1) { p = getenv("MALLOC_OPTIONS"); } else { p = malloc_options; } for (; p && *p; p++) { switch (*p) { case '>': malloc_cache <<= 1; break; case '<': malloc_cache >>= 1; break; case 'a': malloc_abort = 0; break; case 'A': malloc_abort = 1; break; case 'd': malloc_stats = 0; break; case 'D': malloc_stats = 1; break; case 'h': malloc_hint = 0; break; case 'H': malloc_hint = 1; break; case 'r': malloc_realloc = 0; break; case 'R': malloc_realloc = 1; break; case 'j': malloc_junk = 0; break; case 'J': malloc_junk = 1; break; case 'u': malloc_utrace = 0; break; case 'U': malloc_utrace = 1; break; case 'z': malloc_zero = 0; break; case 'Z': malloc_zero = 1; break; default: j = malloc_abort; malloc_abort = 0; wrtwarning("unknown char in MALLOC_OPTIONS\n"); malloc_abort = j; break; } } } UTRACE(0, 0, 0); /* * We want junk in the entire allocation, and zero only in the part * the user asked for. */ if (malloc_zero) malloc_junk=1;#ifdef MALLOC_STATS if (malloc_stats) atexit(malloc_exit);#endif /* MALLOC_STATS */ /* Allocate one page for the page directory */ page_dir = (struct pginfo **) mmap(0, malloc_pagesize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0); if (page_dir == (struct pginfo **) -1) wrterror("mmap(2) failed, check limits.\n"); /* * We need a maximum of malloc_pageshift buckets, steal these from the * front of the page_directory; */ malloc_origo = ((u_long)pageround((u_long)sbrk(0))) >> malloc_pageshift; malloc_origo -= malloc_pageshift; malloc_ninfo = malloc_pagesize / sizeof *page_dir; /* Been here, done that */ malloc_started++; /* Recalculate the cache size in bytes, and make sure it's nonzero */ if (!malloc_cache) malloc_cache++; malloc_cache <<= malloc_pageshift; /* * This is a nice hack from Kaleb Keithly (kaleb@x.org). * We can sbrk(2) further back when we keep this on a low address. */ px = (struct pgfree *) imalloc (sizeof *px);}/* * Allocate a number of complete pages */static void *malloc_pages(size_t size){ void *p, *delay_free = 0; int i; struct pgfree *pf; u_long index; size = pageround(size); p = 0; /* Look for free pages before asking for more */ for(pf = free_list.next; pf; pf = pf->next) {#ifdef EXTRA_SANITY if (pf->size & malloc_pagemask) wrterror("(ES): junk length entry on free_list\n"); if (!pf->size) wrterror("(ES): zero length entry on free_list\n"); if (pf->page == pf->end) wrterror("(ES): zero entry on free_list\n"); if (pf->page > pf->end) wrterror("(ES): sick entry on free_list\n"); if ((void*)pf->page >= (void*)sbrk(0)) wrterror("(ES): entry on free_list past brk\n"); if (page_dir[ptr2index(pf->page)] != MALLOC_FREE) wrterror("(ES): non-free first page on free-list\n"); if (page_dir[ptr2index(pf->end)-1] != MALLOC_FREE) wrterror("(ES): non-free last page on free-list\n");#endif /* EXTRA_SANITY */ if (pf->size < size) continue; if (pf->size == size) { p = pf->page; if (pf->next) pf->next->prev = pf->prev; pf->prev->next = pf->next; delay_free = pf; break; } p = pf->page; pf->page = (char *)pf->page + size; pf->size -= size; break; }#ifdef EXTRA_SANITY if (p && page_dir[ptr2index(p)] != MALLOC_FREE) wrterror("(ES): allocated non-free page on free-list\n");#endif /* EXTRA_SANITY */ size >>= malloc_pageshift; /* Map new pages */ if (!p) p = map_pages(size); if (p) { index = ptr2index(p); page_dir[index] = MALLOC_FIRST; for (i=1;i<size;i++) page_dir[index+i] = MALLOC_FOLLOW; if (malloc_junk) memset(p, SOME_JUNK, size << malloc_pageshift);
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?