esp_wifi/compat/
malloc.rs
1use core::alloc::Layout;
2
3#[no_mangle]
4pub unsafe extern "C" fn malloc(size: usize) -> *mut u8 {
5 trace!("alloc {}", size);
6
7 let total_size = size + 4;
8
9 extern "C" {
10 fn esp_wifi_allocate_from_internal_ram(size: usize) -> *mut u8;
11 }
12
13 let ptr = unsafe { esp_wifi_allocate_from_internal_ram(total_size) };
14
15 if ptr.is_null() {
16 warn!("Unable to allocate {} bytes", size);
17 return ptr;
18 }
19
20 *(ptr as *mut usize) = total_size;
21 ptr.offset(4)
22}
23
24#[no_mangle]
25pub unsafe extern "C" fn free(ptr: *mut u8) {
26 trace!("free {:?}", ptr);
27
28 if ptr.is_null() {
29 return;
30 }
31
32 let ptr = ptr.offset(-4);
33 let total_size = *(ptr as *const usize);
34
35 let layout = Layout::from_size_align_unchecked(total_size, 4);
36 alloc::alloc::dealloc(ptr, layout);
37}
38
39#[no_mangle]
40pub unsafe extern "C" fn calloc(number: u32, size: usize) -> *mut u8 {
41 trace!("calloc {} {}", number, size);
42
43 let total_size = number as usize * size;
44 let ptr = malloc(total_size);
45
46 if !ptr.is_null() {
47 for i in 0..total_size as isize {
48 ptr.offset(i).write_volatile(0);
49 }
50 }
51
52 ptr
53}
54
55#[no_mangle]
56unsafe extern "C" fn realloc(ptr: *mut u8, new_size: usize) -> *mut u8 {
57 trace!("realloc {:?} {}", ptr, new_size);
58
59 extern "C" {
60 fn memcpy(d: *mut u8, s: *const u8, l: usize);
61 }
62
63 unsafe {
64 let p = malloc(new_size);
65 if !p.is_null() && !ptr.is_null() {
66 let len = usize::min(
67 (ptr as *const u32).sub(1).read_volatile() as usize,
68 new_size,
69 );
70 memcpy(p, ptr, len);
71 free(ptr);
72 }
73 p
74 }
75}
76
77#[cfg(feature = "esp-alloc")]
78#[doc(hidden)]
79#[no_mangle]
80pub extern "C" fn esp_wifi_free_internal_heap() -> usize {
81 esp_alloc::HEAP.free_caps(esp_alloc::MemoryCapability::Internal.into())
82}
83
84#[cfg(feature = "esp-alloc")]
85#[doc(hidden)]
86#[no_mangle]
87pub extern "C" fn esp_wifi_allocate_from_internal_ram(size: usize) -> *mut u8 {
88 unsafe {
89 esp_alloc::HEAP.alloc_caps(
90 esp_alloc::MemoryCapability::Internal.into(),
91 core::alloc::Layout::from_size_align_unchecked(size, 4),
92 )
93 }
94}