c_support/memory/allocation.rs
1//! Allocation through the system memory manager, with the C allocator
2//! contract LVGL and LittleFS expect (`malloc`-style pointers carrying their
3//! own metadata header, `realloc` semantics, null on failure).
4//!
5//! # Safety
6//!
7//! The functions are unsafe: pointers must come from this module, must not
8//! be used after being freed, and concurrent access must be synchronized.
9
10use core::ptr::null_mut;
11use core::{ffi::c_void, ptr::NonNull};
12use log::warning;
13use memory::CapabilityFlags;
14use synchronization::blocking_mutex::raw::CriticalSectionRawMutex;
15use synchronization::mutex::Mutex;
16use task::block_on;
17
18use crate::Allocated;
19
20/// Memory capability flags requested from the memory manager.
21pub type MemoryCapabilities = u8;
22
23/// Memory can be used for code execution.
24pub const MEMORY_CAPABILITIES_EXECUTE: MemoryCapabilities =
25 memory::CapabilityFlags::Executable.bits();
26
27/// Memory is accessible by DMA controllers.
28pub const MEMORY_CAPABILITIES_DIRECT_MEMORY_ACCESS: MemoryCapabilities =
29 memory::CapabilityFlags::DirectMemoryAccess.bits();
30
31/// Memory stays accessible when external flash caches are disabled.
32pub const MEMORY_CAPABILITIES_ALWAYS_ACCESSIBLE: MemoryCapabilities =
33 memory::CapabilityFlags::AlwaysAccessible.bits();
34
35/// No special capabilities: standard memory.
36pub const MEMORY_CAPABILITIES_NONE: MemoryCapabilities = 0;
37
38static ALLOCATION_MUTEX: Mutex<CriticalSectionRawMutex, ()> = Mutex::new(());
39
40/// Converts a function that returns an `Option<NonNull<P>>` into a raw C-compatible pointer.
41///
42/// This utility function is used internally to convert Rust's safe pointer types
43/// into C-compatible raw pointers. Returns `null_mut()` if the function returns `None`.
44///
45/// # Type Parameters
46///
47/// * `F` - A function that returns `Option<NonNull<P>>`
48/// * `P` - The pointer type being converted
49///
50/// # Parameters
51///
52/// * `Function` - The function to execute and convert the result
53///
54/// # Returns
55///
56/// A raw C-compatible pointer, or null if the function returns `None`
57pub fn into_pointer<F, P>(function: F) -> *mut c_void
58where
59 F: FnOnce() -> Option<NonNull<P>>,
60{
61 match function() {
62 Some(pointer) => pointer.as_ptr() as *mut c_void,
63 None => null_mut(),
64 }
65}
66
67/// Deallocates a previously allocated memory block.
68///
69/// This function frees memory that was previously allocated using `memory_allocate`
70/// or `memory_reallocate`. It's safe to call this function with a null pointer.
71///
72/// # Safety
73///
74/// - The pointer must have been returned by a previous call to `memory_allocate`
75/// or `memory_reallocate`
76/// - The pointer must not be used after this function returns
77///
78/// # Parameters
79///
80/// * `Pointer` - Pointer to the memory block to deallocate, or null
81///
82/// # Examples
83///
84/// ```text
85/// void* ptr = memory_allocate(NULL, 1024, 8, 0);
86/// memory_deallocate(ptr); // Free the memory
87/// memory_deallocate(NULL); // Safe - ignored
88/// ```
89pub unsafe fn memory_deallocate(pointer: *mut c_void) {
90 let _lock = block_on(ALLOCATION_MUTEX.lock());
91
92 let allocated = match unsafe { Allocated::from_user_pointer(pointer as *mut u8) } {
93 Some(alloc) => alloc,
94 None => {
95 return;
96 }
97 };
98
99 let layout = allocated.get_layout().unwrap();
100 let base_pointer = allocated.get_base_pointer();
101
102 unsafe {
103 memory::global_manager().deallocate(base_pointer, layout);
104 }
105}
106
107/// Reallocates a memory block to a new size.
108///
109/// This function changes the size of a previously allocated memory block. If the new size
110/// is larger, the additional memory is uninitialized. If the new size is smaller, the
111/// excess memory is freed. The original data is preserved up to the minimum of the old
112/// and new sizes. The platform resizes the block in place when it can, and a shrink that keeps
113/// the alignment and DMA constraints can stay in place. Growth follows the platform's placement
114/// policy and always preserves the capability flags requested at allocation time. If no suitable
115/// region can serve the new size and alignment, reallocation fails and the old block is unchanged.
116///
117/// # Safety
118///
119/// - If `Pointer` is not null, it must have been returned by a previous call to
120/// `memory_allocate` or `memory_reallocate`
121/// - Use the returned pointer after a successful resize
122/// - A non-null original pointer remains valid only if a nonzero resize fails
123///
124/// # Parameters
125///
126/// * `Pointer` - Pointer to the memory block to reallocate, or null for new allocation
127/// * `Size` - New size in bytes (0 is equivalent to deallocation). On 32-bit
128/// targets a block, including its header and padding, is limited to 32 MiB.
129///
130/// # Returns
131///
132/// - Pointer to the reallocated memory block
133/// - Null if allocation fails or if size is 0
134/// - If `Pointer` is null and `Size` is nonzero, allocates with default alignment
135///
136/// # Examples
137///
138/// ```text
139/// // Allocate initial memory
140/// void* ptr = memory_reallocate(NULL, 1024);
141///
142/// // Expand the memory
143/// ptr = memory_reallocate(ptr, 2048);
144///
145/// // Shrink the memory
146/// ptr = memory_reallocate(ptr, 512);
147///
148/// // Free the memory
149/// memory_reallocate(ptr, 0);
150/// ```
151pub unsafe fn memory_reallocate(pointer: *mut c_void, size: usize) -> *mut c_void {
152 if size == 0 {
153 // Deallocation takes the allocation mutex itself and accepts null.
154 unsafe { memory_deallocate(pointer) };
155 return null_mut();
156 }
157
158 let _lock = block_on(ALLOCATION_MUTEX.lock());
159
160 unsafe {
161 let pointer = pointer as *mut u8;
162
163 let allocated = match Allocated::from_user_pointer(pointer) {
164 Some(alloc) => alloc,
165 None => {
166 drop(_lock);
167 //trace!("memory_reallocate called with null pointer, allocating new memory of size: {}", size);
168 return memory_allocate_core(size);
169 }
170 };
171
172 let old_layout = allocated.get_layout().unwrap();
173 let Some(new_layout) = Allocated::get_layout_for_allocation(size, old_layout.align())
174 else {
175 return null_mut();
176 };
177 let capabilities = allocated.get_capabilities();
178
179 let pointer = memory::global_manager().reallocate(
180 capabilities,
181 allocated.get_base_pointer(),
182 old_layout,
183 new_layout.size(),
184 );
185
186 let Some(allocated) = Allocated::from_layout(pointer, &new_layout, capabilities) else {
187 return null_mut();
188 };
189
190 allocated.get_user_pointer() as *mut c_void
191 }
192}
193
194/// Allocates a memory block with specified properties.
195///
196/// This function allocates a block of memory with the specified size, alignment,
197/// and capabilities. The memory is uninitialized and must be properly initialized
198/// before use.
199///
200/// # Safety
201///
202/// This function is unsafe because:
203/// - The returned memory is uninitialized
204/// - The caller must ensure proper deallocation
205/// - The hint address, if provided, must be a valid memory address
206///
207/// # Parameters
208///
209/// * `Hint_address` - Preferred memory address (hint only, may be ignored), or null
210/// * `Size` - Size of the memory block in bytes. On 32-bit targets a block,
211/// including its header and padding, is limited to 32 MiB.
212/// * `Alignment` - Required memory alignment in bytes (must be a power of 2)
213/// * `Capabilities` - Memory capabilities flags (see `memory_capabilities_*` constants)
214///
215/// # Returns
216///
217/// - Pointer to the allocated memory block
218/// - Null if allocation fails
219///
220/// # Errors
221///
222/// Returns null if:
223/// - Insufficient memory available
224/// - Invalid alignment (not a power of 2)
225/// - Requested capabilities not supported
226/// - Size is too large
227///
228/// # Examples
229///
230/// ```text
231/// // Allocate 1024 bytes with 8-byte alignment
232/// void* ptr = memory_allocate(NULL, 1024, 8, memory_capabilities_none);
233///
234/// // Allocate executable memory for code
235/// void* code_ptr = memory_allocate(NULL, 4096, 4096, MEMORY_CAPABILITIES_EXECUTE);
236///
237/// // Allocate DMA-capable memory
238/// void* dma_ptr = memory_allocate(NULL, 2048, 32, memory_capabilities_direct_memory_access);
239/// ```
240pub unsafe fn memory_allocate(
241 _: *mut c_void,
242 size: usize,
243 alignment: usize,
244 capabilities: MemoryCapabilities,
245) -> *mut c_void {
246 let _lock = block_on(ALLOCATION_MUTEX.lock());
247
248 //trace!(
249 // "memory_allocate called with Size: {size}, Alignment: {alignment}, Capabilities: {capabilities:?}"
250 //);
251
252 let Some(layout) = Allocated::get_layout_for_allocation(size, alignment) else {
253 return null_mut();
254 };
255
256 let capabilities = match CapabilityFlags::from_bits(capabilities) {
257 Some(flags) => flags,
258 None => {
259 warning!(
260 "memory_allocate called with invalid capabilities: {capabilities:?}, ignoring"
261 );
262 CapabilityFlags::empty()
263 }
264 };
265
266 let pointer = unsafe { memory::global_manager().allocate(capabilities, layout) };
267
268 let Some(allocated) = (unsafe { Allocated::from_layout(pointer, &layout, capabilities) })
269 else {
270 return null_mut();
271 };
272
273 allocated.get_user_pointer() as *mut c_void
274}
275
276/// Allocates a memory block with default properties.
277///
278/// # Safety
279/// This function is unsafe because it dereferences raw pointers.
280pub unsafe fn memory_allocate_core(size: usize) -> *mut c_void {
281 //trace!("memory_allocate_core called with Size: {size}");
282 unsafe {
283 memory_allocate(
284 null_mut(),
285 size,
286 align_of::<usize>(), // Use usize alignment for general-purpose allocations
287 MEMORY_CAPABILITIES_NONE,
288 )
289 }
290}
291
292#[cfg(test)]
293mod tests {
294 //! # Memory Management Tests
295 //!
296 //! This module contains comprehensive tests for the memory management functionality.
297 //! The tests cover various scenarios including basic allocation/deallocation,
298 //! edge cases, error conditions, and stress testing.
299 //!
300 //! ## Test Categories
301 //!
302 //! - **Basic Operations**: Standard allocation, deallocation, and reallocation
303 //! - **Edge Cases**: Zero-size allocations, large alignments, null pointers
304 //! - **Capabilities**: Testing executable and DMA-capable memory
305 //! - **Stress Testing**: Multiple allocations and allocation tracking
306 //! - **Error Handling**: Invalid inputs and error recovery
307 use alloc::vec::Vec;
308 use testing_support::MemoryManager;
309
310 use super::*;
311
312 /// Tests basic memory allocation and deallocation functionality.
313 ///
314 /// This test verifies that:
315 /// - Memory can be successfully allocated with specified size and alignment
316 /// - Allocated memory is readable and writable
317 /// - Memory can be properly deallocated without errors
318 /// - Data written to memory is correctly stored and retrieved
319 #[test]
320 fn test_allocate_deallocate_basic() {
321 unsafe {
322 // Test basic allocation and deallocation
323 let size = 128;
324 let alignment = 8;
325 let capabilities = 0; // Basic capabilities
326 let hint_address = core::ptr::null_mut();
327
328 let pointer = memory_allocate(hint_address, size, alignment, capabilities);
329 assert!(!pointer.is_null(), "Memory allocation should succeed");
330
331 // Write and read to verify the memory is accessible
332 let ptr = pointer as *mut u8;
333 for i in 0..size {
334 *ptr.add(i) = (i % 256) as u8;
335 }
336
337 for i in 0..size {
338 assert_eq!(
339 *ptr.add(i),
340 (i % 256) as u8,
341 "Memory should be readable and writable"
342 );
343 }
344
345 // Deallocate the memory
346 memory_deallocate(pointer);
347 }
348 }
349
350 /// Tests allocation behavior with zero size.
351 ///
352 /// Zero-size allocations are a special case that different allocators
353 /// may handle differently. This test ensures the implementation handles
354 /// them gracefully without crashing.
355 #[test]
356 fn test_allocate_zero_size() {
357 unsafe {
358 // Test allocation with zero size
359 let size = 0;
360 let alignment = 8;
361 let capabilities = 0;
362 let hint_address = core::ptr::null_mut();
363
364 let pointer = memory_allocate(hint_address, size, alignment, capabilities);
365 // Zero-size allocation might return null or a valid pointer, both are acceptable
366 if !pointer.is_null() {
367 memory_deallocate(pointer);
368 }
369 }
370 }
371
372 /// Tests memory allocation with large alignment requirements.
373 ///
374 /// This test verifies that the allocator can handle large alignment
375 /// requirements (64 bytes) and that the returned pointer is properly
376 /// aligned to the requested boundary.
377 #[test]
378 fn test_allocate_large_alignment() {
379 unsafe {
380 // Test allocation with large alignment
381 let size = 256;
382 let alignment = align_of::<u128>();
383 let capabilities = 0;
384 let hint_address = core::ptr::null_mut();
385
386 let pointer = memory_allocate(hint_address, size, alignment, capabilities);
387 assert!(
388 !pointer.is_null(),
389 "Large alignment allocation should succeed"
390 );
391
392 // Verify alignment
393 let addr = pointer as usize;
394 assert_eq!(addr % alignment, 0, "Pointer should be properly aligned");
395
396 memory_deallocate(pointer);
397 }
398 }
399
400 /// Tests memory allocation with small alignments (1, 2, 4 bytes).
401 ///
402 /// This test verifies that the allocator can handle small alignment
403 /// requirements now that CompactLayout supports alignments as low as 1 byte.
404 #[test]
405 fn test_allocate_small_alignments() {
406 unsafe {
407 for &alignment in &[1, 2, 4] {
408 let size = 64;
409 let capabilities = 0;
410 let hint_address = core::ptr::null_mut();
411
412 let pointer = memory_allocate(hint_address, size, alignment, capabilities);
413 assert!(
414 !pointer.is_null(),
415 "Allocation with alignment {} should succeed",
416 alignment
417 );
418
419 // Verify alignment
420 let addr = pointer as usize;
421 assert_eq!(
422 addr % alignment,
423 0,
424 "Pointer should be aligned to {} bytes",
425 alignment
426 );
427
428 // Write and read to verify the memory is accessible
429 let ptr = pointer as *mut u8;
430 for i in 0..size {
431 *ptr.add(i) = (i % 256) as u8;
432 }
433
434 for i in 0..size {
435 assert_eq!(
436 *ptr.add(i),
437 (i % 256) as u8,
438 "Memory should be readable and writable"
439 );
440 }
441
442 memory_deallocate(pointer);
443 }
444 }
445 }
446
447 /// Tests allocation of executable memory.
448 ///
449 /// This test verifies that memory can be allocated with executable
450 /// capabilities, which is necessary for just-in-time compilation
451 /// and dynamic code generation.
452 #[test]
453 fn test_allocate_executable_capability() {
454 unsafe {
455 // Test allocation with executable capability
456 let size = 128;
457 let alignment = 8;
458 let capabilities = MEMORY_CAPABILITIES_EXECUTE;
459 let hint_address = core::ptr::null_mut();
460
461 let pointer = memory_allocate(hint_address, size, alignment, capabilities);
462 assert!(
463 !pointer.is_null(),
464 "Executable memory allocation should succeed"
465 );
466
467 memory_deallocate(pointer);
468 }
469 }
470
471 /// Tests allocation of DMA-capable memory.
472 ///
473 /// DMA-capable memory must meet specific hardware requirements and
474 /// may need to be allocated from special memory regions. This test
475 /// is ignored by default as it requires specific hardware support.
476 #[test]
477 #[ignore = "Requires specific hardware support for DMA"]
478 fn test_allocate_dma_capability() {
479 unsafe {
480 // Test allocation with DMA capability
481 let size = 128;
482 let alignment = 8;
483 let capabilities = MEMORY_CAPABILITIES_DIRECT_MEMORY_ACCESS;
484 let hint_address = core::ptr::null_mut();
485
486 let pointer = memory_allocate(hint_address, size, alignment, capabilities);
487 assert!(!pointer.is_null(), "DMA memory allocation should succeed");
488
489 memory_deallocate(pointer);
490 }
491 }
492
493 /// Tests that deallocating a null pointer is safe.
494 ///
495 /// According to standard behavior, deallocating a null pointer
496 /// should be a no-op and not cause any errors or crashes.
497 #[test]
498 fn test_deallocate_null_pointer() {
499 // Test that deallocating a null pointer doesn't crash
500 unsafe {
501 memory_deallocate(core::ptr::null_mut());
502 }
503 }
504
505 /// Tests reallocation from a null pointer (equivalent to allocation).
506 ///
507 /// When realloc is called with a null pointer, it should behave
508 /// identically to malloc, allocating new memory of the requested size.
509 #[test]
510 fn test_reallocate_null_to_new() {
511 unsafe {
512 // Test reallocating from null (equivalent to allocation)
513 let size = 128;
514 let pointer = memory_reallocate(core::ptr::null_mut(), size);
515 assert!(
516 !pointer.is_null(),
517 "Reallocation from null should work like allocation"
518 );
519
520 // Write to the memory to verify it's usable
521 let ptr = pointer as *mut u8;
522 for i in 0..size {
523 *ptr.add(i) = (i % 256) as u8;
524 }
525
526 memory_deallocate(pointer);
527 }
528 }
529
530 /// Tests expanding memory through reallocation.
531 ///
532 /// This test verifies that existing data is preserved when memory
533 /// is expanded through reallocation, and that the new memory region
534 /// is usable.
535 #[test]
536 fn test_reallocate_expand() {
537 unsafe {
538 // Test expanding memory with reallocation
539 let initial_size = 64;
540 let expanded_size = 128;
541
542 // First allocation
543 let pointer = memory_reallocate(core::ptr::null_mut(), initial_size);
544 assert!(!pointer.is_null(), "Initial allocation should succeed");
545
546 // Fill with test data
547 let ptr = pointer as *mut u8;
548 for i in 0..initial_size {
549 *ptr.add(i) = (i % 256) as u8;
550 }
551
552 // Expand the allocation
553 let new_pointer = memory_reallocate(pointer, expanded_size);
554 assert!(
555 !new_pointer.is_null(),
556 "Reallocation expansion should succeed"
557 );
558
559 // Verify original data is preserved
560 let new_ptr = new_pointer as *mut u8;
561 for i in 0..initial_size {
562 assert_eq!(
563 *new_ptr.add(i),
564 (i % 256) as u8,
565 "Original data should be preserved"
566 );
567 }
568
569 memory_deallocate(new_pointer);
570 }
571 }
572
573 /// Tests shrinking memory through reallocation.
574 ///
575 /// This test verifies that data within the new size bounds is preserved
576 /// when memory is shrunk through reallocation.
577 #[test]
578 fn test_reallocate_shrink() {
579 unsafe {
580 // Test shrinking memory with reallocation
581 let initial_size = 128;
582 let shrunk_size = 64;
583
584 // First allocation
585 let pointer = memory_reallocate(core::ptr::null_mut(), initial_size);
586 assert!(!pointer.is_null(), "Initial allocation should succeed");
587
588 // Fill with test data
589 let ptr = pointer as *mut u8;
590 for i in 0..initial_size {
591 *ptr.add(i) = (i % 256) as u8;
592 }
593
594 // Shrink the allocation
595 let new_pointer = memory_reallocate(pointer, shrunk_size);
596 assert!(
597 !new_pointer.is_null(),
598 "Reallocation shrinking should succeed"
599 );
600
601 // Verify data within new size is preserved
602 let new_ptr = new_pointer as *mut u8;
603 for i in 0..shrunk_size {
604 assert_eq!(
605 *new_ptr.add(i),
606 (i % 256) as u8,
607 "Data within new size should be preserved"
608 );
609 }
610
611 memory_deallocate(new_pointer);
612 }
613 }
614
615 #[test]
616 fn test_invalid_size_and_capability_metadata_on_reallocation() {
617 let caps = CapabilityFlags::DirectMemoryAccess | CapabilityFlags::AlwaysAccessible;
618 unsafe {
619 assert!(memory_allocate(null_mut(), usize::MAX - 7, 8, caps.bits()).is_null());
620 let pointer = core::ptr::NonNull::new(memory_allocate(null_mut(), 64, 64, caps.bits()))
621 .expect("allocation failed")
622 .as_ptr();
623 pointer.cast::<u8>().write_bytes(0x5a, 64);
624
625 for size in [usize::MAX - 7, isize::MAX as usize] {
626 assert!(memory_reallocate(pointer, size).is_null());
627 assert_eq!(
628 core::slice::from_raw_parts(pointer.cast::<u8>(), 64),
629 &[0x5a; 64]
630 );
631 }
632
633 let grown = memory_reallocate(pointer, 4096);
634 assert!(!grown.is_null());
635 assert!(grown.addr().is_multiple_of(64));
636 assert_eq!(
637 core::slice::from_raw_parts(grown.cast::<u8>(), 64),
638 &[0x5a; 64]
639 );
640 assert_eq!(
641 Allocated::from_user_pointer(grown.cast())
642 .unwrap()
643 .get_capabilities(),
644 caps
645 );
646 memory_deallocate(grown);
647 }
648 }
649
650 #[test]
651 fn test_reallocate_to_zero() {
652 let before = MemoryManager::thread_allocations();
653 unsafe {
654 let pointer = memory_allocate_core(64);
655 assert!(!pointer.is_null());
656
657 assert!(memory_reallocate(pointer, 0).is_null());
658 }
659 let delta = MemoryManager::thread_allocations().since(before);
660 assert_eq!(delta.allocations(), 1);
661 assert_eq!(delta.deallocated_bytes(), delta.allocated_bytes());
662 }
663
664 #[test]
665 fn test_reallocate_null_to_zero() {
666 let before = MemoryManager::thread_allocations();
667 unsafe {
668 assert!(memory_reallocate(null_mut(), 0).is_null());
669 }
670 assert_eq!(MemoryManager::thread_allocations(), before);
671 }
672
673 #[test]
674 fn test_multiple_allocations() {
675 unsafe {
676 let mut pointers = Vec::new();
677 let allocation_count = 10;
678 let size = 64;
679 let alignment = 8;
680 let capabilities = 0;
681
682 // Allocate multiple memory blocks
683 for _ in 0..allocation_count {
684 let pointer = memory_allocate(core::ptr::null_mut(), size, alignment, capabilities);
685 assert!(!pointer.is_null(), "Each allocation should succeed");
686 pointers.push(pointer);
687 }
688
689 // Verify each allocation is unique and writable
690 for (i, &pointer) in pointers.iter().enumerate() {
691 let ptr = pointer as *mut u8;
692 let test_value = (i % 256) as u8;
693 *ptr = test_value;
694 assert_eq!(
695 *ptr, test_value,
696 "Each allocation should be independently writable"
697 );
698 }
699
700 // Deallocate all memory blocks
701 for &pointer in &pointers {
702 memory_deallocate(pointer);
703 }
704 }
705 }
706
707 #[test]
708 fn test_reallocation_tracking() {
709 unsafe {
710 // Test that reallocations properly update the tracking table
711 let initial_size = 64;
712 let new_size = 128;
713
714 let pointer = memory_reallocate(core::ptr::null_mut(), initial_size);
715 assert!(!pointer.is_null(), "Initial reallocation should succeed");
716
717 let new_pointer = memory_reallocate(pointer, new_size);
718 assert!(!new_pointer.is_null(), "Reallocation should succeed");
719
720 // The new pointer should be properly tracked
721 memory_deallocate(new_pointer);
722 }
723 }
724}