libmimalloc_sys2/
extended.rs

1#![allow(nonstandard_style)]
2
3use core::ffi::c_void;
4
5use cty::{c_char, c_int, c_long, c_ulonglong};
6
7/// The maximum number of bytes which may be used as an argument to a function
8/// in the `_small` family ([`mi_malloc_small`], [`mi_zalloc_small`], etc).
9pub const MI_SMALL_SIZE_MAX: usize = 128 * core::mem::size_of::<*mut c_void>();
10
11extern "C" {
12    /// Allocate `count` items of `size` length each.
13    ///
14    /// Returns `null` if `count * size` overflows or on out-of-memory.
15    ///
16    /// All items are initialized to zero.
17    pub fn mi_calloc(count: usize, size: usize) -> *mut c_void;
18
19    /// Allocate `count` items of `size` length each.
20    ///
21    /// Returns `null` if `count * size` overflows or on out-of-memory,
22    /// otherwise returns the same as [`mi_malloc(count *
23    /// size)`](crate::mi_malloc).
24    /// Equivalent to [`mi_calloc`], but returns uninitialized (and not zeroed)
25    /// bytes.
26    pub fn mi_mallocn(count: usize, size: usize) -> *mut c_void;
27
28    /// Re-allocate memory to `count` elements of `size` bytes.
29    ///
30    /// The realloc equivalent of the [`mi_mallocn`] interface. Returns `null`
31    /// if `count * size` overflows or on out-of-memory, otherwise returns the
32    /// same as [`mi_realloc(p, count * size)`](crate::mi_realloc).
33    pub fn mi_reallocn(p: *mut c_void, count: usize, size: usize) -> *mut c_void;
34
35    /// Try to re-allocate memory to `newsize` bytes _in place_.
36    ///
37    /// Returns null on out-of-memory or if the memory could not be expanded in
38    /// place. On success, returns the same pointer as `p`.
39    ///
40    /// If `newsize` is larger than the original `size` allocated for `p`, the
41    /// bytes after `size` are uninitialized.
42    ///
43    /// If null is returned, the original pointer is not freed.
44    ///
45    /// Note: Conceptually, this is a realloc-like which returns null if it
46    /// would be forced to reallocate memory and copy. In practice it's
47    /// equivalent testing against [`mi_usable_size`](crate::mi_usable_size).
48    pub fn mi_expand(p: *mut c_void, newsize: usize) -> *mut c_void;
49
50    /// Re-allocate memory to `newsize` bytes.
51    ///
52    /// This differs from [`mi_realloc`](crate::mi_realloc) in that on failure,
53    /// `p` is freed.
54    pub fn mi_reallocf(p: *mut c_void, newsize: usize) -> *mut c_void;
55
56    /// Allocate and duplicate a nul-terminated C string.
57    ///
58    /// This can be useful for Rust code when interacting with the FFI.
59    pub fn mi_strdup(s: *const c_char) -> *mut c_char;
60
61    /// Allocate and duplicate a nul-terminated C string, up to `n` bytes.
62    ///
63    /// This can be useful for Rust code when interacting with the FFI.
64    pub fn mi_strndup(s: *const c_char, n: usize) -> *mut c_char;
65
66    /// Resolve a file path name, producing a `C` string which can be passed to
67    /// [`mi_free`](crate::mi_free).
68    ///
69    /// `resolved_name` should be null, but can also point to a buffer of at
70    /// least `PATH_MAX` bytes.
71    ///
72    /// If successful, returns a pointer to the resolved absolute file name, or
73    /// `null` on failure (with `errno` set to the error code).
74    ///
75    /// If `resolved_name` was `null`, the returned result should be freed with
76    /// [`mi_free`](crate::mi_free).
77    ///
78    /// This can rarely be useful in FFI code, but is mostly included for
79    /// completeness.
80    pub fn mi_realpath(fname: *const c_char, resolved_name: *mut c_char) -> *mut c_char;
81
82    /// Allocate `size * count` bytes aligned by `alignment`.
83    ///
84    /// Return pointer to the allocated memory or null if out of memory or if
85    /// `size * count` overflows.
86    ///
87    /// Returns a unique pointer if called with `size * count` 0.
88    pub fn mi_calloc_aligned(count: usize, size: usize, alignment: usize) -> *mut c_void;
89
90    /// Allocate `size` bytes aligned by `alignment` at a specified `offset`.
91    ///
92    /// Note that the resulting pointer itself is not aligned by the alignment,
93    /// but after `offset` bytes it will be. This can be useful for allocating
94    /// data with an inline header, where the data has a specific alignment
95    /// requirement.
96    ///
97    /// Specifically, if `p` is the returned pointer `p.add(offset)` is aligned
98    /// to `alignment`.
99    pub fn mi_malloc_aligned_at(size: usize, alignment: usize, offset: usize) -> *mut c_void;
100
101    /// Allocate `size` bytes aligned by `alignment` at a specified `offset`,
102    /// zero-initialized.
103    ///
104    /// This is a [`mi_zalloc`](crate::mi_zalloc) equivalent of [`mi_malloc_aligned_at`].
105    pub fn mi_zalloc_aligned_at(size: usize, alignment: usize, offset: usize) -> *mut c_void;
106
107    /// Allocate `size` of bytes aligned by `alignment` and place the address of the
108    /// allocated memory to `ptr`.
109    ///
110    /// Returns zero on success, invalid argument for invalid alignment, or out-of-memory.
111    pub fn mi_posix_memalign(ptr: *mut *mut c_void, alignment: usize, size: usize) -> c_int;
112
113    /// Allocate `size` bytes aligned by `alignment` with alignment as the first
114    /// parameter.
115    ///
116    /// Return pointer to the allocated memory or null if out of memory.
117    pub fn mi_aligned_alloc(alignment: usize, size: usize) -> *mut c_void;
118
119    /// Allocate `size * count` bytes aligned by `alignment` at a specified
120    /// `offset`, zero-initialized.
121    ///
122    /// This is a [`calloc`](crate::mi_calloc) equivalent of [`mi_malloc_aligned_at`].
123    pub fn mi_calloc_aligned_at(
124        count: usize,
125        size: usize,
126        alignment: usize,
127        offset: usize,
128    ) -> *mut c_void;
129
130    /// Re-allocate memory to `newsize` bytes aligned by `alignment` at a
131    /// specified `offset`.
132    ///
133    /// This is a [`realloc`](crate::mi_realloc) equivalent of [`mi_malloc_aligned_at`].
134    pub fn mi_realloc_aligned_at(
135        p: *mut c_void,
136        newsize: usize,
137        alignment: usize,
138        offset: usize,
139    ) -> *mut c_void;
140
141    /// Zero initialized [re-allocation](crate::mi_realloc).
142    ///
143    /// In general, only valid on memory originally allocated by zero
144    /// initialization: [`mi_calloc`](crate::mi_calloc),
145    /// [`mi_zalloc`](crate::mi_zalloc),
146    /// [`mi_zalloc_aligned`](crate::mi_zalloc_aligned), ...
147    pub fn mi_rezalloc(p: *mut c_void, newsize: usize) -> *mut c_void;
148
149    /// Zero initialized [re-allocation](crate::mi_realloc), following `calloc`
150    /// paramater conventions.
151    ///
152    /// In general, only valid on memory originally allocated by zero
153    /// initialization: [`mi_calloc`](crate::mi_calloc),
154    /// [`mi_zalloc`](crate::mi_zalloc),
155    /// [`mi_zalloc_aligned`](crate::mi_zalloc_aligned), ...
156    pub fn mi_recalloc(p: *mut c_void, newcount: usize, size: usize) -> *mut c_void;
157
158    /// Aligned version of [`mi_rezalloc`].
159    pub fn mi_rezalloc_aligned(p: *mut c_void, newsize: usize, alignment: usize) -> *mut c_void;
160
161    /// Offset-aligned version of [`mi_rezalloc`].
162    pub fn mi_rezalloc_aligned_at(
163        p: *mut c_void,
164        newsize: usize,
165        alignment: usize,
166        offset: usize,
167    ) -> *mut c_void;
168
169    /// Aligned version of [`mi_recalloc`].
170    pub fn mi_recalloc_aligned(
171        p: *mut c_void,
172        newcount: usize,
173        size: usize,
174        alignment: usize,
175    ) -> *mut c_void;
176
177    /// Offset-aligned version of [`mi_recalloc`].
178    pub fn mi_recalloc_aligned_at(
179        p: *mut c_void,
180        newcount: usize,
181        size: usize,
182        alignment: usize,
183        offset: usize,
184    ) -> *mut c_void;
185
186    /// Allocate an object of no more than [`MI_SMALL_SIZE_MAX`] bytes.
187    ///
188    /// Does not check that `size` is indeed small.
189    ///
190    /// Note: Currently [`mi_malloc`](crate::mi_malloc) checks if `size` is
191    /// small and calls this if
192    /// so at runtime, so its' only worth using if you know for certain.
193    pub fn mi_malloc_small(size: usize) -> *mut c_void;
194
195    /// Allocate an zero-initialized object of no more than
196    /// [`MI_SMALL_SIZE_MAX`] bytes.
197    ///
198    /// Does not check that `size` is indeed small.
199    ///
200    /// Note: Currently [`mi_zalloc`](crate::mi_zalloc) checks if `size` is
201    /// small and calls this if so at runtime, so its' only worth using if you
202    /// know for certain.
203    pub fn mi_zalloc_small(size: usize) -> *mut c_void;
204
205    /// Return the available bytes in a memory block.
206    ///
207    /// The returned size can be used to call `mi_expand` successfully.
208    pub fn mi_usable_size(p: *const c_void) -> usize;
209
210    /// Return the used allocation size.
211    ///
212    /// Returns the size `n` that will be allocated, where `n >= size`.
213    ///
214    /// Generally, `mi_usable_size(mi_malloc(size)) == mi_good_size(size)`. This
215    /// can be used to reduce internal wasted space when allocating buffers for
216    /// example.
217    ///
218    /// See [`mi_usable_size`](crate::mi_usable_size).
219    pub fn mi_good_size(size: usize) -> usize;
220
221    /// Eagerly free memory.
222    ///
223    /// If `force` is true, aggressively return memory to the OS (can be
224    /// expensive!)
225    ///
226    /// Regular code should not have to call this function. It can be beneficial
227    /// in very narrow circumstances; in particular, when a long running thread
228    /// allocates a lot of blocks that are freed by other threads it may improve
229    /// resource usage by calling this every once in a while.
230    pub fn mi_collect(force: bool);
231
232    /// Checked free: If `p` came from mimalloc's heap (as decided by
233    /// [`mi_is_in_heap_region`]), this is [`mi_free(p)`](crate::mi_free), but
234    /// otherwise it is a no-op.
235    pub fn mi_cfree(p: *mut c_void);
236
237    /// Returns true if this is a pointer into a memory region that has been
238    /// reserved by the mimalloc heap.
239    ///
240    /// This function is described by the mimalloc documentation as "relatively
241    /// fast".
242    ///
243    /// See also [`mi_heap_check_owned`], which is (much) slower and slightly
244    /// more precise, but only concerns a single `mi_heap`.
245    pub fn mi_is_in_heap_region(p: *const c_void) -> bool;
246
247    /// Layout-aware deallocation: Like [`mi_free`](crate::mi_free), but accepts
248    /// the size and alignment as well.
249    ///
250    /// Note: unlike some allocators that require this information for
251    /// performance, mimalloc doesn't need it (as of the current version,
252    /// v2.0.0), and so it currently implements this as a (debug) assertion that
253    /// verifies that `p` is actually aligned to `alignment` and is usable for
254    /// at least `size` bytes, before delegating to `mi_free`.
255    ///
256    /// However, currently there's no way to have this crate enable mimalloc's
257    /// debug assertions, so these checks aren't particularly useful.
258    ///
259    /// Note: It's legal to pass null to this function, and you are not required
260    /// to use this to deallocate memory from an aligned allocation function.
261    pub fn mi_free_size_aligned(p: *mut c_void, size: usize, alignment: usize);
262
263    /// Size-aware deallocation: Like [`mi_free`](crate::mi_free), but accepts
264    /// the size and alignment as well.
265    ///
266    /// Note: unlike some allocators that require this information for
267    /// performance, mimalloc doesn't need it (as of the current version,
268    /// v2.0.0), and so it currently implements this as a (debug) assertion that
269    /// verifies that `p` is actually aligned to `alignment` and is usable for
270    /// at least `size` bytes, before delegating to `mi_free`.
271    ///
272    /// However, currently there's no way to have this crate enable mimalloc's
273    /// debug assertions, so these checks aren't particularly useful.
274    ///
275    /// Note: It's legal to pass null to this function.
276    pub fn mi_free_size(p: *mut c_void, size: usize);
277
278    /// Alignment-aware deallocation: Like [`mi_free`](crate::mi_free), but
279    /// accepts the size and alignment as well.
280    ///
281    /// Note: unlike some allocators that require this information for
282    /// performance, mimalloc doesn't need it (as of the current version,
283    /// v2.0.0), and so it currently implements this as a (debug) assertion that
284    /// verifies that `p` is actually aligned to `alignment` and is usable for
285    /// at least `size` bytes, before delegating to `mi_free`.
286    ///
287    /// However, currently there's no way to have this crate enable mimalloc's
288    /// debug assertions, so these checks aren't particularly useful.
289    ///
290    /// Note: It's legal to pass null to this function.
291    pub fn mi_free_aligned(p: *mut c_void, alignment: usize);
292
293    /// Print the main statistics.
294    ///
295    /// Ignores the passed in argument, and outputs to the registered output
296    /// function or stderr by default.
297    ///
298    /// Most detailed when using a debug build.
299    pub fn mi_stats_print(_: *mut c_void);
300
301    /// Print the main statistics.
302    ///
303    /// Pass `None` for `out` to use the default. If `out` is provided, `arc` is
304    /// passed as it's second parameter.
305    ///
306    /// Most detailed when using a debug build.
307    pub fn mi_stats_print_out(out: mi_output_fun, arg: *mut c_void);
308
309    /// Reset statistics.
310    ///
311    /// Note: This function is thread safe.
312    pub fn mi_stats_reset();
313
314    #[cfg(not(feature = "v3"))]
315    /// Merge thread local statistics with the main statistics and reset.
316    ///
317    /// Note: This function is thread safe.
318    pub fn mi_stats_merge();
319
320    /// Return the mimalloc version number.
321    ///
322    /// For example version 1.6.3 would return the number `163`.
323    pub fn mi_version() -> c_int;
324
325    /// Initialize mimalloc on a thread.
326    ///
327    /// Should not be used as on most systems (pthreads, windows) this is done
328    /// automatically.
329    pub fn mi_thread_init();
330
331    /// Initialize the process.
332    ///
333    /// Should not be used on most systems, as it's called by thread_init or the
334    /// process loader.
335    pub fn mi_process_init();
336
337    /// Return process information (time and memory usage). All parameters are
338    /// optional (nullable) out-params:
339    ///
340    /// | Parameter        | Description |
341    /// | :-               | :- |
342    /// | `elapsed_msecs`  | Elapsed wall-clock time of the process in milli-seconds. |
343    /// | `user_msecs`     | User time in milli-seconds (as the sum over all threads). |
344    /// | `system_msecs`   | System time in milli-seconds. |
345    /// | `current_rss`    | Current working set size (touched pages). |
346    /// | `peak_rss`       | Peak working set size (touched pages). |
347    /// | `current_commit` | Current committed memory (backed by the page file). |
348    /// | `peak_commit`    | Peak committed memory (backed by the page file). |
349    /// | `page_faults`    | Count of hard page faults. |
350    ///
351    /// The `current_rss` is precise on Windows and MacOSX; other systems
352    /// estimate this using `current_commit`. The `commit` is precise on Windows
353    /// but estimated on other systems as the amount of read/write accessible
354    /// memory reserved by mimalloc.
355    pub fn mi_process_info(
356        elapsed_msecs: *mut usize,
357        user_msecs: *mut usize,
358        system_msecs: *mut usize,
359        current_rss: *mut usize,
360        peak_rss: *mut usize,
361        current_commit: *mut usize,
362        peak_commit: *mut usize,
363        page_faults: *mut usize,
364    );
365
366    /// Uninitialize mimalloc on a thread.
367    ///
368    /// Should not be used as on most systems (pthreads, windows) this is done
369    /// automatically. Ensures that any memory that is not freed yet (but will
370    /// be freed by other threads in the future) is properly handled.
371    ///
372    /// Note: This function is thread safe.
373    pub fn mi_thread_done();
374
375    /// Print out heap statistics for this thread.
376    ///
377    /// Pass `None` for `out` to use the default. If `out` is provided, `arc` is
378    /// passed as it's second parameter
379    ///
380    /// Most detailed when using a debug build.
381    ///
382    /// Note: This function is thread safe.
383    pub fn mi_thread_stats_print_out(out: mi_output_fun, arg: *mut c_void);
384
385    /// Register an output function.
386    ///
387    /// - `out` The output function, use `None` to output to stderr.
388    /// - `arg` Argument that will be passed on to the output function.
389    ///
390    /// The `out` function is called to output any information from mimalloc,
391    /// like verbose or warning messages.
392    ///
393    /// Note: This function is thread safe.
394    pub fn mi_register_output(out: mi_output_fun, arg: *mut c_void);
395
396    /// Register a deferred free function.
397    ///
398    /// - `deferred_free` Address of a deferred free-ing function or `None` to
399    ///   unregister.
400    /// - `arg` Argument that will be passed on to the deferred free function.
401    ///
402    /// Some runtime systems use deferred free-ing, for example when using
403    /// reference counting to limit the worst case free time.
404    ///
405    /// Such systems can register (re-entrant) deferred free function to free
406    /// more memory on demand.
407    ///
408    /// - When the `force` parameter is `true` all possible memory should be
409    ///   freed.
410    ///
411    /// - The per-thread `heartbeat` parameter is monotonically increasing and
412    ///   guaranteed to be deterministic if the program allocates
413    ///   deterministically.
414    ///
415    /// - The `deferred_free` function is guaranteed to be called
416    ///   deterministically after some number of allocations (regardless of
417    ///   freeing or available free memory).
418    ///
419    /// At most one `deferred_free` function can be active.
420    ///
421    /// Note: This function is thread safe.
422    pub fn mi_register_deferred_free(out: mi_deferred_free_fun, arg: *mut c_void);
423
424    /// Register an error callback function.
425    ///
426    /// The `errfun` function is called on an error in mimalloc after emitting
427    /// an error message (through the output function).
428    ///
429    /// It as always legal to just return from the `errfun` function in which
430    /// case allocation functions generally return null or ignore the condition.
431    ///
432    /// The default function only calls abort() when compiled in secure mode
433    /// with an `EFAULT` error. The possible error codes are:
434    ///
435    /// - `EAGAIN` (11): Double free was detected (only in debug and secure
436    ///   mode).
437    /// - `EFAULT` (14): Corrupted free list or meta-data was detected (only in
438    ///   debug and secure mode).
439    /// - `ENOMEM` (12): Not enough memory available to satisfy the request.
440    /// - `EOVERFLOW` (75): Too large a request, for example in `mi_calloc`, the
441    ///   `count` and `size` parameters are too large.
442    /// - `EINVAL` (22): Trying to free or re-allocate an invalid pointer.
443    ///
444    /// Note: This function is thread safe.
445    pub fn mi_register_error(out: mi_error_fun, arg: *mut c_void);
446}
447
448/// An output callback. Must be thread-safe.
449///
450/// See [`mi_stats_print_out`], [`mi_thread_stats_print_out`], [`mi_register_output`]
451pub type mi_output_fun = Option<unsafe extern "C" fn(msg: *const c_char, arg: *mut c_void)>;
452
453/// Type of deferred free functions. Must be thread-safe.
454///
455/// - `force`: If true, all outstanding items should be freed.
456/// - `heartbeat` A monotonically increasing count.
457/// - `arg` Argument that was passed at registration to hold extra state.
458///
459/// See [`mi_register_deferred_free`]
460pub type mi_deferred_free_fun =
461    Option<unsafe extern "C" fn(force: bool, heartbeat: c_ulonglong, arg: *mut c_void)>;
462
463/// Type of error callback functions. Must be thread-safe.
464///
465/// - `err`: Error code (see [`mi_register_error`] for a list).
466/// - `arg`: Argument that was passed at registration to hold extra state.
467///
468/// See [`mi_register_error`]
469pub type mi_error_fun = Option<unsafe extern "C" fn(code: c_int, arg: *mut c_void)>;
470
471/// Runtime options. All options are false by default.
472pub type mi_option_t = c_int;
473
474#[cfg(feature = "arena")]
475/// Arena Id
476pub type mi_arena_id_t = c_int;
477
478// Note: mimalloc doc website seems to have the order of show_stats and
479// show_errors reversed as of 1.6.3, however what I have here is correct:
480// https://github.com/microsoft/mimalloc/issues/266#issuecomment-653822341
481
482/// Print error messages to `stderr`.
483pub const mi_option_show_errors: mi_option_t = 0;
484
485/// Print statistics to `stderr` when the program is done.
486pub const mi_option_show_stats: mi_option_t = 1;
487
488/// Print verbose messages to `stderr`.
489pub const mi_option_verbose: mi_option_t = 2;
490
491/// ### The following options are experimental
492///
493/// Option (experimental) Use large OS pages (2MiB in size) if possible.
494///
495/// Use large OS pages (2MiB) when available; for some workloads this can
496/// significantly improve performance. Use mi_option_verbose to check if
497/// the large OS pages are enabled -- usually one needs to explicitly allow
498/// large OS pages (as on Windows and Linux). However, sometimes the OS is
499/// very slow to reserve contiguous physical memory for large OS pages so
500/// use with care on systems that can have fragmented memory (for that
501/// reason, we generally recommend to use mi_option_reserve_huge_os_pages
502/// instead whenever possible).
503pub const mi_option_large_os_pages: mi_option_t = 6;
504
505/// Option (experimental) The number of huge OS pages (1GiB in size) to reserve at the start of the program.
506///
507/// This reserves the huge pages at startup and sometimes this can give a large (latency) performance
508/// improvement on big workloads. Usually it is better to not use MIMALLOC_LARGE_OS_PAGES in
509/// combination with this setting. Just like large OS pages, use with care as reserving contiguous
510/// physical memory can take a long time when memory is fragmented (but reserving the huge pages is
511/// done at startup only once). Note that we usually need to explicitly enable huge OS pages (as on
512/// Windows and Linux)). With huge OS pages, it may be beneficial to set the setting
513/// mi_option_eager_commit_delay=N (N is 1 by default) to delay the initial N segments (of 4MiB) of
514/// a thread to not allocate in the huge OS pages; this prevents threads that are short lived and
515/// allocate just a little to take up space in the huge OS page area (which cannot be reset).
516pub const mi_option_reserve_huge_os_pages: mi_option_t = 7;
517
518/// Option (experimental) Reserve huge OS pages at node N.
519///
520/// The huge pages are usually allocated evenly among NUMA nodes.
521/// You can use mi_option_reserve_huge_os_pages_at=N where `N` is the numa node (starting at 0) to allocate all
522/// the huge pages at a specific numa node instead.
523pub const mi_option_reserve_huge_os_pages_at: mi_option_t = 8;
524
525/// Option (experimental) Reserve specified amount of OS memory at startup, e.g. "1g" or "512m".
526pub const mi_option_reserve_os_memory: mi_option_t = 9;
527
528/// Option (experimental) the first N segments per thread are not eagerly committed (=1).
529pub const mi_option_eager_commit_delay: mi_option_t = 14;
530
531/// Option (experimental) Pretend there are at most N NUMA nodes; Use 0 to use the actual detected NUMA nodes at runtime.
532pub const mi_option_use_numa_nodes: mi_option_t = 16;
533
534/// Option (experimental) If set to 1, do not use OS memory for allocation (but only pre-reserved arenas)
535pub const mi_option_limit_os_alloc: mi_option_t = 17;
536
537/// Option (experimental) OS tag to assign to mimalloc'd memory
538pub const mi_option_os_tag: mi_option_t = 18;
539
540/// Option (experimental)
541pub const mi_option_max_errors: mi_option_t = 19;
542
543/// Option (experimental)
544pub const mi_option_max_warnings: mi_option_t = 20;
545
546/// Option (experimental)
547pub const mi_option_max_segment_reclaim: mi_option_t = 21;
548
549/// Option (experimental)
550pub const mi_option_destroy_on_exit: mi_option_t = 22;
551
552/// Option (experimental)
553pub const mi_option_arena_reserve: mi_option_t = 23;
554
555/// Option (experimental)
556pub const mi_option_arena_purge_mult: mi_option_t = 24;
557
558/// Option (experimental)
559pub const mi_option_purge_extend_delay: mi_option_t = 25;
560
561/// Option (experimental)
562pub const mi_option_abandoned_reclaim_on_free: mi_option_t = 26;
563
564/// Option (experimental)
565pub const mi_option_disallow_arena_alloc: mi_option_t = 27;
566
567/// Option (experimental)
568pub const mi_option_retry_on_oom: mi_option_t = 28;
569
570/// Option (experimental)
571pub const mi_option_visit_abandoned: mi_option_t = 29;
572
573/// Option (experimental)
574pub const mi_option_guarded_min: mi_option_t = 30;
575
576/// Option (experimental)
577pub const mi_option_guarded_max: mi_option_t = 31;
578
579/// Option (experimental)
580pub const mi_option_guarded_precise: mi_option_t = 32;
581
582/// Option (experimental)
583pub const mi_option_guarded_sample_rate: mi_option_t = 33;
584
585/// Option (experimental)
586pub const mi_option_guarded_sample_seed: mi_option_t = 34;
587
588/// Option (experimental)
589pub const mi_option_target_segments_per_thread: mi_option_t = 35;
590
591/// Option (experimental)
592pub const mi_option_generic_collect: mi_option_t = 36;
593
594/// Allow transparent huge pages? (=1) (on Android =0 by default).
595/// Set to 0 to disable THP for the process.
596pub const mi_option_allow_thp: mi_option_t = 37;
597
598/// Last option.
599pub const _mi_option_last: mi_option_t = 38;
600
601extern "C" {
602    // Note: mi_option_{enable,disable} aren't exposed because they're redundant
603    // and because of https://github.com/microsoft/mimalloc/issues/266.
604
605    /// Returns true if the provided option is enabled.
606    ///
607    /// Note: this function is not thread safe.
608    pub fn mi_option_is_enabled(option: mi_option_t) -> bool;
609
610    /// Enable or disable the given option.
611    ///
612    /// Note: this function is not thread safe.
613    pub fn mi_option_set_enabled(option: mi_option_t, enable: bool);
614
615    /// If the given option has not yet been initialized with [`mi_option_set`]
616    /// or [`mi_option_set_enabled`], enables or disables the option. If it has,
617    /// this function does nothing.
618    ///
619    /// Note: this function is not thread safe.
620    pub fn mi_option_set_enabled_default(option: mi_option_t, enable: bool);
621
622    /// Returns the value of the provided option.
623    ///
624    /// The value of boolean options is 1 or 0, however experimental options
625    /// exist which take a numeric value, which is the intended use of this
626    /// function.
627    ///
628    /// These options are not exposed as constants for stability reasons,
629    /// however you can still use them as arguments to this and other
630    /// `mi_option_` functions if needed, see the mimalloc documentation for
631    /// details: https://microsoft.github.io/mimalloc/group__options.html
632    ///
633    /// Note: this function is not thread safe.
634    pub fn mi_option_get(option: mi_option_t) -> c_long;
635
636    /// Set the option to the given value.
637    ///
638    /// The value of boolean options is 1 or 0, however experimental options
639    /// exist which take a numeric value, which is the intended use of this
640    /// function.
641    ///
642    /// These options are not exposed as constants for stability reasons,
643    /// however you can still use them as arguments to this and other
644    /// `mi_option_` functions if needed,
645    ///
646    /// Note: this function is not thread safe.
647    pub fn mi_option_set(option: mi_option_t, value: c_long);
648
649    /// If the given option has not yet been initialized with [`mi_option_set`]
650    /// or [`mi_option_set_enabled`], sets the option to the given value. If it
651    /// has, this function does nothing.
652    ///
653    /// The value of boolean options is 1 or 0, however experimental options
654    /// exist which take a numeric value, which is the intended use of this
655    /// function.
656    ///
657    /// These options are not exposed as constants for stability reasons,
658    /// however you can still use them as arguments to this and other
659    /// `mi_option_` functions if needed.
660    ///
661    /// Note: this function is not thread safe.
662    pub fn mi_option_set_default(option: mi_option_t, value: c_long);
663}
664
665/// First-class heaps that can be destroyed in one go.
666///
667/// Note: The pointers allocated out of a heap can be be freed using
668/// [`mi_free`](crate::mi_free) -- there is no `mi_heap_free`.
669///
670/// # Example
671///
672/// ```
673/// use libmimalloc_sys as mi;
674/// unsafe {
675///     let h = mi::mi_heap_new();
676///     assert!(!h.is_null());
677///     let p = mi::mi_heap_malloc(h, 50);
678///     assert!(!p.is_null());
679///
680///     // use p...
681///     mi::mi_free(p);
682///
683///     // Clean up the heap. Note that pointers allocated from `h`
684///     // are *not* invalided by `mi_heap_delete`. You would have
685///     // to use (the very dangerous) `mi_heap_destroy` for that
686///     // behavior
687///     mi::mi_heap_delete(h);
688/// }
689/// ```
690pub enum mi_heap_t {}
691
692/// An area of heap space contains blocks of a single size.
693///
694/// The bytes in freed blocks are `committed - used`.
695#[repr(C)]
696#[derive(Debug, Clone, Copy)]
697pub struct mi_heap_area_t {
698    /// Start of the area containing heap blocks.
699    pub blocks: *mut c_void,
700    /// Bytes reserved for this area.
701    pub reserved: usize,
702    /// Current committed bytes of this area.
703    pub committed: usize,
704    /// Bytes in use by allocated blocks.
705    pub used: usize,
706    /// Size in bytes of one block.
707    pub block_size: usize,
708    /// Size in bytes of a full block including padding and metadata.
709    pub full_block_size: usize,
710    /// Heap tag associated with this area (see \a mi_heap_new_ex)
711    pub heap_tag: c_int,
712}
713
714/// Visitor function passed to [`mi_heap_visit_blocks`]
715///
716/// Should return `true` to continue, and `false` to stop visiting (i.e. break)
717///
718/// This function is always first called for every `area` with `block` as a null
719/// pointer. If `visit_all_blocks` was `true`, the function is then called for
720/// every allocated block in that area.
721pub type mi_block_visit_fun = Option<
722    unsafe extern "C" fn(
723        heap: *const mi_heap_t,
724        area: *const mi_heap_area_t,
725        block: *mut c_void,
726        block_size: usize,
727        arg: *mut c_void,
728    ) -> bool,
729>;
730
731extern "C" {
732    /// Create a new heap that can be used for allocation.
733    pub fn mi_heap_new() -> *mut mi_heap_t;
734
735    /// Delete a previously allocated heap.
736    ///
737    /// This will release resources and migrate any still allocated blocks in
738    /// this heap (efficienty) to the default heap.
739    ///
740    /// If `heap` is the default heap, the default heap is set to the backing
741    /// heap.
742    pub fn mi_heap_delete(heap: *mut mi_heap_t);
743
744    /// Destroy a heap, freeing all its still allocated blocks.
745    ///
746    /// Use with care as this will free all blocks still allocated in the heap.
747    /// However, this can be a very efficient way to free all heap memory in one
748    /// go.
749    ///
750    /// If `heap` is the default heap, the default heap is set to the backing
751    /// heap.
752    pub fn mi_heap_destroy(heap: *mut mi_heap_t);
753
754    #[cfg(not(feature = "v3"))]
755    /// Set the default heap to use for [`mi_malloc`](crate::mi_malloc) et al.
756    ///
757    /// Returns the previous default heap.
758    pub fn mi_heap_set_default(heap: *mut mi_heap_t) -> *mut mi_heap_t;
759
760    #[cfg(not(feature = "v3"))]
761    /// Get the default heap that is used for [`mi_malloc`](crate::mi_malloc) et al.
762    pub fn mi_heap_get_default() -> *mut mi_heap_t;
763
764    #[cfg(not(feature = "v3"))]
765    /// Get the backing heap.
766    ///
767    /// The _backing_ heap is the initial default heap for a thread and always
768    /// available for allocations. It cannot be destroyed or deleted except by
769    /// exiting the thread.
770    pub fn mi_heap_get_backing() -> *mut mi_heap_t;
771
772    /// Release outstanding resources in a specific heap.
773    ///
774    /// See also [`mi_collect`].
775    pub fn mi_heap_collect(heap: *mut mi_heap_t, force: bool);
776
777    /// Equivalent to [`mi_malloc`](crate::mi_malloc), but allocates out of the
778    /// specific heap instead of the default.
779    pub fn mi_heap_malloc(heap: *mut mi_heap_t, size: usize) -> *mut c_void;
780
781    /// Equivalent to [`mi_zalloc`](crate::mi_zalloc), but allocates out of the
782    /// specific heap instead of the default.
783    pub fn mi_heap_zalloc(heap: *mut mi_heap_t, size: usize) -> *mut c_void;
784
785    /// Equivalent to [`mi_calloc`], but allocates out of the specific heap
786    /// instead of the default.
787    pub fn mi_heap_calloc(heap: *mut mi_heap_t, count: usize, size: usize) -> *mut c_void;
788
789    /// Equivalent to [`mi_mallocn`], but allocates out of the specific heap
790    /// instead of the default.
791    pub fn mi_heap_mallocn(heap: *mut mi_heap_t, count: usize, size: usize) -> *mut c_void;
792
793    /// Equivalent to [`mi_malloc_small`], but allocates out of the specific
794    /// heap instead of the default.
795    ///
796    /// `size` must be smaller or equal to [`MI_SMALL_SIZE_MAX`].
797    pub fn mi_heap_malloc_small(heap: *mut mi_heap_t, size: usize) -> *mut c_void;
798
799    /// Equivalent to [`mi_realloc`](crate::mi_realloc), but allocates out of
800    /// the specific heap instead of the default.
801    pub fn mi_heap_realloc(heap: *mut mi_heap_t, p: *mut c_void, newsize: usize) -> *mut c_void;
802
803    /// Equivalent to [`mi_reallocn`], but allocates out of the specific heap
804    /// instead of the default.
805    pub fn mi_heap_reallocn(
806        heap: *mut mi_heap_t,
807        p: *mut c_void,
808        count: usize,
809        size: usize,
810    ) -> *mut c_void;
811
812    /// Equivalent to [`mi_reallocf`], but allocates out of the specific heap
813    /// instead of the default.
814    pub fn mi_heap_reallocf(heap: *mut mi_heap_t, p: *mut c_void, newsize: usize) -> *mut c_void;
815
816    /// Equivalent to [`mi_strdup`], but allocates out of the specific heap
817    /// instead of the default.
818    pub fn mi_heap_strdup(heap: *mut mi_heap_t, s: *const c_char) -> *mut c_char;
819
820    /// Equivalent to [`mi_strndup`], but allocates out of the specific heap
821    /// instead of the default.
822    pub fn mi_heap_strndup(heap: *mut mi_heap_t, s: *const c_char, n: usize) -> *mut c_char;
823
824    /// Equivalent to [`mi_realpath`], but allocates out of the specific heap
825    /// instead of the default.
826    pub fn mi_heap_realpath(
827        heap: *mut mi_heap_t,
828        fname: *const c_char,
829        resolved_name: *mut c_char,
830    ) -> *mut c_char;
831
832    /// Equivalent to [`mi_malloc_aligned`](crate::mi_malloc_aligned), but
833    /// allocates out of the specific heap instead of the default.
834    pub fn mi_heap_malloc_aligned(
835        heap: *mut mi_heap_t,
836        size: usize,
837        alignment: usize,
838    ) -> *mut c_void;
839
840    /// Equivalent to [`mi_malloc_aligned_at`], but allocates out of the
841    /// specific heap instead of the default.
842    pub fn mi_heap_malloc_aligned_at(
843        heap: *mut mi_heap_t,
844        size: usize,
845        alignment: usize,
846        offset: usize,
847    ) -> *mut c_void;
848
849    /// Equivalent to [`mi_zalloc_aligned`](crate::mi_zalloc_aligned), but
850    /// allocates out of the specific heap instead of the default.
851    pub fn mi_heap_zalloc_aligned(
852        heap: *mut mi_heap_t,
853        size: usize,
854        alignment: usize,
855    ) -> *mut c_void;
856
857    /// Equivalent to [`mi_zalloc_aligned_at`], but allocates out of the
858    /// specific heap instead of the default.
859    pub fn mi_heap_zalloc_aligned_at(
860        heap: *mut mi_heap_t,
861        size: usize,
862        alignment: usize,
863        offset: usize,
864    ) -> *mut c_void;
865
866    /// Equivalent to [`mi_calloc_aligned`], but allocates out of the specific
867    /// heap instead of the default.
868    pub fn mi_heap_calloc_aligned(
869        heap: *mut mi_heap_t,
870        count: usize,
871        size: usize,
872        alignment: usize,
873    ) -> *mut c_void;
874
875    /// Equivalent to [`mi_calloc_aligned_at`], but allocates out of the
876    /// specific heap instead of the default.
877    pub fn mi_heap_calloc_aligned_at(
878        heap: *mut mi_heap_t,
879        count: usize,
880        size: usize,
881        alignment: usize,
882        offset: usize,
883    ) -> *mut c_void;
884
885    /// Equivalent to [`mi_realloc_aligned`](crate::mi_realloc_aligned), but allocates out of the specific
886    /// heap instead of the default.
887    pub fn mi_heap_realloc_aligned(
888        heap: *mut mi_heap_t,
889        p: *mut c_void,
890        newsize: usize,
891        alignment: usize,
892    ) -> *mut c_void;
893
894    /// Equivalent to [`mi_realloc_aligned_at`], but allocates out of the
895    /// specific heap instead of the default.
896    pub fn mi_heap_realloc_aligned_at(
897        heap: *mut mi_heap_t,
898        p: *mut c_void,
899        newsize: usize,
900        alignment: usize,
901        offset: usize,
902    ) -> *mut c_void;
903
904    /// Equivalent to [`mi_rezalloc`], but allocates out of the specific heap
905    /// instead of the default.
906    pub fn mi_heap_rezalloc(heap: *mut mi_heap_t, p: *mut c_void, newsize: usize) -> *mut c_void;
907
908    /// Equivalent to [`mi_recalloc`], but allocates out of the specific heap
909    /// instead of the default.
910    pub fn mi_heap_recalloc(
911        heap: *mut mi_heap_t,
912        p: *mut c_void,
913        newcount: usize,
914        size: usize,
915    ) -> *mut c_void;
916
917    /// Equivalent to [`mi_rezalloc_aligned`], but allocates out of the specific
918    /// heap instead of the default.
919    pub fn mi_heap_rezalloc_aligned(
920        heap: *mut mi_heap_t,
921        p: *mut c_void,
922        newsize: usize,
923        alignment: usize,
924    ) -> *mut c_void;
925
926    /// Equivalent to [`mi_rezalloc_aligned_at`], but allocates out of the
927    /// specific heap instead of the default.
928    pub fn mi_heap_rezalloc_aligned_at(
929        heap: *mut mi_heap_t,
930        p: *mut c_void,
931        newsize: usize,
932        alignment: usize,
933        offset: usize,
934    ) -> *mut c_void;
935
936    /// Equivalent to [`mi_recalloc_aligned`], but allocates out of the
937    /// specific heap instead of the default.
938    pub fn mi_heap_recalloc_aligned(
939        heap: *mut mi_heap_t,
940        p: *mut c_void,
941        newcount: usize,
942        size: usize,
943        alignment: usize,
944    ) -> *mut c_void;
945
946    /// Equivalent to [`mi_recalloc_aligned_at`], but allocates out of the
947    /// specific heap instead of the default.
948    pub fn mi_heap_recalloc_aligned_at(
949        heap: *mut mi_heap_t,
950        p: *mut c_void,
951        newcount: usize,
952        size: usize,
953        alignment: usize,
954        offset: usize,
955    ) -> *mut c_void;
956
957    #[cfg(not(feature = "v3"))]
958    /// Does a heap contain a pointer to a previously allocated block?
959    ///
960    /// `p` must be a pointer to a previously allocated block (in any heap) -- it cannot be some
961    /// random pointer!
962    ///
963    /// Returns `true` if the block pointed to by `p` is in the `heap`.
964    ///
965    /// See [`mi_heap_check_owned`].
966    pub fn mi_heap_contains_block(heap: *mut mi_heap_t, p: *const c_void) -> bool;
967
968    #[cfg(not(feature = "v3"))]
969    /// Check safely if any pointer is part of a heap.
970    ///
971    /// `p` may be any pointer -- not required to be previously allocated by the
972    /// given heap or any other mimalloc heap. Returns `true` if `p` points to a
973    /// block in the given heap, false otherwise.
974    ///
975    /// Note: expensive function, linear in the pages in the heap.
976    ///
977    /// See [`mi_heap_contains_block`], [`mi_heap_get_default`], and
978    /// [`mi_is_in_heap_region`]
979    pub fn mi_heap_check_owned(heap: *mut mi_heap_t, p: *const c_void) -> bool;
980
981    #[cfg(not(feature = "v3"))]
982    /// Check safely if any pointer is part of the default heap of this thread.
983    ///
984    /// `p` may be any pointer -- not required to be previously allocated by the
985    /// default heap for this thread, or any other mimalloc heap. Returns `true`
986    /// if `p` points to a block in the default heap, false otherwise.
987    ///
988    /// Note: expensive function, linear in the pages in the heap.
989    ///
990    /// See [`mi_heap_contains_block`], [`mi_heap_get_default`]
991    pub fn mi_check_owned(p: *const c_void) -> bool;
992
993    /// Visit all areas and blocks in `heap`.
994    ///
995    /// If `visit_all_blocks` is false, the `visitor` is only called once for
996    /// every heap area. If it's true, the `visitor` is also called for every
997    /// allocated block inside every area (with `!block.is_null()`). Return
998    /// `false` from the `visitor` to return early.
999    ///
1000    /// `arg` is an extra argument passed into the `visitor`.
1001    ///
1002    /// Returns `true` if all areas and blocks were visited.
1003    ///
1004    /// Passing a `None` visitor is allowed, and is a no-op.
1005    pub fn mi_heap_visit_blocks(
1006        heap: *const mi_heap_t,
1007        visit_all_blocks: bool,
1008        visitor: mi_block_visit_fun,
1009        arg: *mut c_void,
1010    ) -> bool;
1011
1012    #[cfg(feature = "arena")]
1013    /// Create a heap that only allocates in the specified arena
1014    pub fn mi_heap_new_in_arena(arena_id: mi_arena_id_t) -> *mut mi_heap_t;
1015
1016    #[cfg(feature = "arena")]
1017    /// Reserve OS memory for use by mimalloc. Reserved areas are used
1018    /// before allocating from the OS again. By reserving a large area upfront,
1019    /// allocation can be more efficient, and can be better managed on systems
1020    /// without `mmap`/`VirtualAlloc` (like WASM for example).
1021    ///
1022    /// - `size` The size to reserve.
1023    /// - `commit` Commit the memory upfront.
1024    /// - `allow_large` Allow large OS pages (2MiB) to be used?
1025    /// - `exclusive` Only allow allocations if specifically for this arena.
1026    /// - `arena_id` Pointer who's value will be set to the new arena_id if successful.
1027    ///
1028    /// Returns 0 if successful, and an error code otherwise (e.g. `ENOMEM`)
1029    pub fn mi_reserve_os_memory_ex(
1030        size: usize,
1031        commit: bool,
1032        allow_large: bool,
1033        exclusive: bool,
1034        arena_id: *mut mi_arena_id_t,
1035    ) -> c_int;
1036
1037    #[cfg(feature = "arena")]
1038    /// Manage a particular memory area for use by mimalloc.
1039    /// This is just like `mi_reserve_os_memory_ex` except that the area should already be
1040    /// allocated in some manner and available for use my mimalloc.
1041    ///
1042    /// # Safety
1043    /// mimalloc will likely segfault when allocating from the arena if the arena `start` & `size`
1044    /// aren't aligned with mimalloc's `MI_SEGMENT_ALIGN` (e.g. 32MB on x86_64 machines).
1045    ///
1046    /// - `start` Start of the memory area
1047    /// - `size` The size of the memory area. Must be large than `MI_ARENA_BLOCK_SIZE` (e.g. 64MB
1048    ///          on x86_64 machines).
1049    /// - `commit` Set true if the memory range is already commited.
1050    /// - `is_large` Set true if the memory range consists of large files, or if the memory should
1051    ///              not be decommitted or protected (like rdma etc.).
1052    /// - `is_zero` Set true if the memory range consists only of zeros.
1053    /// - `numa_node` Possible associated numa node or `-1`.
1054    /// - `exclusive` Only allow allocations if specifically for this arena.
1055    /// - `arena_id` Pointer who's value will be set to the new arena_id if successful.
1056    ///
1057    /// Returns `true` if arena was successfully allocated
1058    pub fn mi_manage_os_memory_ex(
1059        start: *const c_void,
1060        size: usize,
1061        is_committed: bool,
1062        is_large: bool,
1063        is_zero: bool,
1064        numa_node: c_int,
1065        exclusive: bool,
1066        arena_id: *mut mi_arena_id_t,
1067    ) -> bool;
1068}
1069
1070#[cfg(test)]
1071mod tests {
1072    use super::*;
1073    use crate::mi_malloc;
1074
1075    #[test]
1076    fn it_calculates_usable_size() {
1077        let ptr = unsafe { mi_malloc(32) } as *mut u8;
1078        let usable_size = unsafe { mi_usable_size(ptr as *mut c_void) };
1079        assert!(
1080            usable_size >= 32,
1081            "usable_size should at least equal to the allocated size"
1082        );
1083    }
1084
1085    #[test]
1086    fn runtime_stable_option() {
1087        unsafe {
1088            assert_eq!(mi_option_get(mi_option_show_errors), 0);
1089            mi_option_set(mi_option_show_errors, 1);
1090            assert_eq!(mi_option_get(mi_option_show_errors), 1);
1091
1092            assert_eq!(mi_option_get(mi_option_show_stats), 0);
1093            mi_option_set(mi_option_show_stats, 1);
1094            assert_eq!(mi_option_get(mi_option_show_stats), 1);
1095
1096            assert_eq!(mi_option_get(mi_option_verbose), 0);
1097            mi_option_set(mi_option_verbose, 1);
1098            assert_eq!(mi_option_get(mi_option_verbose), 1);
1099        }
1100    }
1101}