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