home *** CD-ROM | disk | FTP | other *** search
/ PC Extra Super CD 1998 January / PCPLUS131.iso / DJGPP / V2 / DJLSR201.ZIP / src / libc / ansi / stdlib / malloc.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-12-26  |  9.1 KB  |  348 lines

  1. /* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */
  2. /*
  3.  * Copyright (c) 1983 Regents of the University of California.
  4.  * All rights reserved.
  5.  *
  6.  * Redistribution and use in source and binary forms are permitted
  7.  * provided that: (1) source distributions retain this entire copyright
  8.  * notice and comment, and (2) distributions including binaries display
  9.  * the following acknowledgement:  ``This product includes software
  10.  * developed by the University of California, Berkeley and its contributors''
  11.  * in the documentation or other materials provided with the distribution
  12.  * and in all advertising materials mentioning features or use of this
  13.  * software. Neither the name of the University nor the names of its
  14.  * contributors may be used to endorse or promote products derived
  15.  * from this software without specific prior written permission.
  16.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  17.  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  18.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  19.  */
  20.  
  21. /*
  22.  * malloc.c (Caltech) 2/21/82
  23.  * Chris Kingsley, kingsley@cit-20.
  24.  *
  25.  * This is a very fast storage allocator.  It allocates blocks of a small 
  26.  * number of different sizes, and keeps free lists of each size.  Blocks that
  27.  * don't exactly fit are passed up to the next larger size.  In this 
  28.  * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
  29.  * This is designed for use in a virtual memory environment.
  30.  */
  31.  
  32. #include <libc/stubs.h>
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <unistd.h>
  37.  
  38. #define getpagesize() 4096
  39.  
  40. /*
  41.  * The overhead on a block is at least 4 bytes.  When free, this space
  42.  * contains a pointer to the next free block, and the bottom two bits must
  43.  * be zero.  When in use, the first byte is set to MAGIC, and the second
  44.  * byte is the size index.  The remaining bytes are for alignment.
  45.  * If range checking is enabled then a second word holds the size of the
  46.  * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
  47.  * The order of elements is critical: ov_magic must overlay the low order
  48.  * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
  49.  */
  50. union overhead {
  51.   union    overhead *ov_next;    /* when free */
  52.   struct {
  53.     unsigned char    ovu_magic; /* magic number */
  54.     unsigned char    ovu_index; /* bucket # */
  55. #ifdef RCHECK
  56.     unsigned short    ovu_rmagic; /* range magic number */
  57.     unsigned int    ovu_size; /* actual block size */
  58. #endif
  59.   } ovu;
  60. #define    ov_magic    ovu.ovu_magic
  61. #define    ov_index    ovu.ovu_index
  62. #define    ov_rmagic    ovu.ovu_rmagic
  63. #define    ov_size        ovu.ovu_size
  64. };
  65.  
  66. #define    MAGIC        0xef        /* magic # on accounting info */
  67. #define RMAGIC        0x5555        /* magic # on range info */
  68.  
  69. #ifdef RCHECK
  70. #define    RSLOP        sizeof (unsigned short)
  71. #else
  72. #define    RSLOP        0
  73. #endif
  74.  
  75. /*
  76.  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
  77.  * smallest allocatable block is 8 bytes.  The overhead information
  78.  * precedes the data area returned to the user.
  79.  */
  80. #define    NBUCKETS 30
  81. static    union overhead *nextf[NBUCKETS];
  82.  
  83. static    int pagesz;            /* page size */
  84. static    int pagebucket;            /* page size bucket */
  85.  
  86. #ifdef MSTATS
  87. /*
  88.  * nmalloc[i] is the difference between the number of mallocs and frees
  89.  * for a given block size.
  90.  */
  91. static    unsigned int nmalloc[NBUCKETS];
  92. #endif
  93.  
  94. static void morecore(int bucket);
  95.  
  96. #if defined(DEBUG) || defined(RCHECK)
  97. #define    ASSERT(p)   if (!(p)) botch(#p)
  98. static void
  99. botch(char *s)
  100. {
  101.   fprintf(stderr, "\r\nassertion botched: %s\r\n", s);
  102.   (void) fflush(stderr);    /* just in case user buffered it */
  103.   *((int *)-1) = 0;        /* force fault; abort will probably fail if malloc's dead */
  104.   abort();
  105. }
  106. #else
  107. #define    ASSERT(p)
  108. #endif
  109.  
  110. void *
  111. malloc(size_t nbytes)
  112. {
  113.   union overhead *op;
  114.   int bucket, n;
  115.   unsigned amt;
  116.  
  117.   /*
  118.    * First time malloc is called, setup page size and
  119.    * align break pointer so all data will be page aligned.
  120.    */
  121.   if (pagesz == 0) {
  122.     pagesz = n = getpagesize();
  123.     op = (union overhead *)sbrk(0);
  124.     n = n - sizeof (*op) - ((int)op & (n - 1));
  125.     if (n < 0)
  126.       n += pagesz;
  127.     if (n) {
  128.       if (sbrk(n) == (char *)-1)
  129.     return (NULL);
  130.     }
  131.     bucket = 0;
  132.     amt = 8;
  133.     while (pagesz > amt) {
  134.       amt <<= 1;
  135.       bucket++;
  136.     }
  137.     pagebucket = bucket;
  138.   }
  139.   /*
  140.    * Convert amount of memory requested into closest block size
  141.    * stored in hash buckets which satisfies request.
  142.    * Account for space used per block for accounting.
  143.    */
  144.   if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
  145. #ifndef RCHECK
  146.     amt = 8;            /* size of first bucket */
  147.     bucket = 0;
  148. #else
  149.     amt = 16;            /* size of first bucket */
  150.     bucket = 1;
  151. #endif
  152.     n = -(sizeof (*op) + RSLOP);
  153.   } else {
  154.     amt = pagesz;
  155.     bucket = pagebucket;
  156.   }
  157.   while (nbytes > amt + n) {
  158.     amt <<= 1;
  159.     if (amt == 0)
  160.       return (NULL);
  161.     bucket++;
  162.   }
  163.   /*
  164.    * If nothing in hash bucket right now,
  165.    * request more memory from the system.
  166.    */
  167.   if ((op = nextf[bucket]) == NULL) {
  168.     morecore(bucket);
  169.     if ((op = nextf[bucket]) == NULL)
  170.       return (NULL);
  171.   }
  172.   /* remove from linked list */
  173.   nextf[bucket] = op->ov_next;
  174.   op->ov_magic = MAGIC;
  175.   op->ov_index = bucket;
  176. #ifdef MSTATS
  177.   nmalloc[bucket]++;
  178. #endif
  179. #ifdef RCHECK
  180.   /*
  181.    * Record allocated size of block and
  182.    * bound space with magic numbers.
  183.    */
  184.   op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
  185.   op->ov_rmagic = RMAGIC;
  186.   *(unsigned short *)((char *)(op + 1) + op->ov_size) = RMAGIC;
  187. #endif
  188.   return ((char *)(op + 1));
  189. }
  190.  
  191. /*
  192.  * Allocate more memory to the indicated bucket.
  193.  */
  194. static void
  195. morecore(int bucket)
  196. {
  197.   union overhead *op;
  198.   int sz;            /* size of desired block */
  199.   int amt;            /* amount to allocate */
  200.   int nblks;            /* how many blocks we get */
  201.  
  202.   /*
  203.    * sbrk_size <= 0 only for big, FLUFFY, requests (about
  204.    * 2^30 bytes on a VAX, I think) or for a negative arg.
  205.    */
  206.   sz = 1 << (bucket + 3);
  207. #ifdef DEBUG
  208.   ASSERT(sz > 0);
  209. #else
  210.   if (sz <= 0)
  211.     return;
  212. #endif
  213.   if (sz < pagesz) {
  214.     amt = pagesz;
  215.     nblks = amt / sz;
  216.   } else {
  217.     amt = sz + pagesz;
  218.     nblks = 1;
  219.   }
  220.   op = (union overhead *)sbrk(amt);
  221.   /* no more room! */
  222.   if ((int)op == -1)
  223.     return;
  224.   /*
  225.    * Add new memory allocated to that on
  226.    * free list for this hash bucket.
  227.    */
  228.   nextf[bucket] = op;
  229.   while (--nblks > 0) {
  230.     op->ov_next = (union overhead *)((char *)op + sz);
  231.     op = (union overhead *)((char *)op + sz);
  232.   }
  233.   op->ov_next = 0;
  234. }
  235.  
  236. void
  237. free(void *cp)
  238. {   
  239.   int size;
  240.   union overhead *op;
  241.  
  242.   if (cp == NULL)
  243.     return;
  244.   op = (union overhead *)((char *)cp - sizeof (union overhead));
  245. #ifdef DEBUG
  246.   ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */
  247. #else
  248.   if (op->ov_magic != MAGIC)
  249.     return;            /* sanity */
  250. #endif
  251. #ifdef RCHECK
  252.   ASSERT(op->ov_rmagic == RMAGIC);
  253.   ASSERT(*(unsigned short *)((char *)(op + 1) + op->ov_size) == RMAGIC);
  254. #endif
  255.   size = op->ov_index;
  256.   ASSERT(size < NBUCKETS);
  257.   op->ov_next = nextf[size];    /* also clobbers ov_magic */
  258.   nextf[size] = op;
  259. #ifdef MSTATS
  260.   nmalloc[size]--;
  261. #endif
  262. }
  263.  
  264. void *
  265. realloc(void *cp, size_t nbytes)
  266. {   
  267.   unsigned int onb;
  268.   int i;
  269.   union overhead *op;
  270.   char *res;
  271.   int was_alloced = 0;
  272.  
  273.   if (cp == NULL)
  274.     return (malloc(nbytes));
  275.   op = (union overhead *)((char *)cp - sizeof (union overhead));
  276.   if (op->ov_magic == MAGIC)
  277.   {
  278.     was_alloced++;
  279.     i = op->ov_index;
  280.   }
  281.   else
  282.   {
  283.     return 0;
  284.   }
  285.   onb = 1 << (i + 3);
  286.   if (onb < pagesz)
  287.     onb -= sizeof (*op) + RSLOP;
  288.   else
  289.     onb += pagesz - sizeof (*op) - RSLOP;
  290.   /* avoid the copy if same size block */
  291.   if (was_alloced) {
  292.     if (i) {
  293.       i = 1 << (i + 2);
  294.       if (i < pagesz)
  295.     i -= sizeof (*op) + RSLOP;
  296.       else
  297.     i += pagesz - sizeof (*op) - RSLOP;
  298.     }
  299.     if (nbytes <= onb && nbytes > i) {
  300. #ifdef RCHECK
  301.       op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
  302.       *(unsigned short *)((char *)(op + 1) + op->ov_size) = RMAGIC;
  303. #endif
  304.       return(cp);
  305.     }
  306.     else
  307.       free(cp);
  308.   }
  309.   if ((res = malloc(nbytes)) == NULL)
  310.     return (NULL);
  311.   if (cp != res)
  312.     memcpy(res, cp, (nbytes < onb) ? nbytes : onb);
  313.   return (res);
  314. }
  315.  
  316. #ifdef MSTATS
  317. /*
  318.  * mstats - print out statistics about malloc
  319.  * 
  320.  * Prints two lines of numbers, one showing the length of the free list
  321.  * for each size category, the second showing the number of mallocs -
  322.  * frees for each size category.
  323.  */
  324. _mstats(s)
  325.     char *s;
  326. {
  327.       int i, j;
  328.       union overhead *p;
  329.       int totfree = 0,
  330.       totused = 0;
  331.  
  332.       fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
  333.       for (i = 0; i < NBUCKETS; i++) {
  334.           for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
  335.               ;
  336.           fprintf(stderr, " %d", j);
  337.           totfree += j * (1 << (i + 3));
  338.       }
  339.       fprintf(stderr, "\nused:\t");
  340.       for (i = 0; i < NBUCKETS; i++) {
  341.           fprintf(stderr, " %d", nmalloc[i]);
  342.           totused += nmalloc[i] * (1 << (i + 3));
  343.       }
  344.       fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
  345.         totused, totfree);
  346. }
  347. #endif
  348.