SumGuard

Struct SumGuard 

Source
pub struct SumGuard {
    was_set: bool,
}
Expand description

SUM 位保护器,基于 RAII 实现用户空间内存访问保护。

在创建时保存 sstatus.SUM 位的当前状态并设置为 1(允许内核访问用户空间内存); 在销毁时自动恢复之前保存的状态。

这种设计允许安全的嵌套使用:

  • 如果外层已经设置了 SUM 位,内层 guard 不会重复设置,也不会在销毁时清除
  • 只有最外层的 guard 会在销毁时清除 SUM 位

§Safety

此 guard 必须在访问用户空间内存之前创建,并在访问完成后立即销毁。 不应该长时间持有此 guard,因为它会降低内核的安全性。

§使用示例

// 读取用户空间指针
let user_value = {
    let _guard = SumGuard::new();
    unsafe { core::ptr::read(user_ptr) }
}; // 离开作用域,自动恢复 SUM 位

§为什么需要此 guard

手动调用 sstatus::set_sum()sstatus::clear_sum() 存在安全隐患: 如果在两次调用之间发生 panic(例如,由于无效的用户指针导致缺页异常无法处理), clear_sum() 将不会被执行,导致 SUM 位保持置位状态。这会使内核在后续执行中 意外地允许访问用户空间内存,可能导致安全漏洞。

使用此 RAII guard,即使发生 panic,Rust 的 drop 机制也会确保 SUM 位被正确恢复。

Fields§

§was_set: bool

创建 guard 前 SUM 位是否已设置

Implementations§

Source§

impl SumGuard

Source

pub fn new() -> Self

创建一个新的 SumGuard,保存当前 SUM 位状态并设置为 1。

§Safety

调用者必须确保:

  1. 即将访问的用户空间地址是有效的
  2. 不会长时间持有此 guard
  3. 在 guard 生命周期内访问的所有用户空间指针都已经过验证
Source

pub fn was_set(&self) -> bool

检查在创建此 guard 前,SUM 位是否已经被设置

Trait Implementations§

Source§

impl Drop for SumGuard

Source§

fn drop(&mut self)

当 SumGuard 离开作用域时,恢复之前保存的 SUM 位状态。

Auto Trait Implementations§

§

impl Freeze for SumGuard

§

impl RefUnwindSafe for SumGuard

§

impl Send for SumGuard

§

impl Sync for SumGuard

§

impl Unpin for SumGuard

§

impl UnwindSafe for SumGuard

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.