asterinas / asterinas

Asterinas is a secure, fast, and general-purpose OS kernel, written in Rust and providing Linux-compatible ABI.
https://asterinas.github.io/
Other
832 stars 85 forks source link

Introduce type safety for FileDesc in FileTable #1146

Open grief8 opened 1 month ago

grief8 commented 1 month ago

Description:

Currently, the FileTable structure is able to handle negative values of FileDesc, which is not ideal. Handling these negative values raises concerns about the integrity and safety of file descriptor management. It has been suggested that we need a clearer differentiation between valid and invalid file descriptors at compile time.

Proposed Solution:

To improve type safety, we propose introducing a new type FileDesc to distinguish positive file descriptors from negative ones. The proposed implementation involves the following changes:

  1. Define RawFileDesc as i32 for handling raw file descriptors.
  2. Create a new type FileDesc(u32) that will only accept positive values.
  3. Implement a TryFrom conversion to ensure that only valid positive RawFileDesc values can be converted to FileDesc.

The suggested code snippet is as follows:

pub type RawFileDesc = i32;

pub struct FileDesc(u32);

impl TryFrom<RawFileDesc> for FileDesc {
    fn try_from(raw_fd: RawFileDesc) -> Option<FileDesc> {
        if raw_fd > 0 {
            Some(FileDesc(raw_fd as u32))
        } else {
            None
        }
    }
}

impl FileTable {
    pub fn get_file(&self, fd: FileDesc) {
        // Implementation...
    }
}
grief8 commented 1 month ago

@boterinas claim

StevenJiang1110 commented 1 month ago

This proposal can also be extended to cover other IDs, such as UID (user id) and GID (group id). The syscall interface currently allows users to provide negative values (due to the i32 type), but in actuality, these IDs can only be positive in kernel.