[inseparable changes from patch from perl5.003_12 to perl5.003_13]
[p5sagit/p5-mst-13.2.git] / malloc.c
CommitLineData
a0d0e21e 1/* malloc.c
8d063cd8 2 *
8d063cd8 3 */
4
5#ifndef lint
a687059c 6#ifdef DEBUGGING
8d063cd8 7#define RCHECK
a687059c 8#endif
8d063cd8 9/*
10 * malloc.c (Caltech) 2/21/82
11 * Chris Kingsley, kingsley@cit-20.
12 *
13 * This is a very fast storage allocator. It allocates blocks of a small
14 * number of different sizes, and keeps free lists of each size. Blocks that
15 * don't exactly fit are passed up to the next larger size. In this
16 * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long.
cf5c4ad8 17 * If PACK_MALLOC is defined, small blocks are 2^n bytes long.
8d063cd8 18 * This is designed for use in a program that uses vast quantities of memory,
19 * but bombs when it runs out.
20 */
21
135863df 22#include "EXTERN.h"
135863df 23#include "perl.h"
24
760ac839 25#ifdef DEBUGGING
26#undef DEBUG_m
27#define DEBUG_m(a) if (debug & 128) a
28#endif
29
135863df 30/* I don't much care whether these are defined in sys/types.h--LAW */
31
32#define u_char unsigned char
33#define u_int unsigned int
34#define u_short unsigned short
8d063cd8 35
cf5c4ad8 36/* 286 and atarist like big chunks, which gives too much overhead. */
37#if (defined(RCHECK) || defined(I286) || defined(atarist)) && defined(PACK_MALLOC)
38#undef PACK_MALLOC
39#endif
40
41
8d063cd8 42/*
cf5c4ad8 43 * The description below is applicable if PACK_MALLOC is not defined.
44 *
8d063cd8 45 * The overhead on a block is at least 4 bytes. When free, this space
46 * contains a pointer to the next free block, and the bottom two bits must
47 * be zero. When in use, the first byte is set to MAGIC, and the second
48 * byte is the size index. The remaining bytes are for alignment.
49 * If range checking is enabled and the size of the block fits
50 * in two bytes, then the top two bytes hold the size of the requested block
51 * plus the range checking words, and the header word MINUS ONE.
52 */
53union overhead {
54 union overhead *ov_next; /* when free */
85e6fe83 55#if MEM_ALIGNBYTES > 4
c623bd54 56 double strut; /* alignment problems */
a687059c 57#endif
8d063cd8 58 struct {
59 u_char ovu_magic; /* magic number */
60 u_char ovu_index; /* bucket # */
61#ifdef RCHECK
62 u_short ovu_size; /* actual block size */
63 u_int ovu_rmagic; /* range magic number */
64#endif
65 } ovu;
66#define ov_magic ovu.ovu_magic
67#define ov_index ovu.ovu_index
68#define ov_size ovu.ovu_size
69#define ov_rmagic ovu.ovu_rmagic
70};
71
760ac839 72#ifdef DEBUGGING
a0d0e21e 73static void botch _((char *s));
74#endif
75static void morecore _((int bucket));
76static int findbucket _((union overhead *freep, int srchlen));
77
8d063cd8 78#define MAGIC 0xff /* magic # on accounting info */
79#define RMAGIC 0x55555555 /* magic # on range info */
80#ifdef RCHECK
81#define RSLOP sizeof (u_int)
82#else
83#define RSLOP 0
84#endif
85
cf5c4ad8 86#ifdef PACK_MALLOC
87/*
88 * In this case it is assumed that if we do sbrk() in 2K units, we
89 * will get 2K aligned blocks. The bucket number of the given subblock is
90 * on the boundary of 2K block which contains the subblock.
91 * Several following bytes contain the magic numbers for the subblocks
92 * in the block.
93 *
94 * Sizes of chunks are powers of 2 for chunks in buckets <=
95 * MAX_PACKED, after this they are (2^n - sizeof(union overhead)) (to
96 * get alignment right).
97 *
98 * We suppose that starts of all the chunks in a 2K block are in
99 * different 2^n-byte-long chunks. If the top of the last chunk is
100 * aligned on a boundary of 2K block, this means that
101 * sizeof(union overhead)*"number of chunks" < 2^n, or
102 * sizeof(union overhead)*2K < 4^n, or n > 6 + log2(sizeof()/2)/2, if a
103 * chunk of size 2^n - overhead is used. Since this rules out n = 7
104 * for 8 byte alignment, we specialcase allocation of the first of 16
105 * 128-byte-long chunks.
106 *
107 * Note that with the above assumption we automatically have enough
108 * place for MAGIC at the start of 2K block. Note also that we
109 * overlay union overhead over the chunk, thus the start of the chunk
110 * is immediately overwritten after freeing.
111 */
112# define MAX_PACKED 6
113# define MAX_2_POT_ALGO ((1<<(MAX_PACKED + 1)) - M_OVERHEAD)
114# define TWOK_MASK ((1<<11) - 1)
ff68c719 115# define TWOK_MASKED(x) ((u_int)(x) & ~TWOK_MASK)
116# define TWOK_SHIFT(x) ((u_int)(x) & TWOK_MASK)
cf5c4ad8 117# define OV_INDEXp(block) ((u_char*)(TWOK_MASKED(block)))
118# define OV_INDEX(block) (*OV_INDEXp(block))
119# define OV_MAGIC(block,bucket) (*(OV_INDEXp(block) + \
120 (TWOK_SHIFT(block)>>(bucket + 3)) + \
121 (bucket > MAX_NONSHIFT ? 1 : 0)))
122# define CHUNK_SHIFT 0
123
124static u_char n_blks[11 - 3] = {224, 120, 62, 31, 16, 8, 4, 2};
125static u_short blk_shift[11 - 3] = {256, 128, 64, 32,
126 16*sizeof(union overhead),
127 8*sizeof(union overhead),
128 4*sizeof(union overhead),
129 2*sizeof(union overhead),
130# define MAX_NONSHIFT 2 /* Shift 64 greater than chunk 32. */
131};
132
cf5c4ad8 133#else /* !PACK_MALLOC */
134
135# define OV_MAGIC(block,bucket) (block)->ov_magic
136# define OV_INDEX(block) (block)->ov_index
137# define CHUNK_SHIFT 1
138#endif /* !PACK_MALLOC */
139
140# define M_OVERHEAD (sizeof(union overhead) + RSLOP)
141
8d063cd8 142/*
55497cff 143 * Big allocations are often of the size 2^n bytes. To make them a
144 * little bit better, make blocks of size 2^n+pagesize for big n.
145 */
146
147#ifdef TWO_POT_OPTIMIZE
148
5f05dabc 149# ifndef PERL_PAGESIZE
150# define PERL_PAGESIZE 4096
151# endif
152# ifndef FIRST_BIG_TWO_POT
153# define FIRST_BIG_TWO_POT 14 /* 16K */
154# endif
55497cff 155# define FIRST_BIG_BLOCK (1<<FIRST_BIG_TWO_POT) /* 16K */
156/* If this value or more, check against bigger blocks. */
157# define FIRST_BIG_BOUND (FIRST_BIG_BLOCK - M_OVERHEAD)
158/* If less than this value, goes into 2^n-overhead-block. */
159# define LAST_SMALL_BOUND ((FIRST_BIG_BLOCK>>1) - M_OVERHEAD)
160
161#endif /* TWO_POT_OPTIMIZE */
162
72e5b9db 163#if defined(PERL_EMERGENCY_SBRK) && defined(PERL_CORE)
55497cff 164
165#ifndef BIG_SIZE
166# define BIG_SIZE (1<<16) /* 64K */
167#endif
168
169static char *emergency_buffer;
170static MEM_SIZE emergency_buffer_size;
171
172static char *
173emergency_sbrk(size)
174 MEM_SIZE size;
175{
176 if (size >= BIG_SIZE) {
177 /* Give the possibility to recover: */
178 die("Out of memory during request for %i bytes", size);
179 /* croak may eat too much memory. */
180 }
181
182 if (!emergency_buffer) {
183 /* First offense, give a possibility to recover by dieing. */
184 /* No malloc involved here: */
185 GV **gvp = (GV**)hv_fetch(defstash, "^M", 2, 0);
186 SV *sv;
187 char *pv;
188
189 if (!gvp) gvp = (GV**)hv_fetch(defstash, "\015", 1, 0);
190 if (!gvp || !(sv = GvSV(*gvp)) || !SvPOK(sv)
191 || (SvLEN(sv) < (1<<11) - M_OVERHEAD))
192 return (char *)-1; /* Now die die die... */
193
194 /* Got it, now detach SvPV: */
bbce6d69 195 pv = SvPV(sv, na);
55497cff 196 /* Check alignment: */
ff68c719 197 if (((u_int)(pv - M_OVERHEAD)) & ((1<<11) - 1)) {
55497cff 198 PerlIO_puts(PerlIO_stderr(),"Bad alignment of $^M!\n");
bbce6d69 199 return (char *)-1; /* die die die */
55497cff 200 }
201
202 emergency_buffer = pv - M_OVERHEAD;
203 emergency_buffer_size = SvLEN(sv) + M_OVERHEAD;
204 SvPOK_off(sv);
205 SvREADONLY_on(sv);
206 die("Out of memory!"); /* croak may eat too much memory. */
ff68c719 207 }
208 else if (emergency_buffer_size >= size) {
55497cff 209 emergency_buffer_size -= size;
210 return emergency_buffer + emergency_buffer_size;
211 }
212
213 return (char *)-1; /* poor guy... */
214}
215
72e5b9db 216#else /* !(defined(TWO_POT_OPTIMIZE) && defined(PERL_CORE)) */
55497cff 217# define emergency_sbrk(size) -1
72e5b9db 218#endif /* !(defined(TWO_POT_OPTIMIZE) && defined(PERL_CORE)) */
55497cff 219
220/*
8d063cd8 221 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
222 * smallest allocatable block is 8 bytes. The overhead information
223 * precedes the data area returned to the user.
224 */
225#define NBUCKETS 30
226static union overhead *nextf[NBUCKETS];
cf5c4ad8 227
228#ifdef USE_PERL_SBRK
229#define sbrk(a) Perl_sbrk(a)
230char * Perl_sbrk _((int size));
231#else
8d063cd8 232extern char *sbrk();
cf5c4ad8 233#endif
8d063cd8 234
c07a80fd 235#ifdef DEBUGGING_MSTATS
8d063cd8 236/*
237 * nmalloc[i] is the difference between the number of mallocs and frees
238 * for a given block size.
239 */
240static u_int nmalloc[NBUCKETS];
5f05dabc 241static u_int goodsbrk;
242static u_int sbrk_slack;
243static u_int start_slack;
8d063cd8 244#endif
245
760ac839 246#ifdef DEBUGGING
4dfc412b 247#define ASSERT(p) if (!(p)) botch(STRINGIFY(p)); else
ee0007ab 248static void
8d063cd8 249botch(s)
250 char *s;
251{
4dfc412b 252 PerlIO_printf(PerlIO_stderr(), "assertion botched: %s\n", s);
8d063cd8 253 abort();
254}
255#else
256#define ASSERT(p)
257#endif
258
2304df62 259Malloc_t
8d063cd8 260malloc(nbytes)
ee0007ab 261 register MEM_SIZE nbytes;
8d063cd8 262{
263 register union overhead *p;
264 register int bucket = 0;
ee0007ab 265 register MEM_SIZE shiftr;
8d063cd8 266
55497cff 267#ifdef PERL_CORE
45d8adaa 268#ifdef DEBUGGING
ee0007ab 269 MEM_SIZE size = nbytes;
45d8adaa 270#endif
271
55497cff 272#ifdef HAS_64K_LIMIT
45d8adaa 273 if (nbytes > 0xffff) {
760ac839 274 PerlIO_printf(PerlIO_stderr(), "Allocation too large: %lx\n", (long)nbytes);
79072805 275 my_exit(1);
45d8adaa 276 }
55497cff 277#endif /* HAS_64K_LIMIT */
45d8adaa 278#ifdef DEBUGGING
279 if ((long)nbytes < 0)
463ee0b2 280 croak("panic: malloc");
45d8adaa 281#endif
55497cff 282#endif /* PERL_CORE */
45d8adaa 283
8d063cd8 284 /*
285 * Convert amount of memory requested into
286 * closest block size stored in hash buckets
287 * which satisfies request. Account for
288 * space used per block for accounting.
289 */
cf5c4ad8 290#ifdef PACK_MALLOC
291 if (nbytes > MAX_2_POT_ALGO) {
292#endif
55497cff 293#ifdef TWO_POT_OPTIMIZE
294 if (nbytes >= FIRST_BIG_BOUND) {
295 nbytes -= PERL_PAGESIZE;
296 }
297#endif
cf5c4ad8 298 nbytes += M_OVERHEAD;
299 nbytes = (nbytes + 3) &~ 3;
300#ifdef PACK_MALLOC
301 } else if (nbytes == 0) {
302 nbytes = 1;
303 }
304#endif
8d063cd8 305 shiftr = (nbytes - 1) >> 2;
306 /* apart from this loop, this is O(1) */
307 while (shiftr >>= 1)
308 bucket++;
309 /*
310 * If nothing in hash bucket right now,
311 * request more memory from the system.
312 */
313 if (nextf[bucket] == NULL)
314 morecore(bucket);
45d8adaa 315 if ((p = (union overhead *)nextf[bucket]) == NULL) {
55497cff 316#ifdef PERL_CORE
ee0007ab 317 if (!nomemok) {
760ac839 318 PerlIO_puts(PerlIO_stderr(),"Out of memory!\n");
79072805 319 my_exit(1);
ee0007ab 320 }
45d8adaa 321#else
8d063cd8 322 return (NULL);
45d8adaa 323#endif
324 }
325
55497cff 326#ifdef PERL_CORE
760ac839 327 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) malloc %ld bytes\n",
a0d0e21e 328 (unsigned long)(p+1),an++,(long)size));
55497cff 329#endif /* PERL_CORE */
45d8adaa 330
8d063cd8 331 /* remove from linked list */
bf38876a 332#ifdef RCHECK
333 if (*((int*)p) & (sizeof(union overhead) - 1))
760ac839 334 PerlIO_printf(PerlIO_stderr(), "Corrupt malloc ptr 0x%lx at 0x%lx\n",
a0d0e21e 335 (unsigned long)*((int*)p),(unsigned long)p);
bf38876a 336#endif
337 nextf[bucket] = p->ov_next;
cf5c4ad8 338 OV_MAGIC(p, bucket) = MAGIC;
339#ifndef PACK_MALLOC
340 OV_INDEX(p) = bucket;
341#endif
8d063cd8 342#ifdef RCHECK
343 /*
344 * Record allocated size of block and
345 * bound space with magic numbers.
346 */
347 if (nbytes <= 0x10000)
348 p->ov_size = nbytes - 1;
349 p->ov_rmagic = RMAGIC;
350 *((u_int *)((caddr_t)p + nbytes - RSLOP)) = RMAGIC;
351#endif
cf5c4ad8 352 return ((Malloc_t)(p + CHUNK_SHIFT));
8d063cd8 353}
354
355/*
356 * Allocate more memory to the indicated bucket.
357 */
a0d0e21e 358static void
8d063cd8 359morecore(bucket)
a687059c 360 register int bucket;
8d063cd8 361{
362 register union overhead *op;
363 register int rnu; /* 2^rnu bytes will be requested */
364 register int nblks; /* become nblks blocks of the desired size */
bbce6d69 365 register MEM_SIZE siz, needed;
cf5c4ad8 366 int slack = 0;
8d063cd8 367
368 if (nextf[bucket])
369 return;
55497cff 370 if (bucket == (sizeof(MEM_SIZE)*8 - 3)) {
371 croak("Allocation too large");
372 }
8d063cd8 373 /*
374 * Insure memory is allocated
375 * on a page boundary. Should
376 * make getpageize call?
377 */
ee0007ab 378#ifndef atarist /* on the atari we dont have to worry about this */
8d063cd8 379 op = (union overhead *)sbrk(0);
cf5c4ad8 380# ifndef I286
381# ifdef PACK_MALLOC
ff68c719 382 if ((u_int)op & 0x7ff)
383 (void)sbrk(slack = 2048 - ((u_int)op & 0x7ff));
cf5c4ad8 384# else
ff68c719 385 if ((u_int)op & 0x3ff)
386 (void)sbrk(slack = 1024 - ((u_int)op & 0x3ff));
cf5c4ad8 387# endif
5f05dabc 388# if defined(DEBUGGING_MSTATS)
cf5c4ad8 389 sbrk_slack += slack;
390# endif
391# else
a687059c 392 /* The sbrk(0) call on the I286 always returns the next segment */
cf5c4ad8 393# endif
ee0007ab 394#endif /* atarist */
a687059c 395
ee0007ab 396#if !(defined(I286) || defined(atarist))
8d063cd8 397 /* take 2k unless the block is bigger than that */
398 rnu = (bucket <= 8) ? 11 : bucket + 3;
a687059c 399#else
400 /* take 16k unless the block is bigger than that
ee0007ab 401 (80286s like large segments!), probably good on the atari too */
a687059c 402 rnu = (bucket <= 11) ? 14 : bucket + 3;
403#endif
8d063cd8 404 nblks = 1 << (rnu - (bucket + 3)); /* how many blocks to get */
bbce6d69 405 needed = (MEM_SIZE)1 << rnu;
55497cff 406#ifdef TWO_POT_OPTIMIZE
bbce6d69 407 needed += (bucket >= (FIRST_BIG_TWO_POT - 3) ? PERL_PAGESIZE : 0);
55497cff 408#endif
bbce6d69 409 op = (union overhead *)sbrk(needed);
8d063cd8 410 /* no more room! */
ff68c719 411 if (op == (union overhead *)-1) {
412 op = (union overhead *)emergency_sbrk(needed);
413 if (op == (union overhead *)-1)
8d063cd8 414 return;
ff68c719 415 }
5f05dabc 416#ifdef DEBUGGING_MSTATS
417 goodsbrk += needed;
418#endif
8d063cd8 419 /*
420 * Round up to minimum allocation size boundary
421 * and deduct from block count to reflect.
422 */
a687059c 423#ifndef I286
cf5c4ad8 424# ifdef PACK_MALLOC
ff68c719 425 if ((u_int)op & 0x7ff)
cf5c4ad8 426 croak("panic: Off-page sbrk");
427# endif
ff68c719 428 if ((u_int)op & 7) {
ee0007ab 429 op = (union overhead *)(((MEM_SIZE)op + 8) &~ 7);
8d063cd8 430 nblks--;
431 }
a687059c 432#else
433 /* Again, this should always be ok on an 80286 */
434#endif
8d063cd8 435 /*
436 * Add new memory allocated to that on
437 * free list for this hash bucket.
438 */
8d063cd8 439 siz = 1 << (bucket + 3);
cf5c4ad8 440#ifdef PACK_MALLOC
441 *(u_char*)op = bucket; /* Fill index. */
442 if (bucket <= MAX_PACKED - 3) {
443 op = (union overhead *) ((char*)op + blk_shift[bucket]);
444 nblks = n_blks[bucket];
445# ifdef DEBUGGING_MSTATS
446 start_slack += blk_shift[bucket];
447# endif
448 } else if (bucket <= 11 - 1 - 3) {
449 op = (union overhead *) ((char*)op + blk_shift[bucket]);
450 /* nblks = n_blks[bucket]; */
451 siz -= sizeof(union overhead);
452 } else op++; /* One chunk per block. */
453#endif /* !PACK_MALLOC */
454 nextf[bucket] = op;
5f05dabc 455#ifdef DEBUGGING_MSTATS
456 nmalloc[bucket] += nblks;
457#endif
8d063cd8 458 while (--nblks > 0) {
459 op->ov_next = (union overhead *)((caddr_t)op + siz);
460 op = (union overhead *)((caddr_t)op + siz);
461 }
8595d6f1 462 /* Not all sbrks return zeroed memory.*/
cf5c4ad8 463 op->ov_next = (union overhead *)NULL;
cf5c4ad8 464#ifdef PACK_MALLOC
465 if (bucket == 7 - 3) { /* Special case, explanation is above. */
466 union overhead *n_op = nextf[7 - 3]->ov_next;
467 nextf[7 - 3] = (union overhead *)((caddr_t)nextf[7 - 3]
468 - sizeof(union overhead));
469 nextf[7 - 3]->ov_next = n_op;
470 }
471#endif /* !PACK_MALLOC */
8d063cd8 472}
473
94b6baf5 474Free_t
352d5a3a 475free(mp)
2304df62 476 Malloc_t mp;
8d063cd8 477{
ee0007ab 478 register MEM_SIZE size;
8d063cd8 479 register union overhead *op;
352d5a3a 480 char *cp = (char*)mp;
cf5c4ad8 481#ifdef PACK_MALLOC
482 u_char bucket;
483#endif
8d063cd8 484
55497cff 485#ifdef PERL_CORE
760ac839 486 DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%lx: (%05d) free\n",(unsigned long)cp,an++));
55497cff 487#endif /* PERL_CORE */
45d8adaa 488
cf5c4ad8 489 if (cp == NULL)
490 return;
491 op = (union overhead *)((caddr_t)cp
492 - sizeof (union overhead) * CHUNK_SHIFT);
493#ifdef PACK_MALLOC
494 bucket = OV_INDEX(op);
495#endif
760ac839 496#ifdef DEBUGGING
cf5c4ad8 497 ASSERT(OV_MAGIC(op, bucket) == MAGIC); /* make sure it was in use */
8d063cd8 498#else
cf5c4ad8 499 if (OV_MAGIC(op, bucket) != MAGIC) {
500 static bad_free_warn = -1;
501 if (bad_free_warn == -1) {
502 char *pbf = getenv("PERL_BADFREE");
503 bad_free_warn = (pbf) ? atoi(pbf) : 1;
504 }
505 if (!bad_free_warn)
506 return;
8990e307 507#ifdef RCHECK
a687059c 508 warn("%s free() ignored",
8990e307 509 op->ov_rmagic == RMAGIC - 1 ? "Duplicate" : "Bad");
510#else
511 warn("Bad free() ignored");
512#endif
8d063cd8 513 return; /* sanity */
378cc40b 514 }
8d063cd8 515#endif
516#ifdef RCHECK
517 ASSERT(op->ov_rmagic == RMAGIC);
cf5c4ad8 518 if (OV_INDEX(op) <= 13)
8d063cd8 519 ASSERT(*(u_int *)((caddr_t)op + op->ov_size + 1 - RSLOP) == RMAGIC);
8990e307 520 op->ov_rmagic = RMAGIC - 1;
8d063cd8 521#endif
cf5c4ad8 522 ASSERT(OV_INDEX(op) < NBUCKETS);
523 size = OV_INDEX(op);
8d063cd8 524 op->ov_next = nextf[size];
525 nextf[size] = op;
8d063cd8 526}
527
528/*
529 * When a program attempts "storage compaction" as mentioned in the
530 * old malloc man page, it realloc's an already freed block. Usually
531 * this is the last block it freed; occasionally it might be farther
532 * back. We have to search all the free lists for the block in order
533 * to determine its bucket: 1st we make one pass thru the lists
534 * checking only the first block in each; if that fails we search
378cc40b 535 * ``reall_srchlen'' blocks in each list for a match (the variable
8d063cd8 536 * is extern so the caller can modify it). If that fails we just copy
537 * however many bytes was given to realloc() and hope it's not huge.
538 */
378cc40b 539int reall_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */
8d063cd8 540
2304df62 541Malloc_t
352d5a3a 542realloc(mp, nbytes)
2304df62 543 Malloc_t mp;
ee0007ab 544 MEM_SIZE nbytes;
8d063cd8 545{
ee0007ab 546 register MEM_SIZE onb;
8d063cd8 547 union overhead *op;
548 char *res;
549 register int i;
550 int was_alloced = 0;
352d5a3a 551 char *cp = (char*)mp;
8d063cd8 552
55497cff 553#ifdef PERL_CORE
45d8adaa 554#ifdef DEBUGGING
ee0007ab 555 MEM_SIZE size = nbytes;
45d8adaa 556#endif
557
55497cff 558#ifdef HAS_64K_LIMIT
45d8adaa 559 if (nbytes > 0xffff) {
760ac839 560 PerlIO_printf(PerlIO_stderr(), "Reallocation too large: %lx\n", size);
79072805 561 my_exit(1);
45d8adaa 562 }
55497cff 563#endif /* HAS_64K_LIMIT */
45d8adaa 564 if (!cp)
ee0007ab 565 return malloc(nbytes);
45d8adaa 566#ifdef DEBUGGING
567 if ((long)nbytes < 0)
463ee0b2 568 croak("panic: realloc");
45d8adaa 569#endif
55497cff 570#endif /* PERL_CORE */
45d8adaa 571
cf5c4ad8 572 op = (union overhead *)((caddr_t)cp
573 - sizeof (union overhead) * CHUNK_SHIFT);
574 i = OV_INDEX(op);
575 if (OV_MAGIC(op, i) == MAGIC) {
55497cff 576 was_alloced = 1;
8d063cd8 577 } else {
578 /*
579 * Already free, doing "compaction".
580 *
581 * Search for the old block of memory on the
582 * free list. First, check the most common
583 * case (last element free'd), then (this failing)
378cc40b 584 * the last ``reall_srchlen'' items free'd.
8d063cd8 585 * If all lookups fail, then assume the size of
586 * the memory block being realloc'd is the
587 * smallest possible.
588 */
589 if ((i = findbucket(op, 1)) < 0 &&
378cc40b 590 (i = findbucket(op, reall_srchlen)) < 0)
8d063cd8 591 i = 0;
592 }
cf5c4ad8 593 onb = (1L << (i + 3)) -
594#ifdef PACK_MALLOC
595 (i <= (MAX_PACKED - 3) ? 0 : M_OVERHEAD)
596#else
597 M_OVERHEAD
598#endif
55497cff 599#ifdef TWO_POT_OPTIMIZE
600 + (i >= (FIRST_BIG_TWO_POT - 3) ? PERL_PAGESIZE : 0)
601#endif
cf5c4ad8 602 ;
55497cff 603 /*
604 * avoid the copy if same size block.
605 * We are not agressive with boundary cases. Note that it is
606 * possible for small number of cases give false negative if
607 * both new size and old one are in the bucket for
608 * FIRST_BIG_TWO_POT, but the new one is near the lower end.
609 */
8d063cd8 610 if (was_alloced &&
55497cff 611 nbytes <= onb && (nbytes > ( (onb >> 1) - M_OVERHEAD )
612#ifdef TWO_POT_OPTIMIZE
613 || (i == (FIRST_BIG_TWO_POT - 3)
614 && nbytes >= LAST_SMALL_BOUND )
615#endif
616 )) {
a687059c 617#ifdef RCHECK
618 /*
619 * Record new allocated size of block and
620 * bound space with magic numbers.
621 */
cf5c4ad8 622 if (OV_INDEX(op) <= 13) {
a687059c 623 /*
624 * Convert amount of memory requested into
625 * closest block size stored in hash buckets
626 * which satisfies request. Account for
627 * space used per block for accounting.
628 */
cf5c4ad8 629 nbytes += M_OVERHEAD;
a687059c 630 nbytes = (nbytes + 3) &~ 3;
631 op->ov_size = nbytes - 1;
632 *((u_int *)((caddr_t)op + nbytes - RSLOP)) = RMAGIC;
633 }
634#endif
45d8adaa 635 res = cp;
a687059c 636 }
45d8adaa 637 else {
638 if ((res = (char*)malloc(nbytes)) == NULL)
639 return (NULL);
640 if (cp != res) /* common optimization */
ee0007ab 641 Copy(cp, res, (MEM_SIZE)(nbytes<onb?nbytes:onb), char);
45d8adaa 642 if (was_alloced)
643 free(cp);
644 }
645
55497cff 646#ifdef PERL_CORE
45d8adaa 647#ifdef DEBUGGING
a0d0e21e 648 if (debug & 128) {
760ac839 649 PerlIO_printf(PerlIO_stderr(), "0x%lx: (%05d) rfree\n",(unsigned long)res,an++);
650 PerlIO_printf(PerlIO_stderr(), "0x%lx: (%05d) realloc %ld bytes\n",
a0d0e21e 651 (unsigned long)res,an++,(long)size);
652 }
45d8adaa 653#endif
55497cff 654#endif /* PERL_CORE */
2304df62 655 return ((Malloc_t)res);
8d063cd8 656}
657
658/*
659 * Search ``srchlen'' elements of each free list for a block whose
660 * header starts at ``freep''. If srchlen is -1 search the whole list.
661 * Return bucket number, or -1 if not found.
662 */
ee0007ab 663static int
8d063cd8 664findbucket(freep, srchlen)
665 union overhead *freep;
666 int srchlen;
667{
668 register union overhead *p;
669 register int i, j;
670
671 for (i = 0; i < NBUCKETS; i++) {
672 j = 0;
673 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
674 if (p == freep)
675 return (i);
676 j++;
677 }
678 }
679 return (-1);
680}
681
cf5c4ad8 682Malloc_t
683calloc(elements, size)
684 register MEM_SIZE elements;
685 register MEM_SIZE size;
686{
687 long sz = elements * size;
688 Malloc_t p = malloc(sz);
689
690 if (p) {
691 memset((void*)p, 0, sz);
692 }
693 return p;
694}
695
c07a80fd 696#ifdef DEBUGGING_MSTATS
8d063cd8 697/*
698 * mstats - print out statistics about malloc
699 *
700 * Prints two lines of numbers, one showing the length of the free list
701 * for each size category, the second showing the number of mallocs -
702 * frees for each size category.
703 */
ee0007ab 704void
c07a80fd 705dump_mstats(s)
8d063cd8 706 char *s;
707{
708 register int i, j;
709 register union overhead *p;
5f05dabc 710 int topbucket=0, totfree=0, total=0;
c07a80fd 711 u_int nfree[NBUCKETS];
8d063cd8 712
c07a80fd 713 for (i=0; i < NBUCKETS; i++) {
8d063cd8 714 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
715 ;
c07a80fd 716 nfree[i] = j;
717 totfree += nfree[i] * (1 << (i + 3));
5f05dabc 718 total += nmalloc[i] * (1 << (i + 3));
719 if (nmalloc[i])
c07a80fd 720 topbucket = i;
721 }
722 if (s)
760ac839 723 PerlIO_printf(PerlIO_stderr(), "Memory allocation statistics %s (buckets 8..%d)\n",
c07a80fd 724 s, (1 << (topbucket + 3)) );
5f05dabc 725 PerlIO_printf(PerlIO_stderr(), "%8d free:", totfree);
c07a80fd 726 for (i=0; i <= topbucket; i++) {
5f05dabc 727 PerlIO_printf(PerlIO_stderr(), (i<5 || i==7)?" %5d": (i<9)?" %3d":" %d", nfree[i]);
8d063cd8 728 }
5f05dabc 729 PerlIO_printf(PerlIO_stderr(), "\n%8d used:", total - totfree);
c07a80fd 730 for (i=0; i <= topbucket; i++) {
5f05dabc 731 PerlIO_printf(PerlIO_stderr(), (i<5 || i==7)?" %5d": (i<9)?" %3d":" %d", nmalloc[i] - nfree[i]);
c07a80fd 732 }
5f05dabc 733 PerlIO_printf(PerlIO_stderr(), "\nTotal sbrk(): %8d. Odd ends: sbrk(): %7d, malloc(): %7d bytes.\n",
734 goodsbrk + sbrk_slack, sbrk_slack, start_slack);
c07a80fd 735}
736#else
737void
738dump_mstats(s)
739 char *s;
740{
8d063cd8 741}
742#endif
a687059c 743#endif /* lint */
cf5c4ad8 744
745
746#ifdef USE_PERL_SBRK
747
760ac839 748# ifdef NeXT
749# define PERL_SBRK_VIA_MALLOC
750# endif
751
752# ifdef PERL_SBRK_VIA_MALLOC
72e5b9db 753# if defined(HIDEMYMALLOC) || defined(EMBEDMYMALLOC)
760ac839 754# undef malloc
755# else
72e5b9db 756# include "Error: -DPERL_SBRK_VIA_MALLOC needs -D(HIDE|EMBED)MYMALLOC"
760ac839 757# endif
cf5c4ad8 758
759/* it may seem schizophrenic to use perl's malloc and let it call system */
760/* malloc, the reason for that is only the 3.2 version of the OS that had */
761/* frequent core dumps within nxzonefreenolock. This sbrk routine put an */
762/* end to the cores */
763
760ac839 764# define SYSTEM_ALLOC(a) malloc(a)
cf5c4ad8 765
760ac839 766# endif /* PERL_SBRK_VIA_MALLOC */
cf5c4ad8 767
768static IV Perl_sbrk_oldchunk;
769static long Perl_sbrk_oldsize;
770
760ac839 771# define PERLSBRK_32_K (1<<15)
772# define PERLSBRK_64_K (1<<16)
cf5c4ad8 773
774char *
775Perl_sbrk(size)
776int size;
777{
778 IV got;
779 int small, reqsize;
780
781 if (!size) return 0;
55497cff 782#ifdef PERL_CORE
cf5c4ad8 783 reqsize = size; /* just for the DEBUG_m statement */
784#endif
785 if (size <= Perl_sbrk_oldsize) {
786 got = Perl_sbrk_oldchunk;
787 Perl_sbrk_oldchunk += size;
788 Perl_sbrk_oldsize -= size;
789 } else {
790 if (size >= PERLSBRK_32_K) {
791 small = 0;
792 } else {
55497cff 793#ifndef PERL_CORE
cf5c4ad8 794 reqsize = size;
795#endif
796 size = PERLSBRK_64_K;
797 small = 1;
798 }
799 got = (IV)SYSTEM_ALLOC(size);
800 if (small) {
801 /* Chunk is small, register the rest for future allocs. */
802 Perl_sbrk_oldchunk = got + reqsize;
803 Perl_sbrk_oldsize = size - reqsize;
804 }
805 }
806
55497cff 807#ifdef PERL_CORE
760ac839 808 DEBUG_m(PerlIO_printf(PerlIO_stderr(), "sbrk malloc size %ld (reqsize %ld), left size %ld, give addr 0x%lx\n",
cf5c4ad8 809 size, reqsize, Perl_sbrk_oldsize, got));
810#endif
811
812 return (void *)got;
813}
814
815#endif /* ! defined USE_PERL_SBRK */