@@ -84,40 +84,61 @@ fn base_alloc() -> &'static impl GlobalAlloc {
8484 feature = "custom_allocator" ,
8585 not( any( target_family = "wasm" , target_env = "musl" ) )
8686 ) ) ]
87- return & mimalloc :: MiMalloc ;
87+ return & mimalloc_rspack :: MiMalloc ;
8888 #[ cfg( any(
8989 not( feature = "custom_allocator" ) ,
9090 any( target_family = "wasm" , target_env = "musl" )
9191 ) ) ]
9292 return & std:: alloc:: System ;
9393}
9494
95+ #[ allow( unused_variables) ]
96+ unsafe fn base_alloc_size ( ptr : * const u8 , layout : Layout ) -> usize {
97+ #[ cfg( all(
98+ feature = "custom_allocator" ,
99+ not( any( target_family = "wasm" , target_env = "musl" ) )
100+ ) ) ]
101+ return unsafe { mimalloc_rspack:: MiMalloc . usable_size ( ptr) } ;
102+ #[ cfg( any(
103+ not( feature = "custom_allocator" ) ,
104+ any( target_family = "wasm" , target_env = "musl" )
105+ ) ) ]
106+ return layout. size ( ) ;
107+ }
108+
95109unsafe impl GlobalAlloc for TurboMalloc {
96110 unsafe fn alloc ( & self , layout : Layout ) -> * mut u8 {
97111 let ret = unsafe { base_alloc ( ) . alloc ( layout) } ;
98112 if !ret. is_null ( ) {
99- add ( layout. size ( ) ) ;
113+ let size = unsafe { base_alloc_size ( ret, layout) } ;
114+ add ( size) ;
100115 }
101116 ret
102117 }
103118
104119 unsafe fn dealloc ( & self , ptr : * mut u8 , layout : Layout ) {
120+ let size = unsafe { base_alloc_size ( ptr, layout) } ;
105121 unsafe { base_alloc ( ) . dealloc ( ptr, layout) } ;
106- remove ( layout . size ( ) ) ;
122+ remove ( size) ;
107123 }
108124
109125 unsafe fn alloc_zeroed ( & self , layout : Layout ) -> * mut u8 {
110126 let ret = unsafe { base_alloc ( ) . alloc_zeroed ( layout) } ;
111127 if !ret. is_null ( ) {
112- add ( layout. size ( ) ) ;
128+ let size = unsafe { base_alloc_size ( ret, layout) } ;
129+ add ( size) ;
113130 }
114131 ret
115132 }
116133
117134 unsafe fn realloc ( & self , ptr : * mut u8 , layout : Layout , new_size : usize ) -> * mut u8 {
135+ let old_size = unsafe { base_alloc_size ( ptr, layout) } ;
118136 let ret = unsafe { base_alloc ( ) . realloc ( ptr, layout, new_size) } ;
119137 if !ret. is_null ( ) {
120- let old_size = layout. size ( ) ;
138+ // SAFETY: the caller must ensure that the `new_size` does not overflow.
139+ // `layout.align()` comes from a `Layout` and is thus guaranteed to be valid.
140+ let new_layout = unsafe { Layout :: from_size_align_unchecked ( new_size, layout. align ( ) ) } ;
141+ let new_size = unsafe { base_alloc_size ( ret, new_layout) } ;
121142 update ( old_size, new_size) ;
122143 }
123144 ret
0 commit comments