From 6f6647a532e320129d7ea12b1e922d834175e9ad Mon Sep 17 00:00:00 2001 From: Wedson Almeida Filho Date: Thu, 18 Mar 2021 15:26:06 +0000 Subject: [PATCH] Handle possible allocation failure in `user_ptr`. --- rust/kernel/error.rs | 16 +++++++++------- rust/kernel/lib.rs | 8 +++++++- rust/kernel/user_ptr.rs | 10 ++++------ 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 68117e557e863d..ad084420f46e41 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -4,13 +4,9 @@ //! //! C header: [`include/uapi/asm-generic/errno-base.h`](../../../include/uapi/asm-generic/errno-base.h) -use core::num::TryFromIntError; -use core::str::Utf8Error; - -use alloc::alloc::AllocError; - -use crate::bindings; -use crate::c_types; +use crate::{bindings, c_types}; +use alloc::{alloc::AllocError, collections::TryReserveError}; +use core::{num::TryFromIntError, str::Utf8Error}; /// Generic integer kernel error. /// @@ -72,6 +68,12 @@ impl From for Error { } } +impl From for Error { + fn from(_: TryReserveError) -> Error { + Error::ENOMEM + } +} + /// A [`Result`] with an [`Error`] error type. /// /// To be used as the return type for functions that may fail. diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 49cd6bbe20dae8..504bb0a2149891 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -12,7 +12,13 @@ //! do so first instead of bypassing this crate. #![no_std] -#![feature(allocator_api, alloc_error_handler, const_fn, const_mut_refs)] +#![feature( + allocator_api, + alloc_error_handler, + const_fn, + const_mut_refs, + try_reserve +)] #![deny(clippy::complexity)] #![deny(clippy::correctness)] #![deny(clippy::perf)] diff --git a/rust/kernel/user_ptr.rs b/rust/kernel/user_ptr.rs index fdab26d2f4bb25..82eaea2d769b86 100644 --- a/rust/kernel/user_ptr.rs +++ b/rust/kernel/user_ptr.rs @@ -4,12 +4,8 @@ //! //! C header: [`include/linux/uaccess.h`](../../../../include/linux/uaccess.h) -use alloc::vec; +use crate::{c_types, error}; use alloc::vec::Vec; -use core::u32; - -use crate::c_types; -use crate::error; extern "C" { fn rust_helper_access_ok(addr: *const c_types::c_void, len: c_types::c_ulong) @@ -134,7 +130,9 @@ impl UserSlicePtrReader { /// Returns `EFAULT` if the address does not currently point to /// mapped, readable memory. pub fn read_all(&mut self) -> error::KernelResult> { - let mut data = vec![0; self.1]; + let mut data = Vec::::new(); + data.try_reserve_exact(self.1)?; + data.resize(self.1, 0); self.read(&mut data)?; Ok(data) }