home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / UNIX / Shells / zsh-3.0.5-MIHS / src / Src / mem.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-09-25  |  30.5 KB  |  1,183 lines

  1. /*
  2.  * $Id: mem.c,v 2.13 1996/10/15 20:16:35 hzoli Exp $
  3.  *
  4.  * mem.c - memory management
  5.  *
  6.  * This file is part of zsh, the Z shell.
  7.  *
  8.  * Copyright (c) 1992-1996 Paul Falstad
  9.  * All rights reserved.
  10.  *
  11.  * Permission is hereby granted, without written agreement and without
  12.  * license or royalty fees, to use, copy, modify, and distribute this
  13.  * software and to distribute modified versions of this software for any
  14.  * purpose, provided that the above copyright notice and the following
  15.  * two paragraphs appear in all copies of this software.
  16.  *
  17.  * In no event shall Paul Falstad or the Zsh Development Group be liable
  18.  * to any party for direct, indirect, special, incidental, or consequential
  19.  * damages arising out of the use of this software and its documentation,
  20.  * even if Paul Falstad and the Zsh Development Group have been advised of
  21.  * the possibility of such damage.
  22.  *
  23.  * Paul Falstad and the Zsh Development Group specifically disclaim any
  24.  * warranties, including, but not limited to, the implied warranties of
  25.  * merchantability and fitness for a particular purpose.  The software
  26.  * provided hereunder is on an "as is" basis, and Paul Falstad and the
  27.  * Zsh Development Group have no obligation to provide maintenance,
  28.  * support, updates, enhancements, or modifications.
  29.  *
  30.  */
  31.  
  32. #include "zsh.h"
  33.  
  34. void *(*alloc) _((size_t));
  35. void *(*ncalloc) _((size_t));
  36.  
  37. /*
  38.  
  39.     There are two ways to allocate memory in zsh.  The first way is
  40.     to call zalloc/zcalloc, which call malloc/calloc directly.  It
  41.     is legal to call realloc() or free() on memory allocated this way.
  42.     The second way is to call halloc/hcalloc, which allocates memory
  43.     from one of the memory pools on the heap stack.  Such memory pools 
  44.     will automatically created when the heap allocation routines are
  45.     called.  To be sure that they are freed at appropriate times
  46.     one should call pushheap() before one starts using heaps and
  47.     popheap() after that (when the memory allocated on the heaps since
  48.     the last pushheap() isn't needed anymore).
  49.     pushheap() saves the states of all currently allocated heaps and
  50.     popheap() resets them to the last state saved and destroys the
  51.     information about that state.  If you called pushheap() and
  52.     allocated some memory on the heaps and then come to a place where
  53.     you don't need the allocated memory anymore but you still want
  54.     to allocate memory on the heap, you should call freeheap().  This
  55.     works like popheap(), only that it doesn't free the information
  56.     about the heap states (i.e. the heaps are like after the call to
  57.     pushheap() and you have to call popheap some time later).
  58.  
  59.     Memory allocated in this way does not have to be freed explicitly;
  60.     it will all be freed when the pool is destroyed.  In fact,
  61.     attempting to free this memory may result in a core dump.
  62.     The pair of pointers ncalloc and alloc may point to either
  63.     zalloc & zcalloc or halloc & hcalloc; permalloc() sets them to the
  64.     former, and heapalloc() sets them to the latter. This can be useful.
  65.     For example, the dupstruct() routine duplicates a syntax tree,
  66.     allocating the new memory for the tree using alloc().  If you want
  67.     to duplicate a structure for a one-time use (i.e. to execute the list
  68.     in a for loop), call heapalloc(), then dupstruct().  If you want
  69.     to duplicate a structure in order to preserve it (i.e. a function
  70.     definition), call permalloc(), then dupstruct().
  71.  
  72.     If we use zsh's own allocator we use a simple trick to avoid that
  73.     the (*real*) heap fills up with empty zsh-heaps: we allocate a
  74.     large block of memory before allocating a heap pool, this memory
  75.     is freed again immediately after the pool is allocated. If there
  76.     are only small blocks on the free list this guarantees that the
  77.     memory for the pool is at the end of the memory which means that
  78.     we can give it back to the system when the pool is freed.
  79. */
  80.  
  81. #ifdef ZSH_MEM_WARNING
  82. # ifndef DEBUG
  83. #  define DEBUG 1
  84. # endif
  85. #endif
  86.  
  87. #if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG)
  88.  
  89. int h_m[1025], h_push, h_pop, h_free;
  90.  
  91. #endif
  92.  
  93. #define H_ISIZE  sizeof(long)
  94. #define HEAPSIZE (8192 - H_ISIZE)
  95. #define HEAP_ARENA_SIZE (HEAPSIZE - sizeof(struct heap))
  96. #define HEAPFREE (16384 - H_ISIZE)
  97.  
  98. /* set default allocation to heap stack */
  99.  
  100. /**/
  101. int
  102. global_heapalloc(void)
  103. {
  104.     int luh = useheap;
  105.  
  106.     alloc = hcalloc;
  107.     ncalloc = halloc;
  108.     useheap = 1;
  109.     return luh;
  110. }
  111.  
  112. /* set default allocation to malloc() */
  113.  
  114. /**/
  115. int
  116. global_permalloc(void)
  117. {
  118.     int luh = useheap;
  119.  
  120.     alloc = zcalloc;
  121.     ncalloc = zalloc;
  122.     useheap = 0;
  123.     return luh;
  124. }
  125.  
  126. /* heappush saves the current heap state using this structure */
  127.  
  128. struct heapstack {
  129.     struct heapstack *next;    /* next one in list for this heap */
  130.     size_t used;
  131. };
  132.  
  133. /* A zsh heap. */
  134.  
  135. struct heap {
  136.     struct heap *next;        /* next one                                  */
  137.     size_t used;        /* bytes used from the heap                  */
  138.     struct heapstack *sp;    /* used by pushheap() to save the value used */
  139. #define arena(X)    ((char *) (X) + sizeof(struct heap))
  140. };
  141.  
  142. /* list of zsh heap */
  143.  
  144. Heap heaps;
  145.  
  146. /* save states of zsh heaps */
  147.  
  148. /**/
  149. void
  150. pushheap(void)
  151. {
  152.     Heap h;
  153.     Heapstack hs;
  154.  
  155. #if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG)
  156.     h_push++;
  157. #endif
  158.  
  159.     for (h = heaps; h; h = h->next) {
  160.     hs = (Heapstack) zalloc(sizeof(*hs));
  161.     hs->next = h->sp;
  162.     h->sp = hs;
  163.     hs->used = h->used;
  164.     }
  165. }
  166.  
  167. /* reset heaps to previous state */
  168.  
  169. /**/
  170. void
  171. freeheap(void)
  172. {
  173.     Heap h;
  174.  
  175. #if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG)
  176.     h_free++;
  177. #endif
  178.     for (h = heaps; h; h = h->next) {
  179. #ifdef ZSH_MEM_DEBUG
  180.     if (h->sp)
  181.         memset(arena(h) + h->sp->used, 0xff, h->used - h->sp->used);
  182.     else
  183.         memset(arena(h), 0xff, h->used);
  184. #endif
  185.     h->used = h->sp ? h->sp->used : 0;
  186.     }
  187. }
  188.  
  189. /* reset heap to previous state and destroy state information */
  190.  
  191. /**/
  192. void
  193. popheap(void)
  194. {
  195.     Heap h, hn, hl = NULL;
  196.     Heapstack hs;
  197.  
  198. #if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG)
  199.     h_pop++;
  200. #endif
  201.  
  202.     for (h = heaps; h; h = hn) {
  203.     hn = h->next;
  204.     if ((hs = h->sp)) {
  205.         h->sp = hs->next;
  206. #ifdef ZSH_MEM_DEBUG
  207.         memset(arena(h) + hs->used, 0xff, h->used - hs->used);
  208. #endif
  209.         h->used = hs->used;
  210.         zfree(hs, sizeof(*hs));
  211.  
  212.         hl = h;
  213.     } else
  214.         zfree(h, HEAPSIZE);
  215.     }
  216.     if (hl)
  217.     hl->next = NULL;
  218.     else
  219.     heaps = NULL;
  220. }
  221.  
  222. /* allocate memory from the current memory pool */
  223.  
  224. /**/
  225. void *
  226. halloc(size_t size)
  227. {
  228.     Heap h;
  229.     size_t n;
  230.  
  231.     size = (size + H_ISIZE - 1) & ~(H_ISIZE - 1);
  232.  
  233. #if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG)
  234.     h_m[size < 1024 ? (size / H_ISIZE) : 1024]++;
  235. #endif
  236.  
  237.     /* find a heap with enough free space */
  238.  
  239.     for (h = heaps; h; h = h->next) {
  240.     if (HEAP_ARENA_SIZE >= (n = size + h->used)) {
  241.         h->used = n;
  242.         return arena(h) + n - size;
  243.     }
  244.     }
  245.  
  246.     {
  247.     Heap hp;
  248.         /* not found, allocate new heap */
  249. #ifdef ZSH_MEM
  250.     static int called = 0;
  251.     void *foo = called ? (void *)malloc(HEAPFREE) : NULL;
  252.             /* tricky, see above */
  253. #endif
  254.  
  255.     queue_signals();
  256.     n = HEAP_ARENA_SIZE > size ? HEAP_ARENA_SIZE : size;
  257.     for (hp = NULL, h = heaps; h; hp = h, h = h->next);
  258.  
  259.     h = (Heap) zalloc(n + sizeof(*h));
  260.  
  261. #ifdef ZSH_MEM
  262.     if (called)
  263.         zfree(foo, HEAPFREE);
  264.     called = 1;
  265. #endif
  266.  
  267.     h->used = size;
  268.     h->next = NULL;
  269.     h->sp = NULL;
  270.  
  271.     if (hp)
  272.         hp->next = h;
  273.     else
  274.         heaps = h;
  275.  
  276.     unqueue_signals();
  277.     return arena(h);
  278.     }
  279. }
  280.  
  281. /* allocate memory from the current memory pool and clear it */
  282.  
  283. /**/
  284. void *
  285. hcalloc(size_t size)
  286. {
  287.     void *ptr;
  288.  
  289.     ptr = halloc(size);
  290.     memset(ptr, 0, size);
  291.     return ptr;
  292. }
  293.  
  294. /**/
  295. void *
  296. hrealloc(char *p, int old, int new)
  297. {
  298.     char *ptr;
  299.  
  300.     ptr = (char *)halloc(new);
  301.     memcpy(ptr, p, old);
  302.     return (void *) ptr;
  303. }
  304.  
  305. /* allocate permanent memory */
  306.  
  307. /**/
  308. void *
  309. zalloc(size_t size)
  310. {
  311.     void *ptr;
  312.  
  313.     if (!size)
  314.     size = 1;
  315.     if (!(ptr = (void *) malloc(size))) {
  316.     zerr("fatal error: out of memory", NULL, 0);
  317.     exit(1);
  318.     }
  319.  
  320.     return ptr;
  321. }
  322.  
  323. /**/
  324. void *
  325. zcalloc(size_t size)
  326. {
  327.     void *ptr;
  328.  
  329.     if (!size)
  330.     size = 1;
  331.     if (!(ptr = (void *) malloc(size))) {
  332.     zerr("fatal error: out of memory", NULL, 0);
  333.     exit(1);
  334.     }
  335.     memset(ptr, 0, size);
  336.  
  337.     return ptr;
  338. }
  339.  
  340. /* This front-end to realloc is used to make sure we have a realloc *
  341.  * that conforms to POSIX realloc.  Older realloc's can fail if     *
  342.  * passed a NULL pointer, but POSIX realloc should handle this.  A  *
  343.  * better solution would be for configure to check if realloc is    *
  344.  * POSIX compliant, but I'm not sure how to do that.                */
  345.  
  346. /**/
  347. void *
  348. zrealloc(void *ptr, size_t size)
  349. {
  350.     if (ptr) {
  351.     if (size) {
  352.         /* Do normal realloc */
  353.         if (!(ptr = (void *) realloc(ptr, size))) {
  354.         zerr("fatal error: out of memory", NULL, 0);
  355.         exit(1);
  356.         }
  357.         return ptr;
  358.     }
  359.     else
  360.         /* If ptr is not NULL, but size is zero, *
  361.          * then object pointed to is freed.      */
  362.         free(ptr);
  363.     } else {
  364.     /* If ptr is NULL, then behave like malloc */
  365.     return malloc(size);
  366.     }
  367.  
  368.     return NULL;
  369. }
  370.  
  371. /**/
  372. char *
  373. dupstring(const char *s)
  374. {
  375.     char *t;
  376.  
  377.     if (!s)
  378.     return NULL;
  379.     t = (char *)ncalloc(strlen((char *)s) + 1);
  380.     strcpy(t, s);
  381.     return t;
  382. }
  383.  
  384. /**/
  385. char *
  386. ztrdup(const char *s)
  387. {
  388.     char *t;
  389.  
  390.     if (!s)
  391.     return NULL;
  392.     t = (char *)zalloc(strlen((char *)s) + 1);
  393.     strcpy(t, s);
  394.     return t;
  395. }
  396.  
  397. #ifdef ZSH_MEM
  398.  
  399. /*
  400.    Below is a simple segment oriented memory allocator for systems on
  401.    which it is better than the system's one. Memory is given in blocks
  402.    aligned to an integer multiple of sizeof(long) (4 bytes on most machines,
  403.    but 8 bytes on e.g. a dec alpha). Each block is preceded by a header
  404.    which contains the length of the data part (in bytes). In allocated
  405.    blocks only this field of the structure m_hdr is senseful. In free
  406.    blocks the second field (next) is a pointer to the next free segment
  407.    on the free list.
  408.  
  409.    On top of this simple allocator there is a second allocator for small
  410.    chunks of data. It should be both faster and less space-consuming than
  411.    using the normal segment mechanism for such blocks.
  412.    For the first M_NSMALL-1 possible sizes memory is allocated in arrays
  413.    that can hold M_SNUM blocks. Each array is stored in one segment of the
  414.    main allocator. In these segments the third field of the header structure
  415.    (free) contains a pointer to the first free block in the array. The
  416.    last field (used) gives the number of already used blocks in the array.
  417.  
  418.    If the macro name ZSH_MEM_DEBUG is defined, some information about the memory
  419.    usage is stored. This information can than be viewed by calling the
  420.    builtin `mem' (which is only available if ZSH_MEM_DEBUG is set).
  421.  
  422.    If ZSH_MEM_WARNING is defined, error messages are printed in case of errors.
  423.  
  424.    If ZSH_SECURE_FREE is defined, free() checks if the given address is really
  425.    one that was returned by malloc(), it ignores it if it wasn't (printing
  426.    an error message if ZSH_MEM_WARNING is also defined).
  427. */
  428. #if !defined(__hpux) && !defined(DGUX) && !defined(__osf__)
  429. # if defined(_BSD)
  430. #  ifndef HAVE_BRK_PROTO
  431.    extern int brk _((caddr_t));
  432. #  endif
  433. #  ifndef HAVE_SBRK_PROTO
  434.    extern caddr_t sbrk _((int));
  435. #  endif
  436. # else
  437. #  ifndef HAVE_BRK_PROTO
  438.    extern int brk _((void *));
  439. #  endif
  440. #  ifndef HAVE_SBRK_PROTO
  441.    extern void *sbrk _((int));
  442. #  endif
  443. # endif
  444. #endif
  445.  
  446. #if defined(_BSD) && !defined(STDC_HEADERS)
  447. # define FREE_RET_T   int
  448. # define FREE_ARG_T   char *
  449. # define FREE_DO_RET
  450. # define MALLOC_RET_T char *
  451. # define MALLOC_ARG_T size_t
  452. #else
  453. # define FREE_RET_T   void
  454. # define FREE_ARG_T   void *
  455. # define MALLOC_RET_T void *
  456. # define MALLOC_ARG_T size_t
  457. #endif
  458.  
  459. /* structure for building free list in blocks holding small blocks */
  460.  
  461. struct m_shdr {
  462.     struct m_shdr *next;    /* next one on free list */
  463. };
  464.  
  465. struct m_hdr {
  466.     long len;            /* length of memory block */
  467.     struct m_hdr *next;        /* if free: next on free list
  468.                    if block of small blocks: next one with
  469.                                  small blocks of same size*/
  470.     struct m_shdr *free;    /* if block of small blocks: free list */
  471.     long used;            /* if block of small blocks: number of used
  472.                                                      blocks */
  473. };
  474.  
  475.  
  476. /* alignment for memory blocks */
  477.  
  478. #define M_ALIGN (sizeof(long))
  479.  
  480. /* length of memory header, length of first field of memory header and
  481.    minimal size of a block left free (if we allocate memory and take a
  482.    block from the free list that is larger than needed, it must have at
  483.    least M_MIN extra bytes to be splitted; if it has, the rest is put on
  484.    the free list) */
  485.  
  486. #define M_HSIZE (sizeof(struct m_hdr))
  487. #define M_ISIZE (sizeof(long))
  488. #define M_MIN   (2 * M_ISIZE)
  489.  
  490. /* a pointer to the last free block, a pointer to the free list (the blocks
  491.    on this list are kept in order - lowest address first) */
  492.  
  493. struct m_hdr *m_lfree, *m_free;
  494.  
  495. /* system's pagesize */
  496.  
  497. long m_pgsz = 0;
  498.  
  499. /* the highest and the lowest valid memory addresses, kept for fast validity
  500.    checks in free() and to find out if and when we can give memory back to
  501.    the system */
  502.  
  503. char *m_high, *m_low;
  504.  
  505. /* Management of blocks for small blocks:
  506.    Such blocks are kept in lists (one list for each of the sizes that are
  507.    allocated in such blocks).  The lists are stored in the m_small array.
  508.    M_SIDX() calculates the index into this array for a given size.  M_SNUM
  509.    is the size (in small blocks) of such blocks.  M_SLEN() calculates the
  510.    size of the small blocks held in a memory block, given a pointer to the
  511.    header of it.  M_SBLEN() gives the size of a memory block that can hold
  512.    an array of small blocks, given the size of these small blocks.  M_BSLEN()
  513.    caculates the size of the small blocks held in a memory block, given the
  514.    length of that block (including the header of the memory block.  M_NSMALL
  515.    is the number of possible block sizes that small blocks should be used
  516.    for. */
  517.  
  518.  
  519. #define M_SIDX(S)  ((S) / M_ISIZE)
  520. #define M_SNUM     50
  521. #define M_SLEN(M)  ((M)->len / M_SNUM)
  522. #define M_SBLEN(S) ((S) * M_SNUM + sizeof(struct m_shdr *) +  \
  523.             sizeof(long) + sizeof(struct m_hdr *))
  524. #define M_BSLEN(S) (((S) - sizeof(struct m_shdr *) -  \
  525.              sizeof(long) - sizeof(struct m_hdr *)) / M_SNUM)
  526. #define M_NSMALL 8
  527.  
  528. struct m_hdr *m_small[M_NSMALL];
  529.  
  530. #ifdef ZSH_MEM_DEBUG
  531.  
  532. int m_s = 0, m_b = 0;
  533. int m_m[1025], m_f[1025];
  534.  
  535. struct m_hdr *m_l;
  536.  
  537. #endif /* ZSH_MEM_DEBUG */
  538.  
  539. MALLOC_RET_T
  540. malloc(MALLOC_ARG_T size)
  541. {
  542.     struct m_hdr *m, *mp, *mt;
  543.     long n, s, os = 0;
  544.     struct heap *h, *hp, *hf = NULL, *hfp = NULL;
  545.  
  546.     /* some systems want malloc to return the highest valid address plus one
  547.        if it is called with an argument of zero */
  548.  
  549.     if (!size)
  550.     return (MALLOC_RET_T) m_high;
  551.  
  552.     queue_signals();  /* just queue signals rather than handling them */
  553.  
  554.     /* first call, get page size */
  555.  
  556.     if (!m_pgsz) {
  557.  
  558. #ifdef _SC_PAGESIZE
  559.     m_pgsz = sysconf(_SC_PAGESIZE);     /* SVR4 */
  560. #else
  561. # ifdef _SC_PAGE_SIZE
  562.     m_pgsz = sysconf(_SC_PAGE_SIZE);    /* HPUX */
  563. # else
  564.     m_pgsz = getpagesize();
  565. # endif
  566. #endif
  567.  
  568.     m_free = m_lfree = NULL;
  569.     }
  570.     size = (size + M_ALIGN - 1) & ~(M_ALIGN - 1);
  571.  
  572.     /* Do we need a small block? */
  573.  
  574.     if ((s = M_SIDX(size)) && s < M_NSMALL) {
  575.     /* yep, find a memory block with free small blocks of the
  576.        appropriate size (if we find it in this list, this means that
  577.        it has room for at least one more small block) */
  578.     for (mp = NULL, m = m_small[s]; m && !m->free; mp = m, m = m->next);
  579.  
  580.     if (m) {
  581.         /* we found one */
  582.         struct m_shdr *sh = m->free;
  583.  
  584.         m->free = sh->next;
  585.         m->used++;
  586.  
  587.         /* if all small blocks in this block are allocated, the block is 
  588.            put at the end of the list blocks wth small blocks of this
  589.            size (i.e., we try to keep blocks with free blocks at the
  590.            beginning of the list, to make the search faster */
  591.  
  592.         if (m->used == M_SNUM && m->next) {
  593.         for (mt = m; mt->next; mt = mt->next);
  594.  
  595.         mt->next = m;
  596.         if (mp)
  597.             mp->next = m->next;
  598.         else
  599.             m_small[s] = m->next;
  600.         m->next = NULL;
  601.         }
  602. #ifdef ZSH_MEM_DEBUG
  603.         m_m[size / M_ISIZE]++;
  604. #endif
  605.  
  606.         unqueue_signals();
  607.         return (MALLOC_RET_T) sh;
  608.     }
  609.     /* we still want a small block but there were no block with a free
  610.        small block of the requested size; so we use the real allocation
  611.        routine to allocate a block for small blocks of this size */
  612.     os = size;
  613.     size = M_SBLEN(size);
  614.     } else
  615.     s = 0;
  616.  
  617. /* search the free list for an block of at least the requested size */
  618.     for (mp = NULL, m = m_free; m && m->len < size; mp = m, m = m->next);
  619.  
  620.  /* if there is an empty zsh heap at a lower address we steal it and take
  621.     the memory from it, putting the rest on the free list (remember
  622.     that the blocks on the free list are ordered) */
  623.  
  624.     for (hp = NULL, h = heaps; h; hp = h, h = h->next)
  625.     if (!h->used &&
  626.         (!hf || h < hf) &&
  627.         (!m || ((char *)m) > ((char *)h)))
  628.         hf = h, hfp = hp;
  629.  
  630.     if (hf) {
  631.     /* we found such a heap */
  632.     Heapstack hso, hsn;
  633.  
  634.     /* delete structures on the list holding the heap states */
  635.     for (hso = hf->sp; hso; hso = hsn) {
  636.         hsn = hso->next;
  637.         zfree(hso, sizeof(*hso));
  638.     }
  639.     /* take it from the list of heaps */
  640.     if (hfp)
  641.         hfp->next = hf->next;
  642.     else
  643.         heaps = hf->next;
  644.     /* now we simply free it and than search the free list again */
  645.     zfree(hf, HEAPSIZE);
  646.  
  647.     for (mp = NULL, m = m_free; m && m->len < size; mp = m, m = m->next);
  648.     }
  649.     if (!m) {
  650.     /* no matching free block was found, we have to request new
  651.        memory from the system */
  652.     n = (size + M_HSIZE + m_pgsz - 1) & ~(m_pgsz - 1);
  653.  
  654.     if (((char *)(m = (struct m_hdr *)sbrk(n))) == ((char *)-1)) {
  655.         DPUTS(1, "allocation error at sbrk.");
  656.         unqueue_signals();
  657.         return NULL;
  658.     }
  659.     /* set m_low, for the check in free() */
  660.     if (!m_low)
  661.         m_low = (char *)m;
  662.  
  663. #ifdef ZSH_MEM_DEBUG
  664.     m_s += n;
  665.  
  666.     if (!m_l)
  667.         m_l = m;
  668. #endif
  669.  
  670.     /* save new highest address */
  671.     m_high = ((char *)m) + n;
  672.  
  673.     /* initialize header */
  674.     m->len = n - M_ISIZE;
  675.     m->next = NULL;
  676.  
  677.     /* put it on the free list and set m_lfree pointing to it */
  678.     if ((mp = m_lfree))
  679.         m_lfree->next = m;
  680.     m_lfree = m;
  681.     }
  682.     if ((n = m->len - size) > M_MIN) {
  683.     /* the block we want to use has more than M_MIN bytes plus the
  684.        number of bytes that were requested; we split it in two and
  685.        leave the rest on the free list */
  686.     struct m_hdr *mtt = (struct m_hdr *)(((char *)m) + M_ISIZE + size);
  687.  
  688.     mtt->len = n - M_ISIZE;
  689.     mtt->next = m->next;
  690.  
  691.     m->len = size;
  692.  
  693.     /* put the rest on the list */
  694.     if (m_lfree == m)
  695.         m_lfree = mtt;
  696.  
  697.     if (mp)
  698.         mp->next = mtt;
  699.     else
  700.         m_free = mtt;
  701.     } else if (mp) {
  702.     /* the block we found wasn't the first one on the free list */
  703.     if (m == m_lfree)
  704.         m_lfree = mp;
  705.     mp->next = m->next;
  706.     } else {
  707.     /* it was the first one */
  708.     m_free = m->next;
  709.     if (m == m_lfree)
  710.         m_lfree = m_free;
  711.     }
  712.  
  713.     if (s) {
  714.     /* we are allocating a block that should hold small blocks */
  715.     struct m_shdr *sh, *shn;
  716.  
  717.     /* build the free list in this block and set `used' filed */
  718.     m->free = sh = (struct m_shdr *)(((char *)m) +
  719.                      sizeof(struct m_hdr) + os);
  720.  
  721.     for (n = M_SNUM - 2; n--; sh = shn)
  722.         shn = sh->next = sh + s;
  723.     sh->next = NULL;
  724.  
  725.     m->used = 1;
  726.  
  727.     /* put the block on the list of blocks holding small blocks if
  728.        this size */
  729.     m->next = m_small[s];
  730.     m_small[s] = m;
  731.  
  732. #ifdef ZSH_MEM_DEBUG
  733.     m_m[os / M_ISIZE]++;
  734. #endif
  735.  
  736.     unqueue_signals();
  737.     return (MALLOC_RET_T) (((char *)m) + sizeof(struct m_hdr));
  738.     }
  739. #ifdef ZSH_MEM_DEBUG
  740.     m_m[m->len < (1024 * M_ISIZE) ? (m->len / M_ISIZE) : 1024]++;
  741. #endif
  742.  
  743.     unqueue_signals();
  744.     return (MALLOC_RET_T) & m->next;
  745. }
  746.  
  747. /* this is an internal free(); the second argument may, but need not hold
  748.    the size of the block the first argument is pointing to; if it is the
  749.    right size of this block, freeing it will be faster, though; the value
  750.    0 for this parameter means: `don't know' */
  751.  
  752. /**/
  753. void
  754. zfree(void *p, int sz)
  755. {
  756.     struct m_hdr *m = (struct m_hdr *)(((char *)p) - M_ISIZE), *mp, *mt = NULL;
  757.     int i;
  758. # ifdef DEBUG
  759.     int osz = sz;
  760. # endif
  761.  
  762. #ifdef ZSH_SECURE_FREE
  763.     sz = 0;
  764. #else
  765.     sz = (sz + M_ALIGN - 1) & ~(M_ALIGN - 1);
  766. #endif
  767.  
  768.     if (!p)
  769.     return;
  770.  
  771.     /* first a simple check if the given address is valid */
  772.     if (((char *)p) < m_low || ((char *)p) > m_high ||
  773.     ((long)p) & (M_ALIGN - 1)) {
  774.     DPUTS(1, "attempt to free storage at invalid address");
  775.     return;
  776.     }
  777.  
  778.     queue_signals();
  779.  
  780.   fr_rec:
  781.  
  782.     if ((i = sz / M_ISIZE) < M_NSMALL || !sz)
  783.     /* if the given sizes says that it is a small block, find the
  784.        memory block holding it; we search all blocks with blocks
  785.        of at least the given size; if the size parameter is zero,
  786.        this means, that all blocks are searched */
  787.     for (; i < M_NSMALL; i++) {
  788.         for (mp = NULL, mt = m_small[i];
  789.          mt && (((char *)mt) > ((char *)p) ||
  790.             (((char *)mt) + mt->len) < ((char *)p));
  791.          mp = mt, mt = mt->next);
  792.  
  793.         if (mt) {
  794.         /* we found the block holding the small block */
  795.         struct m_shdr *sh = (struct m_shdr *)p;
  796.  
  797. #ifdef ZSH_SECURE_FREE
  798.         struct m_shdr *sh2;
  799.  
  800.         /* check if the given address is equal to the address of
  801.            the first small block plus an integer multiple of the
  802.            block size */
  803.         if ((((char *)p) - (((char *)mt) + sizeof(struct m_hdr))) %
  804.             M_BSLEN(mt->len)) {
  805.  
  806.             DPUTS(1, "attempt to free storage at invalid address");
  807.             unqueue_signals();
  808.             return;
  809.         }
  810.         /* check, if the address is on the (block-intern) free list */
  811.         for (sh2 = mt->free; sh2; sh2 = sh2->next)
  812.             if (((char *)p) == ((char *)sh2)) {
  813.  
  814.             DPUTS(1, "attempt to free already free storage");
  815.             unqueue_signals();
  816.             return;
  817.             }
  818. #endif
  819.         DPUTS(M_BSLEN(mt->len) < osz,
  820.               "attempt to free more than allocated.");
  821.  
  822. #ifdef ZSH_MEM_DEBUG
  823.         m_f[M_BSLEN(mt->len) / M_ISIZE]++;
  824.         memset(sh, 0xff, M_BSLEN(mt->len));
  825. #endif
  826.  
  827.         /* put the block onto the free list */
  828.         sh->next = mt->free;
  829.         mt->free = sh;
  830.  
  831.         if (--mt->used) {
  832.             /* if there are still used blocks in this block, we
  833.                put it at the beginning of the list with blocks
  834.                holding small blocks of the same size (since we
  835.                know that there is at least one free block in it,
  836.                this will make allocation of small blocks faster;
  837.                it also guarantees that long living memory blocks
  838.                are preferred over younger ones */
  839.             if (mp) {
  840.             mp->next = mt->next;
  841.             mt->next = m_small[i];
  842.             m_small[i] = mt;
  843.             }
  844.             unqueue_signals();
  845.             return;
  846.         }
  847.         /* if there are no more used small blocks in this
  848.            block, we free the whole block */
  849.         if (mp)
  850.             mp->next = mt->next;
  851.         else
  852.             m_small[i] = mt->next;
  853.  
  854.         m = mt;
  855.         p = (void *) & m->next;
  856.  
  857.         break;
  858.         } else if (sz) {
  859.         /* if we didn't find a block and a size was given, try it
  860.            again as if no size were given */
  861.         sz = 0;
  862.         goto fr_rec;
  863.         }
  864.     }
  865. #ifdef ZSH_MEM_DEBUG
  866.     if (!mt)
  867.     m_f[m->len < (1024 * M_ISIZE) ? (m->len / M_ISIZE) : 1024]++;
  868. #endif
  869.  
  870. #ifdef ZSH_SECURE_FREE
  871.     /* search all memory blocks, if one of them is at the given address */
  872.     for (mt = (struct m_hdr *)m_low;
  873.      ((char *)mt) < m_high;
  874.      mt = (struct m_hdr *)(((char *)mt) + M_ISIZE + mt->len))
  875.     if (((char *)p) == ((char *)&mt->next))
  876.         break;
  877.  
  878.     /* no block was found at the given address */
  879.     if (((char *)mt) >= m_high) {
  880.     DPUTS(1, "attempt to free storage at invalid address");
  881.     unqueue_signals();
  882.     return;
  883.     }
  884. #endif
  885.  
  886.     /* see if the block is on the free list */
  887.     for (mp = NULL, mt = m_free; mt && mt < m; mp = mt, mt = mt->next);
  888.  
  889.     if (m == mt) {
  890.     /* it is, ouch! */
  891.     DPUTS(1, "attempt to free already free storage");
  892.     unqueue_signals();
  893.     return;
  894.     }
  895.     DPUTS(m->len < osz, "attempt to free more than allocated.");
  896. #ifdef ZSH_MEM_DEBUG
  897.     memset(p, 0xff, m->len);
  898. #endif
  899.     if (mt && ((char *)mt) == (((char *)m) + M_ISIZE + m->len)) {
  900.     /* the block after the one we are freeing is free, we put them
  901.        together */
  902.     m->len += mt->len + M_ISIZE;
  903.     m->next = mt->next;
  904.  
  905.     if (mt == m_lfree)
  906.         m_lfree = m;
  907.     } else
  908.     m->next = mt;
  909.  
  910.     if (mp && ((char *)m) == (((char *)mp) + M_ISIZE + mp->len)) {
  911.     /* the block before the one we are freeing is free, we put them
  912.        together */
  913.     mp->len += m->len + M_ISIZE;
  914.     mp->next = m->next;
  915.  
  916.     if (m == m_lfree)
  917.         m_lfree = mp;
  918.     } else if (mp)
  919.     /* otherwise, we just put it on the free list */
  920.     mp->next = m;
  921.     else {
  922.     m_free = m;
  923.     if (!m_lfree)
  924.         m_lfree = m_free;
  925.     }
  926.  
  927.     /* if the block we have just freed was at the end of the process heap
  928.        and now there is more than one page size of memory, we can give
  929.        it back to the system (and we do it ;-) */
  930.     if ((((char *)m_lfree) + M_ISIZE + m_lfree->len) == m_high &&
  931.     m_lfree->len >= m_pgsz + M_MIN) {
  932.     long n = (m_lfree->len - M_MIN) & ~(m_pgsz - 1);
  933.  
  934.     m_lfree->len -= n;
  935.     if (brk(m_high -= n) == -1)
  936.         DPUTS(1, "allocation error at brk.");
  937.  
  938. #ifdef ZSH_MEM_DEBUG
  939.     m_b += n;
  940. #endif
  941.     }
  942.     unqueue_signals();
  943. }
  944.  
  945. FREE_RET_T
  946. free(FREE_ARG_T p)
  947. {
  948.     zfree(p, 0);        /* 0 means: size is unknown */
  949.  
  950. #ifdef FREE_DO_RET
  951.     return 0;
  952. #endif
  953. }
  954.  
  955. /* this one is for strings (and only strings, real strings, real C strings,
  956.    those that have a zero byte at the end) */
  957.  
  958. /**/
  959. void
  960. zsfree(char *p)
  961. {
  962.     if (p)
  963.     zfree(p, strlen(p) + 1);
  964. }
  965.  
  966. MALLOC_RET_T
  967. realloc(MALLOC_RET_T p, MALLOC_ARG_T size)
  968. {
  969.     struct m_hdr *m = (struct m_hdr *)(((char *)p) - M_ISIZE), *mp, *mt;
  970.     char *r;
  971.     int i, l = 0;
  972.  
  973.     /* some system..., see above */
  974.     if (!p && size)
  975.     return (MALLOC_RET_T) malloc(size);
  976.     /* and some systems even do this... */
  977.     if (!p || !size)
  978.     return (MALLOC_RET_T) p;
  979.  
  980.     queue_signals();  /* just queue signals caught rather than handling them */
  981.  
  982.     /* check if we are reallocating a small block, if we do, we have
  983.        to compute the size of the block from the sort of block it is in */
  984.     for (i = 0; i < M_NSMALL; i++) {
  985.     for (mp = NULL, mt = m_small[i];
  986.          mt && (((char *)mt) > ((char *)p) ||
  987.             (((char *)mt) + mt->len) < ((char *)p));
  988.          mp = mt, mt = mt->next);
  989.  
  990.     if (mt) {
  991.         l = M_BSLEN(mt->len);
  992.         break;
  993.     }
  994.     }
  995.     if (!l)
  996.     /* otherwise the size of the block is in the memory just before
  997.        the given address */
  998.     l = m->len;
  999.  
  1000.     /* now allocate the new block, copy the old contents, and free the
  1001.        old block */
  1002.     r = malloc(size);
  1003.     memcpy(r, (char *)p, (size > l) ? l : size);
  1004.     free(p);
  1005.  
  1006.     unqueue_signals();
  1007.     return (MALLOC_RET_T) r;
  1008. }
  1009.  
  1010. MALLOC_RET_T
  1011. calloc(MALLOC_ARG_T n, MALLOC_ARG_T size)
  1012. {
  1013.     long l;
  1014.     char *r;
  1015.  
  1016.     if (!(l = n * size))
  1017.     return (MALLOC_RET_T) m_high;
  1018.  
  1019.     r = malloc(l);
  1020.  
  1021.     memset(r, 0, l);
  1022.  
  1023.     return (MALLOC_RET_T) r;
  1024. }
  1025.  
  1026. #ifdef ZSH_MEM_DEBUG
  1027.  
  1028. /**/
  1029. int
  1030. bin_mem(char *name, char **argv, char *ops, int func)
  1031. {
  1032.     int i, ii, fi, ui, j;
  1033.     struct m_hdr *m, *mf, *ms;
  1034.     char *b, *c, buf[40];
  1035.     long u = 0, f = 0;
  1036.  
  1037.     if (ops['v']) {
  1038.     printf("The lower and the upper addresses of the heap. Diff gives\n");
  1039.     printf("the difference between them, i.e. the size of the heap.\n\n");
  1040.     }
  1041.     printf("low mem %ld\t high mem %ld\t diff %ld\n",
  1042.        (long)m_l, (long)m_high, (long)(m_high - ((char *)m_l)));
  1043.  
  1044.     if (ops['v']) {
  1045.     printf("\nThe number of bytes that were allocated using sbrk() and\n");
  1046.     printf("the number of bytes that were given back to the system\n");
  1047.     printf("via brk().\n");
  1048.     }
  1049.     printf("\nsbrk %d\tbrk %d\n", m_s, m_b);
  1050.  
  1051.     if (ops['v']) {
  1052.     printf("\nInformation about the sizes that were allocated or freed.\n");
  1053.     printf("For each size that were used the number of mallocs and\n");
  1054.     printf("frees is shown. Diff gives the difference between these\n");
  1055.     printf("values, i.e. the number of blocks of that size that is\n");
  1056.     printf("currently allocated. Total is the product of size and diff,\n");
  1057.     printf("i.e. the number of bytes that are allocated for blocks of\n");
  1058.     printf("this size.\n");
  1059.     }
  1060.     printf("\nsize\tmalloc\tfree\tdiff\ttotal\n");
  1061.     for (i = 0; i < 1024; i++)
  1062.     if (m_m[i] || m_f[i])
  1063.         printf("%ld\t%d\t%d\t%d\t%ld\n", (long)i * M_ISIZE, m_m[i], m_f[i],
  1064.            m_m[i] - m_f[i], (long)i * M_ISIZE * (m_m[i] - m_f[i]));
  1065.  
  1066.     if (m_m[i] || m_f[i])
  1067.     printf("big\t%d\t%d\t%d\n", m_m[i], m_f[i], m_m[i] - m_f[i]);
  1068.  
  1069.     if (ops['v']) {
  1070.     printf("\nThe list of memory blocks. For each block the following\n");
  1071.     printf("information is shown:\n\n");
  1072.     printf("num\tthe number of this block\n");
  1073.     printf("tnum\tlike num but counted separatedly for used and free\n");
  1074.     printf("\tblocks\n");
  1075.     printf("addr\tthe address of this block\n");
  1076.     printf("len\tthe length of the block\n");
  1077.     printf("state\tthe state of this block, this can be:\n");
  1078.     printf("\t  used\tthis block is used for one big block\n");
  1079.     printf("\t  free\tthis block is free\n");
  1080.     printf("\t  small\tthis block is used for an array of small blocks\n");
  1081.     printf("cum\tthe accumulated sizes of the blocks, counted\n");
  1082.     printf("\tseparatedly for used and free blocks\n");
  1083.     printf("\nFor blocks holding small blocks the number of free\n");
  1084.     printf("blocks, the number of used blocks and the size of the\n");
  1085.     printf("blocks is shown. For otherwise used blocks the first few\n");
  1086.     printf("bytes are shown as an ASCII dump.\n");
  1087.     }
  1088.     printf("\nblock list:\nnum\ttnum\taddr\tlen\tstate\tcum\n");
  1089.     for (m = m_l, mf = m_free, ii = fi = ui = 1; ((char *)m) < m_high;
  1090.      m = (struct m_hdr *)(((char *)m) + M_ISIZE + m->len), ii++) {
  1091.     for (j = 0, ms = NULL; j < M_NSMALL && !ms; j++)
  1092.         for (ms = m_small[j]; ms; ms = ms->next)
  1093.         if (ms == m)
  1094.             break;
  1095.  
  1096.     if (m == mf)
  1097.         buf[0] = '\0';
  1098.     else if (m == ms)
  1099.         sprintf(buf, "%ld %ld %ld", M_SNUM - ms->used, ms->used,
  1100.             (m->len - sizeof(struct m_hdr)) / M_SNUM + 1);
  1101.  
  1102.     else {
  1103.         for (i = 0, b = buf, c = (char *)&m->next; i < 20 && i < m->len;
  1104.          i++, c++)
  1105.         *b++ = (*c >= ' ' && *c < 127) ? *c : '.';
  1106.         *b = '\0';
  1107.     }
  1108.  
  1109.     printf("%d\t%d\t%ld\t%ld\t%s\t%ld\t%s\n", ii,
  1110.            (m == mf) ? fi++ : ui++,
  1111.            (long)m, m->len,
  1112.            (m == mf) ? "free" : ((m == ms) ? "small" : "used"),
  1113.            (m == mf) ? (f += m->len) : (u += m->len),
  1114.            buf);
  1115.  
  1116.     if (m == mf)
  1117.         mf = mf->next;
  1118.     }
  1119.  
  1120.     if (ops['v']) {
  1121.     printf("\nHere is some information about the small blocks used.\n");
  1122.     printf("For each size the arrays with the number of free and the\n");
  1123.     printf("number of used blocks are shown.\n");
  1124.     }
  1125.     printf("\nsmall blocks:\nsize\tblocks (free/used)\n");
  1126.  
  1127.     for (i = 0; i < M_NSMALL; i++)
  1128.     if (m_small[i]) {
  1129.         printf("%ld\t", (long)i * M_ISIZE);
  1130.  
  1131.         for (ii = 0, m = m_small[i]; m; m = m->next) {
  1132.         printf("(%ld/%ld) ", M_SNUM - m->used, m->used);
  1133.         if (!((++ii) & 7))
  1134.             printf("\n\t");
  1135.         }
  1136.         putchar('\n');
  1137.     }
  1138.     if (ops['v']) {
  1139.     printf("\n\nBelow is some information about the allocation\n");
  1140.     printf("behaviour of the zsh heaps. First the number of times\n");
  1141.     printf("pushheap(), popheap(), and freeheap() were called.\n");
  1142.     }
  1143.     printf("\nzsh heaps:\n\n");
  1144.  
  1145.     printf("push %d\tpop %d\tfree %d\n\n", h_push, h_pop, h_free);
  1146.  
  1147.     if (ops['v']) {
  1148.     printf("\nThe next list shows for several sizes the number of times\n");
  1149.     printf("memory of this size were taken from heaps.\n\n");
  1150.     }
  1151.     printf("size\tmalloc\ttotal\n");
  1152.     for (i = 0; i < 1024; i++)
  1153.     if (h_m[i])
  1154.         printf("%ld\t%d\t%ld\n", (long)i * H_ISIZE, h_m[i],
  1155.            (long)i * H_ISIZE * h_m[i]);
  1156.     if (h_m[1024])
  1157.     printf("big\t%d\n", h_m[1024]);
  1158.  
  1159.     return 0;
  1160. }
  1161.  
  1162. #endif
  1163.  
  1164. #else                /* not ZSH_MEM */
  1165.  
  1166. /**/
  1167. void
  1168. zfree(void *p, int sz)
  1169. {
  1170.     if (p)
  1171.     free(p);
  1172. }
  1173.  
  1174. /**/
  1175. void
  1176. zsfree(char *p)
  1177. {
  1178.     if (p)
  1179.     free(p);
  1180. }
  1181.  
  1182. #endif
  1183.