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