Merge remote-tracking branch 'origin/master' into for-steve
[sxemacs] / src / mem / malloc.c
1 /* dynamic memory allocation for GNU.
2    Copyright (C) 1985, 1987 Free Software Foundation, Inc.
3
4                        NO WARRANTY
5
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
15 CORRECTION.
16
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.
27
28                 GENERAL PUBLIC LICENSE TO COPY
29
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.
37
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:
41
42     a) cause the modified files to carry prominent notices stating
43     that you changed the files and the date of any change; and
44
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).
51
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.
55
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.
59
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:
63
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,
67
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,
73
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.)
78
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.
83
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.
91
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.
99
100 In other words, you are welcome to use, share and improve this program.
101 You are forbidden to forbid anyone else to use, share and improve
102 what you give them.   Help stamp out software-hoarding!  */
103
104 /* Synched up with: Not synched with FSF. */
105
106 /*
107  * @(#)nmalloc.c 1 (Caltech) 2/21/82
108  *
109  *      U of M Modified: 20 Jun 1983 ACT: strange hacks for Emacs
110  *
111  *      Nov 1983, Mike@BRL, Added support for 4.1C/4.2 BSD.
112  *
113  * This is a very fast storage allocator.  It allocates blocks of a small
114  * number of different sizes, and keeps free lists of each size.  Blocks
115  * that don't exactly fit are passed up to the next larger size.  In this
116  * implementation, the available sizes are (2^n)-4 (or -16) bytes long.
117  * This is designed for use in a program that uses vast quantities of
118  * memory, but bombs when it runs out.  To make it a little better, it
119  * warns the user when he starts to get near the end.
120  *
121  * June 84, ACT: modified rcheck code to check the range given to malloc,
122  * rather than the range determined by the 2-power used.
123  *
124  * Jan 85, RMS: calls malloc_warning to issue warning on nearly full.
125  * No longer Emacs-specific; can serve as all-purpose malloc for GNU.
126  * You should call malloc_init to reinitialize after loading dumped Emacs.
127  * Call malloc_stats to get info on memory stats if MSTATS turned on.
128  * realloc knows how to return same block given, just changing its size,
129  * if the power of 2 is correct.
130  */
131
132 /*
133  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
134  * smallest allocatable block is 8 bytes.  The overhead information will
135  * go in the first int of the block, and the returned pointer will point
136  * to the second.
137  *
138 #ifdef MSTATS
139  * nmalloc[i] is the difference between the number of mallocs and frees
140  * for a given block size.
141 #endif MSTATS
142  */
143
144 #ifdef emacs
145 /* config.h specifies which kind of system this is.  */
146 #include <config.h>
147 #else
148
149 /* Determine which kind of system this is.  */
150 #include <signal.h>
151 #ifndef SIGTSTP
152 #ifndef USG
153 #define USG
154 #endif
155 #else                           /* SIGTSTP */
156 #ifdef SIGIO
157 #define BSD4_2
158 #endif                          /* SIGIO */
159 #endif                          /* SIGTSTP */
160
161 #if defined(hpux)
162 #define USG
163 #endif
164
165 #endif                          /* not emacs */
166
167 #include <stddef.h>
168
169 /* Define getpagesize () if the system does not.  */
170 #include "ui/getpagesize.h"
171
172 #ifdef HAVE_ULIMIT_H
173 #include <ulimit.h>
174 #endif
175
176 #ifndef BSD4_2
177 #ifndef USG
178 #include <sys/vlimit.h>         /* warn the user when near the end */
179 #endif                          /* not USG */
180 #else                           /* if BSD4_2 */
181 #include <sys/time.h>
182 #include <sys/resource.h>
183 #endif                          /* BSD4_2 */
184
185 #ifdef __STDC__
186 #ifndef HPUX
187 /* not sure where this for NetBSD should really go
188    and it probably applies to other systems */
189 #if !defined(__NetBSD__) && !defined(__bsdi__) && !defined(__OpenBSD__)
190 extern void *sbrk(ptrdiff_t);
191 #else
192 extern char *sbrk();
193 #endif                          /* __NetBSD__ or __OpenBSD__ */
194 #endif                          /* HPUX */
195 #else
196 extern void *sbrk();
197 #endif                          /* __STDC__ */
198
199 extern char *start_of_data(void);
200
201 #ifdef BSD
202 #define start_of_data() &etext
203 #endif
204
205 #ifndef emacs
206 #define start_of_data() &etext
207 #endif
208
209 #define ISALLOC ((char) 0xf7)   /* magic byte that implies allocation */
210 #define ISFREE ((char) 0x54)    /* magic byte that implies free block */
211                                 /* this is for error checking only */
212 #define ISMEMALIGN ((char) 0xd6)        /* Stored before the value returned by
213                                            memalign, with the rest of the word
214                                            being the distance to the true
215                                            beginning of the block.  */
216
217 extern char etext;
218
219 /* These two are for user programs to look at, when they are interested.  */
220
221 unsigned int malloc_sbrk_used;  /* amount of data space used now */
222 unsigned int malloc_sbrk_unused;        /* amount more we can have */
223
224 /* start of data space; can be changed by calling init_malloc */
225 static char *data_space_start;
226
227 #ifdef MSTATS
228 static int nmalloc[30];
229 static int nmal, nfre;
230 #endif                          /* MSTATS */
231
232 /* If range checking is not turned on, all we have is a flag indicating
233    whether memory is allocated, an index in nextf[], and a size field; to
234    realloc() memory we copy either size bytes or 1<<(index+3) bytes depending
235    on whether the former can hold the exact size (given the value of
236    'index').  If range checking is on, we always need to know how much space
237    is allocated, so the 'size' field is never used. */
238
239 struct mhead {
240         char mh_alloc;          /* ISALLOC or ISFREE */
241         char mh_index;          /* index in nextf[] */
242 /* Remainder are valid only when block is allocated */
243         unsigned short mh_size; /* size, if < 0x10000 */
244 #ifdef rcheck
245         unsigned mh_nbytes;     /* number of bytes allocated */
246         int mh_magic4;          /* should be == MAGIC4 */
247 #endif                          /* rcheck */
248 };
249
250 /* Access free-list pointer of a block.
251   It is stored at block + 4.
252   This is not a field in the mhead structure
253   because we want sizeof (struct mhead)
254   to describe the overhead for when the block is in use,
255   and we do not want the free-list pointer to count in that.  */
256
257 #define CHAIN(a) \
258   (*(struct mhead **) (sizeof (char *) + (char *) (a)))
259
260 #ifdef rcheck
261
262 /* To implement range checking, we write magic values in at the beginning and
263    end of each allocated block, and make sure they are undisturbed whenever a
264    free or a realloc occurs. */
265 /* Written in each of the 4 bytes following the block's real space */
266 #define MAGIC1 0x55
267 /* Written in the 4 bytes before the block's real space */
268 #define MAGIC4 0x55555555
269 #define ASSERT(p) if (!(p)) botch("p"); else
270 #define EXTRA  4                /* 4 bytes extra for MAGIC1s */
271 #else
272 #define ASSERT(p)
273 #define EXTRA  0
274 #endif                          /* rcheck */
275
276 /* nextf[i] is free list of blocks of size 2**(i + 3)  */
277
278 static struct mhead *nextf[30];
279
280 /* busy[i] is nonzero while allocation of block size i is in progress.  */
281
282 static char busy[30];
283
284 /* Number of bytes of writable memory we can expect to be able to get */
285 #ifdef _RLIM_T_DECLARED
286 extern rlim_t lim_data;
287 #else
288 extern unsigned long lim_data;
289 #endif
290
291 /* Level number of warnings already issued.
292   0 -- no warnings issued.
293   1 -- 75% warning already issued.
294   2 -- 85% warning already issued.
295 */
296 static int warnlevel;
297
298 /* Function to call to issue a warning;
299    0 means don't issue them.  */
300 static void (*warnfunction) ();
301
302 /* nonzero once initial bunch of free blocks made */
303 static int gotpool;
304
305 char *_malloc_base;
306
307 static void getpool(void);
308
309 /* Cause reinitialization based on job parameters;
310   also declare where the end of pure storage is. */
311 void malloc_init(start, warnfun)
312 char *start;
313 void (*warnfun) ();
314 {
315         if (start)
316                 data_space_start = start;
317         lim_data = 0;
318         warnlevel = 0;
319         warnfunction = warnfun;
320 }
321
322 /* Return the maximum size to which MEM can be realloc'd
323    without actually requiring copying.  */
324
325 int malloc_usable_size(mem)
326 char *mem;
327 {
328         int blocksize = 8 << (((struct mhead *)mem) - 1)->mh_index;
329
330         return blocksize - sizeof(struct mhead) - EXTRA;
331 }
332 \f
333 static void get_lim_data();
334
335 static void morecore(nu)        /* ask system for more memory */
336 int nu;                         /* size index to get more of  */
337 {
338         char *cp;
339         int nblks;
340         unsigned long siz;
341         int oldmask;
342
343 #ifdef BSD
344 #ifndef BSD4_1
345         /* ?? There was a suggestion not to block SIGILL, somehow for GDB's sake.  */
346         oldmask = sigsetmask(-1);
347 #endif
348 #endif
349
350         if (!data_space_start) {
351                 data_space_start = start_of_data();
352         }
353
354         if (lim_data == 0)
355                 get_lim_data();
356
357         /* On initial startup, get two blocks of each size up to 1k bytes */
358         if (!gotpool) {
359                 getpool();
360                 getpool();
361                 gotpool = 1;
362         }
363
364         /* Find current end of memory and issue warning if getting near max */
365
366         cp = sbrk(0);
367         siz = cp - data_space_start;
368
369         if (warnfunction)
370                 switch (warnlevel) {
371                 case 0:
372                         if (siz > (lim_data / 4) * 3) {
373                                 warnlevel++;
374                                 (*warnfunction)
375                                     ("Warning: past 75% of memory limit");
376                         }
377                         break;
378                 case 1:
379                         if (siz > (lim_data / 20) * 17) {
380                                 warnlevel++;
381                                 (*warnfunction)
382                                     ("Warning: past 85% of memory limit");
383                         }
384                         break;
385                 case 2:
386                         if (siz > (lim_data / 20) * 19) {
387                                 warnlevel++;
388                                 (*warnfunction)
389                                     ("Warning: past 95% of memory limit");
390                         }
391                         break;
392                 }
393
394         if ((int)cp & 0x3ff)    /* land on 1K boundaries */
395                 sbrk(1024 - ((int)cp & 0x3ff));
396
397         /* Take at least 2k, and figure out how many blocks of the desired size
398            we're about to get */
399         nblks = 1;
400         if ((siz = nu) < 8)
401                 nblks = 1 << ((siz = 8) - nu);
402
403         if ((cp = sbrk(1 << (siz + 3))) == (char *)-1) {
404 #ifdef BSD
405 #ifndef BSD4_1
406                 sigsetmask(oldmask);
407 #endif
408 #endif
409                 return;         /* no more room! */
410         }
411         malloc_sbrk_used = siz;
412         malloc_sbrk_unused = lim_data - siz;
413
414         if ((int)cp & 7) {      /* shouldn't happen, but just in case */
415                 cp = (char *)(((int)cp + 8) & ~7);
416                 nblks--;
417         }
418
419         /* save new header and link the nblks blocks together */
420         nextf[nu] = (struct mhead *)cp;
421         siz = 1 << (nu + 3);
422         while (1) {
423                 ((struct mhead *)cp)->mh_alloc = ISFREE;
424                 ((struct mhead *)cp)->mh_index = nu;
425                 if (--nblks <= 0)
426                         break;
427                 CHAIN((struct mhead *)cp) = (struct mhead *)(cp + siz);
428                 cp += siz;
429         }
430         CHAIN((struct mhead *)cp) = 0;
431
432 #ifdef BSD
433 #ifndef BSD4_1
434         sigsetmask(oldmask);
435 #endif
436 #endif
437 }
438
439 static void getpool(void)
440 {
441         int nu;
442         char *cp = sbrk(0);
443
444         if ((int)cp & 0x3ff)    /* land on 1K boundaries */
445                 sbrk(1024 - ((int)cp & 0x3ff));
446
447         /* Record address of start of space allocated by malloc.  */
448         if (_malloc_base == 0)
449                 _malloc_base = cp;
450
451         /* Get 2k of storage */
452
453         cp = sbrk(04000);
454         if (cp == (char *)-1)
455                 return;
456
457         /* Divide it into an initial 8-word block
458            plus one block of size 2**nu for nu = 3 ... 10.  */
459
460         CHAIN(cp) = nextf[0];
461         nextf[0] = (struct mhead *)cp;
462         ((struct mhead *)cp)->mh_alloc = ISFREE;
463         ((struct mhead *)cp)->mh_index = 0;
464         cp += 8;
465
466         for (nu = 0; nu < 7; nu++) {
467                 CHAIN(cp) = nextf[nu];
468                 nextf[nu] = (struct mhead *)cp;
469                 ((struct mhead *)cp)->mh_alloc = ISFREE;
470                 ((struct mhead *)cp)->mh_index = nu;
471                 cp += 8 << nu;
472         }
473 }
474 \f
475 char *malloc(n)                 /* get a block */
476 unsigned n;
477 {
478         struct mhead *p;
479         unsigned int nbytes;
480         int nunits = 0;
481
482         /* Figure out how many bytes are required, rounding up to the nearest
483            multiple of 8, then figure out which nestf[] area to use.
484            Both the beginning of the header and the beginning of the
485            block should be on an eight byte boundary.  */
486         nbytes = (n + ((sizeof *p + 7) & ~7) + EXTRA + 7) & ~7;
487         {
488                 unsigned int shiftr = (nbytes - 1) >> 2;
489
490                 while (shiftr >>= 1)
491                         nunits++;
492         }
493
494         /* In case this is reentrant use of malloc from signal handler,
495            pick a block size that no other malloc level is currently
496            trying to allocate.  That's the easiest harmless way not to
497            interfere with the other level of execution.  */
498         while (busy[nunits])
499                 nunits++;
500         busy[nunits] = 1;
501
502         /* If there are no blocks of the appropriate size, go get some */
503         /* COULD SPLIT UP A LARGER BLOCK HERE ... ACT */
504         if (nextf[nunits] == 0)
505                 morecore(nunits);
506
507         /* Get one block off the list, and set the new list head */
508         if ((p = nextf[nunits]) == 0) {
509                 busy[nunits] = 0;
510                 return 0;
511         }
512         nextf[nunits] = CHAIN(p);
513         busy[nunits] = 0;
514
515         /* Check for free block clobbered */
516         /* If not for this check, we would gobble a clobbered free chain ptr */
517         /* and bomb out on the NEXT allocate of this size block */
518         if (p->mh_alloc != ISFREE || p->mh_index != nunits)
519 #ifdef rcheck
520                 botch("block on free list clobbered");
521 #else                           /* not rcheck */
522                 abort();
523 #endif                          /* not rcheck */
524
525         /* Fill in the info, and if range checking, set up the magic numbers */
526         p->mh_alloc = ISALLOC;
527 #ifdef rcheck
528         p->mh_nbytes = n;
529         p->mh_magic4 = MAGIC4;
530         {
531                 /* Get the location n after the beginning of the user's space.  */
532                 char *m = (char *)p + ((sizeof *p + 7) & ~7) + n;
533
534                 *m++ = MAGIC1, *m++ = MAGIC1, *m++ = MAGIC1, *m = MAGIC1;
535         }
536 #else                           /* not rcheck */
537         p->mh_size = n;
538 #endif                          /* not rcheck */
539 #ifdef MSTATS
540         nmalloc[nunits]++;
541         nmal++;
542 #endif                          /* MSTATS */
543         return (char *)p + ((sizeof *p + 7) & ~7);
544 }
545
546 void free(mem)
547 char *mem;
548 {
549         struct mhead *p;
550         {
551                 char *ap = mem;
552
553                 if (ap == 0)
554                         return;
555
556                 p = (struct mhead *)(ap - ((sizeof *p + 7) & ~7));
557                 if (p->mh_alloc == ISMEMALIGN) {
558                         ap -= p->mh_size;
559                         p = (struct mhead *)(ap - ((sizeof *p + 7) & ~7));
560                 }
561 #ifndef rcheck
562                 if (p->mh_alloc != ISALLOC)
563                         abort();
564
565 #else                           /* rcheck */
566                 if (p->mh_alloc != ISALLOC) {
567                         if (p->mh_alloc == ISFREE)
568                                 botch
569                                     ("free: Called with already freed block argument\n");
570                         else
571                                 botch("free: Called with bad argument\n");
572                 }
573
574                 ASSERT(p->mh_magic4 == MAGIC4);
575                 ap += p->mh_nbytes;
576                 ASSERT(*ap++ == MAGIC1);
577                 ASSERT(*ap++ == MAGIC1);
578                 ASSERT(*ap++ == MAGIC1);
579                 ASSERT(*ap == MAGIC1);
580 #endif                          /* rcheck */
581         }
582         {
583                 int nunits = p->mh_index;
584
585                 ASSERT(nunits <= 29);
586                 p->mh_alloc = ISFREE;
587
588                 /* Protect against signal handlers calling malloc.  */
589                 busy[nunits] = 1;
590                 /* Put this block on the free list.  */
591                 CHAIN(p) = nextf[nunits];
592                 nextf[nunits] = p;
593                 busy[nunits] = 0;
594
595 #ifdef MSTATS
596                 nmalloc[nunits]--;
597                 nfre++;
598 #endif                          /* MSTATS */
599         }
600 }
601
602 char *realloc(mem, n)
603 char *mem;
604 unsigned n;
605 {
606         struct mhead *p;
607         unsigned int tocopy;
608         unsigned int nbytes;
609         int nunits;
610
611         if (mem == 0)
612                 return malloc(n);
613         p = (struct mhead *)(mem - ((sizeof *p + 7) & ~7));
614         nunits = p->mh_index;
615         ASSERT(p->mh_alloc == ISALLOC);
616 #ifdef rcheck
617         ASSERT(p->mh_magic4 == MAGIC4);
618         {
619                 char *m = mem + (tocopy = p->mh_nbytes);
620                 ASSERT(*m++ == MAGIC1);
621                 ASSERT(*m++ == MAGIC1);
622                 ASSERT(*m++ == MAGIC1);
623                 ASSERT(*m == MAGIC1);
624         }
625 #else                           /* not rcheck */
626         if (p->mh_index >= 13)
627                 tocopy = (1 << (p->mh_index + 3)) - ((sizeof *p + 7) & ~7);
628         else
629                 tocopy = p->mh_size;
630 #endif                          /* not rcheck */
631
632         /* See if desired size rounds to same power of 2 as actual size. */
633         nbytes = (n + ((sizeof *p + 7) & ~7) + EXTRA + 7) & ~7;
634
635         /* If ok, use the same block, just marking its size as changed.  */
636         if (nbytes > (4 << nunits) && nbytes <= (8 << nunits)) {
637 #ifdef rcheck
638                 char *m = mem + tocopy;
639                 *m++ = 0;
640                 *m++ = 0;
641                 *m++ = 0;
642                 *m++ = 0;
643                 p->mh_nbytes = n;
644                 m = mem + n;
645                 *m++ = MAGIC1;
646                 *m++ = MAGIC1;
647                 *m++ = MAGIC1;
648                 *m++ = MAGIC1;
649 #else                           /* not rcheck */
650                 p->mh_size = n;
651 #endif                          /* not rcheck */
652                 return mem;
653         }
654
655         if (n < tocopy)
656                 tocopy = n;
657         {
658                 char *new;
659
660                 if ((new = malloc(n)) == 0)
661                         return 0;
662                 memcpy(new, mem, tocopy);
663                 free(mem);
664                 return new;
665         }
666 }
667
668 char *memalign(alignment, size)
669 unsigned alignment, size;
670 {
671         char *ptr = malloc(size + alignment);
672         char *aligned;
673         struct mhead *p;
674
675         if (ptr == 0)
676                 return 0;
677         /* If entire block has the desired alignment, just accept it.  */
678         if (((int)ptr & (alignment - 1)) == 0)
679                 return ptr;
680         /* Otherwise, get address of byte in the block that has that alignment.  */
681         aligned = (char *)(((int)ptr + alignment - 1) & -alignment);
682
683         /* Store a suitable indication of how to free the block,
684            so that free can find the true beginning of it.  */
685         p = (struct mhead *)aligned - 1;
686         p->mh_size = aligned - ptr;
687         p->mh_alloc = ISMEMALIGN;
688         return aligned;
689 }
690
691 #ifndef __hpux
692 /* This runs into trouble with getpagesize on HPUX.
693    Patching out seems cleaner than the ugly fix needed.  */
694 char *valloc(size)
695 unsigned size;
696 {
697         return memalign(getpagesize(), size);
698 }
699 #endif                          /* not __hpux */
700 \f
701 #ifdef MSTATS
702 /* Return statistics describing allocation of blocks of size 2**n. */
703
704 struct mstats_value {
705         int blocksize;
706         int nfree;
707         int nused;
708 };
709
710 struct mstats_value malloc_stats(size)
711 int size;
712 {
713         struct mstats_value v;
714         int i;
715         struct mhead *p;
716
717         v.nfree = 0;
718
719         if (size < 0 || size >= 30) {
720                 v.blocksize = 0;
721                 v.nused = 0;
722                 return v;
723         }
724
725         v.blocksize = 1 << (size + 3);
726         v.nused = nmalloc[size];
727
728         for (p = nextf[size]; p; p = CHAIN(p))
729                 v.nfree++;
730
731         return v;
732 }
733 int malloc_mem_used(void)
734 {
735         int i;
736         int size_used;
737
738         size_used = 0;
739
740         for (i = 0; i < 30; i++) {
741                 int allocation_size = 1 << (i + 3);
742                 struct mhead *p;
743
744                 size_used += nmalloc[i] * allocation_size;
745         }
746
747         return size_used;
748 }
749
750 int malloc_mem_free(void)
751 {
752         int i;
753         int size_unused;
754
755         size_unused = 0;
756
757         for (i = 0; i < 30; i++) {
758                 int allocation_size = 1 << (i + 3);
759                 struct mhead *p;
760
761                 for (p = nextf[i]; p; p = CHAIN(p))
762                         size_unused += allocation_size;
763         }
764
765         return size_unused;
766 }
767 #endif                          /* MSTATS */
768 \f
769 /*
770  *      This function returns the total number of bytes that the process
771  *      will be allowed to allocate via the sbrk(2) system call.  On
772  *      BSD systems this is the total space allocatable to stack and
773  *      data.  On USG systems this is the data space only.
774  */
775
776 #ifdef USG
777
778 static void get_lim_data(void)
779 {
780 #ifdef ULIMIT_BREAK_VALUE
781         lim_data = ULIMIT_BREAK_VALUE;
782 #else
783         lim_data = ulimit(3, 0);
784 #endif
785
786         lim_data -= (long)data_space_start;
787 }
788
789 #else                           /* not USG */
790 #ifndef BSD4_2
791
792 static void get_lim_data(void)
793 {
794         lim_data = vlimit(LIM_DATA, -1);
795 }
796
797 #else                           /* BSD4_2 */
798
799 static void get_lim_data(void)
800 {
801         struct rlimit XXrlimit;
802
803         getrlimit(RLIMIT_DATA, &XXrlimit);
804 #ifdef RLIM_INFINITY
805         lim_data = XXrlimit.rlim_cur & RLIM_INFINITY;   /* soft limit */
806 #else
807         lim_data = XXrlimit.rlim_cur;   /* soft limit */
808 #endif
809 }
810
811 #endif                          /* BSD4_2 */
812 #endif                          /* not USG */
813 \f