PATCH std stdio for (Free)BSD
[p5sagit/p5-mst-13.2.git] / malloc.c
1 /*    malloc.c
2  *
3  */
4
5 /*
6   Here are some notes on configuring Perl's malloc.  (For non-perl
7   usage see below.)
8  
9   There are two macros which serve as bulk disablers of advanced
10   features of this malloc: NO_FANCY_MALLOC, PLAIN_MALLOC (undef by
11   default).  Look in the list of default values below to understand
12   their exact effect.  Defining NO_FANCY_MALLOC returns malloc.c to the
13   state of the malloc in Perl 5.004.  Additionally defining PLAIN_MALLOC
14   returns it to the state as of Perl 5.000.
15
16   Note that some of the settings below may be ignored in the code based
17   on values of other macros.  The PERL_CORE symbol is only defined when
18   perl itself is being compiled (so malloc can make some assumptions
19   about perl's facilities being available to it).
20
21   Each config option has a short description, followed by its name,
22   default value, and a comment about the default (if applicable).  Some
23   options take a precise value, while the others are just boolean.
24   The boolean ones are listed first.
25
26     # Enable code for an emergency memory pool in $^M.  See perlvar.pod
27     # for a description of $^M.
28     PERL_EMERGENCY_SBRK         (!PLAIN_MALLOC && PERL_CORE)
29
30     # Enable code for printing memory statistics.
31     DEBUGGING_MSTATS            (!PLAIN_MALLOC && PERL_CORE)
32
33     # Move allocation info for small buckets into separate areas.
34     # Memory optimization (especially for small allocations, of the
35     # less than 64 bytes).  Since perl usually makes a large number
36     # of small allocations, this is usually a win.
37     PACK_MALLOC                 (!PLAIN_MALLOC && !RCHECK)
38
39     # Add one page to big powers of two when calculating bucket size.
40     # This is targeted at big allocations, as are common in image
41     # processing.
42     TWO_POT_OPTIMIZE            !PLAIN_MALLOC
43  
44     # Use intermediate bucket sizes between powers-of-two.  This is
45     # generally a memory optimization, and a (small) speed pessimization.
46     BUCKETS_ROOT2               !NO_FANCY_MALLOC
47
48     # Do not check small deallocations for bad free().  Memory
49     # and speed optimization, error reporting pessimization.
50     IGNORE_SMALL_BAD_FREE       (!NO_FANCY_MALLOC && !RCHECK)
51
52     # Use table lookup to decide in which bucket a given allocation will go.
53     SMALL_BUCKET_VIA_TABLE      !NO_FANCY_MALLOC
54
55     # Use a perl-defined sbrk() instead of the (presumably broken or
56     # missing) system-supplied sbrk().
57     USE_PERL_SBRK               undef
58
59     # Use system malloc() (or calloc() etc.) to emulate sbrk(). Normally
60     # only used with broken sbrk()s.
61     PERL_SBRK_VIA_MALLOC        undef
62
63     # Which allocator to use if PERL_SBRK_VIA_MALLOC
64     SYSTEM_ALLOC(a)             malloc(a)
65
66     # Minimal alignment (in bytes, should be a power of 2) of SYSTEM_ALLOC
67     SYSTEM_ALLOC_ALIGNMENT      MEM_ALIGNBYTES
68
69     # Disable memory overwrite checking with DEBUGGING.  Memory and speed
70     # optimization, error reporting pessimization.
71     NO_RCHECK                   undef
72
73     # Enable memory overwrite checking with DEBUGGING.  Memory and speed
74     # pessimization, error reporting optimization
75     RCHECK                      (DEBUGGING && !NO_RCHECK)
76
77     # Failed allocations bigger than this size croak (if
78     # PERL_EMERGENCY_SBRK is enabled) without touching $^M.  See
79     # perlvar.pod for a description of $^M.
80     BIG_SIZE                     (1<<16)        # 64K
81
82     # Starting from this power of two, add an extra page to the
83     # size of the bucket. This enables optimized allocations of sizes
84     # close to powers of 2.  Note that the value is indexed at 0.
85     FIRST_BIG_POW2              15              # 32K, 16K is used too often
86
87     # Estimate of minimal memory footprint.  malloc uses this value to
88     # request the most reasonable largest blocks of memory from the system.
89     FIRST_SBRK                  (48*1024)
90
91     # Round up sbrk()s to multiples of this.
92     MIN_SBRK                    2048
93
94     # Round up sbrk()s to multiples of this percent of footprint.
95     MIN_SBRK_FRAC               3
96
97     # Add this much memory to big powers of two to get the bucket size.
98     PERL_PAGESIZE               4096
99
100     # This many sbrk() discontinuities should be tolerated even
101     # from the start without deciding that sbrk() is usually
102     # discontinuous.
103     SBRK_ALLOW_FAILURES         3
104
105     # This many continuous sbrk()s compensate for one discontinuous one.
106     SBRK_FAILURE_PRICE          50
107
108     # Some configurations may ask for 12-byte-or-so allocations which
109     # require 8-byte alignment (?!).  In such situation one needs to
110     # define this to disable 12-byte bucket (will increase memory footprint)
111     STRICT_ALIGNMENT            undef
112
113   This implementation assumes that calling PerlIO_printf() does not
114   result in any memory allocation calls (used during a panic).
115
116  */
117
118 /*
119    If used outside of Perl environment, it may be useful to redefine
120    the following macros (listed below with defaults):
121
122      # Type of address returned by allocation functions
123      Malloc_t                           void *
124
125      # Type of size argument for allocation functions
126      MEM_SIZE                           unsigned long
127
128      # size of void*
129      PTRSIZE                            4
130
131      # Maximal value in LONG
132      LONG_MAX                           0x7FFFFFFF
133
134      # Unsigned integer type big enough to keep a pointer
135      UV                                 unsigned long
136
137      # Type of pointer with 1-byte granularity
138      caddr_t                            char *
139
140      # Type returned by free()
141      Free_t                             void
142
143      # Very fatal condition reporting function (cannot call any )
144      fatalcroak(arg)                    write(2,arg,strlen(arg)) + exit(2)
145   
146      # Fatal error reporting function
147      croak(format, arg)                 warn(idem) + exit(1)
148   
149      # Fatal error reporting function
150      croak2(format, arg1, arg2)         warn2(idem) + exit(1)
151   
152      # Error reporting function
153      warn(format, arg)                  fprintf(stderr, idem)
154
155      # Error reporting function
156      warn2(format, arg1, arg2)          fprintf(stderr, idem)
157
158      # Locking/unlocking for MT operation
159      MALLOC_LOCK                        MUTEX_LOCK(&PL_malloc_mutex)
160      MALLOC_UNLOCK                      MUTEX_UNLOCK(&PL_malloc_mutex)
161
162      # Locking/unlocking mutex for MT operation
163      MUTEX_LOCK(l)                      void
164      MUTEX_UNLOCK(l)                    void
165  */
166
167 #ifndef NO_FANCY_MALLOC
168 #  ifndef SMALL_BUCKET_VIA_TABLE
169 #    define SMALL_BUCKET_VIA_TABLE
170 #  endif 
171 #  ifndef BUCKETS_ROOT2
172 #    define BUCKETS_ROOT2
173 #  endif 
174 #  ifndef IGNORE_SMALL_BAD_FREE
175 #    define IGNORE_SMALL_BAD_FREE
176 #  endif 
177 #endif 
178
179 #ifndef PLAIN_MALLOC                    /* Bulk enable features */
180 #  ifndef PACK_MALLOC
181 #      define PACK_MALLOC
182 #  endif 
183 #  ifndef TWO_POT_OPTIMIZE
184 #    define TWO_POT_OPTIMIZE
185 #  endif 
186 #  if defined(PERL_CORE) && !defined(PERL_EMERGENCY_SBRK)
187 #    define PERL_EMERGENCY_SBRK
188 #  endif 
189 #  if defined(PERL_CORE) && !defined(DEBUGGING_MSTATS)
190 #    define DEBUGGING_MSTATS
191 #  endif 
192 #endif
193
194 #define MIN_BUC_POW2 (sizeof(void*) > 4 ? 3 : 2) /* Allow for 4-byte arena. */
195 #define MIN_BUCKET (MIN_BUC_POW2 * BUCKETS_PER_POW2)
196
197 #if !(defined(I286) || defined(atarist) || defined(__MINT__))
198         /* take 2k unless the block is bigger than that */
199 #  define LOG_OF_MIN_ARENA 11
200 #else
201         /* take 16k unless the block is bigger than that 
202            (80286s like large segments!), probably good on the atari too */
203 #  define LOG_OF_MIN_ARENA 14
204 #endif
205
206 #ifndef lint
207 #  if defined(DEBUGGING) && !defined(NO_RCHECK)
208 #    define RCHECK
209 #  endif
210 #  if defined(RCHECK) && defined(IGNORE_SMALL_BAD_FREE)
211 #    undef IGNORE_SMALL_BAD_FREE
212 #  endif 
213 /*
214  * malloc.c (Caltech) 2/21/82
215  * Chris Kingsley, kingsley@cit-20.
216  *
217  * This is a very fast storage allocator.  It allocates blocks of a small 
218  * number of different sizes, and keeps free lists of each size.  Blocks that
219  * don't exactly fit are passed up to the next larger size.  In this 
220  * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long.
221  * If PACK_MALLOC is defined, small blocks are 2^n bytes long.
222  * This is designed for use in a program that uses vast quantities of memory,
223  * but bombs when it runs out.
224  * 
225  * Modifications Copyright Ilya Zakharevich 1996-99.
226  * 
227  * Still very quick, but much more thrifty.  (Std config is 10% slower
228  * than it was, and takes 67% of old heap size for typical usage.)
229  *
230  * Allocations of small blocks are now table-driven to many different
231  * buckets.  Sizes of really big buckets are increased to accomodata
232  * common size=power-of-2 blocks.  Running-out-of-memory is made into
233  * an exception.  Deeply configurable and thread-safe.
234  * 
235  */
236
237 #ifdef PERL_CORE
238 #  include "EXTERN.h"
239 #  define PERL_IN_MALLOC_C
240 #  include "perl.h"
241 #  if defined(PERL_IMPLICIT_CONTEXT)
242 #    define croak       Perl_croak_nocontext
243 #    define croak2      Perl_croak_nocontext
244 #    define warn        Perl_warn_nocontext
245 #    define warn2       Perl_warn_nocontext
246 #  else
247 #    define croak2      croak
248 #    define warn2       warn
249 #  endif
250 #else
251 #  ifdef PERL_FOR_X2P
252 #    include "../EXTERN.h"
253 #    include "../perl.h"
254 #  else
255 #    include <stdlib.h>
256 #    include <stdio.h>
257 #    include <memory.h>
258 #    define _(arg) arg
259 #    ifndef Malloc_t
260 #      define Malloc_t void *
261 #    endif
262 #    ifndef PTRSIZE
263 #      define PTRSIZE 4
264 #    endif
265 #    ifndef MEM_SIZE
266 #      define MEM_SIZE unsigned long
267 #    endif
268 #    ifndef LONG_MAX
269 #      define LONG_MAX 0x7FFFFFFF
270 #    endif
271 #    ifndef UV
272 #      define UV unsigned long
273 #    endif
274 #    ifndef caddr_t
275 #      define caddr_t char *
276 #    endif
277 #    ifndef Free_t
278 #      define Free_t void
279 #    endif
280 #    define Copy(s,d,n,t) (void)memcpy((char*)(d),(char*)(s), (n) * sizeof(t))
281 #    define PerlEnv_getenv getenv
282 #    define PerlIO_printf fprintf
283 #    define PerlIO_stderr() stderr
284 #  endif
285 #  ifndef croak                         /* make depend */
286 #    define croak(mess, arg) (warn((mess), (arg)), exit(1))
287 #  endif 
288 #  ifndef croak2                        /* make depend */
289 #    define croak2(mess, arg1, arg2) (warn2((mess), (arg1), (arg2)), exit(1))
290 #  endif 
291 #  ifndef warn
292 #    define warn(mess, arg) fprintf(stderr, (mess), (arg))
293 #  endif 
294 #  ifndef warn
295 #    define warn2(mess, arg1) fprintf(stderr, (mess), (arg1), (arg2))
296 #  endif 
297 #  ifdef DEBUG_m
298 #    undef DEBUG_m
299 #  endif 
300 #  define DEBUG_m(a)
301 #  ifdef DEBUGGING
302 #     undef DEBUGGING
303 #  endif
304 #  ifndef pTHX
305 #     define pTHX               void
306 #     define pTHX_
307 #     define dTHX               extern int Perl___notused
308 #     define WITH_THX(s)        s
309 #  endif
310 #  ifndef PERL_GET_INTERP
311 #     define PERL_GET_INTERP    PL_curinterp
312 #  endif
313 #  ifndef Perl_malloc
314 #     define Perl_malloc malloc
315 #  endif
316 #  ifndef Perl_mfree
317 #     define Perl_mfree free
318 #  endif
319 #  ifndef Perl_realloc
320 #     define Perl_realloc realloc
321 #  endif
322 #  ifndef Perl_calloc
323 #     define Perl_calloc calloc
324 #  endif
325 #  ifndef Perl_strdup
326 #     define Perl_strdup strdup
327 #  endif
328 #endif
329
330 #ifndef MUTEX_LOCK
331 #  define MUTEX_LOCK(l)
332 #endif 
333
334 #ifndef MUTEX_UNLOCK
335 #  define MUTEX_UNLOCK(l)
336 #endif 
337
338 #ifndef MALLOC_LOCK
339 #  define MALLOC_LOCK           MUTEX_LOCK(&PL_malloc_mutex)
340 #endif 
341
342 #ifndef MALLOC_UNLOCK
343 #  define MALLOC_UNLOCK         MUTEX_UNLOCK(&PL_malloc_mutex)
344 #endif 
345
346 #  ifndef fatalcroak                            /* make depend */
347 #    define fatalcroak(mess)    (write(2, (mess), strlen(mess)), exit(2))
348 #  endif 
349
350 #ifdef DEBUGGING
351 #  undef DEBUG_m
352 #  define DEBUG_m(a)  \
353     STMT_START {                                                        \
354         if (PERL_GET_INTERP) { dTHX; if (PL_debug & 128) { a; } }       \
355     } STMT_END
356 #endif
357
358 #ifdef PERL_IMPLICIT_CONTEXT
359 #  define PERL_IS_ALIVE         aTHX
360 #else
361 #  define PERL_IS_ALIVE         TRUE
362 #endif
363     
364
365 /*
366  * Layout of memory:
367  * ~~~~~~~~~~~~~~~~
368  * The memory is broken into "blocks" which occupy multiples of 2K (and
369  * generally speaking, have size "close" to a power of 2).  The addresses
370  * of such *unused* blocks are kept in nextf[i] with big enough i.  (nextf
371  * is an array of linked lists.)  (Addresses of used blocks are not known.)
372  * 
373  * Moreover, since the algorithm may try to "bite" smaller blocks out
374  * of unused bigger ones, there are also regions of "irregular" size,
375  * managed separately, by a linked list chunk_chain.
376  * 
377  * The third type of storage is the sbrk()ed-but-not-yet-used space, its
378  * end and size are kept in last_sbrk_top and sbrked_remains.
379  * 
380  * Growing blocks "in place":
381  * ~~~~~~~~~~~~~~~~~~~~~~~~~
382  * The address of the block with the greatest address is kept in last_op
383  * (if not known, last_op is 0).  If it is known that the memory above
384  * last_op is not continuous, or contains a chunk from chunk_chain,
385  * last_op is set to 0.
386  * 
387  * The chunk with address last_op may be grown by expanding into
388  * sbrk()ed-but-not-yet-used space, or trying to sbrk() more continuous
389  * memory.
390  * 
391  * Management of last_op:
392  * ~~~~~~~~~~~~~~~~~~~~~
393  * 
394  * free() never changes the boundaries of blocks, so is not relevant.
395  * 
396  * The only way realloc() may change the boundaries of blocks is if it
397  * grows a block "in place".  However, in the case of success such a
398  * chunk is automatically last_op, and it remains last_op.  In the case
399  * of failure getpages_adjacent() clears last_op.
400  * 
401  * malloc() may change blocks by calling morecore() only.
402  * 
403  * morecore() may create new blocks by:
404  *   a) biting pieces from chunk_chain (cannot create one above last_op);
405  *   b) biting a piece from an unused block (if block was last_op, this
406  *      may create a chunk from chain above last_op, thus last_op is
407  *      invalidated in such a case).
408  *   c) biting of sbrk()ed-but-not-yet-used space.  This creates 
409  *      a block which is last_op.
410  *   d) Allocating new pages by calling getpages();
411  * 
412  * getpages() creates a new block.  It marks last_op at the bottom of
413  * the chunk of memory it returns.
414  * 
415  * Active pages footprint:
416  * ~~~~~~~~~~~~~~~~~~~~~~
417  * Note that we do not need to traverse the lists in nextf[i], just take
418  * the first element of this list.  However, we *need* to traverse the
419  * list in chunk_chain, but most the time it should be a very short one,
420  * so we do not step on a lot of pages we are not going to use.
421  * 
422  * Flaws:
423  * ~~~~~
424  * get_from_bigger_buckets(): forget to increment price => Quite
425  * aggressive.
426  */
427
428 /* I don't much care whether these are defined in sys/types.h--LAW */
429
430 #define u_char unsigned char
431 #define u_int unsigned int
432 /* 
433  * I removed the definition of u_bigint which appeared to be u_bigint = UV
434  * u_bigint was only used in TWOK_MASKED and TWOK_SHIFT 
435  * where I have used PTR2UV.  RMB
436  */
437 #define u_short unsigned short
438
439 /* 286 and atarist like big chunks, which gives too much overhead. */
440 #if (defined(RCHECK) || defined(I286) || defined(atarist) || defined(__MINT__)) && defined(PACK_MALLOC)
441 #  undef PACK_MALLOC
442 #endif 
443
444 /*
445  * The description below is applicable if PACK_MALLOC is not defined.
446  *
447  * The overhead on a block is at least 4 bytes.  When free, this space
448  * contains a pointer to the next free block, and the bottom two bits must
449  * be zero.  When in use, the first byte is set to MAGIC, and the second
450  * byte is the size index.  The remaining bytes are for alignment.
451  * If range checking is enabled and the size of the block fits
452  * in two bytes, then the top two bytes hold the size of the requested block
453  * plus the range checking words, and the header word MINUS ONE.
454  */
455 union   overhead {
456         union   overhead *ov_next;      /* when free */
457 #if MEM_ALIGNBYTES > 4
458         double  strut;                  /* alignment problems */
459 #endif
460         struct {
461 /*
462  * Keep the ovu_index and ovu_magic in this order, having a char
463  * field first gives alignment indigestion in some systems, such as
464  * MachTen.
465  */
466                 u_char  ovu_index;      /* bucket # */
467                 u_char  ovu_magic;      /* magic number */
468 #ifdef RCHECK
469                 u_short ovu_size;       /* actual block size */
470                 u_int   ovu_rmagic;     /* range magic number */
471 #endif
472         } ovu;
473 #define ov_magic        ovu.ovu_magic
474 #define ov_index        ovu.ovu_index
475 #define ov_size         ovu.ovu_size
476 #define ov_rmagic       ovu.ovu_rmagic
477 };
478
479 #define MAGIC           0xff            /* magic # on accounting info */
480 #define RMAGIC          0x55555555      /* magic # on range info */
481 #define RMAGIC_C        0x55            /* magic # on range info */
482
483 #ifdef RCHECK
484 #  define       RSLOP           sizeof (u_int)
485 #  ifdef TWO_POT_OPTIMIZE
486 #    define MAX_SHORT_BUCKET (12 * BUCKETS_PER_POW2)
487 #  else
488 #    define MAX_SHORT_BUCKET (13 * BUCKETS_PER_POW2)
489 #  endif 
490 #else
491 #  define       RSLOP           0
492 #endif
493
494 #if !defined(PACK_MALLOC) && defined(BUCKETS_ROOT2)
495 #  undef BUCKETS_ROOT2
496 #endif 
497
498 #ifdef BUCKETS_ROOT2
499 #  define BUCKET_TABLE_SHIFT 2
500 #  define BUCKET_POW2_SHIFT 1
501 #  define BUCKETS_PER_POW2 2
502 #else
503 #  define BUCKET_TABLE_SHIFT MIN_BUC_POW2
504 #  define BUCKET_POW2_SHIFT 0
505 #  define BUCKETS_PER_POW2 1
506 #endif 
507
508 #if !defined(MEM_ALIGNBYTES) || ((MEM_ALIGNBYTES > 4) && !defined(STRICT_ALIGNMENT))
509 /* Figure out the alignment of void*. */
510 struct aligner {
511   char c;
512   void *p;
513 };
514 #  define ALIGN_SMALL ((int)((caddr_t)&(((struct aligner*)0)->p)))
515 #else
516 #  define ALIGN_SMALL MEM_ALIGNBYTES
517 #endif
518
519 #define IF_ALIGN_8(yes,no)      ((ALIGN_SMALL>4) ? (yes) : (no))
520
521 #ifdef BUCKETS_ROOT2
522 #  define MAX_BUCKET_BY_TABLE 13
523 static u_short buck_size[MAX_BUCKET_BY_TABLE + 1] = 
524   { 
525       0, 0, 0, 0, 4, 4, 8, 12, 16, 24, 32, 48, 64, 80,
526   };
527 #  define BUCKET_SIZE(i) ((i) % 2 ? buck_size[i] : (1 << ((i) >> BUCKET_POW2_SHIFT)))
528 #  define BUCKET_SIZE_REAL(i) ((i) <= MAX_BUCKET_BY_TABLE               \
529                                ? buck_size[i]                           \
530                                : ((1 << ((i) >> BUCKET_POW2_SHIFT))     \
531                                   - MEM_OVERHEAD(i)                     \
532                                   + POW2_OPTIMIZE_SURPLUS(i)))
533 #else
534 #  define BUCKET_SIZE(i) (1 << ((i) >> BUCKET_POW2_SHIFT))
535 #  define BUCKET_SIZE_REAL(i) (BUCKET_SIZE(i) - MEM_OVERHEAD(i) + POW2_OPTIMIZE_SURPLUS(i))
536 #endif 
537
538
539 #ifdef PACK_MALLOC
540 /* In this case there are several possible layout of arenas depending
541  * on the size.  Arenas are of sizes multiple to 2K, 2K-aligned, and
542  * have a size close to a power of 2.
543  *
544  * Arenas of the size >= 4K keep one chunk only.  Arenas of size 2K
545  * may keep one chunk or multiple chunks.  Here are the possible
546  * layouts of arenas:
547  *
548  *      # One chunk only, chunksize 2^k + SOMETHING - ALIGN, k >= 11
549  *
550  * INDEX MAGIC1 UNUSED CHUNK1
551  *
552  *      # Multichunk with sanity checking and chunksize 2^k-ALIGN, k>7
553  *
554  * INDEX MAGIC1 MAGIC2 MAGIC3 UNUSED CHUNK1 CHUNK2 CHUNK3 ...
555  *
556  *      # Multichunk with sanity checking and size 2^k-ALIGN, k=7
557  *
558  * INDEX MAGIC1 MAGIC2 MAGIC3 UNUSED CHUNK1 UNUSED CHUNK2 CHUNK3 ...
559  *
560  *      # Multichunk with sanity checking and size up to 80
561  *
562  * INDEX UNUSED MAGIC1 UNUSED MAGIC2 UNUSED ... CHUNK1 CHUNK2 CHUNK3 ...
563  *
564  *      # No sanity check (usually up to 48=byte-long buckets)
565  * INDEX UNUSED CHUNK1 CHUNK2 ...
566  *
567  * Above INDEX and MAGIC are one-byte-long.  Sizes of UNUSED are
568  * appropriate to keep algorithms simple and memory aligned.  INDEX
569  * encodes the size of the chunk, while MAGICn encodes state (used,
570  * free or non-managed-by-us-so-it-indicates-a-bug) of CHUNKn.  MAGIC
571  * is used for sanity checking purposes only.  SOMETHING is 0 or 4K
572  * (to make size of big CHUNK accomodate allocations for powers of two
573  * better).
574  *
575  * [There is no need to alignment between chunks, since C rules ensure
576  *  that structs which need 2^k alignment have sizeof which is
577  *  divisible by 2^k.  Thus as far as the last chunk is aligned at the
578  *  end of the arena, and 2K-alignment does not contradict things,
579  *  everything is going to be OK for sizes of chunks 2^n and 2^n +
580  *  2^k.  Say, 80-bit buckets will be 16-bit aligned, and as far as we
581  *  put allocations for requests in 65..80 range, all is fine.
582  *
583  *  Note, however, that standard malloc() puts more strict
584  *  requirements than the above C rules.  Moreover, our algorithms of
585  *  realloc() may break this idyll, but we suppose that realloc() does
586  *  need not change alignment.]
587  *
588  * Is very important to make calculation of the offset of MAGICm as
589  * quick as possible, since it is done on each malloc()/free().  In
590  * fact it is so quick that it has quite little effect on the speed of
591  * doing malloc()/free().  [By default] We forego such calculations
592  * for small chunks, but only to save extra 3% of memory, not because
593  * of speed considerations.
594  *
595  * Here is the algorithm [which is the same for all the allocations
596  * schemes above], see OV_MAGIC(block,bucket).  Let OFFSETm be the
597  * offset of the CHUNKm from the start of ARENA.  Then offset of
598  * MAGICm is (OFFSET1 >> SHIFT) + ADDOFFSET.  Here SHIFT and ADDOFFSET
599  * are numbers which depend on the size of the chunks only.
600  *
601  * Let as check some sanity conditions.  Numbers OFFSETm>>SHIFT are
602  * different for all the chunks in the arena if 2^SHIFT is not greater
603  * than size of the chunks in the arena.  MAGIC1 will not overwrite
604  * INDEX provided ADDOFFSET is >0 if OFFSET1 < 2^SHIFT.  MAGIClast
605  * will not overwrite CHUNK1 if OFFSET1 > (OFFSETlast >> SHIFT) +
606  * ADDOFFSET.
607  * 
608  * Make SHIFT the maximal possible (there is no point in making it
609  * smaller).  Since OFFSETlast is 2K - CHUNKSIZE, above restrictions
610  * give restrictions on OFFSET1 and on ADDOFFSET.
611  * 
612  * In particular, for chunks of size 2^k with k>=6 we can put
613  * ADDOFFSET to be from 0 to 2^k - 2^(11-k), and have
614  * OFFSET1==chunksize.  For chunks of size 80 OFFSET1 of 2K%80=48 is
615  * large enough to have ADDOFFSET between 1 and 16 (similarly for 96,
616  * when ADDOFFSET should be 1).  In particular, keeping MAGICs for
617  * these sizes gives no additional size penalty.
618  * 
619  * However, for chunks of size 2^k with k<=5 this gives OFFSET1 >=
620  * ADDOFSET + 2^(11-k).  Keeping ADDOFFSET 0 allows for 2^(11-k)-2^(11-2k)
621  * chunks per arena.  This is smaller than 2^(11-k) - 1 which are
622  * needed if no MAGIC is kept.  [In fact, having a negative ADDOFFSET
623  * would allow for slightly more buckets per arena for k=2,3.]
624  * 
625  * Similarly, for chunks of size 3/2*2^k with k<=5 MAGICs would span
626  * the area up to 2^(11-k)+ADDOFFSET.  For k=4 this give optimal
627  * ADDOFFSET as -7..0.  For k=3 ADDOFFSET can go up to 4 (with tiny
628  * savings for negative ADDOFFSET).  For k=5 ADDOFFSET can go -1..16
629  * (with no savings for negative values).
630  *
631  * In particular, keeping ADDOFFSET 0 for sizes of chunks up to 2^6
632  * leads to tiny pessimizations in case of sizes 4, 8, 12, 24, and
633  * leads to no contradictions except for size=80 (or 96.)
634  *
635  * However, it also makes sense to keep no magic for sizes 48 or less.
636  * This is what we do.  In this case one needs ADDOFFSET>=1 also for
637  * chunksizes 12, 24, and 48, unless one gets one less chunk per
638  * arena.
639  *  
640  * The algo of OV_MAGIC(block,bucket) keeps ADDOFFSET 0 until
641  * chunksize of 64, then makes it 1. 
642  *
643  * This allows for an additional optimization: the above scheme leads
644  * to giant overheads for sizes 128 or more (one whole chunk needs to
645  * be sacrifised to keep INDEX).  Instead we use chunks not of size
646  * 2^k, but of size 2^k-ALIGN.  If we pack these chunks at the end of
647  * the arena, then the beginnings are still in different 2^k-long
648  * sections of the arena if k>=7 for ALIGN==4, and k>=8 if ALIGN=8.
649  * Thus for k>7 the above algo of calculating the offset of the magic
650  * will still give different answers for different chunks.  And to
651  * avoid the overrun of MAGIC1 into INDEX, one needs ADDOFFSET of >=1.
652  * In the case k=7 we just move the first chunk an extra ALIGN
653  * backward inside the ARENA (this is done once per arena lifetime,
654  * thus is not a big overhead).  */
655 #  define MAX_PACKED_POW2 6
656 #  define MAX_PACKED (MAX_PACKED_POW2 * BUCKETS_PER_POW2 + BUCKET_POW2_SHIFT)
657 #  define MAX_POW2_ALGO ((1<<(MAX_PACKED_POW2 + 1)) - M_OVERHEAD)
658 #  define TWOK_MASK ((1<<LOG_OF_MIN_ARENA) - 1)
659 #  define TWOK_MASKED(x) (PTR2UV(x) & ~TWOK_MASK)
660 #  define TWOK_SHIFT(x) (PTR2UV(x) & TWOK_MASK)
661 #  define OV_INDEXp(block) (INT2PTR(u_char*,TWOK_MASKED(block)))
662 #  define OV_INDEX(block) (*OV_INDEXp(block))
663 #  define OV_MAGIC(block,bucket) (*(OV_INDEXp(block) +                  \
664                                     (TWOK_SHIFT(block)>>                \
665                                      (bucket>>BUCKET_POW2_SHIFT)) +     \
666                                     (bucket >= MIN_NEEDS_SHIFT ? 1 : 0)))
667     /* A bucket can have a shift smaller than it size, we need to
668        shift its magic number so it will not overwrite index: */
669 #  ifdef BUCKETS_ROOT2
670 #    define MIN_NEEDS_SHIFT (7*BUCKETS_PER_POW2 - 1) /* Shift 80 greater than chunk 64. */
671 #  else
672 #    define MIN_NEEDS_SHIFT (7*BUCKETS_PER_POW2) /* Shift 128 greater than chunk 32. */
673 #  endif 
674 #  define CHUNK_SHIFT 0
675
676 /* Number of active buckets of given ordinal. */
677 #ifdef IGNORE_SMALL_BAD_FREE
678 #define FIRST_BUCKET_WITH_CHECK (6 * BUCKETS_PER_POW2) /* 64 */
679 #  define N_BLKS(bucket) ( (bucket) < FIRST_BUCKET_WITH_CHECK           \
680                          ? ((1<<LOG_OF_MIN_ARENA) - 1)/BUCKET_SIZE(bucket) \
681                          : n_blks[bucket] )
682 #else
683 #  define N_BLKS(bucket) n_blks[bucket]
684 #endif 
685
686 static u_short n_blks[LOG_OF_MIN_ARENA * BUCKETS_PER_POW2] = 
687   {
688 #  if BUCKETS_PER_POW2==1
689       0, 0,
690       (MIN_BUC_POW2==2 ? 384 : 0),
691       224, 120, 62, 31, 16, 8, 4, 2
692 #  else
693       0, 0, 0, 0,
694       (MIN_BUC_POW2==2 ? 384 : 0), (MIN_BUC_POW2==2 ? 384 : 0), /* 4, 4 */
695       224, 149, 120, 80, 62, 41, 31, 25, 16, 16, 8, 8, 4, 4, 2, 2
696 #  endif
697   };
698
699 /* Shift of the first bucket with the given ordinal inside 2K chunk. */
700 #ifdef IGNORE_SMALL_BAD_FREE
701 #  define BLK_SHIFT(bucket) ( (bucket) < FIRST_BUCKET_WITH_CHECK        \
702                               ? ((1<<LOG_OF_MIN_ARENA)                  \
703                                  - BUCKET_SIZE(bucket) * N_BLKS(bucket)) \
704                               : blk_shift[bucket])
705 #else
706 #  define BLK_SHIFT(bucket) blk_shift[bucket]
707 #endif 
708
709 static u_short blk_shift[LOG_OF_MIN_ARENA * BUCKETS_PER_POW2] = 
710   { 
711 #  if BUCKETS_PER_POW2==1
712       0, 0,
713       (MIN_BUC_POW2==2 ? 512 : 0),
714       256, 128, 64, 64,                 /* 8 to 64 */
715       16*sizeof(union overhead), 
716       8*sizeof(union overhead), 
717       4*sizeof(union overhead), 
718       2*sizeof(union overhead), 
719 #  else
720       0, 0, 0, 0,
721       (MIN_BUC_POW2==2 ? 512 : 0), (MIN_BUC_POW2==2 ? 512 : 0),
722       256, 260, 128, 128, 64, 80, 64, 48, /* 8 to 96 */
723       16*sizeof(union overhead), 16*sizeof(union overhead), 
724       8*sizeof(union overhead), 8*sizeof(union overhead), 
725       4*sizeof(union overhead), 4*sizeof(union overhead), 
726       2*sizeof(union overhead), 2*sizeof(union overhead), 
727 #  endif 
728   };
729
730 #  define NEEDED_ALIGNMENT 0x800        /* 2k boundaries */
731 #  define WANTED_ALIGNMENT 0x800        /* 2k boundaries */
732
733 #else  /* !PACK_MALLOC */
734
735 #  define OV_MAGIC(block,bucket) (block)->ov_magic
736 #  define OV_INDEX(block) (block)->ov_index
737 #  define CHUNK_SHIFT 1
738 #  define MAX_PACKED -1
739 #  define NEEDED_ALIGNMENT MEM_ALIGNBYTES
740 #  define WANTED_ALIGNMENT 0x400        /* 1k boundaries */
741
742 #endif /* !PACK_MALLOC */
743
744 #define M_OVERHEAD (sizeof(union overhead) + RSLOP)
745
746 #ifdef PACK_MALLOC
747 #  define MEM_OVERHEAD(bucket) \
748   (bucket <= MAX_PACKED ? 0 : M_OVERHEAD)
749 #  ifdef SMALL_BUCKET_VIA_TABLE
750 #    define START_SHIFTS_BUCKET ((MAX_PACKED_POW2 + 1) * BUCKETS_PER_POW2)
751 #    define START_SHIFT MAX_PACKED_POW2
752 #    ifdef BUCKETS_ROOT2                /* Chunks of size 3*2^n. */
753 #      define SIZE_TABLE_MAX 80
754 #    else
755 #      define SIZE_TABLE_MAX 64
756 #    endif 
757 static char bucket_of[] =
758   {
759 #    ifdef BUCKETS_ROOT2                /* Chunks of size 3*2^n. */
760       /* 0 to 15 in 4-byte increments. */
761       (sizeof(void*) > 4 ? 6 : 5),      /* 4/8, 5-th bucket for better reports */
762       6,                                /* 8 */
763       IF_ALIGN_8(8,7), 8,               /* 16/12, 16 */
764       9, 9, 10, 10,                     /* 24, 32 */
765       11, 11, 11, 11,                   /* 48 */
766       12, 12, 12, 12,                   /* 64 */
767       13, 13, 13, 13,                   /* 80 */
768       13, 13, 13, 13                    /* 80 */
769 #    else /* !BUCKETS_ROOT2 */
770       /* 0 to 15 in 4-byte increments. */
771       (sizeof(void*) > 4 ? 3 : 2),
772       3, 
773       4, 4, 
774       5, 5, 5, 5,
775       6, 6, 6, 6,
776       6, 6, 6, 6
777 #    endif /* !BUCKETS_ROOT2 */
778   };
779 #  else  /* !SMALL_BUCKET_VIA_TABLE */
780 #    define START_SHIFTS_BUCKET MIN_BUCKET
781 #    define START_SHIFT (MIN_BUC_POW2 - 1)
782 #  endif /* !SMALL_BUCKET_VIA_TABLE */
783 #else  /* !PACK_MALLOC */
784 #  define MEM_OVERHEAD(bucket) M_OVERHEAD
785 #  ifdef SMALL_BUCKET_VIA_TABLE
786 #    undef SMALL_BUCKET_VIA_TABLE
787 #  endif 
788 #  define START_SHIFTS_BUCKET MIN_BUCKET
789 #  define START_SHIFT (MIN_BUC_POW2 - 1)
790 #endif /* !PACK_MALLOC */
791
792 /*
793  * Big allocations are often of the size 2^n bytes. To make them a
794  * little bit better, make blocks of size 2^n+pagesize for big n.
795  */
796
797 #ifdef TWO_POT_OPTIMIZE
798
799 #  ifndef PERL_PAGESIZE
800 #    define PERL_PAGESIZE 4096
801 #  endif 
802 #  ifndef FIRST_BIG_POW2
803 #    define FIRST_BIG_POW2 15   /* 32K, 16K is used too often. */
804 #  endif
805 #  define FIRST_BIG_BLOCK (1<<FIRST_BIG_POW2)
806 /* If this value or more, check against bigger blocks. */
807 #  define FIRST_BIG_BOUND (FIRST_BIG_BLOCK - M_OVERHEAD)
808 /* If less than this value, goes into 2^n-overhead-block. */
809 #  define LAST_SMALL_BOUND ((FIRST_BIG_BLOCK>>1) - M_OVERHEAD)
810
811 #  define POW2_OPTIMIZE_ADJUST(nbytes)                          \
812    ((nbytes >= FIRST_BIG_BOUND) ? nbytes -= PERL_PAGESIZE : 0)
813 #  define POW2_OPTIMIZE_SURPLUS(bucket)                         \
814    ((bucket >= FIRST_BIG_POW2 * BUCKETS_PER_POW2) ? PERL_PAGESIZE : 0)
815
816 #else  /* !TWO_POT_OPTIMIZE */
817 #  define POW2_OPTIMIZE_ADJUST(nbytes)
818 #  define POW2_OPTIMIZE_SURPLUS(bucket) 0
819 #endif /* !TWO_POT_OPTIMIZE */
820
821 #if defined(HAS_64K_LIMIT) && defined(PERL_CORE)
822 #  define BARK_64K_LIMIT(what,nbytes,size)                              \
823         if (nbytes > 0xffff) {                                          \
824                 PerlIO_printf(PerlIO_stderr(),                          \
825                               "%s too large: %lx\n", what, size);       \
826                 my_exit(1);                                             \
827         }
828 #else /* !HAS_64K_LIMIT || !PERL_CORE */
829 #  define BARK_64K_LIMIT(what,nbytes,size)
830 #endif /* !HAS_64K_LIMIT || !PERL_CORE */
831
832 #ifndef MIN_SBRK
833 #  define MIN_SBRK 2048
834 #endif 
835
836 #ifndef FIRST_SBRK
837 #  define FIRST_SBRK (48*1024)
838 #endif 
839
840 /* Minimal sbrk in percents of what is already alloced. */
841 #ifndef MIN_SBRK_FRAC
842 #  define MIN_SBRK_FRAC 3
843 #endif 
844
845 #ifndef SBRK_ALLOW_FAILURES
846 #  define SBRK_ALLOW_FAILURES 3
847 #endif 
848
849 #ifndef SBRK_FAILURE_PRICE
850 #  define SBRK_FAILURE_PRICE 50
851 #endif 
852
853 static void     morecore        (register int bucket);
854 #  if defined(DEBUGGING)
855 static void     botch           (char *diag, char *s);
856 #  endif
857 static void     add_to_chain    (void *p, MEM_SIZE size, MEM_SIZE chip);
858 static void*    get_from_chain  (MEM_SIZE size);
859 static void*    get_from_bigger_buckets(int bucket, MEM_SIZE size);
860 static union overhead *getpages (MEM_SIZE needed, int *nblksp, int bucket);
861 static int      getpages_adjacent(MEM_SIZE require);
862
863 #if defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)
864
865 #  ifndef BIG_SIZE
866 #    define BIG_SIZE (1<<16)            /* 64K */
867 #  endif 
868
869 #ifdef I_MACH_CTHREADS
870 #  undef  MUTEX_LOCK
871 #  define MUTEX_LOCK(m)   STMT_START { if (*m) mutex_lock(*m);   } STMT_END
872 #  undef  MUTEX_UNLOCK
873 #  define MUTEX_UNLOCK(m) STMT_START { if (*m) mutex_unlock(*m); } STMT_END
874 #endif
875
876 #ifndef BITS_IN_PTR
877 #  define BITS_IN_PTR (8*PTRSIZE)
878 #endif
879
880 /*
881  * nextf[i] is the pointer to the next free block of size 2^i.  The
882  * smallest allocatable block is 8 bytes.  The overhead information
883  * precedes the data area returned to the user.
884  */
885 #define NBUCKETS (BITS_IN_PTR*BUCKETS_PER_POW2 + 1)
886 static  union overhead *nextf[NBUCKETS];
887
888 #if defined(PURIFY) && !defined(USE_PERL_SBRK)
889 #  define USE_PERL_SBRK
890 #endif
891
892 #ifdef USE_PERL_SBRK
893 #define sbrk(a) Perl_sbrk(a)
894 Malloc_t Perl_sbrk (int size);
895 #else 
896 #ifdef DONT_DECLARE_STD
897 #ifdef I_UNISTD
898 #include <unistd.h>
899 #endif
900 #else
901 extern  Malloc_t sbrk(int);
902 #endif
903 #endif
904
905 #ifdef DEBUGGING_MSTATS
906 /*
907  * nmalloc[i] is the difference between the number of mallocs and frees
908  * for a given block size.
909  */
910 static  u_int nmalloc[NBUCKETS];
911 static  u_int sbrk_slack;
912 static  u_int start_slack;
913 #else   /* !( defined DEBUGGING_MSTATS ) */
914 #  define sbrk_slack    0
915 #endif
916
917 static  u_int goodsbrk;
918
919 static char *emergency_buffer;
920 static MEM_SIZE emergency_buffer_size;
921 static int no_mem;      /* 0 if the last request for more memory succeeded.
922                            Otherwise the size of the failing request. */
923
924 static Malloc_t
925 emergency_sbrk(MEM_SIZE size)
926 {
927     MEM_SIZE rsize = (((size - 1)>>LOG_OF_MIN_ARENA) + 1)<<LOG_OF_MIN_ARENA;
928
929     if (size >= BIG_SIZE && (!no_mem || (size < no_mem))) {
930         /* Give the possibility to recover, but avoid an infinite cycle. */
931         MALLOC_UNLOCK;
932         no_mem = size;
933         croak2("Out of memory during \"large\" request for %"UVuf" bytes, total sbrk() is %"UVuf" bytes", (UV)size, (UV)(goodsbrk + sbrk_slack));
934     }
935
936     if (emergency_buffer_size >= rsize) {
937         char *old = emergency_buffer;
938         
939         emergency_buffer_size -= rsize;
940         emergency_buffer += rsize;
941         return old;
942     } else {            
943         dTHX;
944         /* First offense, give a possibility to recover by dieing. */
945         /* No malloc involved here: */
946         GV **gvp = (GV**)hv_fetch(PL_defstash, "^M", 2, 0);
947         SV *sv;
948         char *pv;
949         int have = 0;
950         STRLEN n_a;
951
952         if (emergency_buffer_size) {
953             add_to_chain(emergency_buffer, emergency_buffer_size, 0);
954             emergency_buffer_size = 0;
955             emergency_buffer = Nullch;
956             have = 1;
957         }
958         if (!gvp) gvp = (GV**)hv_fetch(PL_defstash, "\015", 1, 0);
959         if (!gvp || !(sv = GvSV(*gvp)) || !SvPOK(sv) 
960             || (SvLEN(sv) < (1<<LOG_OF_MIN_ARENA) - M_OVERHEAD)) {
961             if (have)
962                 goto do_croak;
963             return (char *)-1;          /* Now die die die... */
964         }
965         /* Got it, now detach SvPV: */
966         pv = SvPV(sv, n_a);
967         /* Check alignment: */
968         if ((PTR2UV(pv) - sizeof(union overhead)) & (NEEDED_ALIGNMENT - 1)) {
969             PerlIO_puts(PerlIO_stderr(),"Bad alignment of $^M!\n");
970             return (char *)-1;          /* die die die */
971         }
972
973         emergency_buffer = pv - sizeof(union overhead);
974         emergency_buffer_size = malloced_size(pv) + M_OVERHEAD;
975         SvPOK_off(sv);
976         SvPVX(sv) = Nullch;
977         SvCUR(sv) = SvLEN(sv) = 0;
978     }
979   do_croak:
980     MALLOC_UNLOCK;
981     croak("Out of memory during request for %"UVuf" bytes, total sbrk() is %"UVuf" bytes", (UV)size, (UV)(goodsbrk + sbrk_slack));
982     /* NOTREACHED */
983     return Nullch;
984 }
985
986 #else /* !(defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)) */
987 #  define emergency_sbrk(size)  -1
988 #endif /* !(defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)) */
989
990 #ifdef DEBUGGING
991 #undef ASSERT
992 #define ASSERT(p,diag)   if (!(p)) botch(diag,STRINGIFY(p));  else
993 static void
994 botch(char *diag, char *s)
995 {
996         dTHX;
997         PerlIO_printf(PerlIO_stderr(), "assertion botched (%s?): %s\n", diag, s);
998         PerlProc_abort();
999 }
1000 #else
1001 #define ASSERT(p, diag)
1002 #endif
1003
1004 Malloc_t
1005 Perl_malloc(register size_t nbytes)
1006 {
1007         register union overhead *p;
1008         register int bucket;
1009         register MEM_SIZE shiftr;
1010
1011 #if defined(DEBUGGING) || defined(RCHECK)
1012         MEM_SIZE size = nbytes;
1013 #endif
1014
1015         BARK_64K_LIMIT("Allocation",nbytes,nbytes);
1016 #ifdef DEBUGGING
1017         if ((long)nbytes < 0)
1018             croak("%s", "panic: malloc");
1019 #endif
1020
1021         /*
1022          * Convert amount of memory requested into
1023          * closest block size stored in hash buckets
1024          * which satisfies request.  Account for
1025          * space used per block for accounting.
1026          */
1027 #ifdef PACK_MALLOC
1028 #  ifdef SMALL_BUCKET_VIA_TABLE
1029         if (nbytes == 0)
1030             bucket = MIN_BUCKET;
1031         else if (nbytes <= SIZE_TABLE_MAX) {
1032             bucket = bucket_of[(nbytes - 1) >> BUCKET_TABLE_SHIFT];
1033         } else
1034 #  else
1035         if (nbytes == 0)
1036             nbytes = 1;
1037         if (nbytes <= MAX_POW2_ALGO) goto do_shifts;
1038         else
1039 #  endif
1040 #endif 
1041         {
1042             POW2_OPTIMIZE_ADJUST(nbytes);
1043             nbytes += M_OVERHEAD;
1044             nbytes = (nbytes + 3) &~ 3; 
1045           do_shifts:
1046             shiftr = (nbytes - 1) >> START_SHIFT;
1047             bucket = START_SHIFTS_BUCKET;
1048             /* apart from this loop, this is O(1) */
1049             while (shiftr >>= 1)
1050                 bucket += BUCKETS_PER_POW2;
1051         }
1052         MALLOC_LOCK;
1053         /*
1054          * If nothing in hash bucket right now,
1055          * request more memory from the system.
1056          */
1057         if (nextf[bucket] == NULL)    
1058                 morecore(bucket);
1059         if ((p = nextf[bucket]) == NULL) {
1060                 MALLOC_UNLOCK;
1061 #ifdef PERL_CORE
1062                 {
1063                     dTHX;
1064                     if (!PL_nomemok) {
1065                         char buff[80];
1066                         char *eb = buff + sizeof(buff) - 1;
1067                         char *s = eb;
1068                         size_t n = nbytes;
1069
1070                         PerlIO_puts(PerlIO_stderr(),"Out of memory during request for ");
1071 #if defined(DEBUGGING) || defined(RCHECK)
1072                         n = size;
1073 #endif
1074                         *s = 0;                 
1075                         do {
1076                             *--s = '0' + (n % 10);
1077                         } while (n /= 10);
1078                         PerlIO_puts(PerlIO_stderr(),s);
1079                         PerlIO_puts(PerlIO_stderr()," bytes, total sbrk() is ");
1080                         s = eb;
1081                         n = goodsbrk + sbrk_slack;
1082                         do {
1083                             *--s = '0' + (n % 10);
1084                         } while (n /= 10);
1085                         PerlIO_puts(PerlIO_stderr(),s);
1086                         PerlIO_puts(PerlIO_stderr()," bytes!\n");
1087                         my_exit(1);
1088                     }
1089                 }
1090 #endif
1091                 return (NULL);
1092         }
1093
1094         DEBUG_m(PerlIO_printf(Perl_debug_log,
1095                               "0x%"UVxf": (%05lu) malloc %ld bytes\n",
1096                               PTR2UV(p+1), (unsigned long)(PL_an++),
1097                               (long)size));
1098
1099         /* remove from linked list */
1100 #if defined(RCHECK)
1101         if ((PTR2UV(p)) & (MEM_ALIGNBYTES - 1)) {
1102             dTHX;
1103             PerlIO_printf(PerlIO_stderr(),
1104                           "Unaligned pointer in the free chain 0x%"UVxf"\n",
1105                           PTR2UV(p));
1106         }
1107         if ((PTR2UV(p->ov_next)) & (MEM_ALIGNBYTES - 1)) {
1108             dTHX;
1109             PerlIO_printf(PerlIO_stderr(),
1110                           "Unaligned `next' pointer in the free "
1111                           "chain 0x%"UVxf" at 0x%"UVxf"\n",
1112                           PTR2UV(p->ov_next), PTR2UV(p));
1113         }
1114 #endif
1115         nextf[bucket] = p->ov_next;
1116
1117         MALLOC_UNLOCK;
1118
1119 #ifdef IGNORE_SMALL_BAD_FREE
1120         if (bucket >= FIRST_BUCKET_WITH_CHECK)
1121 #endif 
1122             OV_MAGIC(p, bucket) = MAGIC;
1123 #ifndef PACK_MALLOC
1124         OV_INDEX(p) = bucket;
1125 #endif
1126 #ifdef RCHECK
1127         /*
1128          * Record allocated size of block and
1129          * bound space with magic numbers.
1130          */
1131         p->ov_rmagic = RMAGIC;
1132         if (bucket <= MAX_SHORT_BUCKET) {
1133             int i;
1134             
1135             nbytes = size + M_OVERHEAD; 
1136             p->ov_size = nbytes - 1;
1137             if ((i = nbytes & 3)) {
1138                 i = 4 - i;
1139                 while (i--)
1140                     *((char *)((caddr_t)p + nbytes - RSLOP + i)) = RMAGIC_C;
1141             }
1142             nbytes = (nbytes + 3) &~ 3; 
1143             *((u_int *)((caddr_t)p + nbytes - RSLOP)) = RMAGIC;
1144         }
1145 #endif
1146         return ((Malloc_t)(p + CHUNK_SHIFT));
1147 }
1148
1149 static char *last_sbrk_top;
1150 static char *last_op;                   /* This arena can be easily extended. */
1151 static int sbrked_remains;
1152 static int sbrk_good = SBRK_ALLOW_FAILURES * SBRK_FAILURE_PRICE;
1153
1154 #ifdef DEBUGGING_MSTATS
1155 static int sbrks;
1156 #endif 
1157
1158 struct chunk_chain_s {
1159     struct chunk_chain_s *next;
1160     MEM_SIZE size;
1161 };
1162 static struct chunk_chain_s *chunk_chain;
1163 static int n_chunks;
1164 static char max_bucket;
1165
1166 /* Cutoff a piece of one of the chunks in the chain.  Prefer smaller chunk. */
1167 static void *
1168 get_from_chain(MEM_SIZE size)
1169 {
1170     struct chunk_chain_s *elt = chunk_chain, **oldp = &chunk_chain;
1171     struct chunk_chain_s **oldgoodp = NULL;
1172     long min_remain = LONG_MAX;
1173
1174     while (elt) {
1175         if (elt->size >= size) {
1176             long remains = elt->size - size;
1177             if (remains >= 0 && remains < min_remain) {
1178                 oldgoodp = oldp;
1179                 min_remain = remains;
1180             }
1181             if (remains == 0) {
1182                 break;
1183             }
1184         }
1185         oldp = &( elt->next );
1186         elt = elt->next;
1187     }
1188     if (!oldgoodp) return NULL;
1189     if (min_remain) {
1190         void *ret = *oldgoodp;
1191         struct chunk_chain_s *next = (*oldgoodp)->next;
1192         
1193         *oldgoodp = (struct chunk_chain_s *)((char*)ret + size);
1194         (*oldgoodp)->size = min_remain;
1195         (*oldgoodp)->next = next;
1196         return ret;
1197     } else {
1198         void *ret = *oldgoodp;
1199         *oldgoodp = (*oldgoodp)->next;
1200         n_chunks--;
1201         return ret;
1202     }
1203 }
1204
1205 static void
1206 add_to_chain(void *p, MEM_SIZE size, MEM_SIZE chip)
1207 {
1208     struct chunk_chain_s *next = chunk_chain;
1209     char *cp = (char*)p;
1210     
1211     cp += chip;
1212     chunk_chain = (struct chunk_chain_s *)cp;
1213     chunk_chain->size = size - chip;
1214     chunk_chain->next = next;
1215     n_chunks++;
1216 }
1217
1218 static void *
1219 get_from_bigger_buckets(int bucket, MEM_SIZE size)
1220 {
1221     int price = 1;
1222     static int bucketprice[NBUCKETS];
1223     while (bucket <= max_bucket) {
1224         /* We postpone stealing from bigger buckets until we want it
1225            often enough. */
1226         if (nextf[bucket] && bucketprice[bucket]++ >= price) {
1227             /* Steal it! */
1228             void *ret = (void*)(nextf[bucket] - 1 + CHUNK_SHIFT);
1229             bucketprice[bucket] = 0;
1230             if (((char*)nextf[bucket]) - M_OVERHEAD == last_op) {
1231                 last_op = NULL;         /* Disable optimization */
1232             }
1233             nextf[bucket] = nextf[bucket]->ov_next;
1234 #ifdef DEBUGGING_MSTATS
1235             nmalloc[bucket]--;
1236             start_slack -= M_OVERHEAD;
1237 #endif 
1238             add_to_chain(ret, (BUCKET_SIZE(bucket) +
1239                                POW2_OPTIMIZE_SURPLUS(bucket)), 
1240                          size);
1241             return ret;
1242         }
1243         bucket++;
1244     }
1245     return NULL;
1246 }
1247
1248 static union overhead *
1249 getpages(MEM_SIZE needed, int *nblksp, int bucket)
1250 {
1251     /* Need to do (possibly expensive) system call. Try to
1252        optimize it for rare calling. */
1253     MEM_SIZE require = needed - sbrked_remains;
1254     char *cp;
1255     union overhead *ovp;
1256     MEM_SIZE slack = 0;
1257
1258     if (sbrk_good > 0) {
1259         if (!last_sbrk_top && require < FIRST_SBRK) 
1260             require = FIRST_SBRK;
1261         else if (require < MIN_SBRK) require = MIN_SBRK;
1262
1263         if (require < goodsbrk * MIN_SBRK_FRAC / 100)
1264             require = goodsbrk * MIN_SBRK_FRAC / 100;
1265         require = ((require - 1 + MIN_SBRK) / MIN_SBRK) * MIN_SBRK;
1266     } else {
1267         require = needed;
1268         last_sbrk_top = 0;
1269         sbrked_remains = 0;
1270     }
1271
1272     DEBUG_m(PerlIO_printf(Perl_debug_log, 
1273                           "sbrk(%ld) for %ld-byte-long arena\n",
1274                           (long)require, (long) needed));
1275     cp = (char *)sbrk(require);
1276 #ifdef DEBUGGING_MSTATS
1277     sbrks++;
1278 #endif 
1279     if (cp == last_sbrk_top) {
1280         /* Common case, anything is fine. */
1281         sbrk_good++;
1282         ovp = (union overhead *) (cp - sbrked_remains);
1283         last_op = cp - sbrked_remains;
1284         sbrked_remains = require - (needed - sbrked_remains);
1285     } else if (cp == (char *)-1) { /* no more room! */
1286         ovp = (union overhead *)emergency_sbrk(needed);
1287         if (ovp == (union overhead *)-1)
1288             return 0;
1289         if (((char*)ovp) > last_op) {   /* Cannot happen with current emergency_sbrk() */
1290             last_op = 0;
1291         }
1292         return ovp;
1293     } else {                    /* Non-continuous or first sbrk(). */
1294         long add = sbrked_remains;
1295         char *newcp;
1296
1297         if (sbrked_remains) {   /* Put rest into chain, we
1298                                    cannot use it right now. */
1299             add_to_chain((void*)(last_sbrk_top - sbrked_remains),
1300                          sbrked_remains, 0);
1301         }
1302
1303         /* Second, check alignment. */
1304         slack = 0;
1305
1306 #if !defined(atarist) && !defined(__MINT__) /* on the atari we dont have to worry about this */
1307 #  ifndef I286  /* The sbrk(0) call on the I286 always returns the next segment */
1308         /* WANTED_ALIGNMENT may be more than NEEDED_ALIGNMENT, but this may
1309            improve performance of memory access. */
1310         if (PTR2UV(cp) & (WANTED_ALIGNMENT - 1)) { /* Not aligned. */
1311             slack = WANTED_ALIGNMENT - (PTR2UV(cp) & (WANTED_ALIGNMENT - 1));
1312             add += slack;
1313         }
1314 #  endif
1315 #endif /* !atarist && !MINT */
1316                 
1317         if (add) {
1318             DEBUG_m(PerlIO_printf(Perl_debug_log, 
1319                                   "sbrk(%ld) to fix non-continuous/off-page sbrk:\n\t%ld for alignement,\t%ld were assumed to come from the tail of the previous sbrk\n",
1320                                   (long)add, (long) slack,
1321                                   (long) sbrked_remains));
1322             newcp = (char *)sbrk(add);
1323 #if defined(DEBUGGING_MSTATS)
1324             sbrks++;
1325             sbrk_slack += add;
1326 #endif
1327             if (newcp != cp + require) {
1328                 /* Too bad: even rounding sbrk() is not continuous.*/
1329                 DEBUG_m(PerlIO_printf(Perl_debug_log, 
1330                                       "failed to fix bad sbrk()\n"));
1331 #ifdef PACK_MALLOC
1332                 if (slack) {
1333                     MALLOC_UNLOCK;
1334                     fatalcroak("panic: Off-page sbrk\n");
1335                 }
1336 #endif
1337                 if (sbrked_remains) {
1338                     /* Try again. */
1339 #if defined(DEBUGGING_MSTATS)
1340                     sbrk_slack += require;
1341 #endif
1342                     require = needed;
1343                     DEBUG_m(PerlIO_printf(Perl_debug_log, 
1344                                           "straight sbrk(%ld)\n",
1345                                           (long)require));
1346                     cp = (char *)sbrk(require);
1347 #ifdef DEBUGGING_MSTATS
1348                     sbrks++;
1349 #endif 
1350                     if (cp == (char *)-1)
1351                         return 0;
1352                 }
1353                 sbrk_good = -1; /* Disable optimization!
1354                                    Continue with not-aligned... */
1355             } else {
1356                 cp += slack;
1357                 require += sbrked_remains;
1358             }
1359         }
1360
1361         if (last_sbrk_top) {
1362             sbrk_good -= SBRK_FAILURE_PRICE;
1363         }
1364
1365         ovp = (union overhead *) cp;
1366         /*
1367          * Round up to minimum allocation size boundary
1368          * and deduct from block count to reflect.
1369          */
1370
1371 #  if NEEDED_ALIGNMENT > MEM_ALIGNBYTES
1372         if (PTR2UV(ovp) & (NEEDED_ALIGNMENT - 1))
1373             fatalcroak("Misalignment of sbrk()\n");
1374         else
1375 #  endif
1376 #ifndef I286    /* Again, this should always be ok on an 80286 */
1377         if (PTR2UV(ovp) & (MEM_ALIGNBYTES - 1)) {
1378             DEBUG_m(PerlIO_printf(Perl_debug_log, 
1379                                   "fixing sbrk(): %d bytes off machine alignement\n",
1380                                   (int)(PTR2UV(ovp) & (MEM_ALIGNBYTES - 1))));
1381             ovp = INT2PTR(union overhead *,(PTR2UV(ovp) + MEM_ALIGNBYTES) &
1382                                      (MEM_ALIGNBYTES - 1));
1383             (*nblksp)--;
1384 # if defined(DEBUGGING_MSTATS)
1385             /* This is only approx. if TWO_POT_OPTIMIZE: */
1386             sbrk_slack += (1 << (bucket >> BUCKET_POW2_SHIFT));
1387 # endif
1388         }
1389 #endif
1390         ;                               /* Finish `else' */
1391         sbrked_remains = require - needed;
1392         last_op = cp;
1393     }
1394     no_mem = 0;
1395     last_sbrk_top = cp + require;
1396 #ifdef DEBUGGING_MSTATS
1397     goodsbrk += require;
1398 #endif  
1399     return ovp;
1400 }
1401
1402 static int
1403 getpages_adjacent(MEM_SIZE require)
1404 {           
1405     if (require <= sbrked_remains) {
1406         sbrked_remains -= require;
1407     } else {
1408         char *cp;
1409
1410         require -= sbrked_remains;
1411         /* We do not try to optimize sbrks here, we go for place. */
1412         cp = (char*) sbrk(require);
1413 #ifdef DEBUGGING_MSTATS
1414         sbrks++;
1415         goodsbrk += require;
1416 #endif 
1417         if (cp == last_sbrk_top) {
1418             sbrked_remains = 0;
1419             last_sbrk_top = cp + require;
1420         } else {
1421             if (cp == (char*)-1) {      /* Out of memory */
1422 #ifdef DEBUGGING_MSTATS
1423                 goodsbrk -= require;
1424 #endif
1425                 return 0;
1426             }
1427             /* Report the failure: */
1428             if (sbrked_remains)
1429                 add_to_chain((void*)(last_sbrk_top - sbrked_remains),
1430                              sbrked_remains, 0);
1431             add_to_chain((void*)cp, require, 0);
1432             sbrk_good -= SBRK_FAILURE_PRICE;
1433             sbrked_remains = 0;
1434             last_sbrk_top = 0;
1435             last_op = 0;
1436             return 0;
1437         }
1438     }
1439             
1440     return 1;
1441 }
1442
1443 /*
1444  * Allocate more memory to the indicated bucket.
1445  */
1446 static void
1447 morecore(register int bucket)
1448 {
1449         register union overhead *ovp;
1450         register int rnu;       /* 2^rnu bytes will be requested */
1451         int nblks;              /* become nblks blocks of the desired size */
1452         register MEM_SIZE siz, needed;
1453
1454         if (nextf[bucket])
1455                 return;
1456         if (bucket == sizeof(MEM_SIZE)*8*BUCKETS_PER_POW2) {
1457             MALLOC_UNLOCK;
1458             croak("%s", "Out of memory during ridiculously large request");
1459         }
1460         if (bucket > max_bucket)
1461             max_bucket = bucket;
1462
1463         rnu = ( (bucket <= (LOG_OF_MIN_ARENA << BUCKET_POW2_SHIFT)) 
1464                 ? LOG_OF_MIN_ARENA 
1465                 : (bucket >> BUCKET_POW2_SHIFT) );
1466         /* This may be overwritten later: */
1467         nblks = 1 << (rnu - (bucket >> BUCKET_POW2_SHIFT)); /* how many blocks to get */
1468         needed = ((MEM_SIZE)1 << rnu) + POW2_OPTIMIZE_SURPLUS(bucket);
1469         if (nextf[rnu << BUCKET_POW2_SHIFT]) { /* 2048b bucket. */
1470             ovp = nextf[rnu << BUCKET_POW2_SHIFT] - 1 + CHUNK_SHIFT;
1471             nextf[rnu << BUCKET_POW2_SHIFT]
1472                 = nextf[rnu << BUCKET_POW2_SHIFT]->ov_next;
1473 #ifdef DEBUGGING_MSTATS
1474             nmalloc[rnu << BUCKET_POW2_SHIFT]--;
1475             start_slack -= M_OVERHEAD;
1476 #endif 
1477             DEBUG_m(PerlIO_printf(Perl_debug_log, 
1478                                   "stealing %ld bytes from %ld arena\n",
1479                                   (long) needed, (long) rnu << BUCKET_POW2_SHIFT));
1480         } else if (chunk_chain 
1481                    && (ovp = (union overhead*) get_from_chain(needed))) {
1482             DEBUG_m(PerlIO_printf(Perl_debug_log, 
1483                                   "stealing %ld bytes from chain\n",
1484                                   (long) needed));
1485         } else if ( (ovp = (union overhead*)
1486                      get_from_bigger_buckets((rnu << BUCKET_POW2_SHIFT) + 1,
1487                                              needed)) ) {
1488             DEBUG_m(PerlIO_printf(Perl_debug_log, 
1489                                   "stealing %ld bytes from bigger buckets\n",
1490                                   (long) needed));
1491         } else if (needed <= sbrked_remains) {
1492             ovp = (union overhead *)(last_sbrk_top - sbrked_remains);
1493             sbrked_remains -= needed;
1494             last_op = (char*)ovp;
1495         } else 
1496             ovp = getpages(needed, &nblks, bucket);
1497
1498         if (!ovp)
1499             return;
1500
1501         /*
1502          * Add new memory allocated to that on
1503          * free list for this hash bucket.
1504          */
1505         siz = BUCKET_SIZE(bucket);
1506 #ifdef PACK_MALLOC
1507         *(u_char*)ovp = bucket; /* Fill index. */
1508         if (bucket <= MAX_PACKED) {
1509             ovp = (union overhead *) ((char*)ovp + BLK_SHIFT(bucket));
1510             nblks = N_BLKS(bucket);
1511 #  ifdef DEBUGGING_MSTATS
1512             start_slack += BLK_SHIFT(bucket);
1513 #  endif
1514         } else if (bucket < LOG_OF_MIN_ARENA * BUCKETS_PER_POW2) {
1515             ovp = (union overhead *) ((char*)ovp + BLK_SHIFT(bucket));
1516             siz -= sizeof(union overhead);
1517         } else ovp++;           /* One chunk per block. */
1518 #endif /* PACK_MALLOC */
1519         nextf[bucket] = ovp;
1520 #ifdef DEBUGGING_MSTATS
1521         nmalloc[bucket] += nblks;
1522         if (bucket > MAX_PACKED) {
1523             start_slack += M_OVERHEAD * nblks;
1524         }
1525 #endif 
1526         while (--nblks > 0) {
1527                 ovp->ov_next = (union overhead *)((caddr_t)ovp + siz);
1528                 ovp = (union overhead *)((caddr_t)ovp + siz);
1529         }
1530         /* Not all sbrks return zeroed memory.*/
1531         ovp->ov_next = (union overhead *)NULL;
1532 #ifdef PACK_MALLOC
1533         if (bucket == 7*BUCKETS_PER_POW2) { /* Special case, explanation is above. */
1534             union overhead *n_op = nextf[7*BUCKETS_PER_POW2]->ov_next;
1535             nextf[7*BUCKETS_PER_POW2] = 
1536                 (union overhead *)((caddr_t)nextf[7*BUCKETS_PER_POW2] 
1537                                    - sizeof(union overhead));
1538             nextf[7*BUCKETS_PER_POW2]->ov_next = n_op;
1539         }
1540 #endif /* !PACK_MALLOC */
1541 }
1542
1543 Free_t
1544 Perl_mfree(void *mp)
1545 {
1546         register MEM_SIZE size;
1547         register union overhead *ovp;
1548         char *cp = (char*)mp;
1549 #ifdef PACK_MALLOC
1550         u_char bucket;
1551 #endif 
1552
1553         DEBUG_m(PerlIO_printf(Perl_debug_log, 
1554                               "0x%"UVxf": (%05lu) free\n",
1555                               PTR2UV(cp), (unsigned long)(PL_an++)));
1556
1557         if (cp == NULL)
1558                 return;
1559         ovp = (union overhead *)((caddr_t)cp 
1560                                 - sizeof (union overhead) * CHUNK_SHIFT);
1561 #ifdef PACK_MALLOC
1562         bucket = OV_INDEX(ovp);
1563 #endif 
1564 #ifdef IGNORE_SMALL_BAD_FREE
1565         if ((bucket >= FIRST_BUCKET_WITH_CHECK) 
1566             && (OV_MAGIC(ovp, bucket) != MAGIC))
1567 #else
1568         if (OV_MAGIC(ovp, bucket) != MAGIC)
1569 #endif 
1570             {
1571                 static int bad_free_warn = -1;
1572                 if (bad_free_warn == -1) {
1573                     dTHX;
1574                     char *pbf = PerlEnv_getenv("PERL_BADFREE");
1575                     bad_free_warn = (pbf) ? atoi(pbf) : 1;
1576                 }
1577                 if (!bad_free_warn)
1578                     return;
1579 #ifdef RCHECK
1580 #ifdef PERL_CORE
1581                 {
1582                     dTHX;
1583                     if (!PERL_IS_ALIVE || !PL_curcop || ckWARN_d(WARN_MALLOC))
1584                         Perl_warner(aTHX_ WARN_MALLOC, "%s free() ignored",
1585                                     ovp->ov_rmagic == RMAGIC - 1 ?
1586                                     "Duplicate" : "Bad");
1587                 }
1588 #else
1589                 warn("%s free() ignored",
1590                     ovp->ov_rmagic == RMAGIC - 1 ? "Duplicate" : "Bad");
1591 #endif          
1592 #else
1593 #ifdef PERL_CORE
1594                 {
1595                     dTHX;
1596                     if (!PERL_IS_ALIVE || !PL_curcop || ckWARN_d(WARN_MALLOC))
1597                         Perl_warner(aTHX_ WARN_MALLOC, "%s", "Bad free() ignored");
1598                 }
1599 #else
1600                 warn("%s", "Bad free() ignored");
1601 #endif
1602 #endif
1603                 return;                         /* sanity */
1604             }
1605 #ifdef RCHECK
1606         ASSERT(ovp->ov_rmagic == RMAGIC, "chunk's head overwrite");
1607         if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET) {
1608             int i;
1609             MEM_SIZE nbytes = ovp->ov_size + 1;
1610
1611             if ((i = nbytes & 3)) {
1612                 i = 4 - i;
1613                 while (i--) {
1614                     ASSERT(*((char *)((caddr_t)ovp + nbytes - RSLOP + i))
1615                            == RMAGIC_C, "chunk's tail overwrite");
1616                 }
1617             }
1618             nbytes = (nbytes + 3) &~ 3; 
1619             ASSERT(*(u_int *)((caddr_t)ovp + nbytes - RSLOP) == RMAGIC, "chunk's tail overwrite");          
1620         }
1621         ovp->ov_rmagic = RMAGIC - 1;
1622 #endif
1623         ASSERT(OV_INDEX(ovp) < NBUCKETS, "chunk's head overwrite");
1624         size = OV_INDEX(ovp);
1625
1626         MALLOC_LOCK;
1627         ovp->ov_next = nextf[size];
1628         nextf[size] = ovp;
1629         MALLOC_UNLOCK;
1630 }
1631
1632 /* There is no need to do any locking in realloc (with an exception of
1633    trying to grow in place if we are at the end of the chain).
1634    If somebody calls us from a different thread with the same address,
1635    we are sole anyway.  */
1636
1637 Malloc_t
1638 Perl_realloc(void *mp, size_t nbytes)
1639 {
1640         register MEM_SIZE onb;
1641         union overhead *ovp;
1642         char *res;
1643         int prev_bucket;
1644         register int bucket;
1645         int incr;               /* 1 if does not fit, -1 if "easily" fits in a
1646                                    smaller bucket, otherwise 0.  */
1647         char *cp = (char*)mp;
1648
1649 #if defined(DEBUGGING) || !defined(PERL_CORE)
1650         MEM_SIZE size = nbytes;
1651
1652         if ((long)nbytes < 0)
1653             croak("%s", "panic: realloc");
1654 #endif
1655
1656         BARK_64K_LIMIT("Reallocation",nbytes,size);
1657         if (!cp)
1658                 return Perl_malloc(nbytes);
1659
1660         ovp = (union overhead *)((caddr_t)cp 
1661                                 - sizeof (union overhead) * CHUNK_SHIFT);
1662         bucket = OV_INDEX(ovp);
1663
1664 #ifdef IGNORE_SMALL_BAD_FREE
1665         if ((bucket >= FIRST_BUCKET_WITH_CHECK) 
1666             && (OV_MAGIC(ovp, bucket) != MAGIC))
1667 #else
1668         if (OV_MAGIC(ovp, bucket) != MAGIC)
1669 #endif 
1670             {
1671                 static int bad_free_warn = -1;
1672                 if (bad_free_warn == -1) {
1673                     dTHX;
1674                     char *pbf = PerlEnv_getenv("PERL_BADFREE");
1675                     bad_free_warn = (pbf) ? atoi(pbf) : 1;
1676                 }
1677                 if (!bad_free_warn)
1678                     return Nullch;
1679 #ifdef RCHECK
1680 #ifdef PERL_CORE
1681                 {
1682                     dTHX;
1683                     if (!PERL_IS_ALIVE || !PL_curcop || ckWARN_d(WARN_MALLOC))
1684                         Perl_warner(aTHX_ WARN_MALLOC, "%srealloc() %signored",
1685                                     (ovp->ov_rmagic == RMAGIC - 1 ? "" : "Bad "),
1686                                     ovp->ov_rmagic == RMAGIC - 1
1687                                     ? "of freed memory " : "");
1688                 }
1689 #else
1690                 warn("%srealloc() %signored",
1691                     (ovp->ov_rmagic == RMAGIC - 1 ? "" : "Bad "),
1692                      ovp->ov_rmagic == RMAGIC - 1 ? "of freed memory " : "");
1693 #endif
1694 #else
1695 #ifdef PERL_CORE
1696                 {
1697                     dTHX;
1698                     if (!PERL_IS_ALIVE || !PL_curcop || ckWARN_d(WARN_MALLOC))
1699                         Perl_warner(aTHX_ WARN_MALLOC, "%s",
1700                                     "Bad realloc() ignored");
1701                 }
1702 #else
1703                 warn("%s", "Bad realloc() ignored");
1704 #endif
1705 #endif
1706                 return Nullch;                  /* sanity */
1707             }
1708
1709         onb = BUCKET_SIZE_REAL(bucket);
1710         /* 
1711          *  avoid the copy if same size block.
1712          *  We are not agressive with boundary cases. Note that it might
1713          *  (for a small number of cases) give false negative if
1714          *  both new size and old one are in the bucket for
1715          *  FIRST_BIG_POW2, but the new one is near the lower end.
1716          *
1717          *  We do not try to go to 1.5 times smaller bucket so far.
1718          */
1719         if (nbytes > onb) incr = 1;
1720         else {
1721 #ifdef DO_NOT_TRY_HARDER_WHEN_SHRINKING
1722             if ( /* This is a little bit pessimal if PACK_MALLOC: */
1723                 nbytes > ( (onb >> 1) - M_OVERHEAD )
1724 #  ifdef TWO_POT_OPTIMIZE
1725                 || (bucket == FIRST_BIG_POW2 && nbytes >= LAST_SMALL_BOUND )
1726 #  endif        
1727                 )
1728 #else  /* !DO_NOT_TRY_HARDER_WHEN_SHRINKING */
1729                 prev_bucket = ( (bucket > MAX_PACKED + 1) 
1730                                 ? bucket - BUCKETS_PER_POW2
1731                                 : bucket - 1);
1732              if (nbytes > BUCKET_SIZE_REAL(prev_bucket))
1733 #endif /* !DO_NOT_TRY_HARDER_WHEN_SHRINKING */
1734                  incr = 0;
1735              else incr = -1;
1736         }
1737 #ifdef STRESS_REALLOC
1738         goto hard_way;
1739 #endif
1740         if (incr == 0) {
1741           inplace_label:
1742 #ifdef RCHECK
1743                 /*
1744                  * Record new allocated size of block and
1745                  * bound space with magic numbers.
1746                  */
1747                 if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET) {
1748                        int i, nb = ovp->ov_size + 1;
1749
1750                        if ((i = nb & 3)) {
1751                            i = 4 - i;
1752                            while (i--) {
1753                                ASSERT(*((char *)((caddr_t)ovp + nb - RSLOP + i)) == RMAGIC_C, "chunk's tail overwrite");
1754                            }
1755                        }
1756                        nb = (nb + 3) &~ 3; 
1757                        ASSERT(*(u_int *)((caddr_t)ovp + nb - RSLOP) == RMAGIC, "chunk's tail overwrite");
1758                         /*
1759                          * Convert amount of memory requested into
1760                          * closest block size stored in hash buckets
1761                          * which satisfies request.  Account for
1762                          * space used per block for accounting.
1763                          */
1764                         nbytes += M_OVERHEAD;
1765                         ovp->ov_size = nbytes - 1;
1766                         if ((i = nbytes & 3)) {
1767                             i = 4 - i;
1768                             while (i--)
1769                                 *((char *)((caddr_t)ovp + nbytes - RSLOP + i))
1770                                     = RMAGIC_C;
1771                         }
1772                         nbytes = (nbytes + 3) &~ 3; 
1773                         *((u_int *)((caddr_t)ovp + nbytes - RSLOP)) = RMAGIC;
1774                 }
1775 #endif
1776                 res = cp;
1777                 DEBUG_m(PerlIO_printf(Perl_debug_log, 
1778                               "0x%"UVxf": (%05lu) realloc %ld bytes inplace\n",
1779                               PTR2UV(res),(unsigned long)(PL_an++),
1780                               (long)size));
1781         } else if (incr == 1 && (cp - M_OVERHEAD == last_op) 
1782                    && (onb > (1 << LOG_OF_MIN_ARENA))) {
1783             MEM_SIZE require, newarena = nbytes, pow;
1784             int shiftr;
1785
1786             POW2_OPTIMIZE_ADJUST(newarena);
1787             newarena = newarena + M_OVERHEAD;
1788             /* newarena = (newarena + 3) &~ 3; */
1789             shiftr = (newarena - 1) >> LOG_OF_MIN_ARENA;
1790             pow = LOG_OF_MIN_ARENA + 1;
1791             /* apart from this loop, this is O(1) */
1792             while (shiftr >>= 1)
1793                 pow++;
1794             newarena = (1 << pow) + POW2_OPTIMIZE_SURPLUS(pow * BUCKETS_PER_POW2);
1795             require = newarena - onb - M_OVERHEAD;
1796             
1797             MALLOC_LOCK;
1798             if (cp - M_OVERHEAD == last_op /* We *still* are the last chunk */
1799                 && getpages_adjacent(require)) {
1800 #ifdef DEBUGGING_MSTATS
1801                 nmalloc[bucket]--;
1802                 nmalloc[pow * BUCKETS_PER_POW2]++;
1803 #endif      
1804                 *(cp - M_OVERHEAD) = pow * BUCKETS_PER_POW2; /* Fill index. */
1805                 MALLOC_UNLOCK;
1806                 goto inplace_label;
1807             } else {
1808                 MALLOC_UNLOCK;          
1809                 goto hard_way;
1810             }
1811         } else {
1812           hard_way:
1813             DEBUG_m(PerlIO_printf(Perl_debug_log, 
1814                               "0x%"UVxf": (%05lu) realloc %ld bytes the hard way\n",
1815                               PTR2UV(cp),(unsigned long)(PL_an++),
1816                               (long)size));
1817             if ((res = (char*)Perl_malloc(nbytes)) == NULL)
1818                 return (NULL);
1819             if (cp != res)                      /* common optimization */
1820                 Copy(cp, res, (MEM_SIZE)(nbytes<onb?nbytes:onb), char);
1821             Perl_mfree(cp);
1822         }
1823         return ((Malloc_t)res);
1824 }
1825
1826 Malloc_t
1827 Perl_calloc(register size_t elements, register size_t size)
1828 {
1829     long sz = elements * size;
1830     Malloc_t p = Perl_malloc(sz);
1831
1832     if (p) {
1833         memset((void*)p, 0, sz);
1834     }
1835     return p;
1836 }
1837
1838 char *
1839 Perl_strdup(const char *s)
1840 {
1841     MEM_SIZE l = strlen(s);
1842     char *s1 = (char *)Perl_malloc(l+1);
1843
1844     Copy(s, s1, (MEM_SIZE)(l+1), char);
1845     return s1;
1846 }
1847
1848 #ifdef PERL_CORE
1849 int
1850 Perl_putenv(char *a)
1851 {
1852     /* Sometimes system's putenv conflicts with my_setenv() - this is system
1853        malloc vs Perl's free(). */
1854   dTHX;
1855   char *var;
1856   char *val = a;
1857   MEM_SIZE l;
1858   char buf[80];
1859
1860   while (*val && *val != '=')
1861       val++;
1862   if (!*val)
1863       return -1;
1864   l = val - a;
1865   if (l < sizeof(buf))
1866       var = buf;
1867   else
1868       var = Perl_malloc(l + 1);
1869   Copy(a, var, l, char);
1870   var[l + 1] = 0;
1871   my_setenv(var, val+1);
1872   if (var != buf)
1873       Perl_mfree(var);
1874   return 0;
1875 }
1876 #  endif
1877
1878 MEM_SIZE
1879 Perl_malloced_size(void *p)
1880 {
1881     union overhead *ovp = (union overhead *)
1882         ((caddr_t)p - sizeof (union overhead) * CHUNK_SHIFT);
1883     int bucket = OV_INDEX(ovp);
1884 #ifdef RCHECK
1885     /* The caller wants to have a complete control over the chunk,
1886        disable the memory checking inside the chunk.  */
1887     if (bucket <= MAX_SHORT_BUCKET) {
1888         MEM_SIZE size = BUCKET_SIZE_REAL(bucket);
1889         ovp->ov_size = size + M_OVERHEAD - 1;
1890         *((u_int *)((caddr_t)ovp + size + M_OVERHEAD - RSLOP)) = RMAGIC;
1891     }
1892 #endif
1893     return BUCKET_SIZE_REAL(bucket);
1894 }
1895
1896 #  ifdef BUCKETS_ROOT2
1897 #    define MIN_EVEN_REPORT 6
1898 #  else
1899 #    define MIN_EVEN_REPORT MIN_BUCKET
1900 #  endif 
1901
1902 int
1903 Perl_get_mstats(pTHX_ perl_mstats_t *buf, int buflen, int level)
1904 {
1905 #ifdef DEBUGGING_MSTATS
1906         register int i, j;
1907         register union overhead *p;
1908         struct chunk_chain_s* nextchain;
1909
1910         buf->topbucket = buf->topbucket_ev = buf->topbucket_odd 
1911             = buf->totfree = buf->total = buf->total_chain = 0;
1912
1913         buf->minbucket = MIN_BUCKET;
1914         MALLOC_LOCK;
1915         for (i = MIN_BUCKET ; i < NBUCKETS; i++) {
1916                 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
1917                         ;
1918                 if (i < buflen) {
1919                     buf->nfree[i] = j;
1920                     buf->ntotal[i] = nmalloc[i];
1921                 }               
1922                 buf->totfree += j * BUCKET_SIZE_REAL(i);
1923                 buf->total += nmalloc[i] * BUCKET_SIZE_REAL(i);
1924                 if (nmalloc[i]) {
1925                     i % 2 ? (buf->topbucket_odd = i) : (buf->topbucket_ev = i);
1926                     buf->topbucket = i;
1927                 }
1928         }
1929         nextchain = chunk_chain;
1930         while (nextchain) {
1931             buf->total_chain += nextchain->size;
1932             nextchain = nextchain->next;
1933         }
1934         buf->total_sbrk = goodsbrk + sbrk_slack;
1935         buf->sbrks = sbrks;
1936         buf->sbrk_good = sbrk_good;
1937         buf->sbrk_slack = sbrk_slack;
1938         buf->start_slack = start_slack;
1939         buf->sbrked_remains = sbrked_remains;
1940         MALLOC_UNLOCK;
1941         buf->nbuckets = NBUCKETS;
1942         if (level) {
1943             for (i = MIN_BUCKET ; i < NBUCKETS; i++) {
1944                 if (i >= buflen)
1945                     break;
1946                 buf->bucket_mem_size[i] = BUCKET_SIZE(i);
1947                 buf->bucket_available_size[i] = BUCKET_SIZE_REAL(i);
1948             }
1949         }
1950 #endif  /* defined DEBUGGING_MSTATS */
1951         return 0;               /* XXX unused */
1952 }
1953 /*
1954  * mstats - print out statistics about malloc
1955  * 
1956  * Prints two lines of numbers, one showing the length of the free list
1957  * for each size category, the second showing the number of mallocs -
1958  * frees for each size category.
1959  */
1960 void
1961 Perl_dump_mstats(pTHX_ char *s)
1962 {
1963 #ifdef DEBUGGING_MSTATS
1964         register int i;
1965         perl_mstats_t buffer;
1966         UV nf[NBUCKETS];
1967         UV nt[NBUCKETS];
1968
1969         buffer.nfree  = nf;
1970         buffer.ntotal = nt;
1971         get_mstats(&buffer, NBUCKETS, 0);
1972
1973         if (s)
1974             PerlIO_printf(Perl_error_log,
1975                           "Memory allocation statistics %s (buckets %"IVdf"(%"IVdf")..%"IVdf"(%"IVdf")\n",
1976                           s, 
1977                           (IV)BUCKET_SIZE_REAL(MIN_BUCKET), 
1978                           (IV)BUCKET_SIZE(MIN_BUCKET),
1979                           (IV)BUCKET_SIZE_REAL(buffer.topbucket), 
1980                           (IV)BUCKET_SIZE(buffer.topbucket));
1981         PerlIO_printf(Perl_error_log, "%8"IVdf" free:", buffer.totfree);
1982         for (i = MIN_EVEN_REPORT; i <= buffer.topbucket; i += BUCKETS_PER_POW2) {
1983                 PerlIO_printf(Perl_error_log, 
1984                               ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1985                                ? " %5"UVuf 
1986                                : ((i < 12*BUCKETS_PER_POW2) ? " %3"UVuf : " %"UVuf)),
1987                               buffer.nfree[i]);
1988         }
1989 #ifdef BUCKETS_ROOT2
1990         PerlIO_printf(Perl_error_log, "\n\t   ");
1991         for (i = MIN_BUCKET + 1; i <= buffer.topbucket_odd; i += BUCKETS_PER_POW2) {
1992                 PerlIO_printf(Perl_error_log, 
1993                               ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
1994                                ? " %5"UVuf 
1995                                : ((i < 12*BUCKETS_PER_POW2) ? " %3"UVuf : " %"UVuf)),
1996                               buffer.nfree[i]);
1997         }
1998 #endif 
1999         PerlIO_printf(Perl_error_log, "\n%8"IVdf" used:", buffer.total - buffer.totfree);
2000         for (i = MIN_EVEN_REPORT; i <= buffer.topbucket; i += BUCKETS_PER_POW2) {
2001                 PerlIO_printf(Perl_error_log, 
2002                               ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
2003                                ? " %5"IVdf
2004                                : ((i < 12*BUCKETS_PER_POW2) ? " %3"IVdf : " %"IVdf)), 
2005                               buffer.ntotal[i] - buffer.nfree[i]);
2006         }
2007 #ifdef BUCKETS_ROOT2
2008         PerlIO_printf(Perl_error_log, "\n\t   ");
2009         for (i = MIN_BUCKET + 1; i <= buffer.topbucket_odd; i += BUCKETS_PER_POW2) {
2010                 PerlIO_printf(Perl_error_log, 
2011                               ((i < 8*BUCKETS_PER_POW2 || i == 10*BUCKETS_PER_POW2)
2012                                ? " %5"IVdf 
2013                                : ((i < 12*BUCKETS_PER_POW2) ? " %3"IVdf : " %"IVdf)),
2014                               buffer.ntotal[i] - buffer.nfree[i]);
2015         }
2016 #endif 
2017         PerlIO_printf(Perl_error_log, "\nTotal sbrk(): %"IVdf"/%"IVdf":%"IVdf". Odd ends: pad+heads+chain+tail: %"IVdf"+%"IVdf"+%"IVdf"+%"IVdf".\n",
2018                       buffer.total_sbrk, buffer.sbrks, buffer.sbrk_good,
2019                       buffer.sbrk_slack, buffer.start_slack,
2020                       buffer.total_chain, buffer.sbrked_remains);
2021 #endif /* DEBUGGING_MSTATS */
2022 }
2023 #endif /* lint */
2024
2025 #ifdef USE_PERL_SBRK
2026
2027 #   if defined(__MACHTEN_PPC__) || defined(NeXT) || defined(__NeXT__) || defined(PURIFY)
2028 #      define PERL_SBRK_VIA_MALLOC
2029 #   endif
2030
2031 #   ifdef PERL_SBRK_VIA_MALLOC
2032
2033 /* it may seem schizophrenic to use perl's malloc and let it call system */
2034 /* malloc, the reason for that is only the 3.2 version of the OS that had */
2035 /* frequent core dumps within nxzonefreenolock. This sbrk routine put an */
2036 /* end to the cores */
2037
2038 #      ifndef SYSTEM_ALLOC
2039 #         define SYSTEM_ALLOC(a) malloc(a)
2040 #      endif
2041 #      ifndef SYSTEM_ALLOC_ALIGNMENT
2042 #         define SYSTEM_ALLOC_ALIGNMENT MEM_ALIGNBYTES
2043 #      endif
2044
2045 #   endif  /* PERL_SBRK_VIA_MALLOC */
2046
2047 static IV Perl_sbrk_oldchunk;
2048 static long Perl_sbrk_oldsize;
2049
2050 #   define PERLSBRK_32_K (1<<15)
2051 #   define PERLSBRK_64_K (1<<16)
2052
2053 Malloc_t
2054 Perl_sbrk(int size)
2055 {
2056     IV got;
2057     int small, reqsize;
2058
2059     if (!size) return 0;
2060 #ifdef PERL_CORE
2061     reqsize = size; /* just for the DEBUG_m statement */
2062 #endif
2063 #ifdef PACK_MALLOC
2064     size = (size + 0x7ff) & ~0x7ff;
2065 #endif
2066     if (size <= Perl_sbrk_oldsize) {
2067         got = Perl_sbrk_oldchunk;
2068         Perl_sbrk_oldchunk += size;
2069         Perl_sbrk_oldsize -= size;
2070     } else {
2071       if (size >= PERLSBRK_32_K) {
2072         small = 0;
2073       } else {
2074         size = PERLSBRK_64_K;
2075         small = 1;
2076       }
2077 #  if NEEDED_ALIGNMENT > SYSTEM_ALLOC_ALIGNMENT
2078       size += NEEDED_ALIGNMENT - SYSTEM_ALLOC_ALIGNMENT;
2079 #  endif
2080       got = (IV)SYSTEM_ALLOC(size);
2081 #  if NEEDED_ALIGNMENT > SYSTEM_ALLOC_ALIGNMENT
2082       got = (got + NEEDED_ALIGNMENT - 1) & ~(NEEDED_ALIGNMENT - 1);
2083 #  endif
2084       if (small) {
2085         /* Chunk is small, register the rest for future allocs. */
2086         Perl_sbrk_oldchunk = got + reqsize;
2087         Perl_sbrk_oldsize = size - reqsize;
2088       }
2089     }
2090
2091     DEBUG_m(PerlIO_printf(Perl_debug_log, "sbrk malloc size %ld (reqsize %ld), left size %ld, give addr 0x%"UVxf"\n",
2092                     size, reqsize, Perl_sbrk_oldsize, PTR2UV(got)));
2093
2094     return (void *)got;
2095 }
2096
2097 #endif /* ! defined USE_PERL_SBRK */