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