1#[cfg(any(unix, feature = "haxm", feature = "whpx"))]
6use std::arch::x86_64::__cpuid;
7use std::arch::x86_64::_rdtsc;
8use std::arch::x86_64::CpuidResult;
9use std::collections::BTreeMap;
10use std::collections::HashSet;
11use std::sync::Arc;
12
13use anyhow::Context;
14use base::custom_serde::deserialize_seq_to_arr;
15use base::custom_serde::serialize_arr;
16use base::error;
17use base::warn;
18use base::Result;
19use bit_field::*;
20use libc::c_void;
21use serde::Deserialize;
22use serde::Serialize;
23use snapshot::AnySnapshot;
24use vm_memory::GuestAddress;
25
26use crate::Hypervisor;
27use crate::IrqRoute;
28use crate::IrqSource;
29use crate::IrqSourceChip;
30use crate::NestedMode;
31use crate::Vcpu;
32use crate::Vm;
33
34const MSR_F15H_PERF_CTL0: u32 = 0xc0010200;
35const MSR_F15H_PERF_CTL1: u32 = 0xc0010202;
36const MSR_F15H_PERF_CTL2: u32 = 0xc0010204;
37const MSR_F15H_PERF_CTL3: u32 = 0xc0010206;
38const MSR_F15H_PERF_CTL4: u32 = 0xc0010208;
39const MSR_F15H_PERF_CTL5: u32 = 0xc001020a;
40const MSR_F15H_PERF_CTR0: u32 = 0xc0010201;
41const MSR_F15H_PERF_CTR1: u32 = 0xc0010203;
42const MSR_F15H_PERF_CTR2: u32 = 0xc0010205;
43const MSR_F15H_PERF_CTR3: u32 = 0xc0010207;
44const MSR_F15H_PERF_CTR4: u32 = 0xc0010209;
45const MSR_F15H_PERF_CTR5: u32 = 0xc001020b;
46const MSR_IA32_PERF_CAPABILITIES: u32 = 0x00000345;
47
48pub trait HypervisorX86_64: Hypervisor {
50 fn get_supported_cpuid(&self) -> Result<CpuId>;
52
53 fn get_msr_index_list(&self) -> Result<Vec<u32>>;
55}
56
57pub trait VmX86_64: Vm {
59 fn get_hypervisor(&self) -> &dyn HypervisorX86_64;
61
62 fn create_vcpu(&self, id: usize) -> Result<Arc<dyn VcpuX86_64>>;
64
65 fn set_tss_addr(&self, addr: GuestAddress) -> Result<()>;
67
68 fn set_identity_map_addr(&self, addr: GuestAddress) -> Result<()>;
70
71 fn load_protected_vm_firmware(&self, fw_addr: GuestAddress, fw_max_size: u64) -> Result<()>;
75}
76
77pub trait VcpuX86_64: Vcpu {
79 fn set_interrupt_window_requested(&self, requested: bool);
82
83 fn ready_for_interrupt(&self) -> bool;
85
86 fn interrupt(&self, irq: u8) -> Result<()>;
98
99 fn inject_nmi(&self) -> Result<()>;
101
102 fn get_regs(&self) -> Result<Regs>;
104
105 fn set_regs(&self, regs: &Regs) -> Result<()>;
107
108 fn get_sregs(&self) -> Result<Sregs>;
110
111 fn set_sregs(&self, sregs: &Sregs) -> Result<()>;
113
114 fn get_fpu(&self) -> Result<Fpu>;
116
117 fn set_fpu(&self, fpu: &Fpu) -> Result<()>;
119
120 fn get_debugregs(&self) -> Result<DebugRegs>;
122
123 fn set_debugregs(&self, debugregs: &DebugRegs) -> Result<()>;
125
126 fn get_xcrs(&self) -> Result<BTreeMap<u32, u64>>;
128
129 fn set_xcr(&self, xcr: u32, value: u64) -> Result<()>;
131
132 fn get_xsave(&self) -> Result<Xsave>;
134
135 fn set_xsave(&self, xsave: &Xsave) -> Result<()>;
137
138 fn get_hypervisor_specific_state(&self) -> Result<AnySnapshot>;
142
143 fn set_hypervisor_specific_state(&self, data: AnySnapshot) -> Result<()>;
146
147 fn get_msr(&self, msr_index: u32) -> Result<u64>;
149
150 fn get_all_msrs(&self) -> Result<BTreeMap<u32, u64>>;
152
153 fn set_msr(&self, msr_index: u32, value: u64) -> Result<()>;
155
156 fn set_cpuid(&self, cpuid: &CpuId) -> Result<()>;
158
159 fn set_guest_debug(&self, addrs: &[GuestAddress], enable_singlestep: bool) -> Result<()>;
161
162 fn handle_cpuid(&self, entry: &CpuIdEntry) -> Result<()>;
166
167 fn get_tsc_offset(&self) -> Result<u64> {
171 let host_before_tsc = unsafe { _rdtsc() };
174
175 let guest_tsc = self.get_msr(crate::MSR_IA32_TSC)?;
177
178 let host_after_tsc = unsafe { _rdtsc() };
181
182 let host_tsc = ((host_before_tsc as u128 + host_after_tsc as u128) / 2) as u64;
184
185 Ok(guest_tsc.wrapping_sub(host_tsc))
186 }
187
188 fn set_tsc_offset(&self, offset: u64) -> Result<()> {
209 let host_tsc = unsafe { _rdtsc() };
211 self.set_tsc_value(host_tsc.wrapping_add(offset))
212 }
213
214 fn set_tsc_value(&self, value: u64) -> Result<()> {
221 self.set_msr(crate::MSR_IA32_TSC, value)
222 }
223
224 fn restore_timekeeping(&self, host_tsc_reference_moment: u64, tsc_offset: u64) -> Result<()>;
229
230 fn snapshot(&self) -> anyhow::Result<VcpuSnapshot> {
232 Ok(VcpuSnapshot {
233 vcpu_id: self.id(),
234 regs: self.get_regs()?,
235 sregs: self.get_sregs()?,
236 debug_regs: self.get_debugregs()?,
237 xcrs: self.get_xcrs()?,
238 msrs: self.get_all_msrs()?,
239 xsave: self.get_xsave()?,
240 hypervisor_data: self.get_hypervisor_specific_state()?,
241 tsc_offset: self.get_tsc_offset()?,
242 })
243 }
244
245 fn restore(
246 &self,
247 snapshot: &VcpuSnapshot,
248 host_tsc_reference_moment: u64,
249 ) -> anyhow::Result<()> {
250 let msr_allowlist = HashSet::from([
255 MSR_F15H_PERF_CTL0,
256 MSR_F15H_PERF_CTL1,
257 MSR_F15H_PERF_CTL2,
258 MSR_F15H_PERF_CTL3,
259 MSR_F15H_PERF_CTL4,
260 MSR_F15H_PERF_CTL5,
261 MSR_F15H_PERF_CTR0,
262 MSR_F15H_PERF_CTR1,
263 MSR_F15H_PERF_CTR2,
264 MSR_F15H_PERF_CTR3,
265 MSR_F15H_PERF_CTR4,
266 MSR_F15H_PERF_CTR5,
267 MSR_IA32_PERF_CAPABILITIES,
268 ]);
269 assert_eq!(snapshot.vcpu_id, self.id());
270 self.set_regs(&snapshot.regs)?;
271 self.set_sregs(&snapshot.sregs)?;
272 self.set_debugregs(&snapshot.debug_regs)?;
273 for (xcr_index, value) in &snapshot.xcrs {
274 self.set_xcr(*xcr_index, *value)?;
275 }
276
277 for (msr_index, value) in snapshot.msrs.iter() {
278 if self.get_msr(*msr_index) == Ok(*value) {
279 continue; }
281 if let Err(e) = self.set_msr(*msr_index, *value) {
282 if msr_allowlist.contains(msr_index) {
283 warn!(
284 "Failed to set MSR. MSR might not be supported in this kernel. Err: {}",
285 e
286 );
287 } else {
288 return Err(e).context(
289 "Failed to set MSR. MSR might not be supported by the CPU or by the kernel,
290 and was not allow-listed.",
291 );
292 }
293 };
294 }
295 self.set_xsave(&snapshot.xsave)?;
296 self.set_hypervisor_specific_state(snapshot.hypervisor_data.clone())?;
297 self.restore_timekeeping(host_tsc_reference_moment, snapshot.tsc_offset)?;
298 Ok(())
299 }
300}
301
302#[derive(Clone, Debug, Serialize, Deserialize)]
304pub struct VcpuSnapshot {
305 pub vcpu_id: usize,
306 regs: Regs,
307 sregs: Sregs,
308 debug_regs: DebugRegs,
309 xcrs: BTreeMap<u32, u64>,
310 msrs: BTreeMap<u32, u64>,
311 xsave: Xsave,
312 hypervisor_data: AnySnapshot,
313 tsc_offset: u64,
314}
315
316pub const MSR_IA32_TSC: u32 = 0x00000010;
318
319#[cfg(any(unix, feature = "haxm", feature = "whpx"))]
321pub(crate) fn host_phys_addr_bits() -> u8 {
322 let highest_ext_function = unsafe { __cpuid(0x80000000) };
324 if highest_ext_function.eax >= 0x80000008 {
325 let addr_size = unsafe { __cpuid(0x80000008) };
327 addr_size.eax as u8
329 } else {
330 36
331 }
332}
333
334#[derive(Clone, Default)]
336pub struct VcpuInitX86_64 {
337 pub regs: Regs,
339
340 pub sregs: Sregs,
342
343 pub fpu: Fpu,
345
346 pub msrs: BTreeMap<u32, u64>,
348}
349
350#[derive(Clone, Debug, PartialEq, Eq)]
352pub struct CpuConfigX86_64 {
353 pub force_calibrated_tsc_leaf: bool,
355
356 pub host_cpu_topology: bool,
358
359 pub enable_hwp: bool,
361
362 pub no_smt: bool,
364
365 pub itmt: bool,
367
368 pub hybrid_type: Option<CpuHybridType>,
370
371 pub nested: NestedMode,
373}
374
375impl CpuConfigX86_64 {
376 pub fn new(
377 force_calibrated_tsc_leaf: bool,
378 host_cpu_topology: bool,
379 enable_hwp: bool,
380 no_smt: bool,
381 itmt: bool,
382 hybrid_type: Option<CpuHybridType>,
383 nested: NestedMode,
384 ) -> Self {
385 CpuConfigX86_64 {
386 force_calibrated_tsc_leaf,
387 host_cpu_topology,
388 enable_hwp,
389 no_smt,
390 itmt,
391 hybrid_type,
392 nested,
393 }
394 }
395}
396
397#[repr(C)]
403#[derive(Clone, Copy, Debug, PartialEq, Eq)]
404pub struct CpuIdEntry {
405 pub function: u32,
406 pub index: u32,
407 pub flags: u32,
410 pub cpuid: CpuidResult,
411}
412
413pub struct CpuId {
415 pub cpu_id_entries: Vec<CpuIdEntry>,
416}
417
418impl CpuId {
419 pub fn new(initial_capacity: usize) -> Self {
421 CpuId {
422 cpu_id_entries: Vec::with_capacity(initial_capacity),
423 }
424 }
425}
426
427#[bitfield]
428#[derive(Clone, Copy, Debug, PartialEq, Eq)]
429pub enum DestinationMode {
430 Physical = 0,
431 Logical = 1,
432}
433
434#[bitfield]
435#[derive(Clone, Copy, Debug, PartialEq, Eq)]
436pub enum TriggerMode {
437 Edge = 0,
438 Level = 1,
439}
440
441#[bitfield]
442#[derive(Debug, Clone, Copy, PartialEq, Eq)]
443pub enum DeliveryMode {
444 Fixed = 0b000,
445 Lowest = 0b001,
446 SMI = 0b010, RemoteRead = 0b011, NMI = 0b100, Init = 0b101,
450 Startup = 0b110,
451 External = 0b111,
452}
453
454#[bitfield]
459#[derive(Clone, Copy, PartialEq, Eq)]
460pub struct MsiAddressMessage {
461 pub reserved: BitField2,
462 #[bits = 1]
463 pub destination_mode: DestinationMode,
464 pub redirection_hint: BitField1,
465 pub reserved_2: BitField8,
466 pub destination_id: BitField8,
467 pub always_0xfee: BitField12,
469}
470
471#[bitfield]
472#[derive(Clone, Copy, PartialEq, Eq)]
473pub struct MsiDataMessage {
474 pub vector: BitField8,
475 #[bits = 3]
476 pub delivery_mode: DeliveryMode,
477 pub reserved: BitField3,
478 #[bits = 1]
479 pub level: Level,
480 #[bits = 1]
481 pub trigger: TriggerMode,
482 pub reserved2: BitField16,
483}
484
485#[bitfield]
486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487pub enum DeliveryStatus {
488 Idle = 0,
489 Pending = 1,
490}
491
492#[bitfield]
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
495pub enum Level {
496 Deassert = 0,
497 Assert = 1,
498}
499
500#[bitfield]
502#[derive(Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
503pub struct IoapicRedirectionTableEntry {
504 vector: BitField8,
505 #[bits = 3]
506 delivery_mode: DeliveryMode,
507 #[bits = 1]
508 dest_mode: DestinationMode,
509 #[bits = 1]
510 delivery_status: DeliveryStatus,
511 polarity: BitField1,
512 remote_irr: bool,
513 #[bits = 1]
514 trigger_mode: TriggerMode,
515 interrupt_mask: bool, reserved: BitField39,
517 dest_id: BitField8,
518}
519
520pub const NUM_IOAPIC_PINS: usize = 24;
522
523#[repr(C)]
525#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
526pub struct IoapicState {
527 pub base_address: u64,
529 pub ioregsel: u8,
531 pub ioapicid: u32,
533 pub current_interrupt_level_bitmap: u32,
535 #[serde(
537 serialize_with = "serialize_arr",
538 deserialize_with = "deserialize_seq_to_arr"
539 )]
540 pub redirect_table: [IoapicRedirectionTableEntry; NUM_IOAPIC_PINS],
541}
542
543impl Default for IoapicState {
544 fn default() -> IoapicState {
545 unsafe { std::mem::zeroed() }
547 }
548}
549
550#[repr(C)]
551#[derive(Debug, Clone, Copy, PartialEq, Eq)]
552pub enum PicSelect {
553 Primary = 0,
554 Secondary = 1,
555}
556
557#[repr(C)]
558#[derive(enumn::N, Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
559pub enum PicInitState {
560 #[default]
561 Icw1 = 0,
562 Icw2 = 1,
563 Icw3 = 2,
564 Icw4 = 3,
565}
566
567impl From<u8> for PicInitState {
569 fn from(item: u8) -> Self {
570 PicInitState::n(item).unwrap_or_else(|| {
571 error!("Invalid PicInitState {}, setting to 0", item);
572 PicInitState::Icw1
573 })
574 }
575}
576
577#[repr(C)]
579#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
580pub struct PicState {
581 pub last_irr: u8,
583 pub irr: u8,
585 pub imr: u8,
587 pub isr: u8,
589 pub priority_add: u8,
591 pub irq_base: u8,
592 pub read_reg_select: bool,
593 pub poll: bool,
594 pub special_mask: bool,
595 pub init_state: PicInitState,
596 pub auto_eoi: bool,
597 pub rotate_on_auto_eoi: bool,
598 pub special_fully_nested_mode: bool,
599 pub use_4_byte_icw: bool,
602 pub elcr: u8,
606 pub elcr_mask: u8,
607}
608
609#[repr(C)]
613#[derive(Clone, Copy, Serialize, Deserialize)]
614pub struct LapicState {
615 #[serde(
616 serialize_with = "serialize_arr",
617 deserialize_with = "deserialize_seq_to_arr"
618 )]
619 pub regs: [LapicRegister; 64],
620}
621
622pub type LapicRegister = u32;
623
624impl std::fmt::Debug for LapicState {
626 fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
627 self.regs[..].fmt(formatter)
628 }
629}
630
631impl PartialEq for LapicState {
633 fn eq(&self, other: &LapicState) -> bool {
634 self.regs[..] == other.regs[..]
635 }
636}
637
638impl Eq for LapicState {}
640
641#[repr(C)]
644#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
645pub struct PitState {
646 pub channels: [PitChannelState; 3],
647 pub flags: u32,
649}
650
651#[repr(C)]
656#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
657pub enum PitRWMode {
658 None = 0,
660 Least = 1,
662 Most = 2,
664 Both = 3,
667}
668
669impl From<u8> for PitRWMode {
671 fn from(item: u8) -> Self {
672 PitRWMode::n(item).unwrap_or_else(|| {
673 error!("Invalid PitRWMode value {}, setting to 0", item);
674 PitRWMode::None
675 })
676 }
677}
678
679#[repr(C)]
683#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
684pub enum PitRWState {
685 None = 0,
687 LSB = 1,
689 MSB = 2,
691 Word0 = 3,
694 Word1 = 4,
698}
699
700impl From<u8> for PitRWState {
702 fn from(item: u8) -> Self {
703 PitRWState::n(item).unwrap_or_else(|| {
704 error!("Invalid PitRWState value {}, setting to 0", item);
705 PitRWState::None
706 })
707 }
708}
709
710#[repr(C)]
712#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
713pub struct PitChannelState {
714 pub count: u32,
716 pub latched_count: u16,
718 pub count_latched: PitRWState,
720 pub status_latched: bool,
722 pub status: u8,
726 pub read_state: PitRWState,
728 pub write_state: PitRWState,
730 pub reload_value: u16,
733 pub rw_mode: PitRWMode,
735 pub mode: u8,
737 pub bcd: bool,
739 pub gate: bool,
741 pub count_load_time: u64,
743}
744
745impl IrqRoute {
747 pub fn ioapic_irq_route(irq_num: u32) -> IrqRoute {
748 IrqRoute {
749 gsi: irq_num,
750 source: IrqSource::Irqchip {
751 chip: IrqSourceChip::Ioapic,
752 pin: irq_num,
753 },
754 }
755 }
756
757 pub fn pic_irq_route(id: IrqSourceChip, irq_num: u32) -> IrqRoute {
758 IrqRoute {
759 gsi: irq_num,
760 source: IrqSource::Irqchip {
761 chip: id,
762 pin: irq_num % 8,
763 },
764 }
765 }
766}
767
768#[repr(C)]
770#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
771pub struct Regs {
772 pub rax: u64,
773 pub rbx: u64,
774 pub rcx: u64,
775 pub rdx: u64,
776 pub rsi: u64,
777 pub rdi: u64,
778 pub rsp: u64,
779 pub rbp: u64,
780 pub r8: u64,
781 pub r9: u64,
782 pub r10: u64,
783 pub r11: u64,
784 pub r12: u64,
785 pub r13: u64,
786 pub r14: u64,
787 pub r15: u64,
788 pub rip: u64,
789 pub rflags: u64,
790}
791
792impl Default for Regs {
793 fn default() -> Self {
794 Regs {
795 rax: 0,
796 rbx: 0,
797 rcx: 0,
798 rdx: 0,
799 rsi: 0,
800 rdi: 0,
801 rsp: 0,
802 rbp: 0,
803 r8: 0,
804 r9: 0,
805 r10: 0,
806 r11: 0,
807 r12: 0,
808 r13: 0,
809 r14: 0,
810 r15: 0,
811 rip: 0xfff0, rflags: 0x2, }
814 }
815}
816
817#[repr(C)]
819#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
820pub struct Segment {
821 pub base: u64,
822 pub limit_bytes: u32,
824 pub selector: u16,
825 pub type_: u8,
826 pub present: u8,
827 pub dpl: u8,
828 pub db: u8,
829 pub s: u8,
830 pub l: u8,
831 pub g: u8,
832 pub avl: u8,
833}
834
835#[repr(C)]
837#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
838pub struct DescriptorTable {
839 pub base: u64,
840 pub limit: u16,
841}
842
843#[repr(C)]
845#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
846pub struct Sregs {
847 pub cs: Segment,
848 pub ds: Segment,
849 pub es: Segment,
850 pub fs: Segment,
851 pub gs: Segment,
852 pub ss: Segment,
853 pub tr: Segment,
854 pub ldt: Segment,
855 pub gdt: DescriptorTable,
856 pub idt: DescriptorTable,
857 pub cr0: u64,
858 pub cr2: u64,
859 pub cr3: u64,
860 pub cr4: u64,
861 pub cr8: u64,
862 pub efer: u64,
863}
864
865impl Default for Sregs {
866 fn default() -> Self {
867 const SEG_TYPE_DATA: u8 = 0b0000;
869 const SEG_TYPE_DATA_WRITABLE: u8 = 0b0010;
870
871 const SEG_TYPE_CODE: u8 = 0b1000;
872 const SEG_TYPE_CODE_READABLE: u8 = 0b0010;
873
874 const SEG_TYPE_ACCESSED: u8 = 0b0001;
875
876 const SEG_S_SYSTEM: u8 = 0; const SEG_S_CODE_OR_DATA: u8 = 1; let code_seg = Segment {
882 base: 0xffff0000,
883 limit_bytes: 0xffff,
884 selector: 0xf000,
885 type_: SEG_TYPE_CODE | SEG_TYPE_CODE_READABLE | SEG_TYPE_ACCESSED, present: 1,
887 s: SEG_S_CODE_OR_DATA,
888 ..Default::default()
889 };
890
891 let data_seg = Segment {
893 base: 0,
894 limit_bytes: 0xffff,
895 selector: 0,
896 type_: SEG_TYPE_DATA | SEG_TYPE_DATA_WRITABLE | SEG_TYPE_ACCESSED, present: 1,
898 s: SEG_S_CODE_OR_DATA,
899 ..Default::default()
900 };
901
902 let task_seg = Segment {
904 base: 0,
905 limit_bytes: 0xffff,
906 selector: 0,
907 type_: SEG_TYPE_CODE | SEG_TYPE_CODE_READABLE | SEG_TYPE_ACCESSED, present: 1,
909 s: SEG_S_SYSTEM,
910 ..Default::default()
911 };
912
913 let ldt = Segment {
915 base: 0,
916 limit_bytes: 0xffff,
917 selector: 0,
918 type_: SEG_TYPE_DATA | SEG_TYPE_DATA_WRITABLE, present: 1,
920 s: SEG_S_SYSTEM,
921 ..Default::default()
922 };
923
924 let gdt = DescriptorTable {
926 base: 0,
927 limit: 0xffff,
928 };
929
930 let idt = DescriptorTable {
932 base: 0,
933 limit: 0xffff,
934 };
935
936 let cr0 = (1 << 4) | (1 << 30); Sregs {
940 cs: code_seg,
941 ds: data_seg,
942 es: data_seg,
943 fs: data_seg,
944 gs: data_seg,
945 ss: data_seg,
946 tr: task_seg,
947 ldt,
948 gdt,
949 idt,
950 cr0,
951 cr2: 0,
952 cr3: 0,
953 cr4: 0,
954 cr8: 0,
955 efer: 0,
956 }
957 }
958}
959
960#[repr(C)]
962#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
963pub struct FpuReg {
964 pub significand: u64,
966
967 pub sign_exp: u16,
969}
970
971impl FpuReg {
972 pub fn from_16byte_arrays(byte_arrays: &[[u8; 16]; 8]) -> [FpuReg; 8] {
977 let mut regs = [FpuReg::default(); 8];
978 for (dst, src) in regs.iter_mut().zip(byte_arrays.iter()) {
979 let tbyte: [u8; 10] = src[0..10].try_into().unwrap();
980 *dst = FpuReg::from(tbyte);
981 }
982 regs
983 }
984
985 pub fn to_16byte_arrays(regs: &[FpuReg; 8]) -> [[u8; 16]; 8] {
987 let mut byte_arrays = [[0u8; 16]; 8];
988 for (dst, src) in byte_arrays.iter_mut().zip(regs.iter()) {
989 *dst = (*src).into();
990 }
991 byte_arrays
992 }
993}
994
995impl From<[u8; 10]> for FpuReg {
996 fn from(value: [u8; 10]) -> FpuReg {
998 let significand_bytes = value[0..8].try_into().unwrap();
1001 let significand = u64::from_le_bytes(significand_bytes);
1002 let sign_exp_bytes = value[8..10].try_into().unwrap();
1003 let sign_exp = u16::from_le_bytes(sign_exp_bytes);
1004 FpuReg {
1005 significand,
1006 sign_exp,
1007 }
1008 }
1009}
1010
1011impl From<FpuReg> for [u8; 10] {
1012 fn from(value: FpuReg) -> [u8; 10] {
1014 let mut bytes = [0u8; 10];
1015 bytes[0..8].copy_from_slice(&value.significand.to_le_bytes());
1016 bytes[8..10].copy_from_slice(&value.sign_exp.to_le_bytes());
1017 bytes
1018 }
1019}
1020
1021impl From<FpuReg> for [u8; 16] {
1022 fn from(value: FpuReg) -> [u8; 16] {
1025 let mut bytes = [0u8; 16];
1026 bytes[0..8].copy_from_slice(&value.significand.to_le_bytes());
1027 bytes[8..10].copy_from_slice(&value.sign_exp.to_le_bytes());
1028 bytes
1029 }
1030}
1031
1032#[repr(C)]
1034#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
1035pub struct Fpu {
1036 pub fpr: [FpuReg; 8],
1037 pub fcw: u16,
1038 pub fsw: u16,
1039 pub ftwx: u8,
1040 pub last_opcode: u16,
1041 pub last_ip: u64,
1042 pub last_dp: u64,
1043 pub xmm: [[u8; 16usize]; 16usize],
1044 pub mxcsr: u32,
1045}
1046
1047impl Default for Fpu {
1048 fn default() -> Self {
1049 Fpu {
1050 fpr: Default::default(),
1051 fcw: 0x37f, fsw: 0,
1053 ftwx: 0,
1054 last_opcode: 0,
1055 last_ip: 0,
1056 last_dp: 0,
1057 xmm: Default::default(),
1058 mxcsr: 0x1f80, }
1060 }
1061}
1062
1063#[repr(C)]
1065#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
1066pub struct DebugRegs {
1067 pub db: [u64; 4usize],
1068 pub dr6: u64,
1069 pub dr7: u64,
1070}
1071
1072#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1074pub enum CpuHybridType {
1075 Atom,
1077 Core,
1079}
1080
1081#[derive(Clone, Debug, Serialize, Deserialize)]
1084pub struct Xsave {
1085 data: Vec<u32>,
1086
1087 len: usize,
1090}
1091
1092impl Xsave {
1093 pub fn new(len: usize) -> Self {
1098 Xsave {
1099 data: vec![0; len.div_ceil(4)],
1100 len,
1101 }
1102 }
1103
1104 pub fn as_ptr(&self) -> *const c_void {
1105 self.data.as_ptr() as *const c_void
1106 }
1107
1108 pub fn as_mut_ptr(&mut self) -> *mut c_void {
1109 self.data.as_mut_ptr() as *mut c_void
1110 }
1111
1112 pub fn len(&self) -> usize {
1114 self.len
1115 }
1116
1117 pub fn is_empty(&self) -> bool {
1119 self.len() == 0
1120 }
1121}