Skip to content

Commit cff3ded

Browse files
committed
Handle possible allocation failure in user_ptr.
1 parent 016e369 commit cff3ded

File tree

3 files changed

+14
-10
lines changed

3 files changed

+14
-10
lines changed

rust/kernel/error.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,9 @@
44
//!
55
//! C header: [`include/uapi/asm-generic/errno-base.h`](../../../include/uapi/asm-generic/errno-base.h)
66
7-
use core::num::TryFromIntError;
8-
use core::str::Utf8Error;
9-
10-
use alloc::alloc::AllocError;
11-
12-
use crate::bindings;
13-
use crate::c_types;
7+
use crate::{bindings, c_types};
8+
use alloc::{alloc::AllocError, collections::TryReserveError};
9+
use core::{num::TryFromIntError, str::Utf8Error};
1410

1511
/// Generic integer kernel error.
1612
///
@@ -57,6 +53,12 @@ impl From<Utf8Error> for Error {
5753
}
5854
}
5955

56+
impl From<TryReserveError> for Error {
57+
fn from(_: TryReserveError) -> Error {
58+
Error::ENOMEM
59+
}
60+
}
61+
6062
/// A [`Result`] with an [`Error`] error type.
6163
///
6264
/// To be used as the return type for functions that may fail.

rust/kernel/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
//! do so first instead of bypassing this crate.
1313
1414
#![no_std]
15-
#![feature(allocator_api, alloc_error_handler)]
15+
#![feature(allocator_api, alloc_error_handler, try_reserve)]
1616
#![deny(clippy::complexity)]
1717
#![deny(clippy::correctness)]
1818
#![deny(clippy::perf)]

rust/kernel/user_ptr.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
//! C header: [`include/linux/uaccess.h`](../../../../include/linux/uaccess.h)
66
77
use crate::{c_types, error, KernelResult};
8-
use alloc::{vec, vec::Vec};
8+
use alloc::vec::Vec;
99
use core::mem::{size_of, MaybeUninit};
1010

1111
extern "C" {
@@ -143,7 +143,9 @@ impl UserSlicePtrReader {
143143
/// Returns `EFAULT` if the address does not currently point to
144144
/// mapped, readable memory.
145145
pub fn read_all(&mut self) -> KernelResult<Vec<u8>> {
146-
let mut data = vec![0; self.1];
146+
let mut data = Vec::<u8>::new();
147+
data.try_reserve_exact(self.1)?;
148+
data.resize(self.1, 0);
147149
// SAFETY: The output buffer is valid as we just allocated it.
148150
unsafe { self.read_raw(data.as_mut_ptr(), data.len())? };
149151
Ok(data)

0 commit comments

Comments
 (0)