6 * 'The Chamber of Records,' said Gimli. 'I guess that is where we now stand.'
8 * [p.321 of _The Lord of the Rings_, II/v: "The Bridge of Khazad-Dûm"]
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.
18 Here are some notes on configuring Perl's malloc. (For non-perl
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.
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).
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.
38 # Read configuration settings from malloc_cfg.h
39 HAVE_MALLOC_CFG_H undef
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))
45 # Enable code for printing memory statistics.
46 DEBUGGING_MSTATS (!PLAIN_MALLOC && PERL_CORE)
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)
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
57 TWO_POT_OPTIMIZE !PLAIN_MALLOC
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
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)
67 # Use table lookup to decide in which bucket a given allocation will go.
68 SMALL_BUCKET_VIA_TABLE !NO_FANCY_MALLOC
70 # Use a perl-defined sbrk() instead of the (presumably broken or
71 # missing) system-supplied sbrk().
74 # Use system malloc() (or calloc() etc.) to emulate sbrk(). Normally
75 # only used with broken sbrk()s.
76 PERL_SBRK_VIA_MALLOC undef
78 # Which allocator to use if PERL_SBRK_VIA_MALLOC
79 SYSTEM_ALLOC(a) malloc(a)
81 # Minimal alignment (in bytes, should be a power of 2) of SYSTEM_ALLOC
82 SYSTEM_ALLOC_ALIGNMENT MEM_ALIGNBYTES
84 # Disable memory overwrite checking with DEBUGGING. Memory and speed
85 # optimization, error reporting pessimization.
88 # Enable memory overwrite checking with DEBUGGING. Memory and speed
89 # pessimization, error reporting optimization
90 RCHECK (DEBUGGING && !NO_RCHECK)
92 # Do not overwrite uninit areas with DEBUGGING. Speed
93 # optimization, error reporting pessimization
96 # Overwrite uninit areas with DEBUGGING. Speed
97 # pessimization, error reporting optimization
98 MALLOC_FILL (DEBUGGING && !NO_RCHECK && !NO_MFILL)
100 # Do not check overwritten uninit areas with DEBUGGING. Speed
101 # optimization, error reporting pessimization
104 # Check overwritten uninit areas with DEBUGGING. Speed
105 # pessimization, error reporting optimization
106 MALLOC_FILL_CHECK (DEBUGGING && !NO_RCHECK && !NO_FILL_CHECK)
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
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
118 # Estimate of minimal memory footprint. malloc uses this value to
119 # request the most reasonable largest blocks of memory from the system.
122 # Round up sbrk()s to multiples of this.
125 # Round up sbrk()s to multiples of this percent of footprint.
128 # Round up sbrk()s to multiples of this multiple of 1/1000 of footprint.
129 MIN_SBRK_FRAC1000 (10 * MIN_SBRK_FRAC)
131 # Add this much memory to big powers of two to get the bucket size.
134 # This many sbrk() discontinuities should be tolerated even
135 # from the start without deciding that sbrk() is usually
137 SBRK_ALLOW_FAILURES 3
139 # This many continuous sbrk()s compensate for one discontinuous one.
140 SBRK_FAILURE_PRICE 50
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
147 # Do not allow configuration of runtime options at runtime
148 NO_MALLOC_DYNAMIC_CFG undef
150 # Do not allow configuration of runtime options via $ENV{PERL_MALLOC_OPT}
151 NO_PERL_MALLOC_ENV undef
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.]
161 This implementation assumes that calling PerlIO_printf() does not
162 result in any memory allocation calls (used during a panic).
167 If used outside of Perl environment, it may be useful to redefine
168 the following macros (listed below with defaults):
170 # Type of address returned by allocation functions
173 # Type of size argument for allocation functions
174 MEM_SIZE unsigned long
179 # Maximal value in LONG
182 # Unsigned integer type big enough to keep a pointer
185 # Signed integer of the same sizeof() as UV
188 # Type of pointer with 1-byte granularity
191 # Type returned by free()
194 # Conversion of pointer to integer
195 PTR2UV(ptr) ((UV)(ptr))
197 # Conversion of integer to pointer
198 INT2PTR(type, i) ((type)(i))
200 # printf()-%-Conversion of UV to pointer
203 # printf()-%-Conversion of UV to hex pointer
209 # Very fatal condition reporting function (cannot call any )
210 fatalcroak(arg) write(2,arg,strlen(arg)) + exit(2)
212 # Fatal error reporting function
213 croak(format, arg) warn(idem) + exit(1)
215 # Fatal error reporting function
216 croak2(format, arg1, arg2) warn2(idem) + exit(1)
218 # Error reporting function
219 warn(format, arg) fprintf(stderr, idem)
221 # Error reporting function
222 warn2(format, arg1, arg2) fprintf(stderr, idem)
224 # Locking/unlocking for MT operation
225 MALLOC_LOCK MUTEX_LOCK(&PL_malloc_mutex)
226 MALLOC_UNLOCK MUTEX_UNLOCK(&PL_malloc_mutex)
228 # Locking/unlocking mutex for MT operation
233 #ifdef HAVE_MALLOC_CFG_H
234 # include "malloc_cfg.h"
237 #ifndef NO_FANCY_MALLOC
238 # ifndef SMALL_BUCKET_VIA_TABLE
239 # define SMALL_BUCKET_VIA_TABLE
241 # ifndef BUCKETS_ROOT2
242 # define BUCKETS_ROOT2
244 # ifndef IGNORE_SMALL_BAD_FREE
245 # define IGNORE_SMALL_BAD_FREE
249 #ifndef PLAIN_MALLOC /* Bulk enable features */
253 # ifndef TWO_POT_OPTIMIZE
254 # define TWO_POT_OPTIMIZE
256 # if (defined(PERL_CORE) || !defined(NO_MALLOC_DYNAMIC_CFG)) && !defined(PERL_EMERGENCY_SBRK)
257 # define PERL_EMERGENCY_SBRK
259 # if defined(PERL_CORE) && !defined(DEBUGGING_MSTATS)
260 # define DEBUGGING_MSTATS
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)
267 #if !(defined(I286) || defined(atarist))
268 /* take 2k unless the block is bigger than that */
269 # define LOG_OF_MIN_ARENA 11
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
276 #if defined(DEBUGGING) && !defined(NO_RCHECK)
279 #if defined(DEBUGGING) && !defined(NO_RCHECK) && !defined(NO_MFILL) && !defined(MALLOC_FILL)
282 #if defined(DEBUGGING) && !defined(NO_RCHECK) && !defined(NO_FILL_CHECK) && !defined(MALLOC_FILL_CHECK)
283 # define MALLOC_FILL_CHECK
285 #if defined(RCHECK) && defined(IGNORE_SMALL_BAD_FREE)
286 # undef IGNORE_SMALL_BAD_FREE
289 * malloc.c (Caltech) 2/21/82
290 * Chris Kingsley, kingsley@cit-20.
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.
300 * Modifications Copyright Ilya Zakharevich 1996-99.
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.)
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.
314 # define PERL_IN_MALLOC_C
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
322 # define croak2 croak
325 # if defined(USE_5005THREADS) || defined(USE_ITHREADS)
326 # define PERL_MAYBE_ALIVE PL_thr_key
328 # define PERL_MAYBE_ALIVE 1
332 # include "../EXTERN.h"
333 # include "../perl.h"
343 # define Malloc_t void *
349 # define MEM_SIZE unsigned long
352 # define LONG_MAX 0x7FFFFFFF
355 # define UV unsigned long
361 # define caddr_t char *
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)
373 # define INT2PTR(t,i) ((t)(i))
376 # define PTR2UV(p) ((UV)(p))
384 # ifndef MEM_ALIGNBYTES
385 # define MEM_ALIGNBYTES 4
388 # ifndef croak /* make depend */
389 # define croak(mess, arg) (warn((mess), (arg)), exit(1))
391 # ifndef croak2 /* make depend */
392 # define croak2(mess, arg1, arg2) (warn2((mess), (arg1), (arg2)), exit(1))
395 # define warn(mess, arg) fprintf(stderr, (mess), (arg))
398 # define warn2(mess, arg1, arg2) fprintf(stderr, (mess), (arg1), (arg2))
410 # ifdef HASATTRIBUTE_UNUSED
411 # define dTHX extern int Perl___notused PERL_UNUSED_DECL
413 # define dTHX extern int Perl___notused
415 # define WITH_THX(s) s
417 # ifndef PERL_GET_INTERP
418 # define PERL_GET_INTERP PL_curinterp
420 # define PERL_MAYBE_ALIVE 1
422 # define Perl_malloc malloc
425 # define Perl_mfree free
427 # ifndef Perl_realloc
428 # define Perl_realloc realloc
431 # define Perl_calloc calloc
434 # define Perl_strdup strdup
436 #endif /* defined PERL_CORE */
439 # define MUTEX_LOCK(l)
443 # define MUTEX_UNLOCK(l)
447 # define MALLOC_LOCK MUTEX_LOCK(&PL_malloc_mutex)
450 #ifndef MALLOC_UNLOCK
451 # define MALLOC_UNLOCK MUTEX_UNLOCK(&PL_malloc_mutex)
454 # ifndef fatalcroak /* make depend */
455 # define fatalcroak(mess) (write(2, (mess), strlen(mess)), exit(2))
460 # define DEBUG_m(a) \
462 if (PERL_MAYBE_ALIVE && PERL_GET_THX) { \
464 if (DEBUG_m_TEST) { \
465 PL_debug &= ~DEBUG_m_FLAG; \
467 PL_debug |= DEBUG_m_FLAG; \
473 #ifdef PERL_IMPLICIT_CONTEXT
474 # define PERL_IS_ALIVE aTHX
476 # define PERL_IS_ALIVE TRUE
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.)
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.
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.
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.
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
506 * Management of last_op:
507 * ~~~~~~~~~~~~~~~~~~~~~
509 * free() never changes the boundaries of blocks, so is not relevant.
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.
516 * malloc() may change blocks by calling morecore() only.
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();
527 * getpages() creates a new block. It marks last_op at the bottom of
528 * the chunk of memory it returns.
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.
539 * get_from_bigger_buckets(): forget to increment price => Quite
543 /* I don't much care whether these are defined in sys/types.h--LAW */
545 #define u_char unsigned char
546 #define u_int unsigned int
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
552 #define u_short unsigned short
554 /* 286 and atarist like big chunks, which gives too much overhead. */
555 #if (defined(RCHECK) || defined(I286) || defined(atarist)) && defined(PACK_MALLOC)
560 * The description below is applicable if PACK_MALLOC is not defined.
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.
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 */
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
584 u_char ovu_index; /* bucket # */
585 u_char ovu_magic; /* magic number */
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 */
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
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 */
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 */
607 # define MAX_SHORT_BUCKET (13 * BUCKETS_PER_POW2)
613 #if !defined(PACK_MALLOC) && defined(BUCKETS_ROOT2)
614 # undef BUCKETS_ROOT2
618 # define BUCKET_TABLE_SHIFT 2
619 # define BUCKET_POW2_SHIFT 1
620 # define BUCKETS_PER_POW2 2
622 # define BUCKET_TABLE_SHIFT MIN_BUC_POW2
623 # define BUCKET_POW2_SHIFT 0
624 # define BUCKETS_PER_POW2 1
627 #if !defined(MEM_ALIGNBYTES) || ((MEM_ALIGNBYTES > 4) && !defined(STRICT_ALIGNMENT))
628 /* Figure out the alignment of void*. */
633 # define ALIGN_SMALL ((int)((caddr_t)&(((struct aligner*)0)->p)))
635 # define ALIGN_SMALL MEM_ALIGNBYTES
638 #define IF_ALIGN_8(yes,no) ((ALIGN_SMALL>4) ? (yes) : (no))
641 # define MAX_BUCKET_BY_TABLE 13
642 static const u_short buck_size[MAX_BUCKET_BY_TABLE + 1] =
644 0, 0, 0, 0, 4, 4, 8, 12, 16, 24, 32, 48, 64, 80,
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 \
649 : ((1 << ((i) >> BUCKET_POW2_SHIFT)) \
651 + POW2_OPTIMIZE_SURPLUS(i)))
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))
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.
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
668 * # One chunk only, chunksize 2^k + SOMETHING - ALIGN, k >= 11
670 * INDEX MAGIC1 UNUSED CHUNK1
672 * # Multichunk with sanity checking and chunksize 2^k-ALIGN, k>7
674 * INDEX MAGIC1 MAGIC2 MAGIC3 UNUSED CHUNK1 CHUNK2 CHUNK3 ...
676 * # Multichunk with sanity checking and size 2^k-ALIGN, k=7
678 * INDEX MAGIC1 MAGIC2 MAGIC3 UNUSED CHUNK1 UNUSED CHUNK2 CHUNK3 ...
680 * # Multichunk with sanity checking and size up to 80
682 * INDEX UNUSED MAGIC1 UNUSED MAGIC2 UNUSED ... CHUNK1 CHUNK2 CHUNK3 ...
684 * # No sanity check (usually up to 48=byte-long buckets)
685 * INDEX UNUSED CHUNK1 CHUNK2 ...
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
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.
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.]
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.
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.
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) +
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.
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.
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.]
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).
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.)
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
760 * The algo of OV_MAGIC(block,bucket) keeps ADDOFFSET 0 until
761 * chunksize of 64, then makes it 1.
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. */
792 # define MIN_NEEDS_SHIFT (7*BUCKETS_PER_POW2) /* Shift 128 greater than chunk 32. */
794 # define CHUNK_SHIFT 0
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) \
803 # define N_BLKS(bucket) n_blks[bucket]
806 static const u_short n_blks[LOG_OF_MIN_ARENA * BUCKETS_PER_POW2] =
808 # if BUCKETS_PER_POW2==1
810 (MIN_BUC_POW2==2 ? 384 : 0),
811 224, 120, 62, 31, 16, 8, 4, 2
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
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)) \
826 # define BLK_SHIFT(bucket) blk_shift[bucket]
829 static const u_short blk_shift[LOG_OF_MIN_ARENA * BUCKETS_PER_POW2] =
831 # if BUCKETS_PER_POW2==1
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),
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),
850 # define NEEDED_ALIGNMENT 0x800 /* 2k boundaries */
851 # define WANTED_ALIGNMENT 0x800 /* 2k boundaries */
853 #else /* !PACK_MALLOC */
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 */
862 #endif /* !PACK_MALLOC */
864 #define M_OVERHEAD (sizeof(union overhead) + RMAGIC_SZ) /* overhead at start+end */
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
875 # define SIZE_TABLE_MAX 64
877 static const char bucket_of[] =
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 */
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),
897 # endif /* !BUCKETS_ROOT2 */
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
908 # define START_SHIFTS_BUCKET MIN_BUCKET
909 # define START_SHIFT (MIN_BUC_POW2 - 1)
910 #endif /* !PACK_MALLOC */
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.
917 #ifdef TWO_POT_OPTIMIZE
919 # ifndef PERL_PAGESIZE
920 # define PERL_PAGESIZE 4096
922 # ifndef FIRST_BIG_POW2
923 # define FIRST_BIG_POW2 15 /* 32K, 16K is used too often. */
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)
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)
936 #else /* !TWO_POT_OPTIMIZE */
937 # define POW2_OPTIMIZE_ADJUST(nbytes)
938 # define POW2_OPTIMIZE_SURPLUS(bucket) 0
939 #endif /* !TWO_POT_OPTIMIZE */
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); \
948 #else /* !HAS_64K_LIMIT || !PERL_CORE */
949 # define BARK_64K_LIMIT(what,nbytes,size)
950 #endif /* !HAS_64K_LIMIT || !PERL_CORE */
953 # define MIN_SBRK 2048
957 # define FIRST_SBRK (48*1024)
960 /* Minimal sbrk in percents of what is already alloced. */
961 #ifndef MIN_SBRK_FRAC
962 # define MIN_SBRK_FRAC 3
965 #ifndef SBRK_ALLOW_FAILURES
966 # define SBRK_ALLOW_FAILURES 3
969 #ifndef SBRK_FAILURE_PRICE
970 # define SBRK_FAILURE_PRICE 50
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);
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);
985 #ifdef I_MACH_CTHREADS
987 # define MUTEX_LOCK(m) STMT_START { if (*m) mutex_lock(*m); } STMT_END
989 # define MUTEX_UNLOCK(m) STMT_START { if (*m) mutex_unlock(*m); } STMT_END
992 #endif /* defined PERL_CORE */
995 # define PTRSIZE sizeof(void*)
999 # define BITS_IN_PTR (8*PTRSIZE)
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.
1007 #define NBUCKETS (BITS_IN_PTR*BUCKETS_PER_POW2 + 1)
1008 static union overhead *nextf[NBUCKETS];
1010 #if defined(PURIFY) && !defined(USE_PERL_SBRK)
1011 # define USE_PERL_SBRK
1014 #ifdef USE_PERL_SBRK
1015 # define sbrk(a) Perl_sbrk(a)
1016 Malloc_t Perl_sbrk (int size);
1018 # ifndef HAS_SBRK_PROTO /* <unistd.h> usually takes care of this */
1019 extern Malloc_t sbrk(int);
1023 #ifndef MIN_SBRK_FRAC1000 /* Backward compatibility */
1024 # define MIN_SBRK_FRAC1000 (MIN_SBRK_FRAC * 10)
1027 #ifndef START_EXTERN_C
1029 # define START_EXTERN_C extern "C" {
1031 # define START_EXTERN_C
1035 #ifndef END_EXTERN_C
1037 # define END_EXTERN_C };
1039 # define END_EXTERN_C
1043 #include "malloc_ctl.h"
1045 #ifndef NO_MALLOC_DYNAMIC_CFG
1046 # define PERL_MALLOC_OPT_CHARS "FMfAPGdac"
1048 # ifndef FILL_DEAD_DEFAULT
1049 # define FILL_DEAD_DEFAULT 1
1051 # ifndef FILL_ALIVE_DEFAULT
1052 # define FILL_ALIVE_DEFAULT 1
1054 # ifndef FILL_CHECK_DEFAULT
1055 # define FILL_CHECK_DEFAULT 1
1058 static IV MallocCfg[MallocCfg_last] = {
1062 SBRK_ALLOW_FAILURES,
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 */
1074 IV *MallocCfg_ptr = MallocCfg;
1076 static char* MallocCfgP[MallocCfg_last] = {
1077 0, /* MallocCfgP_emergency_buffer */
1078 0, /* MallocCfgP_emergency_buffer_prepared */
1080 char **MallocCfgP_ptr = MallocCfgP;
1084 # undef MIN_SBRK_FRAC1000
1085 # undef SBRK_ALLOW_FAILURES
1086 # undef SBRK_FAILURE_PRICE
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]
1094 # define sbrk_goodness MallocCfg[MallocCfg_sbrk_goodness]
1096 # define emergency_buffer_size MallocCfg[MallocCfg_emergency_buffer_size]
1097 # define emergency_buffer_last_req MallocCfg[MallocCfg_emergency_buffer_last_req]
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)
1104 # define emergency_buffer MallocCfgP[MallocCfgP_emergency_buffer]
1105 # define emergency_buffer_prepared MallocCfgP[MallocCfgP_emergency_buffer_prepared]
1107 #else /* defined(NO_MALLOC_DYNAMIC_CFG) */
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;
1114 # define NO_PERL_MALLOC_ENV
1118 #ifdef DEBUGGING_MSTATS
1120 * nmalloc[i] is the difference between the number of mallocs and frees
1121 * for a given block size.
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
1130 static u_int goodsbrk;
1132 #ifdef PERL_EMERGENCY_SBRK
1135 # define BIG_SIZE (1<<16) /* 64K */
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;
1147 # ifndef emergency_sbrk_croak
1148 # define emergency_sbrk_croak croak2
1153 perl_get_emergency_buffer(IV *size)
1156 /* First offense, give a possibility to recover by dieing. */
1157 /* No malloc involved here: */
1160 GV **gvp = (GV**)hv_fetchs(PL_defstash, "^M", FALSE);
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 */
1178 *size = malloced_size(pv) + M_OVERHEAD;
1179 return pv - sizeof(union overhead);
1181 # define PERL_GET_EMERGENCY_BUFFER(p) perl_get_emergency_buffer(p)
1183 # define PERL_GET_EMERGENCY_BUFFER(p) NULL
1184 # endif /* defined PERL_CORE */
1186 # ifndef NO_MALLOC_DYNAMIC_CFG
1188 get_emergency_buffer(IV *size)
1190 char *pv = emergency_buffer_prepared;
1192 *size = MallocCfg[MallocCfg_emergency_buffer_prepared_size];
1193 emergency_buffer_prepared = 0;
1194 MallocCfg[MallocCfg_emergency_buffer_prepared_size] = 0;
1198 /* Returns 0 on success, -1 on bad alignment, -2 if not implemented */
1200 set_emergency_buffer(char *b, IV size)
1202 if (PTR2UV(b) & (NEEDED_ALIGNMENT - 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;
1211 # define GET_EMERGENCY_BUFFER(p) get_emergency_buffer(p)
1212 # else /* NO_MALLOC_DYNAMIC_CFG */
1213 # define GET_EMERGENCY_BUFFER(p) NULL
1215 set_emergency_buffer(char *b, IV size)
1222 emergency_sbrk(MEM_SIZE size)
1224 MEM_SIZE rsize = (((size - 1)>>LOG_OF_MIN_ARENA) + 1)<<LOG_OF_MIN_ARENA;
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. */
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));
1235 if ((MEM_SIZE)emergency_buffer_size >= rsize) {
1236 char *old = emergency_buffer;
1238 emergency_buffer_size -= rsize;
1239 emergency_buffer += rsize;
1242 /* First offense, give a possibility to recover by dieing. */
1243 /* No malloc involved here: */
1245 char *pv = GET_EMERGENCY_BUFFER(&Size);
1248 if (emergency_buffer_size) {
1249 add_to_chain(emergency_buffer, emergency_buffer_size, 0);
1250 emergency_buffer_size = 0;
1251 emergency_buffer = NULL;
1256 pv = PERL_GET_EMERGENCY_BUFFER(&Size);
1260 return (char *)-1; /* Now die die die... */
1263 /* Check alignment: */
1264 if (PTR2UV(pv) & (NEEDED_ALIGNMENT - 1)) {
1267 PerlIO_puts(PerlIO_stderr(),"Bad alignment of $^M!\n");
1268 return (char *)-1; /* die die die */
1271 emergency_buffer = pv;
1272 emergency_buffer_size = Size;
1276 emergency_sbrk_croak("Out of memory during request for %"UVuf" bytes, total sbrk() is %"UVuf" bytes", (UV)size, (UV)(goodsbrk + sbrk_slack));
1281 #else /* !defined(PERL_EMERGENCY_SBRK) */
1282 # define emergency_sbrk(size) -1
1283 #endif /* defined PERL_EMERGENCY_SBRK */
1286 write2(const char *mess)
1288 write(2, mess, strlen(mess));
1293 #define ASSERT(p,diag) if (!(p)) botch(diag,STRINGIFY(p),__FILE__,__LINE__);
1296 botch(const char *diag, const char *s, const char *file, int line)
1300 if (!(PERL_MAYBE_ALIVE && PERL_GET_THX))
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 (");
1316 char *s = linebuf + sizeof(linebuf) - 1;
1320 *--s = '0' + (n % 10);
1330 #define ASSERT(p, diag)
1334 /* Fill should be long enough to cover long */
1336 fill_pat_4bytes(unsigned char *s, size_t nbytes, const unsigned char *fill)
1338 unsigned char *e = s + nbytes;
1340 const long lfill = *(long*)fill;
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;
1351 while ((unsigned char*)(lp + 1) <= e)
1353 s = (unsigned char*)lp;
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};
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)
1370 # define FILL_DEADBEEF(s, n) ((void)0)
1371 # define FILL_FEEDADAD(s, n) ((void)0)
1372 # undef MALLOC_FILL_CHECK
1375 #ifdef MALLOC_FILL_CHECK
1377 cmp_pat_4bytes(unsigned char *s, size_t nbytes, const unsigned char *fill)
1379 unsigned char *e = s + nbytes;
1381 const long lfill = *(long*)fill;
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;
1393 while ((unsigned char*)(lp + 1) <= e)
1396 s = (unsigned char*)lp;
1398 if (*s++ != *fill++)
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")
1406 # define FILLCHECK_DEADBEEF(s, n) ((void)0)
1410 S_ajust_size_and_find_bucket(size_t *nbytes_p)
1414 size_t nbytes = *nbytes_p;
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.
1423 # ifdef SMALL_BUCKET_VIA_TABLE
1425 bucket = MIN_BUCKET;
1426 else if (nbytes <= SIZE_TABLE_MAX) {
1427 bucket = bucket_of[(nbytes - 1) >> BUCKET_TABLE_SHIFT];
1432 if (nbytes <= MAX_POW2_ALGO) goto do_shifts;
1437 POW2_OPTIMIZE_ADJUST(nbytes);
1438 nbytes += M_OVERHEAD;
1439 nbytes = (nbytes + 3) &~ 3;
1440 #if defined(PACK_MALLOC) && !defined(SMALL_BUCKET_VIA_TABLE)
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;
1454 Perl_malloc(size_t nbytes)
1457 register union overhead *p;
1458 register int bucket;
1460 #if defined(DEBUGGING) || defined(RCHECK)
1461 MEM_SIZE size = nbytes;
1464 BARK_64K_LIMIT("Allocation",nbytes,nbytes);
1466 if ((long)nbytes < 0)
1467 croak("%s", "panic: malloc");
1470 bucket = S_ajust_size_and_find_bucket(&nbytes);
1473 * If nothing in hash bucket right now,
1474 * request more memory from the system.
1476 if (nextf[bucket] == NULL)
1478 if ((p = nextf[bucket]) == NULL) {
1484 #if defined(PLAIN_MALLOC) && defined(NO_FANCY_MALLOC)
1485 PerlIO_puts(PerlIO_stderr(),"Out of memory!\n");
1488 char *eb = buff + sizeof(buff) - 1;
1492 PerlIO_puts(PerlIO_stderr(),"Out of memory during request for ");
1493 #if defined(DEBUGGING) || defined(RCHECK)
1498 *--s = '0' + (n % 10);
1500 PerlIO_puts(PerlIO_stderr(),s);
1501 PerlIO_puts(PerlIO_stderr()," bytes, total sbrk() is ");
1503 n = goodsbrk + sbrk_slack;
1505 *--s = '0' + (n % 10);
1507 PerlIO_puts(PerlIO_stderr(),s);
1508 PerlIO_puts(PerlIO_stderr()," bytes!\n");
1509 #endif /* defined(PLAIN_MALLOC) && defined(NO_FANCY_MALLOC) */
1517 /* remove from linked list */
1519 if ( (PTR2UV(p) & (MEM_ALIGNBYTES - 1))
1520 /* Can't get this low */
1521 || (p && PTR2UV(p) < (1<<LOG_OF_MIN_ARENA)) ) {
1523 PerlIO_printf(PerlIO_stderr(),
1524 "Unaligned pointer in the free chain 0x%"UVxf"\n",
1527 if ( (PTR2UV(p->ov_next) & (MEM_ALIGNBYTES - 1))
1528 || (p->ov_next && PTR2UV(p->ov_next) < (1<<LOG_OF_MIN_ARENA)) ) {
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));
1536 nextf[bucket] = p->ov_next;
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++),
1545 FILLCHECK_DEADBEEF((unsigned char*)(p + CHUNK_SHIFT),
1546 BUCKET_SIZE_REAL(bucket) + RMAGIC_SZ);
1548 #ifdef IGNORE_SMALL_BAD_FREE
1549 if (bucket >= FIRST_BUCKET_WITH_CHECK)
1551 OV_MAGIC(p, bucket) = MAGIC;
1553 OV_INDEX(p) = bucket;
1557 * Record allocated size of block and
1558 * bound space with magic numbers.
1560 p->ov_rmagic = RMAGIC;
1561 if (bucket <= MAX_SHORT_BUCKET) {
1564 nbytes = size + M_OVERHEAD;
1565 p->ov_size = nbytes - 1;
1566 if ((i = nbytes & (RMAGIC_SZ-1))) {
1568 while (i--) /* nbytes - RMAGIC_SZ is end of alloced area */
1569 ((caddr_t)p + nbytes - RMAGIC_SZ)[i] = RMAGIC_C;
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;
1575 FILL_FEEDADAD((unsigned char *)(p + CHUNK_SHIFT), size);
1577 return ((Malloc_t)(p + CHUNK_SHIFT));
1580 static char *last_sbrk_top;
1581 static char *last_op; /* This arena can be easily extended. */
1582 static MEM_SIZE sbrked_remains;
1584 #ifdef DEBUGGING_MSTATS
1588 struct chunk_chain_s {
1589 struct chunk_chain_s *next;
1592 static struct chunk_chain_s *chunk_chain;
1593 static int n_chunks;
1594 static char max_bucket;
1596 /* Cutoff a piece of one of the chunks in the chain. Prefer smaller chunk. */
1598 get_from_chain(MEM_SIZE size)
1600 struct chunk_chain_s *elt = chunk_chain, **oldp = &chunk_chain;
1601 struct chunk_chain_s **oldgoodp = NULL;
1602 long min_remain = LONG_MAX;
1605 if (elt->size >= size) {
1606 long remains = elt->size - size;
1607 if (remains >= 0 && remains < min_remain) {
1609 min_remain = remains;
1615 oldp = &( elt->next );
1618 if (!oldgoodp) return NULL;
1620 void *ret = *oldgoodp;
1621 struct chunk_chain_s *next = (*oldgoodp)->next;
1623 *oldgoodp = (struct chunk_chain_s *)((char*)ret + size);
1624 (*oldgoodp)->size = min_remain;
1625 (*oldgoodp)->next = next;
1628 void *ret = *oldgoodp;
1629 *oldgoodp = (*oldgoodp)->next;
1636 add_to_chain(void *p, MEM_SIZE size, MEM_SIZE chip)
1638 struct chunk_chain_s *next = chunk_chain;
1639 char *cp = (char*)p;
1642 chunk_chain = (struct chunk_chain_s *)cp;
1643 chunk_chain->size = size - chip;
1644 chunk_chain->next = next;
1649 get_from_bigger_buckets(int bucket, MEM_SIZE size)
1652 static int bucketprice[NBUCKETS];
1653 while (bucket <= max_bucket) {
1654 /* We postpone stealing from bigger buckets until we want it
1656 if (nextf[bucket] && bucketprice[bucket]++ >= price) {
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 */
1663 nextf[bucket] = nextf[bucket]->ov_next;
1664 #ifdef DEBUGGING_MSTATS
1666 start_slack -= M_OVERHEAD;
1668 add_to_chain(ret, (BUCKET_SIZE_NO_SURPLUS(bucket) +
1669 POW2_OPTIMIZE_SURPLUS(bucket)),
1678 static union overhead *
1679 getpages(MEM_SIZE needed, int *nblksp, int bucket)
1682 /* Need to do (possibly expensive) system call. Try to
1683 optimize it for rare calling. */
1684 MEM_SIZE require = needed - sbrked_remains;
1686 union overhead *ovp;
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;
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;
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
1710 if (cp == last_sbrk_top) {
1711 /* Common case, anything is fine. */
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)
1720 if (((char*)ovp) > last_op) { /* Cannot happen with current emergency_sbrk() */
1724 } else { /* Non-continuous or first sbrk(). */
1725 long add = sbrked_remains;
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),
1734 /* Second, check alignment. */
1737 #if !defined(atarist) /* 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));
1746 #endif /* !atarist */
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)
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"));
1765 fatalcroak("panic: Off-page sbrk\n");
1768 if (sbrked_remains) {
1770 #if defined(DEBUGGING_MSTATS)
1771 sbrk_slack += require;
1774 DEBUG_m(PerlIO_printf(Perl_debug_log,
1775 "straight sbrk(%ld)\n",
1777 cp = (char *)sbrk(require);
1778 #ifdef DEBUGGING_MSTATS
1781 if (cp == (char *)-1)
1784 sbrk_goodness = -1; /* Disable optimization!
1785 Continue with not-aligned... */
1788 require += sbrked_remains;
1792 if (last_sbrk_top) {
1793 sbrk_goodness -= SBRK_FAILURE_PRICE;
1796 ovp = (union overhead *) cp;
1798 * Round up to minimum allocation size boundary
1799 * and deduct from block count to reflect.
1802 # if NEEDED_ALIGNMENT > MEM_ALIGNBYTES
1803 if (PTR2UV(ovp) & (NEEDED_ALIGNMENT - 1))
1804 fatalcroak("Misalignment of sbrk()\n");
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));
1815 # if defined(DEBUGGING_MSTATS)
1816 /* This is only approx. if TWO_POT_OPTIMIZE: */
1817 sbrk_slack += (1 << (bucket >> BUCKET_POW2_SHIFT));
1821 ; /* Finish "else" */
1822 sbrked_remains = require - needed;
1825 #if !defined(PLAIN_MALLOC) && !defined(NO_FANCY_MALLOC)
1826 emergency_buffer_last_req = 0;
1828 last_sbrk_top = cp + require;
1829 #ifdef DEBUGGING_MSTATS
1830 goodsbrk += require;
1836 getpages_adjacent(MEM_SIZE require)
1838 if (require <= sbrked_remains) {
1839 sbrked_remains -= require;
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
1848 goodsbrk += require;
1850 if (cp == last_sbrk_top) {
1852 last_sbrk_top = cp + require;
1854 if (cp == (char*)-1) { /* Out of memory */
1855 #ifdef DEBUGGING_MSTATS
1856 goodsbrk -= require;
1860 /* Report the failure: */
1862 add_to_chain((void*)(last_sbrk_top - sbrked_remains),
1864 add_to_chain((void*)cp, require, 0);
1865 sbrk_goodness -= SBRK_FAILURE_PRICE;
1877 * Allocate more memory to the indicated bucket.
1880 morecore(register int bucket)
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;
1891 #ifndef NO_PERL_MALLOC_ENV
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;
1900 while ( t && t[0] && t[1] == '='
1901 && ((off = strchr(opts, *t))) ) {
1905 while (*t <= '9' && *t >= '0')
1906 val = 10*val + *t++ - '0';
1907 if (!*t || *t == ';') {
1908 if (MallocCfg[off - opts] != val)
1910 MallocCfg[off - opts] = val;
1916 write2("Unrecognized part of PERL_MALLOC_OPT: \"");
1921 MallocCfg[MallocCfg_cfg_env_read] = 1;
1925 if (bucket == sizeof(MEM_SIZE)*8*BUCKETS_PER_POW2) {
1927 croak("%s", "Out of memory during ridiculously large request");
1929 if (bucket > max_bucket)
1930 max_bucket = bucket;
1932 rnu = ( (bucket <= (LOG_OF_MIN_ARENA << BUCKET_POW2_SHIFT))
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;
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",
1954 } else if ( (ovp = (union overhead*)
1955 get_from_bigger_buckets((rnu << BUCKET_POW2_SHIFT) + 1,
1957 DEBUG_m(PerlIO_printf(Perl_debug_log,
1958 "stealing %ld bytes from bigger buckets\n",
1960 } else if (needed <= sbrked_remains) {
1961 ovp = (union overhead *)(last_sbrk_top - sbrked_remains);
1962 sbrked_remains -= needed;
1963 last_op = (char*)ovp;
1965 ovp = getpages(needed, &nblks, bucket);
1969 FILL_DEADBEEF((unsigned char*)ovp, needed);
1972 * Add new memory allocated to that on
1973 * free list for this hash bucket.
1975 siz = BUCKET_SIZE_NO_SURPLUS(bucket); /* No surplus if nblks > 1 */
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);
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;
1997 while (--nblks > 0) {
1998 ovp->ov_next = (union overhead *)((caddr_t)ovp + siz);
1999 ovp = (union overhead *)((caddr_t)ovp + siz);
2001 /* Not all sbrks return zeroed memory.*/
2002 ovp->ov_next = (union overhead *)NULL;
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;
2011 #endif /* !PACK_MALLOC */
2015 Perl_mfree(Malloc_t where)
2018 register MEM_SIZE size;
2019 register union overhead *ovp;
2020 char *cp = (char*)where;
2025 DEBUG_m(PerlIO_printf(Perl_debug_log,
2026 "0x%"UVxf": (%05lu) free\n",
2027 PTR2UV(cp), (unsigned long)(PL_an++)));
2032 if (PTR2UV(cp) & (MEM_ALIGNBYTES - 1))
2033 croak("%s", "wrong alignment in free()");
2035 ovp = (union overhead *)((caddr_t)cp
2036 - sizeof (union overhead) * CHUNK_SHIFT);
2038 bucket = OV_INDEX(ovp);
2040 #ifdef IGNORE_SMALL_BAD_FREE
2041 if ((bucket >= FIRST_BUCKET_WITH_CHECK)
2042 && (OV_MAGIC(ovp, bucket) != MAGIC))
2044 if (OV_MAGIC(ovp, bucket) != MAGIC)
2047 static int bad_free_warn = -1;
2048 if (bad_free_warn == -1) {
2050 char *pbf = PerlEnv_getenv("PERL_BADFREE");
2051 bad_free_warn = (pbf) ? atoi(pbf) : 1;
2059 if (!PERL_IS_ALIVE || !PL_curcop)
2060 Perl_ck_warner_d(aTHX_ packWARN(WARN_MALLOC), "%s free() ignored (RMAGIC, PERL_CORE)",
2061 ovp->ov_rmagic == RMAGIC - 1 ?
2062 "Duplicate" : "Bad");
2065 warn("%s free() ignored (RMAGIC)",
2066 ovp->ov_rmagic == RMAGIC - 1 ? "Duplicate" : "Bad");
2072 if (!PERL_IS_ALIVE || !PL_curcop)
2073 Perl_ck_warner_d(aTHX_ packWARN(WARN_MALLOC), "%s", "Bad free() ignored (PERL_CORE)");
2076 warn("%s", "Bad free() ignored");
2079 return; /* sanity */
2082 ASSERT(ovp->ov_rmagic == RMAGIC, "chunk's head overwrite");
2083 if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET) {
2085 MEM_SIZE nbytes = ovp->ov_size + 1;
2087 if ((i = nbytes & (RMAGIC_SZ-1))) {
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");
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);
2101 FILL_DEADBEEF((unsigned char*)(ovp+CHUNK_SHIFT),
2102 BUCKET_SIZE_REAL(OV_INDEX(ovp)) + RMAGIC_SZ);
2103 ovp->ov_rmagic = RMAGIC - 1;
2105 ASSERT(OV_INDEX(ovp) < NBUCKETS, "chunk's head overwrite");
2106 size = OV_INDEX(ovp);
2109 ovp->ov_next = nextf[size];
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. */
2120 Perl_realloc(void *mp, size_t nbytes)
2123 register MEM_SIZE onb;
2124 union overhead *ovp;
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;
2132 #if defined(DEBUGGING) || !defined(PERL_CORE)
2133 MEM_SIZE size = nbytes;
2135 if ((long)nbytes < 0)
2136 croak("%s", "panic: realloc");
2139 BARK_64K_LIMIT("Reallocation",nbytes,size);
2141 return Perl_malloc(nbytes);
2143 ovp = (union overhead *)((caddr_t)cp
2144 - sizeof (union overhead) * CHUNK_SHIFT);
2145 bucket = OV_INDEX(ovp);
2147 #ifdef IGNORE_SMALL_BAD_FREE
2148 if ((bucket >= FIRST_BUCKET_WITH_CHECK)
2149 && (OV_MAGIC(ovp, bucket) != MAGIC))
2151 if (OV_MAGIC(ovp, bucket) != MAGIC)
2154 static int bad_free_warn = -1;
2155 if (bad_free_warn == -1) {
2157 char *pbf = PerlEnv_getenv("PERL_BADFREE");
2158 bad_free_warn = (pbf) ? atoi(pbf) : 1;
2166 if (!PERL_IS_ALIVE || !PL_curcop)
2167 Perl_ck_warner_d(aTHX_ packWARN(WARN_MALLOC), "%srealloc() %signored",
2168 (ovp->ov_rmagic == RMAGIC - 1 ? "" : "Bad "),
2169 ovp->ov_rmagic == RMAGIC - 1
2170 ? "of freed memory " : "");
2173 warn2("%srealloc() %signored",
2174 (ovp->ov_rmagic == RMAGIC - 1 ? "" : "Bad "),
2175 ovp->ov_rmagic == RMAGIC - 1 ? "of freed memory " : "");
2181 if (!PERL_IS_ALIVE || !PL_curcop)
2182 Perl_ck_warner_d(aTHX_ packWARN(WARN_MALLOC), "%s",
2183 "Bad realloc() ignored");
2186 warn("%s", "Bad realloc() ignored");
2189 return NULL; /* sanity */
2192 onb = BUCKET_SIZE_REAL(bucket);
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.
2200 * We do not try to go to 1.5 times smaller bucket so far.
2202 if (nbytes > onb) incr = 1;
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 )
2211 #else /* !DO_NOT_TRY_HARDER_WHEN_SHRINKING */
2212 prev_bucket = ( (bucket > MAX_PACKED + 1)
2213 ? bucket - BUCKETS_PER_POW2
2215 if (nbytes > BUCKET_SIZE_REAL(prev_bucket))
2216 #endif /* !DO_NOT_TRY_HARDER_WHEN_SHRINKING */
2220 #ifdef STRESS_REALLOC
2227 * Record new allocated size of block and
2228 * bound space with magic numbers.
2230 if (OV_INDEX(ovp) <= MAX_SHORT_BUCKET) {
2231 int i, nb = ovp->ov_size + 1;
2233 if ((i = nb & (RMAGIC_SZ-1))) {
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");
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));
2249 FILL_DEADBEEF((unsigned char*)cp + nbytes,
2250 nb - M_OVERHEAD + RMAGIC_SZ - nbytes);
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.
2257 nbytes += M_OVERHEAD;
2258 ovp->ov_size = nbytes - 1;
2259 if ((i = nbytes & (RMAGIC_SZ-1))) {
2261 while (i--) /* nbytes - RMAGIC_SZ is end of alloced area */
2262 ((caddr_t)ovp + nbytes - RMAGIC_SZ)[i]
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;
2271 DEBUG_m(PerlIO_printf(Perl_debug_log,
2272 "0x%"UVxf": (%05lu) realloc %ld bytes inplace\n",
2273 PTR2UV(res),(unsigned long)(PL_an++),
2275 } else if (incr == 1 && (cp - M_OVERHEAD == last_op)
2276 && (onb > (1 << LOG_OF_MIN_ARENA))) {
2277 MEM_SIZE require, newarena = nbytes, pow;
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)
2288 newarena = (1 << pow) + POW2_OPTIMIZE_SURPLUS(pow * BUCKETS_PER_POW2);
2289 require = newarena - onb - M_OVERHEAD;
2292 if (cp - M_OVERHEAD == last_op /* We *still* are the last chunk */
2293 && getpages_adjacent(require)) {
2294 #ifdef DEBUGGING_MSTATS
2296 nmalloc[pow * BUCKETS_PER_POW2]++;
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. */
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++),
2313 if ((res = (char*)Perl_malloc(nbytes)) == NULL)
2315 if (cp != res) /* common optimization */
2316 Copy(cp, res, (MEM_SIZE)(nbytes<onb?nbytes:onb), char);
2319 return ((Malloc_t)res);
2323 Perl_calloc(register size_t elements, register size_t size)
2325 long sz = elements * size;
2326 Malloc_t p = Perl_malloc(sz);
2329 memset((void*)p, 0, sz);
2335 Perl_strdup(const char *s)
2337 MEM_SIZE l = strlen(s);
2338 char *s1 = (char *)Perl_malloc(l+1);
2340 return (char *)CopyD(s, s1, (MEM_SIZE)(l+1), char);
2345 Perl_putenv(char *a)
2347 /* Sometimes system's putenv conflicts with my_setenv() - this is system
2348 malloc vs Perl's free(). */
2355 while (*val && *val != '=')
2360 if (l < sizeof(buf))
2363 var = (char *)Perl_malloc(l + 1);
2364 Copy(a, var, l, char);
2366 my_setenv(var, val+1);
2374 Perl_malloced_size(void *p)
2376 union overhead * const ovp = (union overhead *)
2377 ((caddr_t)p - sizeof (union overhead) * CHUNK_SHIFT);
2378 const int bucket = OV_INDEX(ovp);
2380 PERL_ARGS_ASSERT_MALLOCED_SIZE;
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;
2391 return BUCKET_SIZE_REAL(bucket);
2396 Perl_malloc_good_size(size_t wanted)
2398 return BUCKET_SIZE_REAL(S_ajust_size_and_find_bucket(&wanted));
2401 # ifdef BUCKETS_ROOT2
2402 # define MIN_EVEN_REPORT 6
2404 # define MIN_EVEN_REPORT MIN_BUCKET
2408 Perl_get_mstats(pTHX_ perl_mstats_t *buf, int buflen, int level)
2410 #ifdef DEBUGGING_MSTATS
2412 register union overhead *p;
2413 struct chunk_chain_s* nextchain;
2415 PERL_ARGS_ASSERT_GET_MSTATS;
2417 buf->topbucket = buf->topbucket_ev = buf->topbucket_odd
2418 = buf->totfree = buf->total = buf->total_chain = 0;
2420 buf->minbucket = MIN_BUCKET;
2422 for (i = MIN_BUCKET ; i < NBUCKETS; i++) {
2423 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
2427 buf->ntotal[i] = nmalloc[i];
2429 buf->totfree += j * BUCKET_SIZE_REAL(i);
2430 buf->total += nmalloc[i] * BUCKET_SIZE_REAL(i);
2432 i % 2 ? (buf->topbucket_odd = i) : (buf->topbucket_ev = i);
2436 nextchain = chunk_chain;
2438 buf->total_chain += nextchain->size;
2439 nextchain = nextchain->next;
2441 buf->total_sbrk = goodsbrk + sbrk_slack;
2443 buf->sbrk_good = sbrk_goodness;
2444 buf->sbrk_slack = sbrk_slack;
2445 buf->start_slack = start_slack;
2446 buf->sbrked_remains = sbrked_remains;
2448 buf->nbuckets = NBUCKETS;
2450 for (i = MIN_BUCKET ; i < NBUCKETS; i++) {
2453 buf->bucket_mem_size[i] = BUCKET_SIZE_NO_SURPLUS(i);
2454 buf->bucket_available_size[i] = BUCKET_SIZE_REAL(i);
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 */
2463 * mstats - print out statistics about malloc
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.
2470 Perl_dump_mstats(pTHX_ const char *s)
2472 #ifdef DEBUGGING_MSTATS
2474 perl_mstats_t buffer;
2478 PERL_ARGS_ASSERT_DUMP_MSTATS;
2482 get_mstats(&buffer, NBUCKETS, 0);
2485 PerlIO_printf(Perl_error_log,
2486 "Memory allocation statistics %s (buckets %"IVdf"(%"IVdf")..%"IVdf"(%"IVdf")\n",
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)
2497 : ((i < 12*BUCKETS_PER_POW2) ? " %3"UVuf : " %"UVuf)),
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)
2506 : ((i < 12*BUCKETS_PER_POW2) ? " %3"UVuf : " %"UVuf)),
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)
2515 : ((i < 12*BUCKETS_PER_POW2) ? " %3"IVdf : " %"IVdf)),
2516 buffer.ntotal[i] - buffer.nfree[i]);
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)
2524 : ((i < 12*BUCKETS_PER_POW2) ? " %3"IVdf : " %"IVdf)),
2525 buffer.ntotal[i] - buffer.nfree[i]);
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 */
2537 #ifdef USE_PERL_SBRK
2539 # if defined(NeXT) || defined(__NeXT__) || defined(PURIFY)
2540 # define PERL_SBRK_VIA_MALLOC
2543 # ifdef PERL_SBRK_VIA_MALLOC
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 */
2550 # ifndef SYSTEM_ALLOC
2551 # define SYSTEM_ALLOC(a) malloc(a)
2553 # ifndef SYSTEM_ALLOC_ALIGNMENT
2554 # define SYSTEM_ALLOC_ALIGNMENT MEM_ALIGNBYTES
2557 # endif /* PERL_SBRK_VIA_MALLOC */
2559 static IV Perl_sbrk_oldchunk;
2560 static long Perl_sbrk_oldsize;
2562 # define PERLSBRK_32_K (1<<15)
2563 # define PERLSBRK_64_K (1<<16)
2571 if (!size) return 0;
2573 reqsize = size; /* just for the DEBUG_m statement */
2576 size = (size + 0x7ff) & ~0x7ff;
2578 if (size <= Perl_sbrk_oldsize) {
2579 got = Perl_sbrk_oldchunk;
2580 Perl_sbrk_oldchunk += size;
2581 Perl_sbrk_oldsize -= size;
2583 if (size >= PERLSBRK_32_K) {
2586 size = PERLSBRK_64_K;
2589 # if NEEDED_ALIGNMENT > SYSTEM_ALLOC_ALIGNMENT
2590 size += NEEDED_ALIGNMENT - SYSTEM_ALLOC_ALIGNMENT;
2592 got = (IV)SYSTEM_ALLOC(size);
2593 # if NEEDED_ALIGNMENT > SYSTEM_ALLOC_ALIGNMENT
2594 got = (got + NEEDED_ALIGNMENT - 1) & ~(NEEDED_ALIGNMENT - 1);
2597 /* Chunk is small, register the rest for future allocs. */
2598 Perl_sbrk_oldchunk = got + reqsize;
2599 Perl_sbrk_oldsize = size - reqsize;
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)));
2609 #endif /* ! defined USE_PERL_SBRK */
2613 * c-indentation-style: bsd
2615 * indent-tabs-mode: t
2618 * ex: set ts=8 sts=4 sw=4 noet: