home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / gnu / djgppzip / pubquick.c < prev    next >
C/C++ Source or Header  |  1994-03-01  |  42KB  |  1,599 lines

  1. #define _INTERNAL_MALLOC_
  2. #define _IN_OUTPUT_
  3. /* -*-c-*- */
  4. #ifndef _UserMalloc_pre_h_
  5. #define _UserMalloc_pre_h_
  6.  
  7. /*****************************************************************************/
  8. /**  Using Gnu G++ Malloc                                                    */
  9. /*****************************************************************************/
  10.  
  11. #ifndef MallocArgType
  12. #  ifdef __cplusplus
  13. #     define MallocArgType int
  14. #     define MallocPtrType void *
  15. #     define FreePtrType void *
  16. #     define FreeRetType void
  17. #  else
  18. #    ifdef sun
  19. #     ifdef __malloc_h_
  20. #       define MallocArgType int
  21. #       define MallocPtrType malloc_t
  22. #       define FreePtrType malloc_t
  23. #       define FreeRetType int
  24. #     else
  25. #       define MallocArgType int
  26. #       define MallocPtrType char *
  27. #       define FreePtrType void *
  28. #       define FreeRetType int
  29. #     endif
  30. #    else
  31. #     define MallocArgType unsigned int
  32. #     define MallocPtrType void *
  33. #     define FreePtrType void *
  34. #     define FreeRetType void
  35. #    endif
  36. #  endif
  37. #endif
  38.  
  39. extern MallocPtrType __internal_malloc(MallocArgType);
  40.  
  41. typedef unsigned int SizeType;
  42.  
  43. #define MallocChunk struct __CustomAllocMallocChunkStruct
  44. struct __CustomAllocMallocChunkStruct
  45. {
  46.   SizeType       size;
  47.   MallocChunk *fd;
  48. };
  49.  
  50. #endif
  51. /* 
  52. Copyright (C) 1989 Free Software Foundation
  53.     written by Doug Lea (dl@oswego.edu)
  54.  
  55. This file is part of the GNU C++ Library.  This library is free
  56. software; you can redistribute it and/or modify it under the terms of
  57. the GNU Library General Public License as published by the Free
  58. Software Foundation; either version 2 of the License, or (at your
  59. option) any later version.  This library is distributed in the hope
  60. that it will be useful, but WITHOUT ANY WARRANTY; without even the
  61. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  62. PURPOSE.  See the GNU Library General Public License for more details.
  63. You should have received a copy of the GNU Library General Public
  64. License along with this library; if not, write to the Free Software
  65. Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  66. */
  67.  
  68.  
  69. /* compile with -DMALLOC_STATS to collect statistics */
  70. /* collecting statistics slows down malloc by at least 15% */
  71.  
  72. #ifndef MallocArgType
  73. #  ifdef __cplusplus
  74. #     define MallocArgType int
  75. #     define MallocPtrType void *
  76. #     define FreePtrType void *
  77. #     define FreeRetType void
  78. #  else
  79. #    ifdef sun
  80. #     ifdef __malloc_h_
  81. #       define MallocArgType int
  82. #       define MallocPtrType malloc_t
  83. #       define FreePtrType malloc_t
  84. #       define FreeRetType int
  85. #     else
  86. #       define MallocArgType int
  87. #       define MallocPtrType char *
  88. #       define FreePtrType void *
  89. #       define FreeRetType int
  90. #     endif
  91. #    else
  92. #     define MallocArgType unsigned int
  93. #     define MallocPtrType void *
  94. #     define FreePtrType void *
  95. #     define FreeRetType void
  96. #    endif
  97. #  endif
  98. #endif
  99.  
  100.  
  101. #ifdef MALLOC_STATS
  102. #define UPDATE_STATS(ARGS) {ARGS;}
  103. #else
  104. #define UPDATE_STATS(ARGS)
  105. #endif
  106.  
  107. /* History
  108.  
  109.  
  110.    Tue Jan 16 04:54:27 1990  Doug Lea  (dl at g.oswego.edu)
  111.  
  112.      version 1 released in libg++
  113.  
  114.    Sun Jan 21 05:52:47 1990  Doug Lea  (dl at g.oswego.edu)
  115.  
  116.      bins are now own struct for, sanity.
  117.  
  118.      new victim search strategy: scan up and consolidate.
  119.      Both faster and less fragmentation.
  120.  
  121.      refined when to scan bins for consolidation, via consollink, etc.
  122.  
  123.      realloc: always try to expand chunk, avoiding some fragmentation.
  124.  
  125.      changed a few inlines into macros
  126.  
  127.      hardwired SBRK_UNIT to 4096 for uniformity across systems
  128.  
  129.    Tue Mar 20 14:18:23 1990  Doug Lea  (dl at g.oswego.edu)
  130.  
  131.      calloc and cfree now correctly parameterized.
  132.  
  133.    Sun Apr  1 10:00:48 1990  Doug Lea  (dl at g.oswego.edu)
  134.  
  135.      added memalign and valloc.
  136.  
  137.    Sun Jun 24 05:46:48 1990  Doug Lea  (dl at g.oswego.edu)
  138.  
  139.      #include gepagesize.h only ifndef sun
  140.      cache pagesize after first call
  141.  
  142.    Wed Jul 25 08:35:19 1990  Doug Lea  (dl at g.oswego.edu)
  143.  
  144.      No longer rely on a `designated victim':
  145.  
  146.        1. It sometimes caused splits of large chunks
  147.           when smaller ones would do, leading to
  148.           bad worst-case fragmentation.
  149.  
  150.        2. Scanning through the av array fast anyway,
  151.           so the overhead isn't worth it.
  152.  
  153.      To compensate, several other minor changes:
  154.  
  155.        1. Unusable chunks are checked for consolidation during
  156.           searches inside bins, better distributing chunks
  157.           across bins.
  158.  
  159.        2. Chunks are returned when found in malloc_find_space,
  160.            rather than finishing cleaning everything up, to
  161.            avoid wasted iterations due to (1).
  162.  
  163.    Sun Dec 15 08:50:37 1991  Doug Lea  (dl at g.oswego.edu)
  164.  
  165.        unsigned int => size_t
  166.  
  167. */
  168.  
  169. /* 
  170.   A version of malloc/free/realloc tuned for C++ applications.
  171.  
  172.   Here's what you probably want to know first:
  173.  
  174.   In various tests, this appears to be about as fast as,
  175.   and usually substantially less memory-wasteful than BSD/GNUemacs malloc.
  176.  
  177.   Generally, it is slower (by perhaps 20%) than bsd-style malloc
  178.   only when bsd malloc would waste a great deal of space in 
  179.   fragmented blocks, which this malloc recovers; or when, by
  180.   chance or design, nearly all requests are near the bsd malloc
  181.   power-of-2 allocation bin boundaries, and as many chunks are
  182.   used as are allocated. 
  183.  
  184.   It uses more space than bsd malloc only when, again by chance
  185.   or design, only bsdmalloc bin-sized requests are malloced, or when
  186.   little dynamic space is malloced, since this malloc may grab larger
  187.   chunks from the system at a time than bsd.
  188.  
  189.   In other words, this malloc seems generally superior to bsd
  190.   except perhaps for programs that are specially tuned to
  191.   deal with bsdmalloc's characteristics. But even here, the
  192.   performance differences are slight.
  193.  
  194.  
  195.   This malloc, like any other, is a compromised design. 
  196.  
  197.  
  198.   Chunks of memory are maintained using a `boundary tag' method as
  199.   described in e.g., Knuth or Standish.  This means that the size of
  200.   the chunk is stored both in the front of the chunk and at the end.
  201.   This makes consolidating fragmented chunks into bigger chunks very fast.
  202.   The size field is also used to hold bits representing whether a
  203.   chunk is free or in use.
  204.  
  205.   Malloced chunks have space overhead of 8 bytes: The preceding
  206.   and trailing size fields. When they are freed, the list pointer
  207.   fields are also needed.
  208.  
  209.   Available chunks are kept in doubly linked lists. The lists are
  210.   maintained in an array of bins using a power-of-two method, except
  211.   that instead of 32 bins (one for each 1 << i), there are 128: each
  212.   power of two is split in quarters. The use of very fine bin sizes 
  213.   closely approximates the use of one bin per actually used size,
  214.   without necessitating the overhead of locating such bins. It is
  215.   especially desirable in common C++ applications where large numbers
  216.   of identically-sized blocks are malloced/freed in some dynamic
  217.   manner, and then later are all freed. The finer bin sizes make
  218.   finding blocks fast, with little wasted overallocation. The
  219.   consolidation methods ensure that once the collection of blocks is
  220.   no longer useful, fragments are gathered into bigger chunks awaiting new
  221.   roles.
  222.  
  223.   The bins av[i] serve as heads of the lists. Bins contain a dummy
  224.   header for the chunk lists, and a `dirty' field used to indicate
  225.   whether the list may need to be scanned for consolidation.
  226.  
  227.   On allocation, the bin corresponding to the request size is
  228.   scanned, and if there is a chunk with size >= requested, it
  229.   is split, if too big, and used. Chunks on the list which are
  230.   too small are examined for consolidation during this traversal.
  231.  
  232.   If no chunk exists in the list bigger bins are scanned in search of
  233.   a victim.
  234.  
  235.   If no victim can be found, then smaller bins are examined for
  236.   consolidation in order to construct a victim.
  237.  
  238.   Finally, if consolidation fails to come up with a usable chunk,
  239.   more space is obtained from the system.
  240.  
  241.   After a split, the remainder is placed on
  242.   the back of the appropriate bin list. (All freed chunks are placed
  243.   on fronts of lists. All remaindered or consolidated chunks are
  244.   placed on the rear. Correspondingly, searching within a bin
  245.   starts at the front, but finding victims is from the back. All
  246.   of this approximates  the  effect of having 2 kinds of lists per 
  247.   bin: returned chunks vs unallocated chunks, but without the overhead 
  248.   of maintaining 2 lists.)
  249.  
  250.   Deallocation (free) consists only of placing the chunk on
  251.   a list.
  252.  
  253.   Reallocation proceeds in the usual way. If a chunk can be extended,
  254.   it is, else a malloc-copy-free sequence is taken.
  255.  
  256.   memalign requests more than enough space from malloc, finds a
  257.   spot within that chunk that meets the alignment request, and
  258.   then possibly frees the leading and trailing space. Overreliance
  259.   on memalign is a sure way to fragment space.
  260.  
  261.  
  262.   Some other implementation matters:
  263.  
  264.   8 byte alignment is currently hardwired into the design. Calling
  265.   memalign will return a chunk that is both 8-byte aligned, and
  266.   meets the requested alignment.
  267.  
  268.   The basic overhead of a used chunk is 8 bytes: 4 at the front and
  269.   4 at the end.
  270.  
  271.   When a chunk is free, 8 additional bytes are needed for free list
  272.   pointers. Thus, the minimum allocatable size is 16 bytes.
  273.  
  274.   The existence of front and back overhead permits some reasonably
  275.   effective fence-bashing checks: The front and back fields must
  276.   be identical. This is checked only within free() and realloc().
  277.   The checks are fast enough to be made non-optional.
  278.  
  279.   The overwriting of parts of freed memory with the freelist pointers
  280.   can also be very effective (albeit in an annoying way) in helping 
  281.   users track down dangling pointers.
  282.  
  283.   User overwriting of freed space will often result in crashes
  284.   within malloc or free.
  285.   
  286.   These routines are also tuned to C++ in that free(0) is a noop and
  287.   a failed malloc automatically calls (*new_handler)(). 
  288.  
  289.   malloc(0) returns a pointer to something of the minimum allocatable size.
  290.  
  291.   Additional memory is gathered from the system (via sbrk) in a
  292.   way that allows chunks obtained across different sbrk calls to
  293.   be consolidated, but does not require contiguous memory: Thus,
  294.   it should be safe to intersperse mallocs with other sbrk calls.
  295.  
  296.   This malloc is NOT designed to work in multiprocessing applications.
  297.   No semaphores or other concurrency control are provided to ensure
  298.   that multiple malloc or free calls don't run at the same time,
  299.   which could be disasterous.
  300.  
  301.   VERY heavy use of inlines is made, for clarity. If this malloc
  302.   is ported via a compiler without inlining capabilities, all
  303.   inlines should be transformed into macros -- making them non-inline
  304.   makes malloc at least twice as slow.
  305.  
  306.  
  307. */
  308.  
  309.  
  310. /* preliminaries */
  311.  
  312. #include <stddef.h>   /* for size_t */
  313.  
  314. #ifdef __cplusplus
  315. #include <stdio.h>
  316. #else
  317. #include "//usr/include/stdio.h"  /* needed for error reporting */
  318. #endif
  319.  
  320. #ifdef __cplusplus
  321. extern "C" {
  322. #endif
  323.  
  324. #ifdef USG
  325. extern void*     memset(void*, int, int);
  326. extern void*     memcpy(void*,  const void*, int);
  327. inline void      bzero(void* s, int l) { memset(s, 0, l); }
  328. #else
  329. extern void      bzero(void*, size_t      );
  330. #endif
  331.  
  332. extern void      bcopy(void*, void*, size_t      );
  333.  
  334. extern void*     sbrk(size_t      );
  335.  
  336.  
  337. #ifdef __GNUC__
  338. extern volatile void abort();
  339. #else
  340. extern void abort();
  341. #endif
  342.  
  343. #ifdef __cplusplus
  344. };  /* end of extern "C" */
  345. #endif
  346.  
  347.  
  348. /* A good multiple to call sbrk with */
  349.  
  350. #define SBRK_UNIT (2 * 4096)
  351.  
  352. extern MallocPtrType malloc(MallocArgType);
  353. extern FreeRetType free(FreePtrType);
  354.  
  355.  
  356.  
  357. /* how to die on detected error */
  358.  
  359. #ifdef __GNUC__
  360. static volatile void malloc_user_error()
  361. #else
  362. static void malloc_user_error()
  363. #endif
  364. {
  365.   fputs("malloc/free/realloc: clobbered space detected\n", stderr); abort();
  366. }
  367.  
  368.  
  369.  
  370. /*  Basic overhead for each malloc'ed chunk */
  371.  
  372.  
  373. struct malloc_chunk
  374. {
  375.   size_t               size;     /* Size in bytes, including overhead. */
  376.                                  /* Or'ed with INUSE if in use. */
  377.  
  378.   struct malloc_chunk* fd;       /* double links -- used only if free. */
  379.   struct malloc_chunk* bk;
  380.  
  381. };
  382.  
  383. typedef struct malloc_chunk* mchunkptr;
  384.  
  385. struct malloc_bin
  386. {
  387.   struct malloc_chunk hd;        /* dummy list header */
  388.   size_t              dirty;     /* True if maybe consolidatable */
  389.                                  /* Wasting a word here makes */
  390.                                  /* sizeof(bin) a power of 2, */
  391.                                  /* which makes size2bin() faster */
  392. };
  393.  
  394. typedef struct malloc_bin* mbinptr;
  395.  
  396.  
  397. /*  sizes, alignments */
  398.  
  399.  
  400. #define SIZE_SZ                   (sizeof(size_t      ))
  401. #define MALLOC_MIN_OVERHEAD       (SIZE_SZ + SIZE_SZ)
  402. #define MALLOC_ALIGN_MASK         (MALLOC_MIN_OVERHEAD - 1)
  403.  
  404. #define MINSIZE (sizeof(struct malloc_chunk) + SIZE_SZ) /* MUST == 16! */
  405.  
  406.  
  407. /* pad request bytes into a usable size */
  408.  
  409. static inline size_t       request2size(size_t       request)
  410. {
  411.   return  (request == 0) ?  MINSIZE : 
  412.     ((request + MALLOC_MIN_OVERHEAD + MALLOC_ALIGN_MASK) 
  413.       & ~(MALLOC_ALIGN_MASK));
  414. }
  415.  
  416.  
  417. static inline int aligned_OK(void* m)  
  418. {
  419.   return ((size_t      )(m) & (MALLOC_ALIGN_MASK)) == 0;
  420. }
  421.  
  422.  
  423. /* size field or'd with INUSE when in use */
  424. #define INUSE  0x1
  425.  
  426.  
  427.  
  428. /* the bins, initialized to have null double linked lists */
  429.  
  430. #define MAXBIN 120   /* 1 more than needed for 32 bit addresses */
  431.  
  432. #define FIRSTBIN (&(av[0])) 
  433.  
  434. static struct malloc_bin  av[MAXBIN] = 
  435. {
  436.   { { 0, &(av[0].hd),  &(av[0].hd) }, 0 },
  437.   { { 0, &(av[1].hd),  &(av[1].hd) }, 0 },
  438.   { { 0, &(av[2].hd),  &(av[2].hd) }, 0 },
  439.   { { 0, &(av[3].hd),  &(av[3].hd) }, 0 },
  440.   { { 0, &(av[4].hd),  &(av[4].hd) }, 0 },
  441.   { { 0, &(av[5].hd),  &(av[5].hd) }, 0 },
  442.   { { 0, &(av[6].hd),  &(av[6].hd) }, 0 },
  443.   { { 0, &(av[7].hd),  &(av[7].hd) }, 0 },
  444.   { { 0, &(av[8].hd),  &(av[8].hd) }, 0 },
  445.   { { 0, &(av[9].hd),  &(av[9].hd) }, 0 },
  446.  
  447.   { { 0, &(av[10].hd), &(av[10].hd) }, 0 },
  448.   { { 0, &(av[11].hd), &(av[11].hd) }, 0 },
  449.   { { 0, &(av[12].hd), &(av[12].hd) }, 0 },
  450.   { { 0, &(av[13].hd), &(av[13].hd) }, 0 },
  451.   { { 0, &(av[14].hd), &(av[14].hd) }, 0 },
  452.   { { 0, &(av[15].hd), &(av[15].hd) }, 0 },
  453.   { { 0, &(av[16].hd), &(av[16].hd) }, 0 },
  454.   { { 0, &(av[17].hd), &(av[17].hd) }, 0 },
  455.   { { 0, &(av[18].hd), &(av[18].hd) }, 0 },
  456.   { { 0, &(av[19].hd), &(av[19].hd) }, 0 },
  457.  
  458.   { { 0, &(av[20].hd), &(av[20].hd) }, 0 },
  459.   { { 0, &(av[21].hd), &(av[21].hd) }, 0 },
  460.   { { 0, &(av[22].hd), &(av[22].hd) }, 0 },
  461.   { { 0, &(av[23].hd), &(av[23].hd) }, 0 },
  462.   { { 0, &(av[24].hd), &(av[24].hd) }, 0 },
  463.   { { 0, &(av[25].hd), &(av[25].hd) }, 0 },
  464.   { { 0, &(av[26].hd), &(av[26].hd) }, 0 },
  465.   { { 0, &(av[27].hd), &(av[27].hd) }, 0 },
  466.   { { 0, &(av[28].hd), &(av[28].hd) }, 0 },
  467.   { { 0, &(av[29].hd), &(av[29].hd) }, 0 },
  468.  
  469.   { { 0, &(av[30].hd), &(av[30].hd) }, 0 },
  470.   { { 0, &(av[31].hd), &(av[31].hd) }, 0 },
  471.   { { 0, &(av[32].hd), &(av[32].hd) }, 0 },
  472.   { { 0, &(av[33].hd), &(av[33].hd) }, 0 },
  473.   { { 0, &(av[34].hd), &(av[34].hd) }, 0 },
  474.   { { 0, &(av[35].hd), &(av[35].hd) }, 0 },
  475.   { { 0, &(av[36].hd), &(av[36].hd) }, 0 },
  476.   { { 0, &(av[37].hd), &(av[37].hd) }, 0 },
  477.   { { 0, &(av[38].hd), &(av[38].hd) }, 0 },
  478.   { { 0, &(av[39].hd), &(av[39].hd) }, 0 },
  479.  
  480.   { { 0, &(av[40].hd), &(av[40].hd) }, 0 },
  481.   { { 0, &(av[41].hd), &(av[41].hd) }, 0 },
  482.   { { 0, &(av[42].hd), &(av[42].hd) }, 0 },
  483.   { { 0, &(av[43].hd), &(av[43].hd) }, 0 },
  484.   { { 0, &(av[44].hd), &(av[44].hd) }, 0 },
  485.   { { 0, &(av[45].hd), &(av[45].hd) }, 0 },
  486.   { { 0, &(av[46].hd), &(av[46].hd) }, 0 },
  487.   { { 0, &(av[47].hd), &(av[47].hd) }, 0 },
  488.   { { 0, &(av[48].hd), &(av[48].hd) }, 0 },
  489.   { { 0, &(av[49].hd), &(av[49].hd) }, 0 },
  490.  
  491.   { { 0, &(av[50].hd), &(av[50].hd) }, 0 },
  492.   { { 0, &(av[51].hd), &(av[51].hd) }, 0 },
  493.   { { 0, &(av[52].hd), &(av[52].hd) }, 0 },
  494.   { { 0, &(av[53].hd), &(av[53].hd) }, 0 },
  495.   { { 0, &(av[54].hd), &(av[54].hd) }, 0 },
  496.   { { 0, &(av[55].hd), &(av[55].hd) }, 0 },
  497.   { { 0, &(av[56].hd), &(av[56].hd) }, 0 },
  498.   { { 0, &(av[57].hd), &(av[57].hd) }, 0 },
  499.   { { 0, &(av[58].hd), &(av[58].hd) }, 0 },
  500.   { { 0, &(av[59].hd), &(av[59].hd) }, 0 },
  501.  
  502.   { { 0, &(av[60].hd), &(av[60].hd) }, 0 },
  503.   { { 0, &(av[61].hd), &(av[61].hd) }, 0 },
  504.   { { 0, &(av[62].hd), &(av[62].hd) }, 0 },
  505.   { { 0, &(av[63].hd), &(av[63].hd) }, 0 },
  506.   { { 0, &(av[64].hd), &(av[64].hd) }, 0 },
  507.   { { 0, &(av[65].hd), &(av[65].hd) }, 0 },
  508.   { { 0, &(av[66].hd), &(av[66].hd) }, 0 },
  509.   { { 0, &(av[67].hd), &(av[67].hd) }, 0 },
  510.   { { 0, &(av[68].hd), &(av[68].hd) }, 0 },
  511.   { { 0, &(av[69].hd), &(av[69].hd) }, 0 },
  512.  
  513.   { { 0, &(av[70].hd), &(av[70].hd) }, 0 },
  514.   { { 0, &(av[71].hd), &(av[71].hd) }, 0 },
  515.   { { 0, &(av[72].hd), &(av[72].hd) }, 0 },
  516.   { { 0, &(av[73].hd), &(av[73].hd) }, 0 },
  517.   { { 0, &(av[74].hd), &(av[74].hd) }, 0 },
  518.   { { 0, &(av[75].hd), &(av[75].hd) }, 0 },
  519.   { { 0, &(av[76].hd), &(av[76].hd) }, 0 },
  520.   { { 0, &(av[77].hd), &(av[77].hd) }, 0 },
  521.   { { 0, &(av[78].hd), &(av[78].hd) }, 0 },
  522.   { { 0, &(av[79].hd), &(av[79].hd) }, 0 },
  523.  
  524.   { { 0, &(av[80].hd), &(av[80].hd) }, 0 },
  525.   { { 0, &(av[81].hd), &(av[81].hd) }, 0 },
  526.   { { 0, &(av[82].hd), &(av[82].hd) }, 0 },
  527.   { { 0, &(av[83].hd), &(av[83].hd) }, 0 },
  528.   { { 0, &(av[84].hd), &(av[84].hd) }, 0 },
  529.   { { 0, &(av[85].hd), &(av[85].hd) }, 0 },
  530.   { { 0, &(av[86].hd), &(av[86].hd) }, 0 },
  531.   { { 0, &(av[87].hd), &(av[87].hd) }, 0 },
  532.   { { 0, &(av[88].hd), &(av[88].hd) }, 0 },
  533.   { { 0, &(av[89].hd), &(av[89].hd) }, 0 },
  534.  
  535.   { { 0, &(av[90].hd), &(av[90].hd) }, 0 },
  536.   { { 0, &(av[91].hd), &(av[91].hd) }, 0 },
  537.   { { 0, &(av[92].hd), &(av[92].hd) }, 0 },
  538.   { { 0, &(av[93].hd), &(av[93].hd) }, 0 },
  539.   { { 0, &(av[94].hd), &(av[94].hd) }, 0 },
  540.   { { 0, &(av[95].hd), &(av[95].hd) }, 0 },
  541.   { { 0, &(av[96].hd), &(av[96].hd) }, 0 },
  542.   { { 0, &(av[97].hd), &(av[97].hd) }, 0 },
  543.   { { 0, &(av[98].hd), &(av[98].hd) }, 0 },
  544.   { { 0, &(av[99].hd), &(av[99].hd) }, 0 },
  545.  
  546.   { { 0, &(av[100].hd), &(av[100].hd) }, 0 },
  547.   { { 0, &(av[101].hd), &(av[101].hd) }, 0 },
  548.   { { 0, &(av[102].hd), &(av[102].hd) }, 0 },
  549.   { { 0, &(av[103].hd), &(av[103].hd) }, 0 },
  550.   { { 0, &(av[104].hd), &(av[104].hd) }, 0 },
  551.   { { 0, &(av[105].hd), &(av[105].hd) }, 0 },
  552.   { { 0, &(av[106].hd), &(av[106].hd) }, 0 },
  553.   { { 0, &(av[107].hd), &(av[107].hd) }, 0 },
  554.   { { 0, &(av[108].hd), &(av[108].hd) }, 0 },
  555.   { { 0, &(av[109].hd), &(av[109].hd) }, 0 },
  556.  
  557.   { { 0, &(av[110].hd), &(av[110].hd) }, 0 },
  558.   { { 0, &(av[111].hd), &(av[111].hd) }, 0 },
  559.   { { 0, &(av[112].hd), &(av[112].hd) }, 0 },
  560.   { { 0, &(av[113].hd), &(av[113].hd) }, 0 },
  561.   { { 0, &(av[114].hd), &(av[114].hd) }, 0 },
  562.   { { 0, &(av[115].hd), &(av[115].hd) }, 0 },
  563.   { { 0, &(av[116].hd), &(av[116].hd) }, 0 },
  564.   { { 0, &(av[117].hd), &(av[117].hd) }, 0 },
  565.   { { 0, &(av[118].hd), &(av[118].hd) }, 0 },
  566.   { { 0, &(av[119].hd), &(av[119].hd) }, 0 }
  567. };
  568.  
  569. /*
  570.   indexing into bins
  571. */
  572.  
  573. static inline mbinptr size2bin(size_t       sz)
  574. {
  575.   mbinptr b = av;
  576.   while (sz >= (MINSIZE * 2)) { b += 4; sz >>= 1; } /* find power of 2 */
  577.   b += (sz - MINSIZE) >> 2;                         /* find quadrant */
  578.   return b;
  579. }
  580.  
  581.  
  582.  
  583. /* counts maintained if MALLOC_STATS defined */
  584.  
  585. #ifdef MALLOC_STATS
  586.  
  587. static size_t       sbrked_mem;
  588. static size_t       requested_mem;
  589. static size_t       malloced_mem;
  590. static size_t       freed_mem;
  591. static size_t       max_used_mem;
  592.  
  593. static size_t       n_sbrks;
  594. static size_t       n_mallocs;
  595. static size_t       n_frees;
  596. static size_t       n_reallocs;
  597. static size_t       n_reallocs_with_copy;
  598. static size_t       n_avail;
  599. static size_t       max_inuse;
  600.  
  601. static size_t       n_malloc_chunks;
  602. static size_t       n_malloc_bins;
  603.  
  604. static size_t       n_split;
  605. static size_t       n_consol;
  606.  
  607.  
  608. static void do_malloc_stats(const mchunkptr p)
  609. {
  610.   ++n_mallocs;
  611.   if ((n_mallocs-n_frees) > max_inuse)
  612.     max_inuse = n_mallocs - n_frees;
  613.   malloced_mem += (p->size & ~(INUSE));
  614.   if (malloced_mem - freed_mem > max_used_mem)
  615.     max_used_mem = malloced_mem - freed_mem;
  616. }
  617.  
  618. static void do_free_stats(const mchunkptr p)
  619. {
  620.   ++n_frees;
  621.   freed_mem += (p->size & ~(INUSE));
  622. }        
  623.  
  624. #endif
  625.  
  626.  
  627.  
  628. /* Utilities needed below for memalign */
  629. /* This is redundant with libg++ support, but not if used stand-alone */
  630.  
  631. static size_t       gcd(size_t       a, size_t       b)
  632. {
  633.   size_t       tmp;
  634.   
  635.   if (b > a)
  636.   {
  637.     tmp = a; a = b; b = tmp;
  638.   }
  639.   for(;;)
  640.   {
  641.     if (b == 0)
  642.       return a;
  643.     else if (b == 1)
  644.       return b;
  645.     else
  646.     {
  647.       tmp = b;
  648.       b = a % b;
  649.       a = tmp;
  650.     }
  651.   }
  652. }
  653.  
  654. static inline size_t       lcm(size_t       x, size_t       y)
  655. {
  656.   return x / gcd(x, y) * y;
  657. }
  658.  
  659.  
  660.  
  661. /* maintaining INUSE via size field */
  662.  
  663.  
  664. #define inuse(p)       ((p)->size & INUSE)
  665. #define set_inuse(p)   ((p)->size |= INUSE)
  666. #define clear_inuse(b) ((p)->size &= ~INUSE)
  667.  
  668.   
  669. /* operations on  malloc_chunk addresses */
  670.  
  671.  
  672. /* return ptr to next physical malloc_chunk */
  673.  
  674. #define next_chunk(p) ((mchunkptr)((char*)(p) + (p)->size))
  675.  
  676. /* return ptr to previous physical malloc_chunk */
  677.  
  678. #define prev_chunk(p) ((mchunkptr)((char*)(p)-((((int*)(p))[-1]) & ~(INUSE))))
  679.  
  680. /* place size at front and back of chunk */
  681.  
  682.  
  683. static inline void set_size(mchunkptr p, size_t       sz)
  684. {
  685.   p->size = *((int*)((char*)(p) + sz - SIZE_SZ)) = sz;
  686. }
  687.  
  688.  
  689.  
  690.  
  691. /* conversion from malloc headers to user pointers, and back */
  692.  
  693. static inline void* chunk2mem(mchunkptr p) 
  694.   set_inuse(p);
  695.   return (void*)((char*)(p) + SIZE_SZ); 
  696. }
  697.  
  698. static inline mchunkptr mem2chunk(void* mem) 
  699.   mchunkptr p = (mchunkptr)((char*)(mem) - SIZE_SZ); 
  700.  
  701.   /* a quick sanity check */
  702.   size_t       sz = p->size & ~(INUSE);
  703.   if (p->size == sz || sz != *((int*)((char*)(p) + sz - SIZE_SZ)))
  704.     malloc_user_error();
  705.  
  706.   p->size = sz;   /* clears INUSE */
  707.   return p;
  708. }
  709.  
  710.  
  711.  
  712. /* maintaining bins & pointers */
  713.  
  714.  
  715. /* maximum bin actually used */
  716.  
  717. static mbinptr malloc_maxbin = FIRSTBIN;
  718.  
  719.  
  720. /* operations on lists inside bins */
  721.  
  722.  
  723. /* take a chunk off a list */
  724.  
  725. static inline void unlink_chunk(mchunkptr p)
  726. {
  727.   mchunkptr b = p->bk;
  728.   mchunkptr f = p->fd;
  729.  
  730.   f->bk = b;  b->fd = f;
  731.  
  732.   UPDATE_STATS (--n_avail);
  733. }
  734.  
  735.  
  736.  
  737. /* split a chunk and place on the back of a list */
  738.  
  739. static inline void split(mchunkptr p, size_t       offset)
  740. {
  741.   size_t       room = p->size - offset;
  742.   if (room >= MINSIZE)
  743.   {
  744.     mbinptr   bn = size2bin(room);                  /* new bin */
  745.     mchunkptr h  = &(bn->hd);                       /* its head */
  746.     mchunkptr b  = h->bk;                           /* old back element */
  747.     mchunkptr t = (mchunkptr)((char*)(p) + offset); /* remaindered chunk */
  748.     
  749.     /* set size */
  750.     t->size = *((int*)((char*)(t) + room    - SIZE_SZ)) = room;
  751.  
  752.     /* link up */
  753.     t->bk = b;  t->fd = h;  h->bk = b->fd = t;
  754.     
  755.     /* adjust maxbin (h == b means was empty) */
  756.     if (h == b && bn > malloc_maxbin) malloc_maxbin = bn; 
  757.  
  758.     /* adjust size of chunk to be returned */
  759.     p->size = *((int*)((char*)(p) + offset  - SIZE_SZ)) = offset;
  760.  
  761.     UPDATE_STATS ((++n_split, ++n_avail));
  762.   }
  763. }
  764.  
  765.  
  766.  
  767. /* place a consolidated chunk on the back of a list */
  768. /* like above, except no split */
  769.  
  770. static inline void consollink(mchunkptr p)
  771. {
  772.   mbinptr   bn = size2bin(p->size);
  773.   mchunkptr h  = &(bn->hd);
  774.   mchunkptr b  = h->bk;
  775.  
  776.   p->bk = b;  p->fd = h;  h->bk = b->fd = p;
  777.  
  778.   if (h == b && bn > malloc_maxbin) malloc_maxbin = bn; 
  779.  
  780.   UPDATE_STATS(++n_avail);
  781. }
  782.  
  783.  
  784. /* place a freed chunk on the front of a list */
  785.  
  786. static inline void frontlink(mchunkptr p)
  787. {
  788.   mbinptr   bn = size2bin(p->size);
  789.   mchunkptr h  = &(bn->hd);
  790.   mchunkptr f  = h->fd;
  791.  
  792.   p->bk = h;  p->fd = f;  f->bk = h->fd = p;
  793.  
  794.   if (h == f && bn > malloc_maxbin) malloc_maxbin = bn;  
  795.  
  796.   bn->dirty = 1;
  797.  
  798.   UPDATE_STATS(++n_avail);
  799. }
  800.  
  801.  
  802.  
  803. /* Dealing with sbrk */
  804.  
  805.  
  806. /* To link consecutive sbrk regions when possible */
  807.  
  808. static int* last_sbrk_end;
  809.  
  810. /*  who to call when sbrk returns failure */
  811.  
  812. static mchunkptr malloc_from_sys(unsigned nb)
  813. {
  814.   mchunkptr p;
  815.   size_t       sbrk_size;
  816.   int* ip;
  817.   
  818.   /* Minimally, we need to pad with enough space */
  819.   /* to place dummy size/use fields to ends if needed */
  820.  
  821.   sbrk_size = ((nb + SBRK_UNIT - 1 + SIZE_SZ + SIZE_SZ) 
  822.                / SBRK_UNIT) * SBRK_UNIT;
  823.  
  824.   ip = (int*)(sbrk(sbrk_size));
  825.   if ((char*)ip == (char*)(-1)) /* sbrk returns -1 on failure */
  826.   {
  827.     return 0;
  828.   }
  829.  
  830.   UPDATE_STATS ((++n_sbrks, sbrked_mem += sbrk_size));
  831.  
  832.  
  833.   if (last_sbrk_end != &ip[-1]) 
  834.   {                             
  835.     /* It's either first time through or someone else called sbrk. */
  836.     /* Arrange end-markers at front & back */
  837.  
  838.     /* Shouldn't be necessary, but better to be safe */
  839.     while (!aligned_OK(ip)) { ++ip; sbrk_size -= SIZE_SZ; }
  840.  
  841.  
  842.     /* Mark the front as in use to prevent merging. */
  843.     /* Note we can get away with only 1 word, not MINSIZE overhead here */
  844.  
  845.     *ip++ = SIZE_SZ | INUSE;
  846.     
  847.     p = (mchunkptr)ip;
  848.     set_size(p,sbrk_size - (SIZE_SZ + SIZE_SZ)); 
  849.     
  850.   }
  851.   else 
  852.   {
  853.     mchunkptr l;  
  854.  
  855.     /* We can safely make the header start at end of prev sbrked chunk. */
  856.     /* We will still have space left at the end from a previous call */
  857.     /* to place the end marker, below */
  858.  
  859.     p = (mchunkptr)(last_sbrk_end);
  860.     set_size(p, sbrk_size);
  861.  
  862.  
  863.     /* Even better, maybe we can merge with last fragment: */
  864.  
  865.     l = prev_chunk(p);
  866.     if (!inuse(l))  
  867.     {
  868.       unlink_chunk(l);
  869.       set_size(l, p->size + l->size);
  870.       p = l;
  871.     }
  872.  
  873.   }
  874.  
  875.   /* mark the end of sbrked space as in use to prevent merging */
  876.  
  877.   last_sbrk_end = (int*)((char*)p + p->size);
  878.   *last_sbrk_end = SIZE_SZ | INUSE;
  879.  
  880.   UPDATE_STATS((++n_avail, ++n_malloc_chunks));
  881.  
  882.   /* make it safe to unlink in malloc */
  883.   UPDATE_STATS(++n_avail);
  884.   p->fd = p->bk = p;
  885.  
  886.   return p;
  887. }
  888.  
  889.  
  890.  
  891. /* Consolidate dirty bins. */
  892. /* Stop if found a chunk big enough to satisfy current malloc request */
  893.  
  894. /* (It requires much less bookkeeping to consolidate entire bins */
  895. /* at once than to keep records of which chunks might be */
  896. /* consolidatable. So long as the lists are short, which we */
  897. /* try to ensure via small bin ranges, there is little wasted effort.) */
  898.  
  899. static mchunkptr malloc_find_space(size_t       nb)
  900. {
  901.   mbinptr b;
  902.  
  903.   /* first, re-adjust max used bin */
  904.  
  905. #ifdef _USE_RECOVERY_
  906.   static unsigned int recover(int);
  907.   int did_recovery = 0;
  908. #endif
  909.  
  910.   TOTALLY_BOGUS_HACK:
  911.  
  912.   while (malloc_maxbin >= FIRSTBIN && 
  913.          malloc_maxbin->hd.bk == &(malloc_maxbin->hd))
  914.   {
  915.     malloc_maxbin->dirty = 0;
  916.     --malloc_maxbin;
  917.   }
  918.  
  919.   for (b = malloc_maxbin; b >= FIRSTBIN; --b)
  920.   {
  921.     UPDATE_STATS(++n_malloc_bins);
  922.  
  923.     if (b->dirty)
  924.     {
  925.       mchunkptr h = &(b->hd);         /* head of list */
  926.       mchunkptr p = h->fd;            /* chunk traverser */
  927.  
  928.       while (p != h)
  929.       {
  930.         mchunkptr nextp = p->fd;       /* save, in case of relinks */
  931.         int consolidated = 0;          /* only unlink/relink if consolidated */
  932.  
  933.         mchunkptr t;
  934.  
  935.         UPDATE_STATS(++n_malloc_chunks);
  936.  
  937.         while (!inuse(t = prev_chunk(p))) /* consolidate backward */
  938.         {
  939.           if (!consolidated) { consolidated = 1; unlink_chunk(p); }
  940.           if (t == nextp) nextp = t->fd;
  941.           unlink_chunk(t);
  942.           set_size(t, t->size + p->size);
  943.           p = t;
  944.           UPDATE_STATS (++n_consol);
  945.         }
  946.         
  947.         while (!inuse(t = next_chunk(p))) /* consolidate forward */
  948.         {
  949.           if (!consolidated) { consolidated = 1; unlink_chunk(p); }
  950.           if (t == nextp) nextp = t->fd;
  951.           unlink_chunk(t);
  952.           set_size(p, p->size + t->size);
  953.           UPDATE_STATS (++n_consol);
  954.         }
  955.  
  956.        if (consolidated)
  957.        {
  958.           if (p->size >= nb)
  959.           {
  960.             /* make it safe to unlink in malloc */
  961.             UPDATE_STATS(++n_avail);
  962.             p->fd = p->bk = p;
  963.             return p;
  964.           }
  965.           else
  966.             consollink(p);
  967.         }
  968.  
  969.         p = nextp;
  970.  
  971.       }
  972.  
  973.       b->dirty = 0;
  974.  
  975.     }
  976.   }
  977.  
  978. #ifdef _USE_RECOVERY_
  979.   if ( !did_recovery ) {
  980.     did_recovery = 1;
  981.     if ( recover(nb) > nb ) goto TOTALLY_BOGUS_HACK;
  982.   }
  983. #endif
  984.  
  985.   /* nothing available - sbrk some more */
  986.  
  987.   return malloc_from_sys(nb);
  988. }
  989.  
  990.  
  991.  
  992. /*   Finally, the user-level functions  */
  993.  
  994. #ifdef _INTERNAL_MALLOC_
  995. MallocPtrType __internal_malloc(MallocArgType bytes)
  996. #else
  997. MallocPtrType malloc(MallocArgType bytes)
  998. #endif
  999. {
  1000.   size_t       nb  = request2size(bytes);  /* padded request size */
  1001.   mbinptr      b   = size2bin(nb);         /* corresponding bin */
  1002.   mchunkptr    hd  = &(b->hd);             /* head of its list */
  1003.   mchunkptr    p   = hd->fd;               /* chunk traverser */
  1004.  
  1005.   UPDATE_STATS((requested_mem+=bytes, ++n_malloc_bins));
  1006.  
  1007.   /* Try a (near) exact match in own bin */
  1008.   /* clean out unusable but consolidatable chunks in bin while traversing */
  1009.  
  1010.   while (p != hd)
  1011.   {
  1012.     UPDATE_STATS(++n_malloc_chunks);
  1013.     if (p->size >= nb)
  1014.       goto found;
  1015.     else    /* try to consolidate; same code as malloc_find_space */
  1016.     {
  1017.       mchunkptr nextp = p->fd;       /* save, in case of relinks */
  1018.       int consolidated = 0;          /* only unlink/relink if consolidated */
  1019.       
  1020.       mchunkptr t;
  1021.  
  1022.       while (!inuse(t = prev_chunk(p))) /* consolidate backward */
  1023.       {
  1024.         if (!consolidated) { consolidated = 1; unlink_chunk(p); }
  1025.         if (t == nextp) nextp = t->fd;
  1026.         unlink_chunk(t);
  1027.         set_size(t, t->size + p->size);
  1028.         p = t;
  1029.         UPDATE_STATS (++n_consol);
  1030.       }
  1031.       
  1032.       while (!inuse(t = next_chunk(p))) /* consolidate forward */
  1033.       {
  1034.         if (!consolidated) { consolidated = 1; unlink_chunk(p); }
  1035.         if (t == nextp) nextp = t->fd;
  1036.         unlink_chunk(t);
  1037.         set_size(p, p->size + t->size);
  1038.         UPDATE_STATS (++n_consol);
  1039.       }
  1040.       
  1041.       if (consolidated)
  1042.       {
  1043.         if (p->size >= nb)
  1044.         {
  1045.           /* make it safe to unlink again below */
  1046.           UPDATE_STATS(++n_avail);
  1047.           p->fd = p->bk = p;
  1048.           goto found;
  1049.         }
  1050.         else
  1051.           consollink(p);
  1052.       }
  1053.  
  1054.       p = nextp;
  1055.  
  1056.     }
  1057.   }
  1058.  
  1059.   b->dirty = 0; /* true if got here */
  1060.  
  1061.   /*  Scan bigger bins for a victim */
  1062.  
  1063.   while (++b <= malloc_maxbin)
  1064.   {
  1065.     UPDATE_STATS(++n_malloc_bins);
  1066.     if ((p = b->hd.bk) != &(b->hd))    /* no need to check size */
  1067.       goto found;
  1068.   }
  1069.  
  1070.   /* Consolidate or sbrk */
  1071.  
  1072.   p = malloc_find_space(nb);
  1073.  
  1074.   if (p == 0) return 0; /* allocation failure */
  1075.  
  1076.  found:   /* Use what we found */
  1077.  
  1078.   unlink_chunk(p);
  1079.   split(p, nb); 
  1080.   UPDATE_STATS(do_malloc_stats(p));
  1081.   return chunk2mem(p);
  1082. }
  1083.  
  1084.  
  1085.  
  1086.  
  1087. #ifdef _INTERNAL_MALLOC_
  1088. static inline void __internal_free(void* mem)
  1089. #else
  1090. FreeRetType free(FreePtrType mem)
  1091. #endif
  1092. {
  1093.   if (mem != 0)
  1094.   {
  1095.     mchunkptr p = mem2chunk(mem);
  1096.     UPDATE_STATS(do_free_stats(p));
  1097.     frontlink(p);
  1098.   }
  1099. }
  1100.  
  1101.  
  1102. void* calloc(size_t       n, size_t       elem_size)
  1103. {
  1104.   size_t       sz = n * elem_size;
  1105.   void* p = (void *) malloc(sz);
  1106.   bzero(p, sz);
  1107.   return p;
  1108. };
  1109.  
  1110. /* This is here for compatibility with older systems */
  1111. void cfree(void *mem)
  1112. {
  1113.   free(mem);
  1114. }
  1115.  
  1116.  
  1117. size_t       malloc_usable_size(void* mem)
  1118. {
  1119.   if (mem == 0)
  1120.     return 0;
  1121.   else
  1122.   {
  1123.     mchunkptr p = (mchunkptr)((char*)(mem) - SIZE_SZ); 
  1124.     size_t       sz = p->size & ~(INUSE);
  1125.     if (p->size == sz || sz != *((int*)((char*)(p) + sz - SIZE_SZ)))
  1126.       return 0;
  1127.     else
  1128.       return sz - MALLOC_MIN_OVERHEAD;
  1129.   }
  1130. }
  1131.  
  1132.  
  1133.  
  1134. #ifdef _INTERNAL_MALLOC_
  1135. static inline void* __internal_realloc(void* mem, unsigned int bytes)
  1136. #else
  1137. void* realloc(void* mem, unsigned int bytes)
  1138. #endif
  1139. {
  1140.   if (mem == 0) 
  1141.     return (void *) malloc(bytes);
  1142.   else
  1143.   {
  1144.     size_t       nb      = request2size(bytes);
  1145.     mchunkptr    p       = mem2chunk(mem);
  1146.     size_t       oldsize = p->size;
  1147.     int          room;
  1148.     mchunkptr    nxt;
  1149.  
  1150.     UPDATE_STATS((++n_reallocs, requested_mem += bytes-oldsize));
  1151.     
  1152.     /* try to expand (even if already big enough), to clean up chunk */
  1153.  
  1154.     while (!inuse(nxt = next_chunk(p)))
  1155.     {
  1156.       UPDATE_STATS ((malloced_mem += nxt->size, ++n_consol));
  1157.       unlink_chunk(nxt);
  1158.       set_size(p, p->size + nxt->size);
  1159.     }
  1160.  
  1161.     room = p->size - nb;
  1162.     if (room >= 0)
  1163.     {
  1164.       split(p, nb);
  1165.       UPDATE_STATS(malloced_mem -= room);
  1166.       return chunk2mem(p);
  1167.     }
  1168.     else /* do the obvious */
  1169.     {
  1170.       void* newmem;
  1171.       set_inuse(p);    /* don't let malloc consolidate us yet! */
  1172.       newmem = malloc(nb);
  1173.       bcopy(mem, newmem, oldsize - SIZE_SZ);
  1174.       free(mem);
  1175.       UPDATE_STATS(++n_reallocs_with_copy);
  1176.       return newmem;
  1177.     }
  1178.   }
  1179. }
  1180.  
  1181.  
  1182.  
  1183. /* return a pointer to space with at least the alignment requested */
  1184.  
  1185. void* memalign(size_t       alignment, size_t       bytes)
  1186. {
  1187.   mchunkptr p;
  1188.   size_t       nb = request2size(bytes);
  1189.  
  1190.   /* find an alignment that both we and the user can live with: */
  1191.   /* least common multiple guarantees mutual happiness */
  1192.   size_t       align = lcm(alignment, MALLOC_MIN_OVERHEAD);
  1193.   size_t       mask = align - 1;
  1194.  
  1195.   /* call malloc with worst case padding to hit alignment; */
  1196.   /* we will give back extra */
  1197.  
  1198.   size_t       req = nb + align + MINSIZE;
  1199.   void* m = malloc(req);
  1200.  
  1201.   if (m == 0) return m;
  1202.  
  1203.   p = mem2chunk(m);
  1204.  
  1205.   /* keep statistics on track */
  1206.  
  1207.   UPDATE_STATS(--n_mallocs);
  1208.   UPDATE_STATS(malloced_mem -= p->size);
  1209.   UPDATE_STATS(requested_mem -= req);
  1210.   UPDATE_STATS(requested_mem += bytes);
  1211.  
  1212.   if (((int)(m) & (mask)) != 0) /* misaligned */
  1213.   {
  1214.  
  1215.     /* find an aligned spot inside chunk */
  1216.  
  1217.     mchunkptr ap = (mchunkptr)(( ((int)(m) + mask) & -align) - SIZE_SZ);
  1218.  
  1219.     size_t       gap = (size_t      )(ap) - (size_t      )(p);
  1220.     size_t       room;
  1221.  
  1222.     /* we need to give back leading space in a chunk of at least MINSIZE */
  1223.  
  1224.     if (gap < MINSIZE)
  1225.     {
  1226.       /* This works since align >= MINSIZE */
  1227.       /* and we've malloc'd enough total room */
  1228.  
  1229.       ap = (mchunkptr)( (int)(ap) + align );
  1230.       gap += align;    
  1231.     }
  1232.  
  1233.     if (gap + nb > p->size) /* can't happen unless chunk sizes corrupted */
  1234.       malloc_user_error();
  1235.  
  1236.     room = p->size - gap;
  1237.  
  1238.     /* give back leader */
  1239.     set_size(p, gap);
  1240.     consollink(p);
  1241.  
  1242.     /* use the rest */
  1243.     p = ap;
  1244.     set_size(p, room);
  1245.   }
  1246.  
  1247.   /* also give back spare room at the end */
  1248.  
  1249.   split(p, nb); 
  1250.   UPDATE_STATS(do_malloc_stats(p));
  1251.   return chunk2mem(p);
  1252.  
  1253. }
  1254.  
  1255. #ifndef sun
  1256. #include <getpagesize.h>
  1257. #endif
  1258.  
  1259. static size_t       malloc_pagesize = 0;
  1260.  
  1261. void* valloc(size_t       bytes)
  1262. {
  1263.   if (malloc_pagesize == 0) malloc_pagesize = getpagesize();
  1264.   return memalign (malloc_pagesize, bytes);
  1265. }
  1266.     
  1267.  
  1268. void malloc_stats()
  1269. {
  1270. #ifndef MALLOC_STATS
  1271. }
  1272. #else
  1273.   int i;
  1274.   mchunkptr p;
  1275.   double nm = (double)(n_mallocs + n_reallocs);
  1276.  
  1277.   fprintf(stderr, "\nmalloc statistics\n\n");
  1278.  
  1279.   if (n_mallocs != 0)
  1280.   fprintf(stderr, "requests  = %10u total size = %10u\tave = %10u\n",
  1281.           n_mallocs, requested_mem, requested_mem/n_mallocs);
  1282.  
  1283.   if (n_mallocs != 0)
  1284.   fprintf(stderr, "mallocs   = %10u total size = %10u\tave = %10u\n",
  1285.           n_mallocs, malloced_mem, malloced_mem/n_mallocs);
  1286.   
  1287.   if (n_frees != 0)
  1288.   fprintf(stderr, "frees     = %10u total size = %10u\tave = %10u\n",
  1289.           n_frees, freed_mem, freed_mem/n_frees);
  1290.   
  1291.   if (n_mallocs-n_frees != 0)
  1292.   fprintf(stderr, "in use    = %10u total size = %10u\tave = %10u\n",
  1293.           n_mallocs-n_frees, malloced_mem-freed_mem, 
  1294.           (malloced_mem-freed_mem) / (n_mallocs-n_frees));
  1295.  
  1296.   if (max_inuse != 0)
  1297.   fprintf(stderr, "max in use= %10u total size = %10u\tave = %10u\n",
  1298.           max_inuse, max_used_mem, max_used_mem / max_inuse);
  1299.   
  1300.   if (n_avail != 0)
  1301.   fprintf(stderr, "available = %10u total size = %10u\tave = %10u\n",
  1302.           n_avail, sbrked_mem - (malloced_mem-freed_mem), 
  1303.           (sbrked_mem - (malloced_mem-freed_mem)) / n_avail);
  1304.  
  1305.   if (n_sbrks != 0)
  1306.   fprintf(stderr, "sbrks     = %10u total size = %10u\tave = %10u\n\n",
  1307.           n_sbrks, sbrked_mem, sbrked_mem/ n_sbrks);
  1308.  
  1309.   if (n_reallocs != 0)
  1310.   fprintf(stderr, "reallocs  = %10u with copy  = %10u\n\n",
  1311.           n_reallocs, n_reallocs_with_copy);
  1312.  
  1313.  
  1314.   if (nm != 0)
  1315.   {
  1316.     fprintf(stderr, "chunks scanned per malloc = %6.3f\n", 
  1317.             n_malloc_chunks / nm);
  1318.     fprintf(stderr, "bins scanned per malloc   = %6.3f\n", 
  1319.             n_malloc_bins / nm);
  1320.     fprintf(stderr, "splits per malloc         = %6.3f\n", 
  1321.             n_split / nm);
  1322.     fprintf(stderr, "consolidations per malloc = %6.3f\n", 
  1323.             n_consol / nm);
  1324.   }
  1325.  
  1326.   fprintf(stderr, "\nfree chunks:\n");
  1327.   for (i = 0; i < MAXBIN; ++i)
  1328.   {
  1329.     p = av[i].hd.fd;
  1330.     if (p != &(av[i].hd))
  1331.     {
  1332.       size_t       count = 1;
  1333.       size_t       sz = p->size;
  1334.       for (p = p->fd; p != &(av[i].hd); p = p->fd)
  1335.       {
  1336.         if (p->size == sz)
  1337.           ++count;
  1338.         else
  1339.         {
  1340.           fprintf(stderr, "\tsize = %10u count = %5u\n", sz, count);
  1341.           count = 1;
  1342.           sz = p->size;
  1343.         }
  1344.       }
  1345.  
  1346.       fprintf(stderr, "\tsize = %10u count = %5u\n", sz, count);
  1347.  
  1348.     }
  1349.   }
  1350. }
  1351. #endif /* MALLOC_STATS */
  1352. /* -*-c-*- */
  1353. #ifndef _UserMalloc_h_
  1354. #define _UserMalloc_h_
  1355.  
  1356. #ifndef _UserMalloc_pre_h_
  1357. #  include "UserMalloc-pre.h"
  1358. #endif
  1359.  
  1360. #ifndef SIZE_SZ
  1361. #  define SIZE_SZ                   (sizeof(SizeType))
  1362. #endif
  1363.  
  1364. #ifndef MINSIZE
  1365. #  define MINSIZE              16 /* from malloc.c */
  1366. #endif
  1367.  
  1368. /*
  1369.  * Return the malloc_chunk structure from a value returned by malloc
  1370.  */
  1371.  
  1372. static inline MallocChunk *external_to_malloc(SizeType *v)
  1373. {
  1374.   return( (MallocChunk*) &v[-1]) ;
  1375. }
  1376.  
  1377. /*
  1378.  * The other way around
  1379.  */
  1380. static inline SizeType *malloc_to_external(MallocChunk *p)
  1381. {
  1382.   SizeType *v = (SizeType*) p;
  1383.   return( &v[1]);
  1384. }
  1385.  
  1386. static inline int malloc_size(MallocChunk *p)
  1387. {
  1388.   return ( (p -> size) & ~0x1 );
  1389. }
  1390.  
  1391. /*****************************************************************************/
  1392.  
  1393.  
  1394. #ifndef CUSTOMALLOC_CACHE_BITS
  1395. #  define CUSTOMALLOC_CACHE_BITS    (5)
  1396. #endif
  1397.  
  1398. #define CUSTOMALLOC_CACHE_VALUE    (1 << CUSTOMALLOC_CACHE_BITS)
  1399. #define CUSTOMALLOC_CACHE_MASK    (~(CUSTOMALLOC_CACHE_VALUE - 1 ))
  1400.  
  1401. #ifdef _IN_OUTPUT_
  1402. static inline void *__customalloc_unlink(char **list)
  1403. {
  1404.   char **p = (char **) *list;
  1405.   *list = p[0];
  1406.   return( &p[0] );
  1407. }
  1408.  
  1409. static inline void __customalloc_link(char **list, void *ptr)
  1410. {
  1411.   char **p = (char **) ptr;
  1412.   p[0] = *list;
  1413.   *list = (char *) ptr;
  1414. }
  1415. #endif
  1416.  
  1417. static inline int size_external_to_internal (int size)
  1418. {
  1419.   return( (size + CUSTOMALLOC_CACHE_VALUE - 1) & CUSTOMALLOC_CACHE_MASK );
  1420. }
  1421.  
  1422. static inline int size_malloc_to_internal (int size)
  1423. {
  1424.   return( size & CUSTOMALLOC_CACHE_MASK );
  1425. }
  1426.  
  1427. #endif
  1428. static char *sbrk_base = 0;
  1429. static char *sbrk_ptr = 0;
  1430. static char *sbrk_end = 0;
  1431.  
  1432. static inline int is_sbrk(void *mem)
  1433. {
  1434.   SizeType* foo = (SizeType *) mem;
  1435.   return( foo[-1] & 0x2 );
  1436. }
  1437.  
  1438. /*
  1439.  * The sbrk malloc allocates 2 * SIZE_SZ overhead, just like the other
  1440.  * malloc, because we want to consistency check routines to be happy.
  1441.  */
  1442. static inline MallocPtrType __sbrk_malloc(MallocArgType size)
  1443. {
  1444.   int rounded_size = ((size + 0x3) & (~0x3)) + 2 * SIZE_SZ;
  1445.   SizeType *next = (unsigned int *) (sbrk_ptr + rounded_size);
  1446.   SizeType *base; 
  1447.  
  1448.   if ( (SizeType) next >= (SizeType) sbrk_end ) {
  1449.  
  1450. #ifndef __customalloc_HowMuchToSbrk_
  1451. #  define __customalloc_HowMuchToSbrk_ ((8 * 1024) - (4 * SIZE_SZ))
  1452. #endif
  1453.  
  1454.     int alloc = __customalloc_HowMuchToSbrk_;
  1455.     int over = sbrk_end - sbrk_ptr;
  1456.  
  1457.     /*
  1458.      * Return unused portion of this extent
  1459.      */
  1460.     if ( sbrk_base && over > MINSIZE ) {
  1461.       /*
  1462.        * We know this will never copy.
  1463.        */
  1464.       int required = sbrk_ptr - sbrk_base + 4;
  1465.       char *new = __internal_realloc(sbrk_base, required + 4);
  1466.       if ( (unsigned int) new != (unsigned int) sbrk_base ) abort();
  1467.  
  1468.       sbrk_base = 0;
  1469.       sbrk_ptr = 0;
  1470.       sbrk_end = 0;
  1471.     }
  1472.  
  1473.     if ( alloc < rounded_size ) {
  1474.       return( __internal_malloc(size) );
  1475.     } 
  1476.     sbrk_base = (char *) __internal_malloc( alloc );
  1477.     sbrk_ptr = sbrk_base;
  1478.     sbrk_end = sbrk_ptr + alloc;
  1479.     next = (SizeType *) (sbrk_ptr + rounded_size);
  1480.   }
  1481.  
  1482.   base = (SizeType *) sbrk_ptr;
  1483.   base[0] = rounded_size | 0x3; /* Mark front end of the chunk */
  1484.   sbrk_ptr = (char *) next;
  1485.   return( (MallocPtrType) &base[1] );
  1486. }
  1487.  
  1488. char *__customalloc_FreeList[9] = {0};
  1489.  
  1490. static int __customalloc_SizeClasses = 9;
  1491.  
  1492. static int __customalloc_ObjectSize[8] = {0, 4, 8, 12, 16, 20, 24, 32};
  1493. static inline MallocPtrType __sbrk_realloc(MallocPtrType mem,
  1494.                          MallocArgType bytes)
  1495. {
  1496.   if ( mem == 0 ) {
  1497.     /*
  1498.      * Some people do the weirdest things.
  1499.      */
  1500.     return( (MallocPtrType) malloc(bytes) );
  1501.   } else {
  1502.     /*
  1503.      * We know p is a pointer to an sbrk'd region at this point
  1504.      */
  1505.     int new_user_size = ((bytes + 0x3) & (~0x3));
  1506.     int new_rounded_size = new_user_size + (2 * SIZE_SZ);
  1507.     
  1508.     SizeType *ptr = (SizeType *) mem;
  1509.     char *base = (char *) &ptr[-1];
  1510.     int old_rounded_size = ptr[-1] & ~0x3;
  1511.     int old_user_size = old_rounded_size - (2 * SIZE_SZ);
  1512.     
  1513.     /*
  1514.      *  OK to simply extend?
  1515.      */
  1516.     if ( (base + old_rounded_size) == sbrk_ptr
  1517.     && ((base + new_rounded_size) < sbrk_end ) ) {
  1518.       sbrk_ptr = base + new_rounded_size;
  1519.       ptr[-1] = ((SizeType) new_rounded_size) | 0x3;
  1520.       return( (MallocPtrType) ptr );
  1521.     } else {
  1522.       int copy_size = (old_user_size < new_user_size )
  1523.     ? old_user_size  : new_user_size;
  1524.       
  1525.       MallocPtrType newmem = (MallocPtrType) malloc(new_user_size);
  1526.       bcopy(mem, newmem, copy_size);
  1527.       free( mem );
  1528.       return( (MallocPtrType) newmem );
  1529.     }
  1530.   }
  1531. }
  1532. /*
  1533.  * Quick fit
  1534.  */
  1535.  
  1536. MallocPtrType realloc(MallocPtrType mem, MallocArgType bytes)
  1537. {
  1538.    if ( mem == 0 ) {
  1539.      return( malloc(bytes) );
  1540.    } else {
  1541.      if ( is_sbrk(mem) ) {
  1542.         return( __sbrk_realloc(mem,bytes));
  1543.      } else {
  1544.         return( __internal_realloc(mem,bytes));
  1545.      }
  1546.    }
  1547. }
  1548.  
  1549. MallocPtrType malloc(MallocArgType bytes)
  1550. {
  1551.   if ( bytes <= 32 ) {
  1552.     /*
  1553.      * Round size up by 4
  1554.      */
  1555.     int index = (bytes+3) >> 2;
  1556.     int size = index << 2;
  1557.     if (__customalloc_FreeList[index]) 
  1558.       return(__customalloc_unlink(&(__customalloc_FreeList[index])));
  1559.     else
  1560.       /*
  1561.        * create it of appropriate size to fit in this bin..
  1562.        */
  1563.       return( __sbrk_malloc(size) ); 
  1564.   } else {
  1565.     return __internal_malloc(bytes);
  1566.   }
  1567. }
  1568.  
  1569. FreeRetType free(FreePtrType p)
  1570. {
  1571.   if ( p ) {
  1572.      MallocChunk *chunk = external_to_malloc(p);
  1573.      int bytes = malloc_size(chunk) - (2 * SIZE_SZ);
  1574.  
  1575.      if ( bytes <= 32 ) {
  1576.        /*
  1577.     * Truncate size
  1578.     */
  1579.        int index = bytes >> 2;
  1580.        __customalloc_link(&(__customalloc_FreeList[index]), p);
  1581.      } else {
  1582.        /*
  1583.     * If it's an sbrk, it must be returned to a freelist
  1584.     */
  1585.        if (is_sbrk(p)) {
  1586.      int index = bytes >> 2;
  1587.      if ( index >= __customalloc_SizeClasses ) {
  1588.        index = __customalloc_SizeClasses - 1;
  1589.      }
  1590.      __customalloc_link(&(__customalloc_FreeList[index]), p);
  1591.        } else {
  1592.      __internal_free(p);
  1593.        }
  1594.      }
  1595.    }
  1596. }
  1597.