allocator_test.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! So far the kernel's `Box` and `Vec` types can't be used by userspace test cases, since all users
  3. //! of those types (e.g. `CString`) use kernel allocators for instantiation.
  4. //!
  5. //! In order to allow userspace test cases to make use of such types as well, implement the
  6. //! `Cmalloc` allocator within the allocator_test module and type alias all kernel allocators to
  7. //! `Cmalloc`. The `Cmalloc` allocator uses libc's `realloc()` function as allocator backend.
  8. #![allow(missing_docs)]
  9. use super::{flags::*, AllocError, Allocator, Flags};
  10. use core::alloc::Layout;
  11. use core::cmp;
  12. use core::ptr;
  13. use core::ptr::NonNull;
  14. /// The userspace allocator based on libc.
  15. pub struct Cmalloc;
  16. pub type Kmalloc = Cmalloc;
  17. pub type Vmalloc = Kmalloc;
  18. pub type KVmalloc = Kmalloc;
  19. impl Cmalloc {
  20. /// Returns a [`Layout`] that makes [`Kmalloc`] fulfill the requested size and alignment of
  21. /// `layout`.
  22. pub fn aligned_layout(layout: Layout) -> Layout {
  23. // Note that `layout.size()` (after padding) is guaranteed to be a multiple of
  24. // `layout.align()` which together with the slab guarantees means that `Kmalloc` will return
  25. // a properly aligned object (see comments in `kmalloc()` for more information).
  26. layout.pad_to_align()
  27. }
  28. }
  29. extern "C" {
  30. #[link_name = "aligned_alloc"]
  31. fn libc_aligned_alloc(align: usize, size: usize) -> *mut crate::ffi::c_void;
  32. #[link_name = "free"]
  33. fn libc_free(ptr: *mut crate::ffi::c_void);
  34. }
  35. // SAFETY:
  36. // - memory remains valid until it is explicitly freed,
  37. // - passing a pointer to a valid memory allocation created by this `Allocator` is always OK,
  38. // - `realloc` provides the guarantees as provided in the `# Guarantees` section.
  39. unsafe impl Allocator for Cmalloc {
  40. unsafe fn realloc(
  41. ptr: Option<NonNull<u8>>,
  42. layout: Layout,
  43. old_layout: Layout,
  44. flags: Flags,
  45. ) -> Result<NonNull<[u8]>, AllocError> {
  46. let src = match ptr {
  47. Some(src) => {
  48. if old_layout.size() == 0 {
  49. ptr::null_mut()
  50. } else {
  51. src.as_ptr()
  52. }
  53. }
  54. None => ptr::null_mut(),
  55. };
  56. if layout.size() == 0 {
  57. // SAFETY: `src` is either NULL or was previously allocated with this `Allocator`
  58. unsafe { libc_free(src.cast()) };
  59. return Ok(NonNull::slice_from_raw_parts(
  60. crate::alloc::dangling_from_layout(layout),
  61. 0,
  62. ));
  63. }
  64. // ISO C (ISO/IEC 9899:2011) defines `aligned_alloc`:
  65. //
  66. // > The value of alignment shall be a valid alignment supported by the implementation
  67. // [...].
  68. //
  69. // As an example of the "supported by the implementation" requirement, POSIX.1-2001 (IEEE
  70. // 1003.1-2001) defines `posix_memalign`:
  71. //
  72. // > The value of alignment shall be a power of two multiple of sizeof (void *).
  73. //
  74. // and POSIX-based implementations of `aligned_alloc` inherit this requirement. At the time
  75. // of writing, this is known to be the case on macOS (but not in glibc).
  76. //
  77. // Satisfy the stricter requirement to avoid spurious test failures on some platforms.
  78. let min_align = core::mem::size_of::<*const crate::ffi::c_void>();
  79. let layout = layout.align_to(min_align).map_err(|_| AllocError)?;
  80. let layout = layout.pad_to_align();
  81. // SAFETY: Returns either NULL or a pointer to a memory allocation that satisfies or
  82. // exceeds the given size and alignment requirements.
  83. let dst = unsafe { libc_aligned_alloc(layout.align(), layout.size()) } as *mut u8;
  84. let dst = NonNull::new(dst).ok_or(AllocError)?;
  85. if flags.contains(__GFP_ZERO) {
  86. // SAFETY: The preceding calls to `libc_aligned_alloc` and `NonNull::new`
  87. // guarantee that `dst` points to memory of at least `layout.size()` bytes.
  88. unsafe { dst.as_ptr().write_bytes(0, layout.size()) };
  89. }
  90. if !src.is_null() {
  91. // SAFETY:
  92. // - `src` has previously been allocated with this `Allocator`; `dst` has just been
  93. // newly allocated, hence the memory regions do not overlap.
  94. // - both` src` and `dst` are properly aligned and valid for reads and writes
  95. unsafe {
  96. ptr::copy_nonoverlapping(
  97. src,
  98. dst.as_ptr(),
  99. cmp::min(layout.size(), old_layout.size()),
  100. )
  101. };
  102. }
  103. // SAFETY: `src` is either NULL or was previously allocated with this `Allocator`
  104. unsafe { libc_free(src.cast()) };
  105. Ok(NonNull::slice_from_raw_parts(dst, layout.size()))
  106. }
  107. }