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