dragonos_malloc.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. use crate::ALLOCATOR;
  2. use core::{
  3. alloc::{GlobalAlloc, Layout},
  4. ptr::null_mut,
  5. sync::atomic::{AtomicUsize, Ordering},
  6. };
  7. use super::types::*;
  8. extern "C" {
  9. fn _dragonos_free(ptr: *mut c_void) -> *mut c_void;
  10. fn _dragonos_malloc(size: usize) -> *mut c_void;
  11. }
  12. pub struct Allocator {
  13. mstate: AtomicUsize,
  14. }
  15. pub const NEWALLOCATOR: Allocator = Allocator {
  16. mstate: AtomicUsize::new(0),
  17. };
  18. impl Allocator {
  19. pub fn set_book_keeper(&self, mstate: usize) {
  20. self.mstate.store(mstate, Ordering::Relaxed);
  21. }
  22. pub fn get_book_keeper(&self) -> usize {
  23. self.mstate.load(Ordering::Relaxed)
  24. }
  25. }
  26. unsafe impl<'a> GlobalAlloc for Allocator {
  27. unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
  28. alloc(layout.size()) as *mut u8
  29. //alloc_align(layout.size(), layout.align()) as *mut u8
  30. }
  31. unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
  32. free(ptr as *mut c_void);
  33. }
  34. }
  35. pub unsafe fn alloc(size: usize) -> *mut c_void {
  36. // println!("alloc size: {}", size);
  37. _dragonos_malloc(size)
  38. //mspace_malloc(ALLOCATOR.get_book_keeper(), size)
  39. }
  40. fn align_up(addr: usize, align: usize) -> usize {
  41. (addr + align - 1) & !(align - 1)
  42. }
  43. pub unsafe fn alloc_align(mut size: usize, alignment: usize) -> *mut c_void {
  44. // println!("alloc align size: {}, alignment: {}", size, alignment);
  45. size = align_up(size, alignment);
  46. // TODO: 实现对齐分配
  47. _dragonos_malloc(size)
  48. //mspace_memalign(ALLOCATOR.get_book_keeper(), alignment, size)
  49. }
  50. pub unsafe fn realloc(ptr: *mut c_void, size: size_t) -> *mut c_void {
  51. todo!()
  52. }
  53. pub unsafe fn free(ptr: *mut c_void) {
  54. // println!("free ptr: {:#018x}", ptr as usize);
  55. _dragonos_free(ptr);
  56. //mspace_free(ALLOCATOR.get_book_keeper(), ptr)
  57. }
  58. #[cfg(target_os = "dragonos")]
  59. pub fn new_mspace() -> usize {
  60. // dbg!("new_mspace");
  61. 1
  62. }