Skip to main content

memory/
test.rs

1//! Test template for `ManagerTrait` implementations.
2//!
3//! This module provides a comprehensive test suite that can be used to validate
4//! any implementation of the `ManagerTrait`. The tests cover all the core functionality
5//! including allocation, deallocation, reallocation, and cache management.
6//!
7//! # Usage
8//!
9//! ## Using the Macro (Recommended)
10//!
11//! The easiest way to test your memory manager implementation is to use the
12//! `implement_memory_manager_tests!` macro, which generates individual test
13//! functions for each test category:
14//!
15//! ```rust,ignore
16//! use memory::implement_memory_manager_tests;
17//!
18//! #[cfg(test)]
19//! mod tests {
20//!     use super::*;
21//!     use memory::{Manager, ManagerTrait};
22//!     
23//!     struct MyAllocator;
24//!     impl ManagerTrait for MyAllocator {
25//!         // ... implementation ...
26//!     }
27//!     
28//!     static ALLOCATOR: MyAllocator = MyAllocator;
29//!     
30//!     implement_memory_manager_tests! {
31//!         Manager::new(&ALLOCATOR)
32//!     }
33//! }
34//! ```
35//!
36//! This will generate 14 individual `#[test]` functions, each testing a specific
37//! aspect of your memory manager implementation.
38//!
39//! ## Using Individual Test Functions
40//!
41//! You can also call individual test functions directly:
42//!
43//! ```rust,ignore
44//! use memory::{Manager, test_template};
45//!
46//! #[cfg(test)]
47//! mod tests {
48//!     use super::*;
49//!
50//!     fn get_test_manager() -> Manager<'static> {
51//!         static ALLOCATOR: YourAllocatorType = YourAllocatorType::new();
52//!         Manager::new(&ALLOCATOR)
53//!     }
54//!
55//!     #[test]
56//!     fn test_basic_allocation() {
57//!         let manager = get_test_manager();
58//!         test_template::test_basic_allocation($manager);
59//!     }
60//!
61//!     #[test]
62//!     fn test_all() {
63//!         let manager = get_test_manager();
64//!         test_template::run_all_tests($manager);
65//!     }
66//! }
67//! ```
68//!
69//! # Test Categories
70//!
71//! ## Basic Allocation Tests
72//! - `test_basic_allocation` - Basic allocation and deallocation
73//! - `test_zero_sized_allocation` - Zero-size allocation handling
74//! - `test_aligned_allocation` - Various alignment requirements
75//! - `test_allocation_with_capabilities` - Capability-based allocation
76//!
77//! ## Deallocation & Reallocation Tests
78//! - `test_deallocation` - Memory deallocation and usage tracking
79//! - `test_reallocation_grow` - Growing allocations
80//! - `test_reallocation_shrink` - Shrinking allocations
81//! - `test_reallocation_same_size` - Same-size reallocation
82//!
83//! ## Complex Operations Tests
84//! - `test_multiple_allocations` - Multiple simultaneous allocations
85//! - `test_allocation_pattern` - Complex allocation/deallocation patterns
86//! - `test_large_allocation` - Large memory allocations
87//!
88//! ## Manager Features Tests
89//! - `test_memory_statistics` - Memory usage statistics
90//! - `test_page_size` - Page size reporting
91//! - `test_cache_flush_operations` - Cache management operations
92
93use crate::{CapabilityFlags, Layout, Manager, ManagerTrait};
94use alloc::vec::Vec;
95
96/// Tests basic memory allocation.
97///
98/// Verifies that the manager can allocate memory with a simple layout
99/// and default capabilities, and that the returned pointer is valid.
100///
101/// # Parameters
102/// * `manager` - The memory manager to test
103///
104/// # Panics
105/// Panics if allocation fails or returns a null pointer.
106pub fn test_basic_allocation(allocator: impl ManagerTrait) {
107    let manager = Manager::new(&allocator);
108
109    let layout = Layout::from_size_align(64, 8).unwrap();
110    let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
111
112    assert!(
113        !ptr.is_null(),
114        "Basic allocation should not return null pointer"
115    );
116
117    // Verify we can write to the allocated memory
118    unsafe {
119        core::ptr::write_bytes(ptr, 0xAA, layout.size());
120
121        // Verify the write worked
122        for i in 0..layout.size() {
123            assert_eq!(*ptr.add(i), 0xAA, "Memory should be writable");
124        }
125
126        manager.deallocate(ptr, layout);
127    }
128}
129
130/// Tests zero-sized allocation behavior.
131///
132/// Verifies that allocating zero bytes returns a null pointer as expected.
133///
134/// # Parameters
135/// * `manager` - The memory manager to test
136pub fn test_zero_sized_allocation(allocator: impl ManagerTrait) {
137    let manager = Manager::new(&allocator);
138
139    let layout = Layout::from_size_align(0, 1).unwrap();
140    let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
141
142    assert!(
143        ptr.is_null(),
144        "Zero-sized allocation should return null pointer"
145    );
146}
147
148/// Tests allocation with specific alignment requirements.
149///
150/// Verifies that the manager respects alignment requirements and returns
151/// properly aligned memory addresses.
152///
153/// # Parameters
154/// * `manager` - The memory manager to test
155///
156/// # Panics
157/// Panics if allocation fails or the returned pointer is not properly aligned.
158pub fn test_aligned_allocation(allocator: impl ManagerTrait) {
159    let manager = Manager::new(&allocator);
160
161    let alignments = [8, 16, 32, 64, 128];
162
163    for &align in &alignments {
164        let layout = Layout::from_size_align(256, align).unwrap();
165        let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
166
167        assert!(
168            !ptr.is_null(),
169            "Aligned allocation should not return null pointer"
170        );
171        assert_eq!(
172            ptr as usize % align,
173            0,
174            "Pointer should be aligned to {} bytes",
175            align
176        );
177
178        unsafe { manager.deallocate(ptr, layout) };
179    }
180}
181
182/// Tests allocation with different capability flags.
183///
184/// Verifies that the manager can handle allocations with different capability
185/// requirements (executable, direct memory access, etc.).
186///
187/// # Parameters
188/// * `manager` - The memory manager to test
189///
190/// # Panics
191/// Panics if allocation with capabilities fails.
192pub fn test_allocation_with_capabilities(allocator: impl ManagerTrait) {
193    let layout = Layout::from_size_align(128, 128).unwrap();
194    let expected = CapabilityFlags::Executable | CapabilityFlags::AlwaysAccessible;
195    for capability in expected.iter() {
196        let pointer = unsafe { allocator.allocate(capability, layout) };
197        let pointer = pointer.expect("supported capability");
198        unsafe { allocator.deallocate(pointer, layout) };
199    }
200}
201
202/// Checks which individual capabilities a platform supports for an aligned layout.
203pub fn test_supported_capabilities(allocator: impl ManagerTrait, supported: CapabilityFlags) {
204    let layout = Layout::from_size_align(128, 128).unwrap();
205    for capability in CapabilityFlags::all().iter() {
206        let pointer = unsafe { allocator.allocate(capability, layout) };
207        assert_eq!(
208            pointer.is_some(),
209            supported.contains(capability),
210            "{capability:?}"
211        );
212        if let Some(pointer) = pointer {
213            unsafe { allocator.deallocate(pointer, layout) };
214        }
215    }
216}
217
218/// Tests memory deallocation.
219///
220/// Verifies that memory can be allocated and then safely deallocated.
221///
222/// # Parameters
223/// * `manager` - The memory manager to test
224pub fn test_deallocation(allocator: impl ManagerTrait) {
225    let manager = Manager::new(&allocator);
226
227    let layout = Layout::from_size_align(128, 8).unwrap();
228
229    let initial_used = manager.get_used();
230
231    let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
232    assert!(!ptr.is_null(), "Allocation should succeed");
233
234    let used_after_alloc = manager.get_used();
235    assert!(
236        used_after_alloc >= initial_used,
237        "Used memory should increase after allocation"
238    );
239
240    unsafe { manager.deallocate(ptr, layout) };
241
242    // Note: The used memory might not return exactly to initial_used due to
243    // allocator overhead, but it should not increase further
244}
245/// Tests memory reallocation to a larger size.
246///
247/// Verifies that the manager can grow an existing allocation and preserve
248/// the original data.
249///
250/// # Parameters
251/// * `manager` - The memory manager to test
252///
253/// # Panics
254/// Panics if reallocation fails or data is not preserved.
255pub fn test_reallocation_grow(allocator: impl ManagerTrait) {
256    let manager = Manager::new(&allocator);
257    let initial_size = 64;
258    let new_size = 256;
259    let layout = Layout::from_size_align(initial_size, 8).unwrap();
260
261    let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
262    assert!(!ptr.is_null(), "Initial allocation should succeed");
263
264    // Write pattern to memory
265    unsafe {
266        for i in 0..initial_size {
267            *ptr.add(i) = (i % 256) as u8;
268        }
269    }
270
271    // Reallocate to larger size
272    let new_ptr = unsafe { manager.reallocate(CapabilityFlags::empty(), ptr, layout, new_size) };
273    assert!(!new_ptr.is_null(), "Reallocation should succeed");
274
275    // Verify original data is preserved
276    unsafe {
277        for i in 0..initial_size {
278            assert_eq!(
279                *new_ptr.add(i),
280                (i % 256) as u8,
281                "Original data should be preserved after reallocation"
282            );
283        }
284    }
285
286    let new_layout = Layout::from_size_align(new_size, 8).unwrap();
287    unsafe { manager.deallocate(new_ptr, new_layout) };
288}
289
290/// Tests memory reallocation to a smaller size.
291///
292/// Verifies that the manager can shrink an existing allocation and preserve
293/// data up to the new size.
294///
295/// # Parameters
296/// * `manager` - The memory manager to test
297///
298/// # Panics
299/// Panics if reallocation fails or data is not preserved.
300pub fn test_reallocation_shrink(allocator: impl ManagerTrait) {
301    let manager = Manager::new(&allocator);
302    let initial_size = 256;
303    let new_size = 64;
304    let layout = Layout::from_size_align(initial_size, 8).unwrap();
305
306    let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
307    assert!(!ptr.is_null(), "Initial allocation should succeed");
308
309    // Write pattern to memory
310    unsafe {
311        for i in 0..initial_size {
312            *ptr.add(i) = (i % 256) as u8;
313        }
314    }
315
316    // Reallocate to smaller size
317    let new_ptr = unsafe { manager.reallocate(CapabilityFlags::empty(), ptr, layout, new_size) };
318    assert!(!new_ptr.is_null(), "Reallocation should succeed");
319
320    // Verify data up to new size is preserved
321    unsafe {
322        for i in 0..new_size {
323            assert_eq!(
324                *new_ptr.add(i),
325                (i % 256) as u8,
326                "Data should be preserved up to new size after reallocation"
327            );
328        }
329    }
330
331    let new_layout = Layout::from_size_align(new_size, 8).unwrap();
332    unsafe { manager.deallocate(new_ptr, new_layout) };
333}
334
335/// Tests reallocation with the same size.
336///
337/// Verifies that reallocating with the same size either returns the same pointer
338/// or successfully creates a new allocation with preserved data.
339///
340/// # Parameters
341/// * `manager` - The memory manager to test
342pub fn test_reallocation_same_size(allocator: impl ManagerTrait) {
343    let manager = Manager::new(&allocator);
344    let size = 128;
345    let layout = Layout::from_size_align(size, 8).unwrap();
346
347    let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
348    assert!(!ptr.is_null(), "Initial allocation should succeed");
349
350    // Write pattern to memory
351    unsafe {
352        for i in 0..size {
353            *ptr.add(i) = (i % 256) as u8;
354        }
355    }
356
357    // Reallocate with same size
358    let new_ptr = unsafe { manager.reallocate(CapabilityFlags::empty(), ptr, layout, size) };
359    assert!(!new_ptr.is_null(), "Reallocation should succeed");
360
361    // Verify data is preserved
362    unsafe {
363        for i in 0..size {
364            assert_eq!(
365                *new_ptr.add(i),
366                (i % 256) as u8,
367                "Data should be preserved after same-size reallocation"
368            );
369        }
370    }
371
372    unsafe { manager.deallocate(new_ptr, layout) };
373}
374
375/// Tests multiple simultaneous allocations.
376///
377/// Verifies that the manager can handle multiple allocations at once
378/// without interference.
379///
380/// # Parameters
381/// * `manager` - The memory manager to test
382///
383/// # Panics
384/// Panics if any allocation fails or data is corrupted.
385pub fn test_multiple_allocations(allocator: impl ManagerTrait) {
386    let manager = Manager::new(&allocator);
387    const NUM_ALLOCATIONS: usize = 10;
388    let mut allocations = [(
389        core::ptr::null_mut::<u8>(),
390        Layout::from_size_align(1, 1).unwrap(),
391    ); NUM_ALLOCATIONS];
392
393    // Allocate multiple blocks
394    for (i, allocation) in allocations.iter_mut().enumerate().take(NUM_ALLOCATIONS) {
395        let size = 64 + i * 32;
396        let layout = Layout::from_size_align(size, 8).unwrap();
397        let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
398
399        assert!(!ptr.is_null(), "Allocation {} should succeed", i);
400
401        // Write unique pattern to each allocation
402        unsafe {
403            for j in 0..size {
404                *ptr.add(j) = ((i + j) % 256) as u8;
405            }
406        }
407
408        *allocation = (ptr, layout);
409    }
410
411    // Verify all allocations still have correct data
412    for (i, &(ptr, layout)) in allocations.iter().enumerate().take(NUM_ALLOCATIONS) {
413        let size = layout.size();
414
415        unsafe {
416            for j in 0..size {
417                assert_eq!(
418                    *ptr.add(j),
419                    ((i + j) % 256) as u8,
420                    "Data should be preserved in allocation {}",
421                    i
422                );
423            }
424        }
425    }
426
427    // Deallocate all blocks
428    for &(ptr, layout) in allocations.iter().take(NUM_ALLOCATIONS) {
429        unsafe { manager.deallocate(ptr, layout) };
430    }
431}
432
433/// Tests memory usage statistics.
434///
435/// Verifies that the manager correctly tracks used and free memory.
436///
437/// # Parameters
438/// * `manager` - The memory manager to test
439pub fn test_memory_statistics(allocator: impl ManagerTrait) {
440    let manager = Manager::new(&allocator);
441    let initial_used = manager.get_used();
442    //let initial_free = manager.get_free();
443
444    let layout = Layout::from_size_align(1024, 8).unwrap();
445    let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
446
447    assert!(!ptr.is_null(), "Allocation should succeed");
448
449    let used_after_alloc = manager.get_used();
450    //let free_after_alloc = manager.get_free(); // Used memory should increase
451    assert!(
452        used_after_alloc >= initial_used,
453        "Used memory should increase after allocation"
454    );
455
456    // Free memory should decrease or stay the same
457    // assert!(
458    //     free_after_alloc <= initial_free,
459    //     "Free memory should decrease or stay the same after allocation"
460    // );
461
462    unsafe { manager.deallocate(ptr, layout) };
463}
464
465/// Tests the page size reporting.
466///
467/// Verifies that the manager reports a valid page size.
468///
469/// # Parameters
470/// * `manager` - The memory manager to test
471pub fn test_page_size(allocator: impl ManagerTrait) {
472    let manager = Manager::new(&allocator);
473    let page_size = manager.get_page_size();
474
475    assert!(page_size > 0, "Page size should be greater than zero");
476    assert!(
477        page_size.is_power_of_two(),
478        "Page size should be a power of two"
479    );
480}
481
482/// Tests cache flush operations.
483///
484/// Verifies that cache flush operations can be called without panicking.
485/// Note: This doesn't verify actual cache behavior as that's hardware-specific.
486///
487/// # Parameters
488/// * `manager` - The memory manager to test
489pub fn test_cache_flush_operations(allocator: impl ManagerTrait) {
490    let manager = Manager::new(&allocator);
491    // Test data cache flush
492    manager.flush_data_cache();
493
494    // Test instruction cache flush with allocated memory
495    let layout = Layout::from_size_align(256, 8).unwrap();
496    let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
497
498    if !ptr.is_null() {
499        unsafe {
500            manager.flush_instruction_cache(ptr, layout.size());
501            manager.deallocate(ptr, layout);
502        }
503    }
504}
505
506/// Tests large memory allocation.
507///
508/// Verifies that the manager can handle larger allocations.
509///
510/// # Parameters
511/// * `manager` - The memory manager to test
512pub fn test_large_allocation(allocator: impl ManagerTrait) {
513    let manager = Manager::new(&allocator);
514    let large_size = 1024 * 1024; // 1 MB
515    let layout = Layout::from_size_align(large_size, 8).unwrap();
516
517    let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
518
519    if !ptr.is_null() {
520        // If allocation succeeded, verify we can use the memory
521        unsafe {
522            *ptr = 0xFF;
523            *ptr.add(large_size - 1) = 0xFF;
524
525            assert_eq!(
526                *ptr, 0xFF,
527                "Should be able to write to start of large allocation"
528            );
529            assert_eq!(
530                *ptr.add(large_size - 1),
531                0xFF,
532                "Should be able to write to end of large allocation"
533            );
534
535            manager.deallocate(ptr, layout);
536        }
537    }
538    // Note: It's acceptable for very large allocations to fail on some systems
539}
540
541/// Tests allocation and deallocation pattern.
542///
543/// Verifies that the manager can handle a complex pattern of allocations
544/// and deallocations without memory leaks or corruption.
545///
546/// # Parameters
547/// * `manager` - The memory manager to test
548pub fn test_allocation_pattern(allocator: impl ManagerTrait) {
549    let manager = Manager::new(&allocator);
550    let initial_used = manager.get_used();
551
552    // Pattern: allocate 5, deallocate 2, allocate 3, deallocate all
553    let mut ptrs = Vec::new(); // Allocate 5
554    for i in 0..5 {
555        let size = 128 + i * 64;
556        let layout = Layout::from_size_align(size, 8).unwrap();
557        let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
558        assert!(!ptr.is_null(), "Allocation should succeed");
559        ptrs.push((ptr, layout));
560    }
561
562    // Deallocate 2
563    for _ in 0..2 {
564        if let Some((ptr, layout)) = ptrs.pop() {
565            unsafe { manager.deallocate(ptr, layout) };
566        }
567    }
568
569    // Allocate 3 more
570    for i in 0..3 {
571        let size = 96 + i * 32;
572        let layout = Layout::from_size_align(size, 8).unwrap();
573        let ptr = unsafe { manager.allocate(CapabilityFlags::empty(), layout) };
574        assert!(!ptr.is_null(), "Allocation should succeed");
575        ptrs.push((ptr, layout));
576    }
577
578    // Deallocate all
579    for (ptr, layout) in ptrs {
580        unsafe { manager.deallocate(ptr, layout) };
581    }
582
583    let final_used = manager.get_used();
584
585    // Memory usage should be close to initial (allowing for some allocator overhead)
586    assert!(
587        final_used <= initial_used + 1024,
588        "Memory should be mostly freed after pattern completion"
589    );
590}
591
592/// Macro to implement all memory manager tests for a given `ManagerTrait` implementation.
593///
594/// This macro generates individual test functions for each test category, making it easy
595/// to integrate comprehensive memory manager testing into your test suite.
596///
597/// # Usage
598///
599/// ```rust,ignore
600/// use memory::implement_memory_manager_tests;
601///
602/// mod tests {
603///     use super::*;
604///     use memory::{Manager, ManagerTrait};
605///     
606///     struct MyAllocator;
607///     impl ManagerTrait for MyAllocator {
608///         // ... implementation ...
609///     }
610///     
611///     static ALLOCATOR: MyAllocator = MyAllocator;
612///     
613///     implement_memory_manager_tests! {
614///         Manager::new(&ALLOCATOR)
615///     }
616/// }
617/// ```
618///
619/// This will generate individual `#[test]` functions for each test category:
620/// - test_basic_allocation
621/// - test_zero_sized_allocation
622/// - test_aligned_allocation
623/// - test_allocation_with_capabilities
624/// - test_deallocation
625/// - test_reallocation_grow
626/// - test_reallocation_shrink
627/// - test_reallocation_same_size
628/// - test_multiple_allocations
629/// - test_memory_statistics
630/// - test_page_size
631/// - test_cache_flush_operations
632/// - test_large_allocation
633/// - test_allocation_pattern
634///
635/// To verify a platform-specific capability set, pass the test attribute and
636/// expected flags as `([#[test]], manager, capabilities = flags)`. The attribute
637/// can also select a target-specific test harness.
638#[macro_export]
639macro_rules! implement_memory_manager_tests {
640    ([$($attribute:tt)*], $manager:expr, capabilities = $supported:expr) => {
641        $crate::implement_memory_manager_tests!(
642            @impl, [$($attribute)*], $manager,
643            $crate::test::test_supported_capabilities($manager, $supported)
644        );
645    };
646    (@impl, [$($attribute:tt)*], $manager:expr, $capabilities_test:expr) => {
647        $($attribute)*
648        fn test_basic_allocation() {
649            $crate::test::test_basic_allocation($manager);
650        }
651
652        $($attribute)*
653        fn test_zero_sized_allocation() {
654            $crate::test::test_zero_sized_allocation($manager);
655        }
656
657        $($attribute)*
658        fn test_aligned_allocation() {
659            $crate::test::test_aligned_allocation($manager);
660        }
661
662        $($attribute)*
663        fn test_allocation_with_capabilities() {
664            $capabilities_test;
665        }
666
667        $($attribute)*
668        fn test_deallocation() {
669            $crate::test::test_deallocation($manager);
670        }
671
672        $($attribute)*
673        fn test_reallocation_grow() {
674            $crate::test::test_reallocation_grow($manager);
675        }
676
677        $($attribute)*
678        fn test_reallocation_shrink() {
679            $crate::test::test_reallocation_shrink($manager);
680        }
681
682        $($attribute)*
683        fn test_reallocation_same_size() {
684            $crate::test::test_reallocation_same_size($manager);
685        }
686
687        $($attribute)*
688        fn test_multiple_allocations() {
689            $crate::test::test_multiple_allocations($manager);
690        }
691
692        $($attribute)*
693        fn test_memory_statistics() {
694            $crate::test::test_memory_statistics($manager);
695        }
696
697        $($attribute)*
698        fn test_page_size() {
699            $crate::test::test_page_size($manager);
700        }
701
702        $($attribute)*
703        fn test_cache_flush_operations() {
704            $crate::test::test_cache_flush_operations($manager);
705        }
706
707        $($attribute)*
708        fn test_large_allocation() {
709            $crate::test::test_large_allocation($manager);
710        }
711
712        $($attribute)*
713        fn test_allocation_pattern() {
714            $crate::test::test_allocation_pattern($manager);
715        }
716    };
717    ($manager:expr) => {
718        $crate::implement_memory_manager_tests!(
719            @impl, [#[test]], $manager,
720            $crate::test::test_allocation_with_capabilities($manager)
721        );
722    };
723}