gz / rust-x86

Rust library to use x86 (amd64) specific functionality and registers.
https://docs.rs/x86
MIT License
303 stars 63 forks source link

Invalid value for CR4 #156

Open not-matthias opened 8 months ago

not-matthias commented 8 months ago

While writing my hypervisor, I noticed crashes after 10 seconds. After a week debugging this issue, I realized that reading CR4 using this crate is the issue.

INFO: CR4 (manual): b52ef8
INFO: CR4 (x86_64): b52ef8
INFO: CR4 (x86):    352ef8

How to reproduce:

let mut value= 0;
unsafe { core::arch::asm!("mov {}, cr4", out(reg) value) };
log::info!("CR4 (manual): {:x}", value);

let value = x86_64::registers::control::Cr4::read_raw();
log::info!("CR4 (x86_64): {:x}",  value);

let value = unsafe { x86::controlregs::cr4() };
log::info!("CR4 (x86): {:x}", value);
gz commented 8 months ago

Hm sorry about that, the cr4 function uses from_bits_truncate from bitflags https://github.com/gz/rust-x86/blob/ae3306a372c82a92b2e0f7ca81c6664455625c7f/src/controlregs.rs#L152 to make sure the value only sets the bits that are known to the Cr4 bitflag struct.

This is probably not the best way (when hardware supports new flags that the library doesn't know about yet the bits are dropped).