From 701b1998e9a0d993005460e29433e6ab4cfa30d3 Mon Sep 17 00:00:00 2001 From: Dan Gohman Date: Thu, 3 Jan 2019 12:04:19 -0800 Subject: [PATCH] Avoid creating slices with null pointers. --- lib/environ/src/module.rs | 1 + lib/jit/src/code_memory.rs | 2 +- lib/runtime/src/memory.rs | 1 - lib/runtime/src/mmap.rs | 9 ++++++--- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/environ/src/module.rs b/lib/environ/src/module.rs index d60006afbd..4397ab266f 100644 --- a/lib/environ/src/module.rs +++ b/lib/environ/src/module.rs @@ -56,6 +56,7 @@ impl MemoryStyle { if maximum <= tunables.static_memory_bound { // A heap with a declared maximum can be immovable, so make // it static. + assert!(tunables.static_memory_bound >= memory.minimum); return ( MemoryStyle::Static { bound: tunables.static_memory_bound, diff --git a/lib/jit/src/code_memory.rs b/lib/jit/src/code_memory.rs index b9bf13f636..5374ad7800 100644 --- a/lib/jit/src/code_memory.rs +++ b/lib/jit/src/code_memory.rs @@ -70,7 +70,7 @@ impl CodeMemory { self.position = 0; for m in &mut self.mmaps[self.published..] { - if !m.as_ptr().is_null() { + if m.len() != 0 { unsafe { region::protect(m.as_mut_ptr(), m.len(), region::Protection::ReadExecute) } diff --git a/lib/runtime/src/memory.rs b/lib/runtime/src/memory.rs index a5a6ea38ae..71e56b34df 100644 --- a/lib/runtime/src/memory.rs +++ b/lib/runtime/src/memory.rs @@ -121,7 +121,6 @@ impl LinearMemory { if new_bytes > self.mmap.len() - self.offset_guard_size { // If we have no maximum, this is a "dynamic" heap, and it's allowed to move. - assert!(self.maximum.is_none()); let guard_bytes = self.offset_guard_size; let request_bytes = new_bytes.checked_add(guard_bytes)?; diff --git a/lib/runtime/src/mmap.rs b/lib/runtime/src/mmap.rs index 3384318371..fef3004ed3 100644 --- a/lib/runtime/src/mmap.rs +++ b/lib/runtime/src/mmap.rs @@ -24,8 +24,11 @@ pub struct Mmap { impl Mmap { /// Construct a new empty instance of `Mmap`. pub fn new() -> Self { + // Rust's slices require non-null pointers, even when empty. `Vec` + // contains code to create a non-null dangling pointer value when + // constructed empty, so we reuse that here. Self { - ptr: ptr::null_mut(), + ptr: Vec::new().as_mut_ptr(), len: 0, } } @@ -119,7 +122,7 @@ impl Mmap { impl Drop for Mmap { #[cfg(not(target_os = "windows"))] fn drop(&mut self) { - if !self.ptr.is_null() { + if self.len != 0 { let r = unsafe { libc::munmap(self.ptr as *mut libc::c_void, self.len) }; assert_eq!(r, 0, "munmap failed: {}", errno::errno()); } @@ -127,7 +130,7 @@ impl Drop for Mmap { #[cfg(target_os = "windows")] fn drop(&mut self) { - if !self.ptr.is_null() { + if self.len != 0 { use winapi::um::memoryapi::VirtualFree; use winapi::um::winnt::MEM_RELEASE; let r = unsafe { VirtualFree(self.ptr as *mut libc::c_void, self.len, MEM_RELEASE) };