Pārlūkot izejas kodu

Cleanup allocation functions

Jeremy Soller 6 gadi atpakaļ
vecāks
revīzija
42abc98a99
4 mainītis faili ar 18 papildinājumiem un 10 dzēšanām
  1. 14 1
      src/platform/src/lib.rs
  2. 1 1
      src/stdio/src/helpers.rs
  3. 2 7
      src/stdlib/src/lib.rs
  4. 1 1
      src/string/src/lib.rs

+ 14 - 1
src/platform/src/lib.rs

@@ -97,7 +97,7 @@ pub unsafe fn memcpy(s1: *mut c_void, s2: *const c_void, n: usize) -> *mut c_voi
     s1
 }
 
-pub unsafe fn alloc(size: usize, offset: usize, align: usize) -> *mut c_void {
+unsafe fn alloc_inner(size: usize, offset: usize, align: usize) -> *mut c_void {
     let ptr = ralloc::alloc(size + offset, align);
     if !ptr.is_null() {
         *(ptr as *mut u64) = (size + offset) as u64;
@@ -108,6 +108,19 @@ pub unsafe fn alloc(size: usize, offset: usize, align: usize) -> *mut c_void {
     }
 }
 
+pub unsafe fn alloc(size: usize) -> *mut c_void {
+    alloc_inner(size, 16, 8)
+}
+
+pub unsafe fn alloc_align(size: usize, alignment: usize) -> *mut c_void {
+    let mut align = 32;
+    while align <= alignment {
+        align *= 2;
+    }
+
+    alloc_inner(size, align/2, align)
+}
+
 pub unsafe fn realloc(ptr: *mut c_void, size: size_t) -> *mut c_void {
     let old_ptr = (ptr as *mut u8).offset(-16);
     let old_size = *(old_ptr as *mut u64);

+ 1 - 1
src/stdio/src/helpers.rs

@@ -62,7 +62,7 @@ pub unsafe fn _fdopen(fd: c_int, mode: *const c_char) -> Option<*mut FILE> {
         flags |= F_APP;
     }
 
-    let f = platform::alloc(mem::size_of::<FILE>(), 16, 8) as *mut FILE;
+    let f = platform::alloc(mem::size_of::<FILE>()) as *mut FILE;
     // Allocate the file
     if f.is_null() {
         None

+ 2 - 7
src/stdlib/src/lib.rs

@@ -328,17 +328,12 @@ pub extern "C" fn lrand48() -> c_long {
 
 #[no_mangle]
 pub unsafe extern "C" fn malloc(size: size_t) -> *mut c_void {
-    platform::alloc(size, 16, 8)
+    platform::alloc(size)
 }
 
 #[no_mangle]
 pub unsafe extern "C" fn memalign(alignment: size_t, size: size_t) -> *mut c_void {
-    let mut align = 32;
-    while align <= alignment as usize {
-        align *= 2;
-    }
-
-    platform::alloc(size, align / 2, align)
+    platform::alloc_align(size, alignment)
 }
 
 #[no_mangle]

+ 1 - 1
src/string/src/lib.rs

@@ -191,7 +191,7 @@ pub unsafe extern "C" fn strndup(s1: *const c_char, size: usize) -> *mut c_char
     let len = strnlen(s1, size);
 
     // the "+ 1" is to account for the NUL byte
-    let buffer = platform::alloc(len + 1, 16, 8) as *mut c_char;
+    let buffer = platform::alloc(len + 1) as *mut c_char;
     if buffer.is_null() {
         platform::errno = ENOMEM as c_int;
     } else {