Merge pull request #2713 from gregoryyoung/master
[mono.git] / mono / utils / dlmalloc.h
1 /*
2   Default header file for malloc-2.8.x, written by Doug Lea
3   and released to the public domain, as explained at
4   http://creativecommons.org/licenses/publicdomain. 
5  
6   last update: Mon Aug 15 08:55:52 2005  Doug Lea  (dl at gee)
7
8   This header is for ANSI C/C++ only.  You can set any of
9   the following #defines before including:
10
11   * If USE_DL_PREFIX is defined, it is assumed that malloc.c 
12     was also compiled with this option, so all routines
13     have names starting with "dl".
14
15   * If HAVE_USR_INCLUDE_MALLOC_H is defined, it is assumed that this
16     file will be #included AFTER <malloc.h>. This is needed only if
17     your system defines a struct mallinfo that is incompatible with the
18     standard one declared here.  Otherwise, you can include this file
19     INSTEAD of your system system <malloc.h>.  At least on ANSI, all
20     declarations should be compatible with system versions
21
22   * If MSPACES is defined, declarations for mspace versions are included.
23 */
24
25 #ifndef MALLOC_280_H
26 #define MALLOC_280_H
27
28 #ifdef __cplusplus
29 extern "C" {
30 #endif
31
32 #include <stddef.h>   /* for size_t */
33 #include <mono/utils/mono-compiler.h>
34
35 #if !ONLY_MSPACES
36
37 #ifndef USE_DL_PREFIX
38 #define dlcalloc               calloc
39 #define dlfree                 free
40 #define dlmalloc               malloc
41 #define dlmemalign             memalign
42 #define dlrealloc              realloc
43 #define dlvalloc               valloc
44 #define dlpvalloc              pvalloc
45 #define dlmallinfo             mallinfo
46 #define dlmallopt              mallopt
47 #define dlmalloc_trim          malloc_trim
48 #define dlmalloc_stats         malloc_stats
49 #define dlmalloc_usable_size   malloc_usable_size
50 #define dlmalloc_footprint     malloc_footprint
51 #define dlindependent_calloc   independent_calloc
52 #define dlindependent_comalloc independent_comalloc
53 #endif /* USE_DL_PREFIX */
54
55 #define dlcalloc               mono_dlcalloc
56 #define dlfree                 mono_dlfree
57 #define dlmalloc               mono_dlmalloc
58 #define dlmemalign             mono_dlmemalign
59 #define dlrealloc              mono_dlrealloc
60 #define dlvalloc               mono_dlvalloc
61 #define dlpvalloc              mono_dlpvalloc
62 #define dlmallinfo             mono_dlmallinfo
63 #define dlmallopt              mono_dlmallopt
64 #define dlmalloc_trim          mono_dlmalloc_trim
65 #define dlmalloc_stats         mono_dlmalloc_stats
66 #define dlmalloc_usable_size   mono_dlmalloc_usable_size
67 #define dlmalloc_footprint     mono_dlmalloc_footprint
68 #define dlindependent_calloc   mono_dlindependent_calloc
69 #define dlindependent_comalloc mono_dlindependent_comalloc
70
71 /*
72   malloc(size_t n)
73   Returns a pointer to a newly allocated chunk of at least n bytes, or
74   null if no space is available, in which case errno is set to ENOMEM
75   on ANSI C systems.
76
77   If n is zero, malloc returns a minimum-sized chunk. (The minimum
78   size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
79   systems.)  Note that size_t is an unsigned type, so calls with
80   arguments that would be negative if signed are interpreted as
81   requests for huge amounts of space, which will often fail. The
82   maximum supported value of n differs across systems, but is in all
83   cases less than the maximum representable value of a size_t.
84 */
85 void* dlmalloc(size_t);
86
87 /*
88   free(void* p)
89   Releases the chunk of memory pointed to by p, that had been previously
90   allocated using malloc or a related routine such as realloc.
91   It has no effect if p is null. If p was not malloced or already
92   freed, free(p) will by default cuase the current program to abort.
93 */
94 void  dlfree(void*);
95
96 /*
97   calloc(size_t n_elements, size_t element_size);
98   Returns a pointer to n_elements * element_size bytes, with all locations
99   set to zero.
100 */
101 void* dlcalloc(size_t, size_t);
102
103 /*
104   realloc(void* p, size_t n)
105   Returns a pointer to a chunk of size n that contains the same data
106   as does chunk p up to the minimum of (n, p's size) bytes, or null
107   if no space is available.
108
109   The returned pointer may or may not be the same as p. The algorithm
110   prefers extending p in most cases when possible, otherwise it
111   employs the equivalent of a malloc-copy-free sequence.
112
113   If p is null, realloc is equivalent to malloc.
114
115   If space is not available, realloc returns null, errno is set (if on
116   ANSI) and p is NOT freed.
117
118   if n is for fewer bytes than already held by p, the newly unused
119   space is lopped off and freed if possible.  realloc with a size
120   argument of zero (re)allocates a minimum-sized chunk.
121
122   The old unix realloc convention of allowing the last-free'd chunk
123   to be used as an argument to realloc is not supported.
124 */
125
126 void* dlrealloc(void*, size_t);
127
128 /*
129   memalign(size_t alignment, size_t n);
130   Returns a pointer to a newly allocated chunk of n bytes, aligned
131   in accord with the alignment argument.
132
133   The alignment argument should be a power of two. If the argument is
134   not a power of two, the nearest greater power is used.
135   8-byte alignment is guaranteed by normal malloc calls, so don't
136   bother calling memalign with an argument of 8 or less.
137
138   Overreliance on memalign is a sure way to fragment space.
139 */
140 void* dlmemalign(size_t, size_t);
141
142 /*
143   valloc(size_t n);
144   Equivalent to memalign(pagesize, n), where pagesize is the page
145   size of the system. If the pagesize is unknown, 4096 is used.
146 */
147 void* dlvalloc(size_t);
148
149 /*
150   mallopt(int parameter_number, int parameter_value)
151   Sets tunable parameters The format is to provide a
152   (parameter-number, parameter-value) pair.  mallopt then sets the
153   corresponding parameter to the argument value if it can (i.e., so
154   long as the value is meaningful), and returns 1 if successful else
155   0.  SVID/XPG/ANSI defines four standard param numbers for mallopt,
156   normally defined in malloc.h.  None of these are use in this malloc,
157   so setting them has no effect. But this malloc also supports other
158   options in mallopt:
159
160   Symbol            param #  default    allowed param values
161   M_TRIM_THRESHOLD     -1   2*1024*1024   any   (-1U disables trimming)
162   M_GRANULARITY        -2     page size   any power of 2 >= page size
163   M_MMAP_THRESHOLD     -3      256*1024   any   (or 0 if no MMAP support)
164 */
165 int dlmallopt(int, int);
166
167 #define M_TRIM_THRESHOLD     (-1)
168 #define M_GRANULARITY        (-2)
169 #define M_MMAP_THRESHOLD     (-3)
170
171
172 /*
173   malloc_footprint();
174   Returns the number of bytes obtained from the system.  The total
175   number of bytes allocated by malloc, realloc etc., is less than this
176   value. Unlike mallinfo, this function returns only a precomputed
177   result, so can be called frequently to monitor memory consumption.
178   Even if locks are otherwise defined, this function does not use them,
179   so results might not be up to date.
180 */
181 size_t dlmalloc_footprint(void);
182
183 #if !NO_MALLINFO
184 /*
185   mallinfo()
186   Returns (by copy) a struct containing various summary statistics:
187
188   arena:     current total non-mmapped bytes allocated from system
189   ordblks:   the number of free chunks
190   smblks:    always zero.
191   hblks:     current number of mmapped regions
192   hblkhd:    total bytes held in mmapped regions
193   usmblks:   the maximum total allocated space. This will be greater
194                 than current total if trimming has occurred.
195   fsmblks:   always zero
196   uordblks:  current total allocated space (normal or mmapped)
197   fordblks:  total free space
198   keepcost:  the maximum number of bytes that could ideally be released
199                back to system via malloc_trim. ("ideally" means that
200                it ignores page restrictions etc.)
201
202   Because these fields are ints, but internal bookkeeping may
203   be kept as longs, the reported values may wrap around zero and
204   thus be inaccurate.
205 */
206 #ifndef HAVE_USR_INCLUDE_MALLOC_H
207 #ifndef _MALLOC_H
208 #ifndef MALLINFO_FIELD_TYPE
209 #define MALLINFO_FIELD_TYPE size_t
210 #endif /* MALLINFO_FIELD_TYPE */
211 struct mallinfo {
212   MALLINFO_FIELD_TYPE arena;    /* non-mmapped space allocated from system */
213   MALLINFO_FIELD_TYPE ordblks;  /* number of free chunks */
214   MALLINFO_FIELD_TYPE smblks;   /* always 0 */
215   MALLINFO_FIELD_TYPE hblks;    /* always 0 */
216   MALLINFO_FIELD_TYPE hblkhd;   /* space in mmapped regions */
217   MALLINFO_FIELD_TYPE usmblks;  /* maximum total allocated space */
218   MALLINFO_FIELD_TYPE fsmblks;  /* always 0 */
219   MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
220   MALLINFO_FIELD_TYPE fordblks; /* total free space */
221   MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
222 };
223 #endif  /* _MALLOC_H */
224 #endif  /* HAVE_USR_INCLUDE_MALLOC_H */
225
226 struct mallinfo dlmallinfo(void);
227 #endif  /* NO_MALLINFO */
228
229 /*
230   independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
231
232   independent_calloc is similar to calloc, but instead of returning a
233   single cleared space, it returns an array of pointers to n_elements
234   independent elements that can hold contents of size elem_size, each
235   of which starts out cleared, and can be independently freed,
236   realloc'ed etc. The elements are guaranteed to be adjacently
237   allocated (this is not guaranteed to occur with multiple callocs or
238   mallocs), which may also improve cache locality in some
239   applications.
240
241   The "chunks" argument is optional (i.e., may be null, which is
242   probably the most typical usage). If it is null, the returned array
243   is itself dynamically allocated and should also be freed when it is
244   no longer needed. Otherwise, the chunks array must be of at least
245   n_elements in length. It is filled in with the pointers to the
246   chunks.
247
248   In either case, independent_calloc returns this pointer array, or
249   null if the allocation failed.  If n_elements is zero and "chunks"
250   is null, it returns a chunk representing an array with zero elements
251   (which should be freed if not wanted).
252
253   Each element must be individually freed when it is no longer
254   needed. If you'd like to instead be able to free all at once, you
255   should instead use regular calloc and assign pointers into this
256   space to represent elements.  (In this case though, you cannot
257   independently free elements.)
258
259   independent_calloc simplifies and speeds up implementations of many
260   kinds of pools.  It may also be useful when constructing large data
261   structures that initially have a fixed number of fixed-sized nodes,
262   but the number is not known at compile time, and some of the nodes
263   may later need to be freed. For example:
264
265   struct Node { int item; struct Node* next; };
266
267   struct Node* build_list() {
268     struct Node** pool;
269     int n = read_number_of_nodes_needed();
270     if (n <= 0) return 0;
271     pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
272     if (pool == 0) die();
273     // organize into a linked list...
274     struct Node* first = pool[0];
275     for (i = 0; i < n-1; ++i)
276       pool[i]->next = pool[i+1];
277     free(pool);     // Can now free the array (or not, if it is needed later)
278     return first;
279   }
280 */
281 void** dlindependent_calloc(size_t, size_t, void**);
282
283 /*
284   independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
285
286   independent_comalloc allocates, all at once, a set of n_elements
287   chunks with sizes indicated in the "sizes" array.    It returns
288   an array of pointers to these elements, each of which can be
289   independently freed, realloc'ed etc. The elements are guaranteed to
290   be adjacently allocated (this is not guaranteed to occur with
291   multiple callocs or mallocs), which may also improve cache locality
292   in some applications.
293
294   The "chunks" argument is optional (i.e., may be null). If it is null
295   the returned array is itself dynamically allocated and should also
296   be freed when it is no longer needed. Otherwise, the chunks array
297   must be of at least n_elements in length. It is filled in with the
298   pointers to the chunks.
299
300   In either case, independent_comalloc returns this pointer array, or
301   null if the allocation failed.  If n_elements is zero and chunks is
302   null, it returns a chunk representing an array with zero elements
303   (which should be freed if not wanted).
304
305   Each element must be individually freed when it is no longer
306   needed. If you'd like to instead be able to free all at once, you
307   should instead use a single regular malloc, and assign pointers at
308   particular offsets in the aggregate space. (In this case though, you
309   cannot independently free elements.)
310
311   independent_comallac differs from independent_calloc in that each
312   element may have a different size, and also that it does not
313   automatically clear elements.
314
315   independent_comalloc can be used to speed up allocation in cases
316   where several structs or objects must always be allocated at the
317   same time.  For example:
318
319   struct Head { ... }
320   struct Foot { ... }
321
322   void send_message(char* msg) {
323     int msglen = strlen(msg);
324     size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
325     void* chunks[3];
326     if (independent_comalloc(3, sizes, chunks) == 0)
327       die();
328     struct Head* head = (struct Head*)(chunks[0]);
329     char*        body = (char*)(chunks[1]);
330     struct Foot* foot = (struct Foot*)(chunks[2]);
331     // ...
332   }
333
334   In general though, independent_comalloc is worth using only for
335   larger values of n_elements. For small values, you probably won't
336   detect enough difference from series of malloc calls to bother.
337
338   Overuse of independent_comalloc can increase overall memory usage,
339   since it cannot reuse existing noncontiguous small chunks that
340   might be available for some of the elements.
341 */
342 void** dlindependent_comalloc(size_t, size_t*, void**);
343
344
345 /*
346   pvalloc(size_t n);
347   Equivalent to valloc(minimum-page-that-holds(n)), that is,
348   round up n to nearest pagesize.
349  */
350 void*  dlpvalloc(size_t);
351
352 /*
353   malloc_trim(size_t pad);
354
355   If possible, gives memory back to the system (via negative arguments
356   to sbrk) if there is unused memory at the `high' end of the malloc
357   pool or in unused MMAP segments. You can call this after freeing
358   large blocks of memory to potentially reduce the system-level memory
359   requirements of a program. However, it cannot guarantee to reduce
360   memory. Under some allocation patterns, some large free blocks of
361   memory will be locked between two used chunks, so they cannot be
362   given back to the system.
363
364   The `pad' argument to malloc_trim represents the amount of free
365   trailing space to leave untrimmed. If this argument is zero, only
366   the minimum amount of memory to maintain internal data structures
367   will be left. Non-zero arguments can be supplied to maintain enough
368   trailing space to service future expected allocations without having
369   to re-obtain memory from the system.
370
371   Malloc_trim returns 1 if it actually released any memory, else 0.
372 */
373 int  dlmalloc_trim(size_t);
374
375 /*
376   malloc_usable_size(void* p);
377
378   Returns the number of bytes you can actually use in
379   an allocated chunk, which may be more than you requested (although
380   often not) due to alignment and minimum size constraints.
381   You can use this many bytes without worrying about
382   overwriting other allocated objects. This is not a particularly great
383   programming practice. malloc_usable_size can be more useful in
384   debugging and assertions, for example:
385
386   p = malloc(n);
387   assert(malloc_usable_size(p) >= 256);
388 */
389 size_t dlmalloc_usable_size(void*);
390
391 /*
392   malloc_stats();
393   Prints on stderr the amount of space obtained from the system (both
394   via sbrk and mmap), the maximum amount (which may be more than
395   current if malloc_trim and/or munmap got called), and the current
396   number of bytes allocated via malloc (or realloc, etc) but not yet
397   freed. Note that this is the number of bytes allocated, not the
398   number requested. It will be larger than the number requested
399   because of alignment and bookkeeping overhead. Because it includes
400   alignment wastage as being in use, this figure may be greater than
401   zero even when no user-level chunks are allocated.
402
403   The reported current and maximum system memory can be inaccurate if
404   a program makes other calls to system memory allocation functions
405   (normally sbrk) outside of malloc.
406
407   malloc_stats prints only the most commonly interesting statistics.
408   More information can be obtained by calling mallinfo.
409 */
410 void  dlmalloc_stats(void);
411
412 #endif /* !ONLY_MSPACES */
413
414 #if MSPACES
415
416 /*
417   mspace is an opaque type representing an independent
418   region of space that supports mspace_malloc, etc.
419 */
420 typedef void* mspace;
421
422 /*
423   create_mspace creates and returns a new independent space with the
424   given initial capacity, or, if 0, the default granularity size.  It
425   returns null if there is no system memory available to create the
426   space.  If argument locked is non-zero, the space uses a separate
427   lock to control access. The capacity of the space will grow
428   dynamically as needed to service mspace_malloc requests.  You can
429   control the sizes of incremental increases of this space by
430   compiling with a different DEFAULT_GRANULARITY or dynamically
431   setting with mallopt(M_GRANULARITY, value).
432 */
433 mspace create_mspace(size_t capacity, int locked);
434
435 /*
436   destroy_mspace destroys the given space, and attempts to return all
437   of its memory back to the system, returning the total number of
438   bytes freed. After destruction, the results of access to all memory
439   used by the space become undefined.
440 */
441 size_t destroy_mspace(mspace msp);
442
443 /*
444   create_mspace_with_base uses the memory supplied as the initial base
445   of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
446   space is used for bookkeeping, so the capacity must be at least this
447   large. (Otherwise 0 is returned.) When this initial space is
448   exhausted, additional memory will be obtained from the system.
449   Destroying this space will deallocate all additionally allocated
450   space (if possible) but not the initial base.
451 */
452 mspace create_mspace_with_base(void* base, size_t capacity, int locked);
453
454 /*
455   mspace_malloc behaves as malloc, but operates within
456   the given space.
457 */
458 void* mspace_malloc(mspace msp, size_t bytes);
459
460 /*
461   mspace_free behaves as free, but operates within
462   the given space.
463
464   If compiled with FOOTERS==1, mspace_free is not actually needed.
465   free may be called instead of mspace_free because freed chunks from
466   any space are handled by their originating spaces.
467 */
468 void mspace_free(mspace msp, void* mem);
469
470 /*
471   mspace_realloc behaves as realloc, but operates within
472   the given space.
473
474   If compiled with FOOTERS==1, mspace_realloc is not actually
475   needed.  realloc may be called instead of mspace_realloc because
476   realloced chunks from any space are handled by their originating
477   spaces.
478 */
479 void* mspace_realloc(mspace msp, void* mem, size_t newsize);
480
481 /*
482   mspace_calloc behaves as calloc, but operates within
483   the given space.
484 */
485 void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
486
487 /*
488   mspace_memalign behaves as memalign, but operates within
489   the given space.
490 */
491 void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
492
493 /*
494   mspace_independent_calloc behaves as independent_calloc, but
495   operates within the given space.
496 */
497 void** mspace_independent_calloc(mspace msp, size_t n_elements,
498                                  size_t elem_size, void* chunks[]);
499
500 /*
501   mspace_independent_comalloc behaves as independent_comalloc, but
502   operates within the given space.
503 */
504 void** mspace_independent_comalloc(mspace msp, size_t n_elements,
505                                    size_t sizes[], void* chunks[]);
506
507 /*
508   mspace_footprint() returns the number of bytes obtained from the
509   system for this space.
510 */
511 size_t mspace_footprint(mspace msp);
512
513
514 #if !NO_MALLINFO
515 /*
516   mspace_mallinfo behaves as mallinfo, but reports properties of
517   the given space.
518 */
519 struct mallinfo mspace_mallinfo(mspace msp);
520 #endif /* NO_MALLINFO */
521
522 /*
523   mspace_malloc_stats behaves as malloc_stats, but reports
524   properties of the given space.
525 */
526 void mspace_malloc_stats(mspace msp);
527
528 /*
529   mspace_trim behaves as malloc_trim, but
530   operates within the given space.
531 */
532 int mspace_trim(mspace msp, size_t pad);
533
534 /*
535   An alias for mallopt.
536 */
537 int mspace_mallopt(int, int);
538
539 #endif  /* MSPACES */
540
541 #ifdef __cplusplus
542 };  /* end of extern "C" */
543 #endif
544
545 #endif /* MALLOC_280_H */