summaryrefslogtreecommitdiff
path: root/tools/rust/src/dlmalloc.rs
blob: e60b2d1f8a15f989fbc2db4393e1ccba52412c62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// SPDX-License-Identifier: MIT

use core::alloc::{GlobalAlloc, Layout};
use core::ffi::c_void;
use core::ptr;
use cty::*;

extern "C" {
    pub fn malloc(size: size_t) -> *mut c_void;
    pub fn realloc_in_place(p: *mut c_void, size: size_t) -> *mut c_void;
    pub fn free(p: *mut c_void);
    pub fn posix_memalign(p: *mut *mut c_void, alignment: size_t, size: size_t) -> c_int;
}

pub struct DLMalloc;

unsafe impl GlobalAlloc for DLMalloc {
    #[inline]
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let mut ptr = ptr::null_mut();
        let ret = unsafe {
            posix_memalign(
                &mut ptr,
                layout.align().max(core::mem::size_of::<usize>()),
                layout.size(),
            )
        };
        if ret == 0 {
            ptr as *mut u8
        } else {
            ptr::null_mut()
        }
    }

    #[inline]
    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        // Unfortunately, calloc doesn't make any alignment guarantees, so the memory
        // has to be manually zeroed-out.
        let ptr = unsafe { self.alloc(layout) };
        if !ptr.is_null() {
            unsafe { ptr::write_bytes(ptr, 0, layout.size()) };
        }
        ptr
    }

    #[inline]
    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
        unsafe {
            free(ptr as *mut c_void);
        }
    }

    #[inline]
    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        // Unfortunately, realloc doesn't make any alignment guarantees, so the memory
        // has to be manually allocated as aligned memory if it cannot be resized
        // in-place.
        let mut new_ptr = unsafe { realloc_in_place(ptr as *mut c_void, new_size) as *mut u8 };

        // return early if in-place resize succeeded
        if !new_ptr.is_null() {
            return new_ptr;
        }

        // allocate new aligned storage with correct layout
        new_ptr =
            unsafe { self.alloc(Layout::from_size_align_unchecked(new_size, layout.align())) };

        // return early if allocation failed
        if new_ptr.is_null() {
            return ptr::null_mut();
        }

        // copy over the data and deallocate the old storage
        unsafe { ptr::copy(ptr, new_ptr, layout.size().min(new_size)) };
        unsafe { self.dealloc(ptr, layout) };
        new_ptr
    }
}