1 /* dynamic memory allocation for GNU.
2 Copyright (C) 1985, 1987 Free Software Foundation, Inc.
6 BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
7 NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT
8 WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
9 RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
10 WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
11 BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
12 FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY
13 AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
14 DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
17 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
18 STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
19 WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
20 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
21 OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
22 USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
23 DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
24 A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
25 PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
26 DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
28 GENERAL PUBLIC LICENSE TO COPY
30 1. You may copy and distribute verbatim copies of this source file
31 as you receive it, in any medium, provided that you conspicuously and
32 appropriately publish on each copy a valid copyright notice "Copyright
33 (C) 1985 Free Software Foundation, Inc."; and include following the
34 copyright notice a verbatim copy of the above disclaimer of warranty
35 and of this License. You may charge a distribution fee for the
36 physical act of transferring a copy.
38 2. You may modify your copy or copies of this source file or
39 any portion of it, and copy and distribute such modifications under
40 the terms of Paragraph 1 above, provided that you also do the following:
42 a) cause the modified files to carry prominent notices stating
43 that you changed the files and the date of any change; and
45 b) cause the whole of any work that you distribute or publish,
46 that in whole or in part contains or is a derivative of this
47 program or any part thereof, to be licensed at no charge to all
48 third parties on terms identical to those contained in this
49 License Agreement (except that you may choose to grant more extensive
50 warranty protection to some or all third parties, at your option).
52 c) You may charge a distribution fee for the physical act of
53 transferring a copy, and you may at your option offer warranty
54 protection in exchange for a fee.
56 Mere aggregation of another unrelated program with this program (or its
57 derivative) on a volume of a storage or distribution medium does not bring
58 the other program under the scope of these terms.
60 3. You may copy and distribute this program (or a portion or derivative
61 of it, under Paragraph 2) in object code or executable form under the terms
62 of Paragraphs 1 and 2 above provided that you also do one of the following:
64 a) accompany it with the complete corresponding machine-readable
65 source code, which must be distributed under the terms of
66 Paragraphs 1 and 2 above; or,
68 b) accompany it with a written offer, valid for at least three
69 years, to give any third party free (except for a nominal
70 shipping charge) a complete machine-readable copy of the
71 corresponding source code, to be distributed under the terms of
72 Paragraphs 1 and 2 above; or,
74 c) accompany it with the information you received as to where the
75 corresponding source code may be obtained. (This alternative is
76 allowed only for noncommercial distribution and only if you
77 received the program in object code or executable form alone.)
79 For an executable file, complete source code means all the source code for
80 all modules it contains; but, as a special exception, it need not include
81 source code for modules which are standard libraries that accompany the
82 operating system on which the executable file runs.
84 4. You may not copy, sublicense, distribute or transfer this program
85 except as expressly provided under this License Agreement. Any attempt
86 otherwise to copy, sublicense, distribute or transfer this program is void and
87 your rights to use the program under this License agreement shall be
88 automatically terminated. However, parties who have received computer
89 software programs from you with this License Agreement will not have
90 their licenses terminated so long as such parties remain in full compliance.
92 5. If you wish to incorporate parts of this program into other free
93 programs whose distribution conditions are different, write to the
94 Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
95 MA 02111-1307, USA.. We have not yet worked out a simple rule that
96 can be stated here, but we will often permit this. We will be guided
97 by the two goals of preserving the free status of all derivatives of
98 our free software and of promoting the sharing and reuse of software.
101 In other words, you are welcome to use, share and improve this program.
102 You are forbidden to forbid anyone else to use, share and improve
103 what you give them. Help stamp out software-hoarding! */
105 /* Synched up with: Not synched with FSF. */
109 * @(#)nmalloc.c 1 (Caltech) 2/21/82
111 * U of M Modified: 20 Jun 1983 ACT: strange hacks for Emacs
113 * Nov 1983, Mike@BRL, Added support for 4.1C/4.2 BSD.
115 * This is a very fast storage allocator. It allocates blocks of a small
116 * number of different sizes, and keeps free lists of each size. Blocks
117 * that don't exactly fit are passed up to the next larger size. In this
118 * implementation, the available sizes are (2^n)-4 (or -16) bytes long.
119 * This is designed for use in a program that uses vast quantities of
120 * memory, but bombs when it runs out. To make it a little better, it
121 * warns the user when he starts to get near the end.
123 * June 84, ACT: modified rcheck code to check the range given to malloc,
124 * rather than the range determined by the 2-power used.
126 * Jan 85, RMS: calls malloc_warning to issue warning on nearly full.
127 * No longer Emacs-specific; can serve as all-purpose malloc for GNU.
128 * You should call malloc_init to reinitialize after loading dumped Emacs.
129 * Call malloc_stats to get info on memory stats if MSTATS turned on.
130 * realloc knows how to return same block given, just changing its size,
131 * if the power of 2 is correct.
135 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
136 * smallest allocatable block is 8 bytes. The overhead information will
137 * go in the first int of the block, and the returned pointer will point
141 * nmalloc[i] is the difference between the number of mallocs and frees
142 * for a given block size.
147 /* config.h specifies which kind of system this is. */
151 /* Determine which kind of system this is. */
167 #endif /* not emacs */
171 /* Define getpagesize () if the system does not. */
172 #include "getpagesize.h"
180 #include <sys/vlimit.h> /* warn the user when near the end */
182 #else /* if BSD4_2 */
183 #include <sys/time.h>
184 #include <sys/resource.h>
189 /* not sure where this for NetBSD should really go
190 and it probably applies to other systems */
191 #if !defined(__NetBSD__) && !defined(__bsdi__) && !defined(__OpenBSD__)
192 extern void *sbrk (ptrdiff_t);
194 extern char *sbrk ();
195 #endif /* __NetBSD__ or __OpenBSD__ */
198 extern void *sbrk ();
199 #endif /* __STDC__ */
201 extern char *start_of_data (void);
204 #ifndef DATA_SEG_BITS
205 #define start_of_data() &etext
210 #define start_of_data() &etext
213 #define ISALLOC ((char) 0xf7) /* magic byte that implies allocation */
214 #define ISFREE ((char) 0x54) /* magic byte that implies free block */
215 /* this is for error checking only */
216 #define ISMEMALIGN ((char) 0xd6) /* Stored before the value returned by
217 memalign, with the rest of the word
218 being the distance to the true
219 beginning of the block. */
223 /* These two are for user programs to look at, when they are interested. */
225 unsigned int malloc_sbrk_used; /* amount of data space used now */
226 unsigned int malloc_sbrk_unused; /* amount more we can have */
228 /* start of data space; can be changed by calling init_malloc */
229 static char *data_space_start;
232 static int nmalloc[30];
233 static int nmal, nfre;
236 /* If range checking is not turned on, all we have is a flag indicating
237 whether memory is allocated, an index in nextf[], and a size field; to
238 realloc() memory we copy either size bytes or 1<<(index+3) bytes depending
239 on whether the former can hold the exact size (given the value of
240 'index'). If range checking is on, we always need to know how much space
241 is allocated, so the 'size' field is never used. */
244 char mh_alloc; /* ISALLOC or ISFREE */
245 char mh_index; /* index in nextf[] */
246 /* Remainder are valid only when block is allocated */
247 unsigned short mh_size; /* size, if < 0x10000 */
249 unsigned mh_nbytes; /* number of bytes allocated */
250 int mh_magic4; /* should be == MAGIC4 */
254 /* Access free-list pointer of a block.
255 It is stored at block + 4.
256 This is not a field in the mhead structure
257 because we want sizeof (struct mhead)
258 to describe the overhead for when the block is in use,
259 and we do not want the free-list pointer to count in that. */
262 (*(struct mhead **) (sizeof (char *) + (char *) (a)))
266 /* To implement range checking, we write magic values in at the beginning and
267 end of each allocated block, and make sure they are undisturbed whenever a
268 free or a realloc occurs. */
269 /* Written in each of the 4 bytes following the block's real space */
271 /* Written in the 4 bytes before the block's real space */
272 #define MAGIC4 0x55555555
273 #define ASSERT(p) if (!(p)) botch("p"); else
274 #define EXTRA 4 /* 4 bytes extra for MAGIC1s */
281 /* nextf[i] is free list of blocks of size 2**(i + 3) */
283 static struct mhead *nextf[30];
285 /* busy[i] is nonzero while allocation of block size i is in progress. */
287 static char busy[30];
289 /* Number of bytes of writable memory we can expect to be able to get */
290 extern unsigned int lim_data;
292 /* Level number of warnings already issued.
293 0 -- no warnings issued.
294 1 -- 75% warning already issued.
295 2 -- 85% warning already issued.
297 static int warnlevel;
299 /* Function to call to issue a warning;
300 0 means don't issue them. */
301 static void (*warnfunction) ();
303 /* nonzero once initial bunch of free blocks made */
308 static void getpool (void);
310 /* Cause reinitialization based on job parameters;
311 also declare where the end of pure storage is. */
313 malloc_init (start, warnfun)
318 data_space_start = start;
321 warnfunction = warnfun;
324 /* Return the maximum size to which MEM can be realloc'd
325 without actually requiring copying. */
328 malloc_usable_size (mem)
331 int blocksize = 8 << (((struct mhead *) mem) - 1) -> mh_index;
333 return blocksize - sizeof (struct mhead) - EXTRA;
336 static void get_lim_data ();
339 morecore (nu) /* ask system for more memory */
340 int nu; /* size index to get more of */
349 /* ?? There was a suggestion not to block SIGILL, somehow for GDB's sake. */
350 oldmask = sigsetmask (-1);
354 if (!data_space_start)
356 data_space_start = start_of_data ();
362 /* On initial startup, get two blocks of each size up to 1k bytes */
364 { getpool (); getpool (); gotpool = 1; }
366 /* Find current end of memory and issue warning if getting near max */
369 siz = cp - data_space_start;
375 if (siz > (lim_data / 4) * 3)
378 (*warnfunction) ("Warning: past 75% of memory limit");
382 if (siz > (lim_data / 20) * 17)
385 (*warnfunction) ("Warning: past 85% of memory limit");
389 if (siz > (lim_data / 20) * 19)
392 (*warnfunction) ("Warning: past 95% of memory limit");
397 if ((int) cp & 0x3ff) /* land on 1K boundaries */
398 sbrk (1024 - ((int) cp & 0x3ff));
400 /* Take at least 2k, and figure out how many blocks of the desired size
401 we're about to get */
404 nblks = 1 << ((siz = 8) - nu);
406 if ((cp = sbrk (1 << (siz + 3))) == (char *) -1)
410 sigsetmask (oldmask);
413 return; /* no more room! */
415 malloc_sbrk_used = siz;
416 malloc_sbrk_unused = lim_data - siz;
419 { /* shouldn't happen, but just in case */
420 cp = (char *) (((int) cp + 8) & ~7);
424 /* save new header and link the nblks blocks together */
425 nextf[nu] = (struct mhead *) cp;
429 ((struct mhead *) cp) -> mh_alloc = ISFREE;
430 ((struct mhead *) cp) -> mh_index = nu;
431 if (--nblks <= 0) break;
432 CHAIN ((struct mhead *) cp) = (struct mhead *) (cp + siz);
435 CHAIN ((struct mhead *) cp) = 0;
439 sigsetmask (oldmask);
450 if ((int) cp & 0x3ff) /* land on 1K boundaries */
451 sbrk (1024 - ((int) cp & 0x3ff));
453 /* Record address of start of space allocated by malloc. */
454 if (_malloc_base == 0)
457 /* Get 2k of storage */
460 if (cp == (char *) -1)
463 /* Divide it into an initial 8-word block
464 plus one block of size 2**nu for nu = 3 ... 10. */
466 CHAIN (cp) = nextf[0];
467 nextf[0] = (struct mhead *) cp;
468 ((struct mhead *) cp) -> mh_alloc = ISFREE;
469 ((struct mhead *) cp) -> mh_index = 0;
472 for (nu = 0; nu < 7; nu++)
474 CHAIN (cp) = nextf[nu];
475 nextf[nu] = (struct mhead *) cp;
476 ((struct mhead *) cp) -> mh_alloc = ISFREE;
477 ((struct mhead *) cp) -> mh_index = nu;
483 malloc (n) /* get a block */
490 /* Figure out how many bytes are required, rounding up to the nearest
491 multiple of 8, then figure out which nestf[] area to use.
492 Both the beginning of the header and the beginning of the
493 block should be on an eight byte boundary. */
494 nbytes = (n + ((sizeof *p + 7) & ~7) + EXTRA + 7) & ~7;
496 unsigned int shiftr = (nbytes - 1) >> 2;
502 /* In case this is reentrant use of malloc from signal handler,
503 pick a block size that no other malloc level is currently
504 trying to allocate. That's the easiest harmless way not to
505 interfere with the other level of execution. */
506 while (busy[nunits]) nunits++;
509 /* If there are no blocks of the appropriate size, go get some */
510 /* COULD SPLIT UP A LARGER BLOCK HERE ... ACT */
511 if (nextf[nunits] == 0)
514 /* Get one block off the list, and set the new list head */
515 if ((p = nextf[nunits]) == 0)
520 nextf[nunits] = CHAIN (p);
523 /* Check for free block clobbered */
524 /* If not for this check, we would gobble a clobbered free chain ptr */
525 /* and bomb out on the NEXT allocate of this size block */
526 if (p -> mh_alloc != ISFREE || p -> mh_index != nunits)
528 botch ("block on free list clobbered");
529 #else /* not rcheck */
531 #endif /* not rcheck */
533 /* Fill in the info, and if range checking, set up the magic numbers */
534 p -> mh_alloc = ISALLOC;
537 p -> mh_magic4 = MAGIC4;
539 /* Get the location n after the beginning of the user's space. */
540 char *m = (char *) p + ((sizeof *p + 7) & ~7) + n;
542 *m++ = MAGIC1, *m++ = MAGIC1, *m++ = MAGIC1, *m = MAGIC1;
544 #else /* not rcheck */
546 #endif /* not rcheck */
551 return (char *) p + ((sizeof *p + 7) & ~7);
565 p = (struct mhead *) (ap - ((sizeof *p + 7) & ~7));
566 if (p -> mh_alloc == ISMEMALIGN)
569 p = (struct mhead *) (ap - ((sizeof *p + 7) & ~7));
573 if (p -> mh_alloc != ISALLOC)
577 if (p -> mh_alloc != ISALLOC)
579 if (p -> mh_alloc == ISFREE)
580 botch ("free: Called with already freed block argument\n");
582 botch ("free: Called with bad argument\n");
585 ASSERT (p -> mh_magic4 == MAGIC4);
586 ap += p -> mh_nbytes;
587 ASSERT (*ap++ == MAGIC1); ASSERT (*ap++ == MAGIC1);
588 ASSERT (*ap++ == MAGIC1); ASSERT (*ap == MAGIC1);
592 int nunits = p -> mh_index;
594 ASSERT (nunits <= 29);
595 p -> mh_alloc = ISFREE;
597 /* Protect against signal handlers calling malloc. */
599 /* Put this block on the free list. */
600 CHAIN (p) = nextf[nunits];
623 p = (struct mhead *) (mem - ((sizeof *p + 7) & ~7));
624 nunits = p -> mh_index;
625 ASSERT (p -> mh_alloc == ISALLOC);
627 ASSERT (p -> mh_magic4 == MAGIC4);
629 char *m = mem + (tocopy = p -> mh_nbytes);
630 ASSERT (*m++ == MAGIC1); ASSERT (*m++ == MAGIC1);
631 ASSERT (*m++ == MAGIC1); ASSERT (*m == MAGIC1);
633 #else /* not rcheck */
634 if (p -> mh_index >= 13)
635 tocopy = (1 << (p -> mh_index + 3)) - ((sizeof *p + 7) & ~7);
637 tocopy = p -> mh_size;
638 #endif /* not rcheck */
640 /* See if desired size rounds to same power of 2 as actual size. */
641 nbytes = (n + ((sizeof *p + 7) & ~7) + EXTRA + 7) & ~7;
643 /* If ok, use the same block, just marking its size as changed. */
644 if (nbytes > (4 << nunits) && nbytes <= (8 << nunits))
647 char *m = mem + tocopy;
648 *m++ = 0; *m++ = 0; *m++ = 0; *m++ = 0;
651 *m++ = MAGIC1; *m++ = MAGIC1; *m++ = MAGIC1; *m++ = MAGIC1;
652 #else /* not rcheck */
654 #endif /* not rcheck */
663 if ((new = malloc (n)) == 0)
665 memcpy (new, mem, tocopy);
673 memalign (alignment, size)
674 unsigned alignment, size;
676 char *ptr = malloc (size + alignment);
682 /* If entire block has the desired alignment, just accept it. */
683 if (((int) ptr & (alignment - 1)) == 0)
685 /* Otherwise, get address of byte in the block that has that alignment. */
686 aligned = (char *) (((int) ptr + alignment - 1) & -alignment);
688 /* Store a suitable indication of how to free the block,
689 so that free can find the true beginning of it. */
690 p = (struct mhead *) aligned - 1;
691 p -> mh_size = aligned - ptr;
692 p -> mh_alloc = ISMEMALIGN;
697 /* This runs into trouble with getpagesize on HPUX.
698 Patching out seems cleaner than the ugly fix needed. */
703 return memalign (getpagesize (), size);
705 #endif /* not __hpux */
708 /* Return statistics describing allocation of blocks of size 2**n. */
721 struct mstats_value v;
727 if (size < 0 || size >= 30)
734 v.blocksize = 1 << (size + 3);
735 v.nused = nmalloc[size];
737 for (p = nextf[size]; p; p = CHAIN (p))
750 for (i = 0; i < 30; i++)
752 int allocation_size = 1 << (i + 3);
755 size_used += nmalloc[i] * allocation_size;
769 for (i = 0; i < 30; i++)
771 int allocation_size = 1 << (i + 3);
774 for (p = nextf[i]; p ; p = CHAIN (p))
775 size_unused += allocation_size;
783 * This function returns the total number of bytes that the process
784 * will be allowed to allocate via the sbrk(2) system call. On
785 * BSD systems this is the total space allocatable to stack and
786 * data. On USG systems this is the data space only.
794 #ifdef ULIMIT_BREAK_VALUE
795 lim_data = ULIMIT_BREAK_VALUE;
797 lim_data = ulimit (3, 0);
800 lim_data -= (long) data_space_start;
809 lim_data = vlimit (LIM_DATA, -1);
817 struct rlimit XXrlimit;
819 getrlimit (RLIMIT_DATA, &XXrlimit);
821 lim_data = XXrlimit.rlim_cur & RLIM_INFINITY; /* soft limit */
823 lim_data = XXrlimit.rlim_cur; /* soft limit */