Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to add iomap to TSS (take 2) #194

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
83 changes: 78 additions & 5 deletions src/structures/gdt.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
//! Types for the Global Descriptor Table and segment selectors.

pub use crate::registers::segmentation::SegmentSelector;
use crate::structures::tss::TaskStateSegment;
use crate::structures::tss::{InvalidIoMap, TaskStateSegment};
use crate::PrivilegeLevel;
use bit_field::BitField;
use bitflags::bitflags;
use core::fmt;
use core::{cmp, fmt, mem};
// imports for intra-doc links
#[cfg(doc)]
use crate::registers::segmentation::{Segment, CS, SS};
Expand Down Expand Up @@ -439,17 +439,90 @@ impl Descriptor {
/// being used.
#[inline]
pub unsafe fn tss_segment_unchecked(tss: *const TaskStateSegment) -> Descriptor {
// SAFETY: if iomap_size is zero, there are no requirements to uphold.
unsafe { Self::tss_segment_raw(tss, 0) }
}

/// Creates a TSS system descriptor for the given TSS, setting up the IO permissions bitmap.
///
/// # Example
///
/// ```
/// use x86_64::structures::gdt::Descriptor;
/// use x86_64::structures::tss::TaskStateSegment;
///
/// /// A helper that places some I/O map bytes behind a TSS.
/// #[repr(C)]
/// struct TssWithIOMap {
/// tss: TaskStateSegment,
/// iomap: [u8; 5],
/// }
///
/// static TSS: TssWithIOMap = TssWithIOMap {
/// tss: TaskStateSegment::new(),
/// iomap: [0xff, 0xff, 0x00, 0x80, 0xff],
/// };
///
/// let tss = Descriptor::tss_segment_with_iomap(&TSS.tss, &TSS.iomap).unwrap();
/// ```
pub fn tss_segment_with_iomap(
tss: &'static TaskStateSegment,
iomap: &'static [u8],
Comment on lines +469 to +470

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like how this makes the caller of this function have to make sure that the tss and iomap are close enough to each other. Also idk if it's bad to put other data between the tss and iomap but personally I think it's better to have the iomap go right after the tss.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like how this makes the caller of this function have to make sure that the tss and iomap are close enough to each other.

It's certainly a trade-off, but I think it's one worth making. The big advantage of this approach is that we don't force a given layout and users are free to choose their own. This API is compatible with both statically sized and dynamically sized I/O maps and I'm not sure if we can easily achieve this if we enforce a given layout with a struct in this crate.

When it comes to actually using this, I think runtime errors can be easily avoided. Users can define their own structs containing the TSS and an I/O map of their choice:

#[repr(C)]
struct TssWithIOMap {
    tss: TaskStateSegment,
    iomap: [u8; 26],
}

let tss: &'static TssWithIOMap = todo!();
let tss = Descriptor::tss_segment_with_iomap(&tss.tss, &tss.iomap).unwrap();

We might want to consider adding something like this as an example in the doc comment.

For more advanced uses (e.g. dynamically sized I/O maps on the heap) users can implement whatever layout fits them.

Also idk if it's bad to put other data between the tss and iomap but personally I think it's better to have the iomap go right after the tss.

Having other data between the two should be completely fine.

) -> Result<Descriptor, InvalidIoMap> {
if iomap.len() > 8193 {
return Err(InvalidIoMap::TooLong { len: iomap.len() });
}

let iomap_addr = iomap.as_ptr() as usize;
let tss_addr = tss as *const _ as usize;

if tss_addr > iomap_addr {
return Err(InvalidIoMap::IoMapBeforeTss);
}

let base = iomap_addr - tss_addr;
if base > 0xdfff {
return Err(InvalidIoMap::TooFarFromTss { distance: base });
}

let last_byte = *iomap.last().unwrap_or(&0xff);
if last_byte != 0xff {
return Err(InvalidIoMap::InvalidTerminatingByte { byte: last_byte });
}

if tss.iomap_base != base as u16 {
return Err(InvalidIoMap::InvalidBase {
expected: base as u16,
got: tss.iomap_base,
});
}

// SAFETY: all invariants checked above
Ok(unsafe { Self::tss_segment_raw(tss, iomap.len() as u16) })
}

/// Creates a TSS system descriptor for the given TSS, setting up the IO permissions bitmap.
///
/// # Safety
///
/// There must be a valid IO map at `(tss as *const u8).offset(tss.iomap_base)`
/// of length `iomap_size`, with the terminating `0xFF` byte. Additionally, `iomap_base` must
/// not exceed `0xDFFF`.
unsafe fn tss_segment_raw(tss: *const TaskStateSegment, iomap_size: u16) -> Descriptor {
use self::DescriptorFlags as Flags;
use core::mem::size_of;

let ptr = tss as u64;

let mut low = Flags::PRESENT.bits();
// base
low.set_bits(16..40, ptr.get_bits(0..24));
low.set_bits(56..64, ptr.get_bits(24..32));
// limit (the `-1` in needed since the bound is inclusive)
low.set_bits(0..16, (size_of::<TaskStateSegment>() - 1) as u64);
// limit (the `-1` is needed since the bound is inclusive)
let iomap_limit = u64::from(unsafe { (*tss).iomap_base }) + u64::from(iomap_size);
low.set_bits(
0..16,
cmp::max(mem::size_of::<TaskStateSegment>() as u64, iomap_limit) - 1,
);
// type (0b1001 = available 64-bit tss)
low.set_bits(40..44, 0b1001);

Expand Down
67 changes: 65 additions & 2 deletions src/structures/tss.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
//! Provides a type for the task state segment structure.

use crate::VirtAddr;
use core::mem::size_of;
use core::{
fmt::{self, Display},
mem::size_of,
};

/// In 64-bit mode the TSS holds information that is not
/// directly related to the task-switch mechanism,
Expand All @@ -19,7 +22,8 @@ pub struct TaskStateSegment {
pub interrupt_stack_table: [VirtAddr; 7],
reserved_3: u64,
reserved_4: u16,
/// The 16-bit offset to the I/O permission bit map from the 64-bit TSS base.
/// The 16-bit offset to the I/O permission bit map from the 64-bit TSS base. It must not
/// exceed `0xDFFF`.
pub iomap_base: u16,
}

Expand Down Expand Up @@ -51,6 +55,65 @@ impl Default for TaskStateSegment {
}
}

/// The given IO permissions bitmap is invalid.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum InvalidIoMap {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be great to have a Display implementation for this struct as a quick way to print an error.

/// The IO permissions bitmap is before the TSS. It must be located after the TSS.
IoMapBeforeTss,
/// The IO permissions bitmap is too far from the TSS. It must be within `0xdfff` bytes of the
/// start of the TSS. Note that if the IO permissions bitmap is located before the TSS, then
/// `IoMapBeforeTss` will be returned instead.
TooFarFromTss {
/// The distance of the IO permissions bitmap from the beginning of the TSS.
distance: usize,
},
/// The final byte of the IO permissions bitmap was not 0xff
InvalidTerminatingByte {
/// The byte found at the end of the IO permissions bitmap.
byte: u8,
},
/// The IO permissions bitmap exceeds the maximum length (8193).
TooLong {
/// The length of the IO permissions bitmap.
len: usize,
},
/// The `iomap_base` in the `TaskStateSegment` struct was not what was expected.
InvalidBase {
/// The expected `iomap_base` to be set in the `TaskStateSegment` struct.
expected: u16,
/// The actual `iomap_base` set in the `TaskStateSegment` struct.
got: u16,
},
}

impl Display for InvalidIoMap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
InvalidIoMap::IoMapBeforeTss => {
write!(f, "the IO permissions bitmap is before the TSS")
}
InvalidIoMap::TooFarFromTss { distance } => write!(
f,
"the IO permissions bitmap is too far from the TSS (distance {distance})"
),
InvalidIoMap::InvalidTerminatingByte { byte } => write!(
f,
"The final byte of the IO permissions bitmap was not 0xff ({byte}"
),
InvalidIoMap::TooLong { len } => {
write!(
f,
"The IO permissions bitmap exceeds the maximum length ({len} > 8193)"
)
}
InvalidIoMap::InvalidBase { expected, got } => write!(
f,
"the `iomap_base` in the `TaskStateSegment` struct was not what was expected (expected {expected}, got {got})"
),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
Loading