repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -677,32 +930,65 @@ impl PageTable { static INIT_PGTABLE: SpinLock<PageTableRef> = SpinLock::new(PageTableRef::unset()); +/// Sets the initial page table unless it is already set. +/// +/// # Parameters +/// - `pgtable`: The page table reference to set as the initial page table. +/// +/// # Panics +/// Panics if the initial page table is already set. +/// pub fn set_init_pgtable(pgtable: PageTableRef) { let mut init_pgtable = INIT_PGTABLE.lock(); assert!(!init_pgtable.is_set()); *init_pgtable = pgtable; } +/// Acquires a lock and returns a guard for the initial page table, which +/// is locked for the duration of the guard's scope. +/// +/// # Returns +/// A `LockGuard` for the initial page table. +/// pub fn get_init_pgtable_locked<'a>() -> LockGuard<'a, PageTableRef> { INIT_PGTABLE.lock() } +/// A reference wrapper for a [`PageTable`]. #[derive(Debug)] pub struct PageTableRef { pgtable_ptr: *mut PageTable, } impl PageTableRef { + /// Creates a new [`PageTableRef`]. + /// + /// # Parameters + /// - `pgtable_ptr`: A raw pointer to a [`PageTable`]. + /// + /// # Returns + /// A new [`PageTableRef`]. + /// pub fn new(pgtable_ptr: *mut PageTable) -> PageTableRef { Self { pgtable_ptr } } + /// Creates an unset [`PageTableRef`], i.e. a NULL pointer. + /// + /// # Returns + /// An unset [`PageTableRef`]. + /// pub const fn unset() -> PageTableRef {
The function signature here is pretty self-explanatory, I'd remove the `# Returns`.
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -677,32 +930,65 @@ impl PageTable { static INIT_PGTABLE: SpinLock<PageTableRef> = SpinLock::new(PageTableRef::unset()); +/// Sets the initial page table unless it is already set. +/// +/// # Parameters +/// - `pgtable`: The page table reference to set as the initial page table. +/// +/// # Panics +/// Panics if the initial page table is already set. +/// pub fn set_init_pgtable(pgtable: PageTableRef) { let mut init_pgtable = INIT_PGTABLE.lock(); assert!(!init_pgtable.is_set()); *init_pgtable = pgtable; } +/// Acquires a lock and returns a guard for the initial page table, which +/// is locked for the duration of the guard's scope. +/// +/// # Returns +/// A `LockGuard` for the initial page table. +/// pub fn get_init_pgtable_locked<'a>() -> LockGuard<'a, PageTableRef> { INIT_PGTABLE.lock() } +/// A reference wrapper for a [`PageTable`]. #[derive(Debug)] pub struct PageTableRef { pgtable_ptr: *mut PageTable, } impl PageTableRef { + /// Creates a new [`PageTableRef`]. + /// + /// # Parameters + /// - `pgtable_ptr`: A raw pointer to a [`PageTable`]. + /// + /// # Returns + /// A new [`PageTableRef`]. + ///
The function signature here is pretty self-explanatory. ```suggestion /// Creates a new [`PageTableRef`] from a raw pointer to a [`PageTable`]. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -677,32 +930,65 @@ impl PageTable { static INIT_PGTABLE: SpinLock<PageTableRef> = SpinLock::new(PageTableRef::unset()); +/// Sets the initial page table unless it is already set. +/// +/// # Parameters +/// - `pgtable`: The page table reference to set as the initial page table. +/// +/// # Panics +/// Panics if the initial page table is already set. +/// pub fn set_init_pgtable(pgtable: PageTableRef) { let mut init_pgtable = INIT_PGTABLE.lock(); assert!(!init_pgtable.is_set()); *init_pgtable = pgtable; } +/// Acquires a lock and returns a guard for the initial page table, which +/// is locked for the duration of the guard's scope. +/// +/// # Returns +/// A `LockGuard` for the initial page table. +///
The text already explains the return, so I'd remove the `# Returns` section.
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -663,6 +911,11 @@ impl PageTable { } } + /// Populates a part of the page table with the specified attributes. + /// + /// # Parameters + /// - `part`: The part of the page table to populate. + ///
```suggestion /// Populates this page table with the contents of the given subtree in `part`. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -640,6 +883,11 @@ impl PageTable { Ok(()) } + /// Unmaps a memory region. + /// + /// # Parameters + /// - `vregion`: The virtual memory region to unmap. + ///
```suggestion /// Unmaps the virtual memory region `vregion`. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -605,12 +833,27 @@ impl PageTable { Ok(()) } + /// Unmaps a region of memory using 2MB pages. + /// + /// # Parameters + /// - `vregion`: The virtual memory region to unmap. + ///
```suggestion /// Unmaps a region `vregion` of 2MB pages. The region must be /// 2MB-aligned and correspond to a set of huge mappings. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -468,6 +607,17 @@ impl PageTable { } } + /// Sets the encryption state for a 4KB page. + /// + /// # Parameters + /// - `vaddr`: The virtual address of the page. + /// + /// # Returns + /// A result indicating success or an error code. + /// + /// # Errors + /// Returns `SvsmError` if the operation fails. + ///
```suggestion /// Attempts to set the C-bit for the given page at `vaddr`. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -16,6 +16,7 @@ use crate::types::{PAGE_SIZE, PAGE_SIZE_2M}; use crate::utils::MemoryRegion; +/// Guard for a per-CPU page mapping to ensure adequate cleanup if drop.
"if drop" sounds a bit strange. Should be "when dropped": ```suggestion /// Guard used to unmap a per-CPU mapping when dropped. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -24,6 +25,19 @@ pub struct PerCPUPageMappingGuard { } impl PerCPUPageMappingGuard { + /// Creates a new [`PerCPUPageMappingGuard`] for the specified physical + /// address range and alignment. + /// + /// # Arguments + /// + /// * `paddr_start` - The starting physical address of the range. + /// * `paddr_end` - The ending physical address of the range. + /// * `alignment` - The desired alignment for the mapping. + /// + /// # Returns + /// + /// A `Result` containing the [`PerCPUPageMappingGuard`] if successful, + /// or an `SvsmError` if an error occurs.
Missing `# Panics` section.
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -66,10 +80,22 @@ impl PerCPUPageMappingGuard { }) } + /// Creates a new [`PerCPUPageMappingGuard`] for a 4KB page at the + /// specified physical address. + /// + /// # Arguments + /// + /// * `paddr` - The physical address for the 4KB page. + /// + /// # Returns + /// + /// A `Result` containing the [`PerCPUPageMappingGuard`] if successful, + /// or an `SvsmError` if an error occurs.
```suggestion /// Creates a new [`PerCPUPageMappingGuard`] for a 4KB page at the /// specified physical address, or an `SvsmError` if an error occurs. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -66,10 +80,22 @@ impl PerCPUPageMappingGuard { }) } + /// Creates a new [`PerCPUPageMappingGuard`] for a 4KB page at the + /// specified physical address. + /// + /// # Arguments + /// + /// * `paddr` - The physical address for the 4KB page. + /// + /// # Returns + /// + /// A `Result` containing the [`PerCPUPageMappingGuard`] if successful, + /// or an `SvsmError` if an error occurs. pub fn create_4k(paddr: PhysAddr) -> Result<Self, SvsmError> { Self::create(paddr, paddr + PAGE_SIZE, 0) } + /// Returns the virtual address associated with the guard.
This sounds like it's the address of the guard object. ```suggestion /// Returns the virtual address for the new mapping. ```
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -8,6 +8,9 @@ use crate::types::{PAGE_SHIFT, PAGE_SIZE}; use core::fmt; use core::ops; +extern crate alloc; +use alloc::slice;
Should probably use `core::slice` instead.
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -251,6 +254,25 @@ impl VirtAddr { pub const fn const_add(&self, offset: usize) -> Self { VirtAddr::new(self.0 + offset) } + + /// Converts the `VirtAddr` to a slice of a given type + /// + /// # Arguments: + /// + /// * `len` - Number of elements of type `T` in the slice + /// + /// # Returns + /// + /// Slice with `len` elements of type `T` + /// + /// # Safety + /// + /// The caller must assure that the virtual mapping at `VirtAddr` covers + /// the whole slice and that the data at the virtual address contains valid + /// instances of type `T`.
And that alignment is met. See the requirements in `core::slice::from_raw_parts`
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -213,6 +213,10 @@ impl VirtAddr { Self(sign_extend(addr)) } + pub const fn to_idx(&self) -> usize {
The method name does not explain much, I would make it more verbose or at least add some documentation. Could we also make it generic over the page table level, like `PageTable::index()`?
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -917,6 +917,19 @@ impl PageRef { pub fn phys_addr(&self) -> PhysAddr { self.phys_addr } + + pub fn try_copy_page(&self) -> Result<Self, SvsmError> { + let virt_addr = allocate_file_page()?; + unsafe { + let src = self.virt_addr.as_ptr::<[u8; PAGE_SIZE]>(); + let dst = virt_addr.as_mut_ptr::<[u8; PAGE_SIZE]>(); + dst.write(*src);
`copy_to_nonoverlapping()` seems more appropriate and cannot create an intermediate copy in debug builds.
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -153,18 +197,51 @@ extern "C" fn ex_handler_hypervisor_injection(_ctx: &mut X86ExceptionContext) { // VMM Communication handler #[no_mangle] -extern "C" fn ex_handler_vmm_communication(ctx: &mut X86ExceptionContext) { - handle_vc_exception(ctx).expect("Failed to handle #VC"); +extern "C" fn ex_handler_vmm_communication(ctxt: &mut X86ExceptionContext) { + let rip = ctxt.frame.rip; + let err = ctxt.error_code; + + if handle_vc_exception(ctxt).is_err() {
We could also retrieve the specific error from `handle_vc_exception()` and display it.
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -969,11 +970,30 @@ impl PageTablePart { /// A new instance of PageTablePart pub fn new(start: VirtAddr) -> Self { PageTablePart { - raw: Box::<RawPageTablePart>::default(), + raw: None, idx: PageTable::index::<3>(start), } } + pub fn alloc(&mut self) { + self.get_or_init_mut(); + } + + fn get_or_init_mut(&mut self) -> &mut RawPageTablePart { + if self.raw.is_none() { + self.raw = Some(Box::<RawPageTablePart>::default()); + } + self.raw.as_mut().unwrap() + }
```suggestion fn get_or_init_mut(&mut self) -> &mut RawPageTablePart { self.raw.get_or_insert_with(|| Box::default()) } ```
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -153,18 +197,51 @@ extern "C" fn ex_handler_hypervisor_injection(_ctx: &mut X86ExceptionContext) { // VMM Communication handler #[no_mangle] -extern "C" fn ex_handler_vmm_communication(ctx: &mut X86ExceptionContext) { - handle_vc_exception(ctx).expect("Failed to handle #VC"); +extern "C" fn ex_handler_vmm_communication(ctxt: &mut X86ExceptionContext) { + let rip = ctxt.frame.rip; + let err = ctxt.error_code; + + if handle_vc_exception(ctxt).is_err() { + if user_mode(ctxt) { + log::error!("Failed to handle #VC from user-mode at RIP {:#018x} error code: {:#018x} - Terminating task", rip, err); + terminate(); + } else { + panic!("Failed to handle #VC from user-mode at RIP {:#018x} error code: {:#018x} - Terminating task", rip, err); + } + } +} + +// System Call SoftIRQ handler +#[no_mangle] +extern "C" fn ex_handler_system_call(ctxt: &mut X86ExceptionContext) { + let input = TryInto::<u64>::try_into(ctxt.regs.rax); + + if !user_mode(ctxt) { + panic!("Syscall handler called from kernel mode!"); + } + + if input.is_err() { + ctxt.regs.rax = !0; + return; + } + + ctxt.regs.rax = match input.unwrap() { + SYS_HELLO => sys_hello(), + SYS_EXIT => sys_exit(), + _ => !0, + };
This should get rid of an unnecessary unwrap: ```suggestion if !user_mode(ctxt) { panic!("Syscall handler called from kernel mode!"); } let Ok(input) = u64::try_from(ctx.regs.rax) else { ctx.regs.rax = !0; return; }; ctx.regs.rax = match input { SYS_HELLO => sys_hello(), SYS_EXIT => sys_exit(), _ => !0, }; ```
svsm
github_2023
others
314
coconut-svsm
cxdong
@@ -136,3 +145,6 @@ default_entry_no_ist name=vc handler=vmm_communication error_code=1 vector=29 // #SX Security Exception (Vector 30) default_entry_no_ist name=sx handler=panic error_code=1 vector=30 + +// INT 0x80 system call handler +default_entry_no_ist name=int80 handler=system_call error_code=0 vector=0x80
The TDX and SEV have disabled int80 in linux kernel with commits around this ( https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/arch/x86/coco/tdx?h=v6.7&id=b82a8dbd3d2f4563156f7150c6f2ecab6e960b30), which looks like to prevent with the Ahoi (https://ahoi-attacks.github.io/) attacks. It appears that enabling SEV's interrupt restriction can prevent host to inject 0x80 to SVSM to mitigate the Ahoi attack. But still would like to know if there is any consideration of not using SYSCALL/SYSRET instruction?
svsm
github_2023
others
320
coconut-svsm
00xc
@@ -44,12 +44,23 @@ struct PValidateRequest { resv: u32, } -fn core_create_vcpu_error_restore(vaddr: VirtAddr) { - if let Err(err) = rmp_clear_guest_vmsa(vaddr) { - log::error!("Failed to restore page permissions: {:#?}", err); +fn core_create_vcpu_error_restore(paddr: Option<PhysAddr>, vaddr: Option<VirtAddr>) { + for v in vaddr.iter() { + if let Err(err) = rmp_clear_guest_vmsa(*v) { + log::error!("Failed to restore page permissions: {:#?}", err); + } }
Why not `if let Some(v) = vaddr { ... }`? Seems more clear. Same thing below with `paddr`.
svsm
github_2023
others
320
coconut-svsm
00xc
@@ -44,12 +44,23 @@ struct PValidateRequest { resv: u32, } -fn core_create_vcpu_error_restore(vaddr: VirtAddr) { - if let Err(err) = rmp_clear_guest_vmsa(vaddr) { - log::error!("Failed to restore page permissions: {:#?}", err); +fn core_create_vcpu_error_restore(paddr: Option<PhysAddr>, vaddr: Option<VirtAddr>) { + for v in vaddr.iter() { + if let Err(err) = rmp_clear_guest_vmsa(*v) { + log::error!("Failed to restore page permissions: {:#?}", err); + } } + // In case mappings have been changed flush_tlb_global_sync(); + + for p in paddr.iter() { + // SAFETY: this can only fail if another CPU unregisters our + // unused VMSA. This is not possible, since unregistration of + // an unused VMSA only happens in the error path for this function, + // with a physical address that only this CPU managed to register.
This comment should be updated. This is only called in the error path for `core_create_vcpu()`.
svsm
github_2023
others
320
coconut-svsm
00xc
@@ -86,6 +86,11 @@ fn core_create_vcpu(params: &RequestParams) -> Result<(), SvsmReqError> { return Err(SvsmReqError::invalid_address()); } + // Check whether VMSA page and CAA region overlap + if overlap(paddr, paddr + PAGE_SIZE - 1, pcaa, pcaa + 7) {
Maybe this is clearer: ```suggestion if overlap(paddr, paddr + PAGE_SIZE - 1, pcaa, pcaa + size_of::<SvsmCaa> - 1) { ```
svsm
github_2023
others
320
coconut-svsm
roy-hopkins
@@ -293,6 +293,9 @@ fn core_pvalidate_one(entry: u64, flush: &mut bool) -> Result<(), SvsmReqError> // down the #NPF loops. // if writable_phys_addr(paddr) { + // FIXME: This checks leaves a window open for the attack described
"This check leaves" (remove the s).
svsm
github_2023
others
326
coconut-svsm
p4zuu
@@ -1653,10 +1631,9 @@ pub fn layout_from_size(size: usize) -> Layout { pub fn layout_from_ptr(ptr: *mut u8) -> Option<Layout> { let va = VirtAddr::from(ptr); - let Ok(pfn) = ROOT_MEM.lock().get_pfn(va) else { - return None; - }; - let info = ROOT_MEM.lock().read_page_info(pfn);
Double-fetch bug indeed, nice catch
svsm
github_2023
others
323
coconut-svsm
00xc
@@ -84,6 +87,15 @@ test-in-svsm: utils/cbit bin/coconut-test-qemu.igvm doc: cargo doc -p svsm --open --all-features --document-private-items +docsite: + mkdir -p ${DOC_SITE} + cargo doc -p svsm --all-features --document-private-items --no-deps
For the public docs I think we could omit `--document-private-items`? Or maybe leave it as an option.
svsm
github_2023
others
312
coconut-svsm
joergroedel
@@ -255,75 +324,51 @@ pub struct PerCpu { /// Task list that has been assigned for scheduling on this CPU runqueue: RWLock<RunQueue>, - /// Stack boundaries of the currently running task. This is stored in - /// [PerCpu] because it needs lockless read access. - pub current_stack: MemoryRegion<VirtAddr>, - /// WaitQueue for request processing request_waitqueue: WaitQueue, - - // The borrow count tuple holds (total, mutable) borrow counts. - #[cfg(debug_assertions)] - borrow_count: (usize, usize), } impl PerCpu { - fn new(apic_id: u32, shared: &'static PerCpuShared) -> Self { + fn new(apic_id: u32, cpu_unsafe: *const PerCpuUnsafe) -> Self { PerCpu { - shared, - online: AtomicBool::new(false), + cpu_unsafe, apic_id, pgtbl: SpinLock::<PageTableRef>::new(PageTableRef::unset()), - ghcb: ptr::null_mut(), - init_stack: None, - ist: IstStacks::new(), tss: X86Tss::new(), svsm_vmsa: None, reset_ip: 0xffff_fff0u64, vm_range: VMR::new(SVSM_PERCPU_BASE, SVSM_PERCPU_END, PTEntryFlags::GLOBAL), vrange_4k: VirtualRange::new(), vrange_2m: VirtualRange::new(), runqueue: RWLock::new(RunQueue::new()), - current_stack: MemoryRegion::new(VirtAddr::null(), 0), request_waitqueue: WaitQueue::new(), - - // Every new CPU is constructed with via a raw pointer so no - // borrow is active at the time of construction. - #[cfg(debug_assertions)] - borrow_count: (0, 0), } } - pub fn alloc(apic_id: u32) -> Result<*mut PerCpu, SvsmError> { + pub fn alloc(apic_id: u32) -> Result<RefMut<'static, PerCpu>, SvsmError> { let vaddr = allocate_zeroed_page()?; unsafe { // Within each CPU state page, the first portion is the private // mutable state and remainder is the shared state. - let private_size = size_of::<PerCpu>(); - let shared_size = size_of::<PerCpuShared>(); - if private_size + shared_size > PAGE_SIZE { + if size_of::<PerCpuUnsafe>() > PAGE_SIZE { panic!("Per-CPU data is larger than one page!"); } - let shared_vaddr = vaddr + private_size; - let percpu_shared = shared_vaddr.as_mut_ptr::<PerCpuShared>(); - (*percpu_shared) = PerCpuShared::new(); - - let percpu = vaddr.as_mut_ptr::<PerCpu>(); - - (*percpu) = PerCpu::new(apic_id, &*percpu_shared); + let percpu_unsafe = vaddr.as_mut_ptr::<PerCpuUnsafe>(); + (*percpu_unsafe) = PerCpuUnsafe::new(apic_id, percpu_unsafe);
This creates a confusing imbalance. `alloc()` is an associated method of `struct PerCpu`, but does allocate a struct `PerCpuUnsafe` and returns an inner member of it. So while at it, the allocation of `PerCpuUnsafe` data structures should be moved into a generic function.
svsm
github_2023
others
135
coconut-svsm
Freax13
@@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (C) 2023 IBM +// +// Authors: Claudio Carvalho <cclaudio@linux.ibm.com> + +/// This crate implements the C wrappers required to build the libvtpm.a dependencies +use crate::console::_print; +use crate::mm::alloc::{ + layout_from_ptr, layout_from_size, mem_allocate, mem_deallocate, mem_reallocate, +}; +use crate::sev::msr_protocol::request_termination_msr; + +use core::alloc::Layout; +use core::ffi::{c_char, c_int, c_ulong, c_void}; +use core::ptr; +use core::slice::from_raw_parts; +use core::str::from_utf8; + +#[no_mangle] +pub extern "C" fn malloc(size: c_ulong) -> *mut c_void { + let layout: Layout = layout_from_size(size as usize); + mem_allocate(layout) as *mut c_void +} + +#[no_mangle] +pub extern "C" fn calloc(items: c_ulong, size: c_ulong) -> *mut c_void { + if let Some(new_size) = items.checked_mul(size as u64) { + return malloc(new_size); + } + ptr::null_mut() +} + +#[no_mangle] +pub extern "C" fn realloc(p: *mut c_void, size: c_ulong) -> *mut c_void {
This function, `free` and `serial_out` should be marked as unsafe.
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,140 @@ +LIBCRT_DIR = $(CURDIR)/libcrt +OPENSSL_DIR = $(CURDIR)/openssl +MSTPM_DIR = $(CURDIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a + +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A = Platform/src/libplatform.a +LIBPLATFORM = $(MSTPM_DIR)/$(LIBPLATFORM_A) + +OPENSSL_MAKEFILE = $(OPENSSL_DIR)/Makefile +MSTPM_MAKEFILE = $(MSTPM_DIR)/Makefile + +LIBS = $(LIBCRT) $(LIBCRYPTO) $(LIBTPM) $(LIBPLATFORM) + +all: libvtpm.a bindings.rs + +libvtpm.a: $(LIBS) + rm -f $@ + ar rcsTPD $@ $^ + +# libcrt +$(LIBCRT): + $(MAKE) -C $(LIBCRT_DIR) + +# openssl +$(LIBCRYPTO): $(OPENSSL_MAKEFILE) $(LIBCRT) + $(MAKE) -C $(OPENSSL_DIR) -j$$(nproc) + +$(OPENSSL_MAKEFILE): + (cd $(OPENSSL_DIR) && git checkout OpenSSL_1_1_1q && \ + ./Configure \ + --config=$(CURDIR)/openssl_svsm.conf \ + SVSM \ + no-afalgeng \ + no-async \ + no-autoerrinit \ + no-autoload-config \ + no-bf \ + no-blake2 \ + no-capieng \ + no-cast \ + no-chacha \ + no-cms \ + no-ct \ + no-deprecated \ + no-des \ + no-dgram \ + no-dsa \ + no-dynamic-engine \ + no-ec2m \ + no-engine \ + no-err \ + no-filenames \ + no-gost \ + no-hw \ + no-idea \ + no-md4 \ + no-mdc2 \ + no-pic \ + no-ocb \ + no-poly1305 \ + no-posix-io \ + no-rc2 \ + no-rc4 \ + no-rfc3779 \ + no-rmd160 \ + no-scrypt \ + no-seed \ + no-sock \ + no-srp \ + no-ssl \ + no-stdio \ + no-threads \ + no-ts \ + no-whirlpool \ + no-shared \ + no-sse2 \ + no-ui-console \ + no-asm \ + --with-rand-seed=getrandom \ + -I$(LIBCRT_DIR)/include \ + -Wl,rpath=$(LIBCRT_DIR) -lcrt -g -O0) + +# ms-tpm +$(LIBTPM): $(MSTPM_MAKEFILE) $(LIBCRYPTO) + $(MAKE) -C $(MSTPM_DIR) $(LIBTPM_A) + +$(LIBPLATFORM): $(MSTPM_MAKEFILE) $(LIBCRYPTO) + $(MAKE) -C $(MSTPM_DIR) $(LIBPLATFORM_A) + +MSTPM_CFLAGS := -static -nostdinc -fno-stack-protector -fPIE +MSTPM_CFLAGS += -DSIMULATION=NO -DFILE_BACKED_NV=NO +MSTPM_CFLAGS += -I$(LIBCRT_DIR)/include +MSTPM_CFLAGS += -I$(OPENSSL_DIR)/include + +# Configure the Microsoft TPM and remove the pthread requirement. +# In fact, pthread is required only in the TPM simulator, but we +# are not building the simulator. +$(MSTPM_MAKEFILE): + (cd $(MSTPM_DIR) && \ + sed -i '/^AX_PTHREAD/d' configure.ac && \ + ./bootstrap && \ + ./configure \ + CFLAGS="${MSTPM_CFLAGS}" \ + LIBCRYPTO_LIBS="${$(LIBCRT) $(LIBCRYPTO)}") + +# bindings.rs +BINDGEN = ${HOME}/.cargo/bin/bindgen +BINDGEN_FLAGS = --use-core +CLANG_FLAGS = -Wno-incompatible-library-redeclaration + +$(BINDGEN): + cargo install bindgen-cli
On my system, I had an older version installed `bindgen v0.60.1` and after some struggle, I realized that this command was not updating it and I had several errors, so I suggest setting a version here: ```suggestion cargo install bindgen-cli@~0.69 ```
svsm
github_2023
others
135
coconut-svsm
roy-hopkins
@@ -0,0 +1,140 @@ +LIBCRT_DIR = $(CURDIR)/libcrt +OPENSSL_DIR = $(CURDIR)/openssl +MSTPM_DIR = $(CURDIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a + +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A = Platform/src/libplatform.a +LIBPLATFORM = $(MSTPM_DIR)/$(LIBPLATFORM_A) + +OPENSSL_MAKEFILE = $(OPENSSL_DIR)/Makefile +MSTPM_MAKEFILE = $(MSTPM_DIR)/Makefile + +LIBS = $(LIBCRT) $(LIBCRYPTO) $(LIBTPM) $(LIBPLATFORM) + +all: libvtpm.a bindings.rs + +libvtpm.a: $(LIBS) + rm -f $@ + ar rcsTPD $@ $^ + +# libcrt +$(LIBCRT): + $(MAKE) -C $(LIBCRT_DIR) + +# openssl +$(LIBCRYPTO): $(OPENSSL_MAKEFILE) $(LIBCRT) + $(MAKE) -C $(OPENSSL_DIR) -j$$(nproc) + +$(OPENSSL_MAKEFILE): + (cd $(OPENSSL_DIR) && git checkout OpenSSL_1_1_1q && \ + ./Configure \ + --config=$(CURDIR)/openssl_svsm.conf \ + SVSM \ + no-afalgeng \ + no-async \ + no-autoerrinit \ + no-autoload-config \ + no-bf \ + no-blake2 \ + no-capieng \ + no-cast \ + no-chacha \ + no-cms \ + no-ct \ + no-deprecated \ + no-des \ + no-dgram \ + no-dsa \ + no-dynamic-engine \ + no-ec2m \ + no-engine \ + no-err \ + no-filenames \ + no-gost \ + no-hw \ + no-idea \ + no-md4 \ + no-mdc2 \ + no-pic \ + no-ocb \ + no-poly1305 \ + no-posix-io \ + no-rc2 \ + no-rc4 \ + no-rfc3779 \ + no-rmd160 \ + no-scrypt \ + no-seed \ + no-sock \ + no-srp \ + no-ssl \ + no-stdio \ + no-threads \ + no-ts \ + no-whirlpool \ + no-shared \ + no-sse2 \ + no-ui-console \ + no-asm \ + --with-rand-seed=getrandom \ + -I$(LIBCRT_DIR)/include \ + -Wl,rpath=$(LIBCRT_DIR) -lcrt -g -O0) + +# ms-tpm +$(LIBTPM): $(MSTPM_MAKEFILE) $(LIBCRYPTO) + $(MAKE) -C $(MSTPM_DIR) $(LIBTPM_A) + +$(LIBPLATFORM): $(MSTPM_MAKEFILE) $(LIBCRYPTO) + $(MAKE) -C $(MSTPM_DIR) $(LIBPLATFORM_A) + +MSTPM_CFLAGS := -static -nostdinc -fno-stack-protector -fPIE +MSTPM_CFLAGS += -DSIMULATION=NO -DFILE_BACKED_NV=NO +MSTPM_CFLAGS += -I$(LIBCRT_DIR)/include +MSTPM_CFLAGS += -I$(OPENSSL_DIR)/include
The MSTPM library is currently building with SSE enabled resulting in an exception on guest startup: ``` Thread 2 received signal SIGINT, Interrupt. [Switching to Thread 1.5] 0xffffff800013a730 in svsm::debug::gdbstub::svsm_gdbstub::debug_break () at src/debug/gdbstub.rs:172 172 asm!("int3"); (gdb) x/10i 0xffffff8000004375 0xffffff8000004375 <CryptEccValidateSignature+113>: pxor %xmm0,%xmm0 0xffffff8000004379 <CryptEccValidateSignature+117>: movaps %xmm0,-0x150(%rbp) 0xffffff8000004380 <CryptEccValidateSignature+124>: movaps %xmm0,-0x140(%rbp) 0xffffff8000004387 <CryptEccValidateSignature+131>: movaps %xmm0,-0x130(%rbp) 0xffffff800000438e <CryptEccValidateSignature+138>: movaps %xmm0,-0x120(%rbp) 0xffffff8000004395 <CryptEccValidateSignature+145>: movq %xmm0,-0x110(%rbp) 0xffffff800000439d <CryptEccValidateSignature+153>: movq $0x6,-0x150(%rbp) 0xffffff80000043a8 <CryptEccValidateSignature+164>: pxor %xmm0,%xmm0 0xffffff80000043ac <CryptEccValidateSignature+168>: movaps %xmm0,-0x1a0(%rbp) 0xffffff80000043b3 <CryptEccValidateSignature+175>: movaps %xmm0,-0x190(%rbp) ``` This seems to fix it: ```suggestion MSTPM_CFLAGS := -static -nostdinc -fno-stack-protector -fPIE -mno-sse MSTPM_CFLAGS += -DSIMULATION=NO -DFILE_BACKED_NV=NO MSTPM_CFLAGS += -I$(LIBCRT_DIR)/include MSTPM_CFLAGS += -I$(OPENSSL_DIR)/include ```
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,140 @@ +LIBCRT_DIR = $(CURDIR)/libcrt +OPENSSL_DIR = $(CURDIR)/openssl +MSTPM_DIR = $(CURDIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a + +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A = Platform/src/libplatform.a +LIBPLATFORM = $(MSTPM_DIR)/$(LIBPLATFORM_A) + +OPENSSL_MAKEFILE = $(OPENSSL_DIR)/Makefile +MSTPM_MAKEFILE = $(MSTPM_DIR)/Makefile + +LIBS = $(LIBCRT) $(LIBCRYPTO) $(LIBTPM) $(LIBPLATFORM) + +all: libvtpm.a bindings.rs + +libvtpm.a: $(LIBS) + rm -f $@ + ar rcsTPD $@ $^ + +# libcrt +$(LIBCRT): + $(MAKE) -C $(LIBCRT_DIR) + +# openssl +$(LIBCRYPTO): $(OPENSSL_MAKEFILE) $(LIBCRT) + $(MAKE) -C $(OPENSSL_DIR) -j$$(nproc) + +$(OPENSSL_MAKEFILE): + (cd $(OPENSSL_DIR) && git checkout OpenSSL_1_1_1q && \
Using `./scripts/container/build.sh` in a `svsm` working tree created with `git-worktree`, I have the following issue: ``` (cd /home/stefano/repos/coconut/svsm-review/libvtpm/openssl && git checkout OpenSSL_1_1_1q && \ ./Configure \ --config=/home/stefano/repos/coconut/svsm-review/libvtpm/openssl_svsm.conf \ SVSM \ no-afalgeng \ no-async \ no-autoerrinit \ no-autoload-config \ no-bf \ no-blake2 \ no-capieng \ no-cast \ no-chacha \ no-cms \ no-ct \ no-deprecated \ no-des \ no-dgram \ no-dsa \ no-dynamic-engine \ no-ec2m \ no-engine \ no-err \ no-filenames \ no-gost \ no-hw \ no-idea \ no-md4 \ no-mdc2 \ no-pic \ no-ocb \ no-poly1305 \ no-posix-io \ no-rc2 \ no-rc4 \ no-rfc3779 \ no-rmd160 \ no-scrypt \ no-seed \ no-sock \ no-srp \ no-ssl \ no-stdio \ no-threads \ no-ts \ no-whirlpool \ no-shared \ no-sse2 \ no-ui-console \ no-asm \ --with-rand-seed=getrandom \ -I/home/stefano/repos/coconut/svsm-review/libvtpm/libcrt/include \ -Wl,rpath=/home/stefano/repos/coconut/svsm-review/libvtpm/libcrt -lcrt -g -O0) fatal: not a git repository: /home/stefano/repos/coconut/svsm-review/libvtpm/openssl/../../../svsm/.git/worktrees/svsm-review1/modules/libvtpm/openssl make[1]: *** [Makefile:35: /home/stefano/repos/coconut/svsm-review/libvtpm/openssl/Makefile] Error 128 make[1]: Leaving directory '/home/stefano/repos/coconut/svsm-review/libvtpm' make: *** [Makefile:70: libvtpm/bindings.rs] Error 2 ``` I suggest removing the `git checkout` here, since the git-submodules should already be at the right commit we have in the history: ```suggestion (cd $(OPENSSL_DIR) && \ ``` This fixes the issue I saw, but I don't know if there is a better way.
svsm
github_2023
c
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: MIT */ + +#include <stdlib.h> +#include <stdint.h> +#include <stdio.h> + +static uint64_t seed; + +void srand(unsigned s) +{ + seed = s - 1; +} + +/* return 0 on success */ +static inline int rdrand64(uint64_t *rnd) +{ + unsigned char ok; + + __asm__ volatile("rdrand %0; setc %1":"=r"(*rnd), "=qm"(ok)); + + return (ok) ? 0 : -1; +} + +int rand(void) +{ + uint64_t r = 0; + + if (rdrand64(&r)) {
I got a little lost in this thread [[1]](https://lore.kernel.org/linux-coco/62c3cd00-d072-4daa-8e67-442d52325cde@linux.intel.com/T/), but it seems that at least on Intel (so not our case for now), rdrand might fail. So should we cycle or panic here? Or should we use `rdseed` (and cycle of course, since it's even more probaile to fail) ? [1] https://lore.kernel.org/linux-coco/62c3cd00-d072-4daa-8e67-442d52325cde@linux.intel.com/T/
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -53,14 +58,23 @@ bin/coconut-hyperv.igvm: $(IGVMBUILDER) stage1/kernel.elf stage1/stage2.bin $(IGVMBUILDER) --sort --output $@ --stage2 stage1/stage2.bin --kernel stage1/kernel.elf --comport 3 hyper-v test: - cargo test --target=x86_64-unknown-linux-gnu + cargo test ${CARGO_ARGS_TEST} --target=x86_64-unknown-linux-gnu test-in-svsm: utils/cbit stage1/test-kernel.elf svsm.bin ./scripts/test-in-svsm.sh doc: cargo doc --open --all-features --document-private-items +libvtpm/libvtpm.a: + make -C libvtpm + +src/vtpm/mstpm/bindings.rs: libvtpm/bindings.rs + cp libvtpm/bindings.rs $@ + +libvtpm/bindings.rs:
I think this target conflicts with `libvtpm/libvtpm.a:`, because running with `make -j10` I have several errors: ``` checking for suffix of object files... make[1]: *** [Makefile:105: /home/stefano/repos/coconut/svsm-review/libvtpm/ms-tpm-20-ref/TPMCmd/Makefile] Error 77 make[1]: Leaving directory '/home/stefano/repos/coconut/svsm-review/libvtpm' make: *** [Makefile:76: libvtpm/bindings.rs] Error 2 make: *** Waiting for unfinished jobs.... sed: can't read conftest.c: No such file or directory configure: error: in `/home/stefano/repos/coconut/svsm-review/libvtpm/ms-tpm-20-ref/TPMCmd': configure: error: cannot compute suffix of object files: cannot compile See `config.log' for more details make[1]: *** [Makefile:105: /home/stefano/repos/coconut/svsm-review/libvtpm/ms-tpm-20-ref/TPMCmd/Makefile] Error 1 make[1]: Leaving directory '/home/stefano/repos/coconut/svsm-review/libvtpm' make: *** [Makefile:70: libvtpm/libvtpm.a] Error 2 ``` Maybe adding a dependency will help: ```suggestion libvtpm/bindings.rs: libvtpm/libvtpm.a ``` But I'm not sure it is fully right or just a workaround. Note: I found another issue running `make` with multiple jobs, but not related to this PR, so I opened #247
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,141 @@ +DEPS_DIR = $(CURDIR)/deps + +LIBCRT_DIR = $(DEPS_DIR)/libcrt +OPENSSL_DIR = $(DEPS_DIR)/openssl +MSTPM_DIR = $(DEPS_DIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A = Platform/src/libplatform.a +LIBPLATFORM = $(MSTPM_DIR)/$(LIBPLATFORM_A) + +OPENSSL_MAKEFILE = $(OPENSSL_DIR)/Makefile +MSTPM_MAKEFILE = $(MSTPM_DIR)/Makefile + +LIBS = $(LIBCRT) $(LIBCRYPTO) $(LIBTPM) $(LIBPLATFORM) + +all: libmstpm.a src/bindings.rs + +libmstpm.a: $(LIBS) + rm -f $@ + ar rcsTPD $@ $^ + +# libcrt +$(LIBCRT): + $(MAKE) -C $(LIBCRT_DIR) + +# openssl +$(LIBCRYPTO): $(OPENSSL_MAKEFILE) $(LIBCRT) + $(MAKE) -C $(OPENSSL_DIR) -j$$(nproc) + +$(OPENSSL_MAKEFILE): + (cd $(OPENSSL_DIR) && \ + ./Configure \ + --config=$(DEPS_DIR)/openssl_svsm.conf \ + SVSM \ + no-afalgeng \ + no-async \ + no-autoerrinit \ + no-autoload-config \ + no-bf \ + no-blake2 \ + no-capieng \ + no-cast \ + no-chacha \ + no-cms \ + no-ct \ + no-deprecated \ + no-des \ + no-dgram \ + no-dsa \ + no-dynamic-engine \ + no-ec2m \ + no-engine \ + no-err \ + no-filenames \ + no-gost \ + no-hw \ + no-idea \ + no-md4 \ + no-mdc2 \ + no-pic \ + no-ocb \ + no-poly1305 \ + no-posix-io \ + no-rc2 \ + no-rc4 \ + no-rfc3779 \ + no-rmd160 \ + no-scrypt \ + no-seed \ + no-sock \ + no-srp \ + no-ssl \ + no-stdio \ + no-threads \ + no-ts \ + no-whirlpool \ + no-shared \ + no-sse2 \ + no-ui-console \ + no-asm \ + --with-rand-seed=getrandom \ + -I$(LIBCRT_DIR)/include \ + -Wl,rpath=$(LIBCRT_DIR) -lcrt -g -O0) + +# ms-tpm +$(LIBTPM): $(MSTPM_MAKEFILE) $(LIBCRYPTO) + $(MAKE) -C $(MSTPM_DIR) $(LIBTPM_A) + +$(LIBPLATFORM): $(MSTPM_MAKEFILE) $(LIBCRYPTO) + $(MAKE) -C $(MSTPM_DIR) $(LIBPLATFORM_A) + +MSTPM_CFLAGS := -static -nostdinc -fno-stack-protector -fPIE -mno-sse +MSTPM_CFLAGS += -DSIMULATION=NO -DFILE_BACKED_NV=NO
Playing with ms-tpm, I realized that `DEBUG=YES` is the default, so should we add `-DDEBUG=NO` here?
svsm
github_2023
others
135
coconut-svsm
joergroedel
@@ -139,15 +139,16 @@ openSUSE you can do this by: $ sudo zypper si -d qemu-ovmf-x86_64 ``` -Then go back to the EDK2 source directory and follow these steps to -build the firmware: +Then go back to the EDK2 source directory and follow the steps below to +build the firmware. `-DTPM2_ENABLE` is required only if you want to use +the SVSM vTPM. ``` $ export PYTHON3_ENABLE=TRUE $ export PYTHON_COMMAND=python3 $ make -j16 -C BaseTools/ -$ source ./edksetup.sh -$ build -a X64 -b DEBUG -t GCC5 -D DEBUG_ON_SERIAL_PORT -D DEBUG_VERBOSE -p OvmfPkg/OvmfPkgX64.dsc +$ source ./edksetup.sh --reconfig
Why is the --reconfig needed?
svsm
github_2023
others
135
coconut-svsm
joergroedel
@@ -0,0 +1,141 @@ +DEPS_DIR = $(CURDIR)/deps + +LIBCRT_DIR = $(DEPS_DIR)/libcrt +OPENSSL_DIR = $(DEPS_DIR)/openssl +MSTPM_DIR = $(DEPS_DIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A = Platform/src/libplatform.a +LIBPLATFORM = $(MSTPM_DIR)/$(LIBPLATFORM_A) + +OPENSSL_MAKEFILE = $(OPENSSL_DIR)/Makefile +MSTPM_MAKEFILE = $(MSTPM_DIR)/Makefile + +LIBS = $(LIBCRT) $(LIBCRYPTO) $(LIBTPM) $(LIBPLATFORM) + +all: libmstpm.a src/bindings.rs + +libmstpm.a: $(LIBS) + rm -f $@ + ar rcsTPD $@ $^ + +# libcrt +$(LIBCRT): + $(MAKE) -C $(LIBCRT_DIR) + +# openssl +$(LIBCRYPTO): $(OPENSSL_MAKEFILE) $(LIBCRT) + $(MAKE) -C $(OPENSSL_DIR) -j$$(nproc) + +$(OPENSSL_MAKEFILE): + (cd $(OPENSSL_DIR) && \ + ./Configure \ + --config=$(DEPS_DIR)/openssl_svsm.conf \ + SVSM \ + no-afalgeng \ + no-async \ + no-autoerrinit \ + no-autoload-config \ + no-bf \ + no-blake2 \ + no-capieng \ + no-cast \ + no-chacha \ + no-cms \ + no-ct \ + no-deprecated \ + no-des \ + no-dgram \ + no-dsa \ + no-dynamic-engine \ + no-ec2m \ + no-engine \ + no-err \ + no-filenames \ + no-gost \ + no-hw \ + no-idea \ + no-md4 \ + no-mdc2 \ + no-pic \ + no-ocb \ + no-poly1305 \ + no-posix-io \ + no-rc2 \ + no-rc4 \ + no-rfc3779 \ + no-rmd160 \ + no-scrypt \ + no-seed \ + no-sock \ + no-srp \ + no-ssl \ + no-stdio \ + no-threads \ + no-ts \ + no-whirlpool \ + no-shared \ + no-sse2 \ + no-ui-console \ + no-asm \ + --with-rand-seed=getrandom \ + -I$(LIBCRT_DIR)/include \ + -Wl,rpath=$(LIBCRT_DIR) -lcrt -g -O0) + +# ms-tpm +$(LIBTPM): $(MSTPM_MAKEFILE) $(LIBCRYPTO) + $(MAKE) -C $(MSTPM_DIR) $(LIBTPM_A) + +$(LIBPLATFORM): $(MSTPM_MAKEFILE) $(LIBCRYPTO) + $(MAKE) -C $(MSTPM_DIR) $(LIBPLATFORM_A) + +MSTPM_CFLAGS := -static -nostdinc -fno-stack-protector -fPIE -mno-sse +MSTPM_CFLAGS += -DSIMULATION=NO -DFILE_BACKED_NV=NO -DDEBUG=NO +MSTPM_CFLAGS += -I$(LIBCRT_DIR)/include +MSTPM_CFLAGS += -I$(OPENSSL_DIR)/include + +# Configure the Microsoft TPM and remove the pthread requirement. +# In fact, pthread is required only in the TPM simulator, but we +# are not building the simulator. +$(MSTPM_MAKEFILE): + (cd $(MSTPM_DIR) && \ + sed -i '/^AX_PTHREAD/d' configure.ac && \ + ./bootstrap && \ + ./configure \ + CFLAGS="${MSTPM_CFLAGS}" \ + LIBCRYPTO_LIBS="${$(LIBCRT) $(LIBCRYPTO)}") + +# bindings.rs +BINDGEN = ${HOME}/.cargo/bin/bindgen +BINDGEN_FLAGS = --use-core +CLANG_FLAGS = -Wno-incompatible-library-redeclaration + +$(BINDGEN): + cargo install bindgen-cli@0.69
Please do not install build dependencies on Makefiles. The right way to do this is to just call `cargo bindgen` and let the user install it (e.g. via distro package manager). I think changing this also requires updates to the documentation about which build dependencies to install and the docker-files.
svsm
github_2023
others
135
coconut-svsm
deeglaze
@@ -189,6 +193,15 @@ Building the SVSM itself requires: - `x86_64-unknown-none` target toolchain installed (`rustup target add x86_64-unknown-none`) - `binutils` >= 2.39 +You may also need to install the Microsoft TPM build dependencies. On OpenSUSE +you can do this by: + +``` +$ sudo zypper in system-user-mail make gcc curl patterns-devel-base-devel_basis \ + glibc-devel-static git libclang13 autoconf autoconf-archive pkg-config \ + automake libopenssl-devel
I don't think we should be leaving the C library dependencies to open to the toolchain container. These need to be part of SVSM's own dependency management.
svsm
github_2023
others
135
coconut-svsm
deeglaze
@@ -6,11 +6,14 @@ pub mod core; pub mod errors; +#[cfg(feature = "mstpm")]
Is it possible to allow the build to have the tpm linked in but have a qemufwcfg file specify whether to make it discoverable? We want to have a single binary to release but still allow users to decide whether or not to attach a vTPM to their instance.
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -0,0 +1,192 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM +// +// Authors: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! This crate implements the virtual TPM interfaces for the TPM 2.0 +//! Reference Implementation (by Microsoft) + +/// Functions required to build the Microsoft TPM libraries +#[cfg(not(feature = "default-test"))] +mod wrapper; + +extern crate alloc; + +use alloc::vec::Vec; +use core::{ffi::c_void, ptr::addr_of_mut}; +use libmstpm::bindings::{ + TPM_Manufacture, TPM_TearDown, _plat__LocalitySet, _plat__NVDisable, _plat__NVEnable, + _plat__RunCommand, _plat__SetNvAvail, _plat__Signal_PowerOn, _plat__Signal_Reset, +}; + +use crate::{ + address::VirtAddr, + protocols::{errors::SvsmReqError, vtpm::TpmPlatformCommand}, + types::PAGE_SIZE, + vtpm::{MsTpmSimulatorInterface, VtpmInterface, VtpmProtocolInterface}, +}; + +#[derive(Debug, Copy, Clone)] +pub struct MsTpm { + is_powered_on: bool, +} + +impl MsTpm { + pub const fn new() -> MsTpm { + MsTpm { + is_powered_on: false, + } + } + + fn teardown(&self) -> Result<(), SvsmReqError> { + let result = unsafe { TPM_TearDown() }; + match result { + 0 => Ok(()), + rc => { + log::error!("TPM_Teardown failed rc={}", rc); + Err(SvsmReqError::incomplete()) + } + } + } + + fn manufacture(&self, first_time: i32) -> Result<i32, SvsmReqError> { + let result = unsafe { TPM_Manufacture(first_time) }; + match result { + // TPM manufactured successfully + 0 => Ok(0), + // TPM already manufactured + 1 => Ok(1), + // TPM failed to manufacture + rc => { + log::error!("TPM_Manufacture failed rc={}", rc); + Err(SvsmReqError::incomplete()) + } + } + } +} + +const TPM_CMDS_SUPPORTED: &[TpmPlatformCommand] = &[TpmPlatformCommand::SendCommand]; + +impl VtpmProtocolInterface for MsTpm { + fn get_supported_commands(&self) -> &[TpmPlatformCommand] { + TPM_CMDS_SUPPORTED + } +} + +pub const TPM_BUFFER_MAX_SIZE: usize = PAGE_SIZE; + +impl MsTpmSimulatorInterface for MsTpm { + fn send_tpm_command( + &self, + buffer: &mut [u8], + length: &mut usize, + locality: u8, + ) -> Result<(), SvsmReqError> { + if !self.is_powered_on { + return Err(SvsmReqError::invalid_request()); + } + if *length > TPM_BUFFER_MAX_SIZE || *length > buffer.len() { + return Err(SvsmReqError::invalid_parameter()); + } + + let mut request_ffi = Vec::<u8>::with_capacity(*length); + request_ffi.extend_from_slice(&buffer[..*length]);
```suggestion let mut request_ffi = buffer[..*length].to_vec(); ```
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -441,6 +443,11 @@ pub extern "C" fn svsm_main() { prepare_fw_launch(fw_meta).expect("Failed to setup guest VMSA/CAA"); } + #[cfg(feature = "mstpm")] + if let Err(e) = vtpm_init() { + panic!("vTPM failed to initialize - {:?}", e); + }
This will also display the error and is shorter: ```suggestion vtpm_init().expect("vTPM failed to initialize"); ```
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -0,0 +1,220 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM Corp +// +// Author: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! vTPM protocol implementation (SVSM spec, chapter 8). + +extern crate alloc; + +use alloc::vec::Vec; + +use crate::{ + address::{Address, PhysAddr, VirtAddr}, + mm::{valid_phys_address, GuestPtr, PerCPUPageMappingGuard}, + protocols::{errors::SvsmReqError, RequestParams}, + types::PAGE_SIZE, + vtpm::{vtpm_get_locked, MsTpmSimulatorInterface, VtpmProtocolInterface}, +}; + +/// vTPM platform commands (SVSM spec, section 8.1 - SVSM_VTPM_QUERY) +/// +/// The platform commmand values follow the values used by the +/// Official TPM 2.0 Reference Implementation by Microsoft. +/// +/// `ms-tpm-20-ref/TPMCmd/Simulator/include/TpmTcpProtocol.h` +#[repr(u32)] +#[derive(PartialEq, Copy, Clone, Debug)] +pub enum TpmPlatformCommand { + SendCommand = 8, +} + +impl TryFrom<u32> for TpmPlatformCommand { + type Error = SvsmReqError; + + fn try_from(value: u32) -> Result<Self, Self::Error> { + let cmd = match value { + x if x == TpmPlatformCommand::SendCommand as u32 => TpmPlatformCommand::SendCommand, + other => { + log::warn!("Failed to convert {} to a TPM platform command", other); + return Err(SvsmReqError::invalid_parameter()); + } + }; + + Ok(cmd) + } +} + +fn vtpm_platform_commands_supported_bitmap() -> u64 { + let mut bitmap: u64 = 0; + let vtpm = vtpm_get_locked(); + + for cmd in vtpm.get_supported_commands() { + bitmap |= 1u64 << *cmd as u32; + } + + bitmap +} + +fn is_vtpm_platform_command_supported(cmd: TpmPlatformCommand) -> bool { + let vtpm = vtpm_get_locked(); + vtpm.get_supported_commands().iter().any(|x| *x == cmd) +} + +const SEND_COMMAND_REQ_INBUF_SIZE: usize = PAGE_SIZE - 9; + +// vTPM protocol services (SVSM spec, table 14) +const SVSM_VTPM_QUERY: u32 = 0; +const SVSM_VTPM_COMMAND: u32 = 1; + +/// TPM_SEND_COMMAND request structure (SVSM spec, table 16) +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +struct TpmSendCommandRequest { + /// MSSIM platform command ID + command: u32, + /// Locality usage for the vTPM is not defined yet (must be zero) + locality: u8, + /// Size of the input buffer + inbuf_size: u32, + /// Input buffer that contains the TPM command + inbuf: [u8; SEND_COMMAND_REQ_INBUF_SIZE], +} + +impl TpmSendCommandRequest { + pub fn send(&self) -> Result<Vec<u8>, SvsmReqError> { + // TODO: Before implementing locality, we need to agree what it means + // to the platform + if self.locality != 0 { + return Err(SvsmReqError::invalid_parameter()); + } + + let mut length = self.inbuf_size as usize; + + let tpm_cmd = self + .inbuf + .get(..length) + .ok_or_else(SvsmReqError::invalid_parameter)?; + let mut buffer: Vec<u8> = Vec::with_capacity(SEND_COMMAND_RESP_OUTBUF_SIZE); + buffer.extend_from_slice(tpm_cmd); + + // The buffer slice must be large enough to hold the TPM command response + unsafe { buffer.set_len(buffer.capacity()) };
This creates a reference to uninitialized memory and is undefined behavior, even if memory is not accessed. ```suggestion // The buffer slice must be large enough to hold the TPM command response buffer.resize(SEND_COMMAND_RESP_OUTBUF_SIZE, 0); ```
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -0,0 +1,220 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM Corp +// +// Author: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! vTPM protocol implementation (SVSM spec, chapter 8). + +extern crate alloc; + +use alloc::vec::Vec; + +use crate::{ + address::{Address, PhysAddr, VirtAddr}, + mm::{valid_phys_address, GuestPtr, PerCPUPageMappingGuard}, + protocols::{errors::SvsmReqError, RequestParams}, + types::PAGE_SIZE, + vtpm::{vtpm_get_locked, MsTpmSimulatorInterface, VtpmProtocolInterface}, +}; + +/// vTPM platform commands (SVSM spec, section 8.1 - SVSM_VTPM_QUERY) +/// +/// The platform commmand values follow the values used by the +/// Official TPM 2.0 Reference Implementation by Microsoft. +/// +/// `ms-tpm-20-ref/TPMCmd/Simulator/include/TpmTcpProtocol.h` +#[repr(u32)] +#[derive(PartialEq, Copy, Clone, Debug)] +pub enum TpmPlatformCommand { + SendCommand = 8, +} + +impl TryFrom<u32> for TpmPlatformCommand { + type Error = SvsmReqError; + + fn try_from(value: u32) -> Result<Self, Self::Error> { + let cmd = match value { + x if x == TpmPlatformCommand::SendCommand as u32 => TpmPlatformCommand::SendCommand, + other => { + log::warn!("Failed to convert {} to a TPM platform command", other); + return Err(SvsmReqError::invalid_parameter()); + } + }; + + Ok(cmd) + } +} + +fn vtpm_platform_commands_supported_bitmap() -> u64 { + let mut bitmap: u64 = 0; + let vtpm = vtpm_get_locked(); + + for cmd in vtpm.get_supported_commands() { + bitmap |= 1u64 << *cmd as u32; + } + + bitmap +} + +fn is_vtpm_platform_command_supported(cmd: TpmPlatformCommand) -> bool { + let vtpm = vtpm_get_locked(); + vtpm.get_supported_commands().iter().any(|x| *x == cmd) +} + +const SEND_COMMAND_REQ_INBUF_SIZE: usize = PAGE_SIZE - 9; + +// vTPM protocol services (SVSM spec, table 14) +const SVSM_VTPM_QUERY: u32 = 0; +const SVSM_VTPM_COMMAND: u32 = 1; + +/// TPM_SEND_COMMAND request structure (SVSM spec, table 16) +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +struct TpmSendCommandRequest { + /// MSSIM platform command ID + command: u32, + /// Locality usage for the vTPM is not defined yet (must be zero) + locality: u8, + /// Size of the input buffer + inbuf_size: u32, + /// Input buffer that contains the TPM command + inbuf: [u8; SEND_COMMAND_REQ_INBUF_SIZE], +} + +impl TpmSendCommandRequest { + pub fn send(&self) -> Result<Vec<u8>, SvsmReqError> { + // TODO: Before implementing locality, we need to agree what it means + // to the platform + if self.locality != 0 { + return Err(SvsmReqError::invalid_parameter()); + } + + let mut length = self.inbuf_size as usize; + + let tpm_cmd = self + .inbuf + .get(..length) + .ok_or_else(SvsmReqError::invalid_parameter)?; + let mut buffer: Vec<u8> = Vec::with_capacity(SEND_COMMAND_RESP_OUTBUF_SIZE); + buffer.extend_from_slice(tpm_cmd); + + // The buffer slice must be large enough to hold the TPM command response + unsafe { buffer.set_len(buffer.capacity()) }; + + let vtpm = vtpm_get_locked(); + vtpm.send_tpm_command(buffer.as_mut_slice(), &mut length, self.locality)?; + + unsafe { + if length > buffer.capacity() { + return Err(SvsmReqError::invalid_request()); + } + buffer.set_len(length); + }
Again, we cannot set the length to capacity because that could include allocated but uninitialized memory (note that capacity might be greater than `SEND_COMMAND_RESP_OUTBUF_SIZE`, we are only guaranteed that's the minimum). With my previous suggestion we filled up buffer until `SEND_COMMAND_RESP_OUTBUF_SIZE` with zeroes, so we can simply check that the new length is equal or smaller, and then truncate, avoiding unsafe completely. ```suggestion if length > buffer.len() { return Err(SvsmReqError::invalid_request()); } buffer.truncate(length); ```
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -0,0 +1,220 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM Corp +// +// Author: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! vTPM protocol implementation (SVSM spec, chapter 8). + +extern crate alloc; + +use alloc::vec::Vec; + +use crate::{ + address::{Address, PhysAddr, VirtAddr}, + mm::{valid_phys_address, GuestPtr, PerCPUPageMappingGuard}, + protocols::{errors::SvsmReqError, RequestParams}, + types::PAGE_SIZE, + vtpm::{vtpm_get_locked, MsTpmSimulatorInterface, VtpmProtocolInterface}, +}; + +/// vTPM platform commands (SVSM spec, section 8.1 - SVSM_VTPM_QUERY) +/// +/// The platform commmand values follow the values used by the +/// Official TPM 2.0 Reference Implementation by Microsoft. +/// +/// `ms-tpm-20-ref/TPMCmd/Simulator/include/TpmTcpProtocol.h` +#[repr(u32)] +#[derive(PartialEq, Copy, Clone, Debug)] +pub enum TpmPlatformCommand { + SendCommand = 8, +} + +impl TryFrom<u32> for TpmPlatformCommand { + type Error = SvsmReqError; + + fn try_from(value: u32) -> Result<Self, Self::Error> { + let cmd = match value { + x if x == TpmPlatformCommand::SendCommand as u32 => TpmPlatformCommand::SendCommand, + other => { + log::warn!("Failed to convert {} to a TPM platform command", other); + return Err(SvsmReqError::invalid_parameter()); + } + }; + + Ok(cmd) + } +} + +fn vtpm_platform_commands_supported_bitmap() -> u64 { + let mut bitmap: u64 = 0; + let vtpm = vtpm_get_locked(); + + for cmd in vtpm.get_supported_commands() { + bitmap |= 1u64 << *cmd as u32; + } + + bitmap +} + +fn is_vtpm_platform_command_supported(cmd: TpmPlatformCommand) -> bool { + let vtpm = vtpm_get_locked(); + vtpm.get_supported_commands().iter().any(|x| *x == cmd) +} + +const SEND_COMMAND_REQ_INBUF_SIZE: usize = PAGE_SIZE - 9; + +// vTPM protocol services (SVSM spec, table 14) +const SVSM_VTPM_QUERY: u32 = 0; +const SVSM_VTPM_COMMAND: u32 = 1; + +/// TPM_SEND_COMMAND request structure (SVSM spec, table 16) +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +struct TpmSendCommandRequest { + /// MSSIM platform command ID + command: u32, + /// Locality usage for the vTPM is not defined yet (must be zero) + locality: u8, + /// Size of the input buffer + inbuf_size: u32, + /// Input buffer that contains the TPM command + inbuf: [u8; SEND_COMMAND_REQ_INBUF_SIZE], +} + +impl TpmSendCommandRequest { + pub fn send(&self) -> Result<Vec<u8>, SvsmReqError> { + // TODO: Before implementing locality, we need to agree what it means + // to the platform + if self.locality != 0 { + return Err(SvsmReqError::invalid_parameter()); + } + + let mut length = self.inbuf_size as usize; + + let tpm_cmd = self + .inbuf + .get(..length) + .ok_or_else(SvsmReqError::invalid_parameter)?; + let mut buffer: Vec<u8> = Vec::with_capacity(SEND_COMMAND_RESP_OUTBUF_SIZE); + buffer.extend_from_slice(tpm_cmd); + + // The buffer slice must be large enough to hold the TPM command response + unsafe { buffer.set_len(buffer.capacity()) }; + + let vtpm = vtpm_get_locked(); + vtpm.send_tpm_command(buffer.as_mut_slice(), &mut length, self.locality)?; + + unsafe { + if length > buffer.capacity() { + return Err(SvsmReqError::invalid_request()); + } + buffer.set_len(length); + } + + Ok(buffer) + } +} + +const SEND_COMMAND_RESP_OUTBUF_SIZE: usize = PAGE_SIZE - 4; + +/// TPM_SEND_COMMAND response structure (SVSM spec, table 17) +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +struct TpmSendCommandResponse { + /// Size of the output buffer + outbuf_size: u32, + /// Output buffer that will hold the command response + outbuf: [u8; SEND_COMMAND_RESP_OUTBUF_SIZE], +} + +impl TpmSendCommandResponse { + /// Write the response to the outbuf + /// + /// # Arguments + /// + /// * `response`: TPM_SEND_COMMAND response slice + pub fn set_outbuf(&mut self, response: &[u8]) -> Result<(), SvsmReqError> { + self.outbuf + .get_mut(..response.len()) + .ok_or_else(SvsmReqError::invalid_request)? + .copy_from_slice(response); + self.outbuf_size = response.len() as u32; + + Ok(()) + } +} + +fn vtpm_query_request(params: &mut RequestParams) -> Result<(), SvsmReqError> { + // Bitmap of the supported vTPM commands + params.rcx = vtpm_platform_commands_supported_bitmap(); + // Supported vTPM features. Must-be-zero + params.rdx = 0; + + Ok(()) +} + +fn tpm_send_command_request(iobuf: VirtAddr) -> Result<u32, SvsmReqError> { + let outbuf: Vec<u8> = { + let request = unsafe { &*iobuf.as_mut_ptr::<TpmSendCommandRequest>() }; + request.send()? + }; + let response = unsafe { &mut *iobuf.as_mut_ptr::<TpmSendCommandResponse>() }; + let _ = response.set_outbuf(outbuf.as_slice()); + + Ok(outbuf.len() as u32) +}
Please mark this function as unsafe - the caller must make sure that `iobuf` points to a sufficiently large region of memory, that it's properly aligned, that it is initialized to a valid representation of `TpmSendCommandResponse` and that it's not aliased.
svsm
github_2023
others
135
coconut-svsm
roy-hopkins
@@ -189,6 +193,15 @@ Building the SVSM itself requires: - `x86_64-unknown-none` target toolchain installed (`rustup target add x86_64-unknown-none`) - `binutils` >= 2.39 +You may also need to install the Microsoft TPM build dependencies. On OpenSUSE +you can do this by: + +``` +$ sudo zypper in system-user-mail make gcc curl patterns-devel-base-devel_basis \ + glibc-devel-static git libclang13 autoconf autoconf-archive pkg-config \ + automake libopenssl-devel +``` + Then checkout the SVSM repository and build the SVSM binary: ```
I may have missed it elsewhere in the documentation but do we need to install git submodules now when cloning the SVSM repository? ``` $ git clone https://github.com/coconut-svsm/svsm $ git submodule update --init ```
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -85,3 +110,8 @@ pub fn vtpm_init() -> Result<(), SvsmReqError> { vtpm.init()?; Ok(()) } + +pub fn vtpm_get_locked() -> VtpmRef { + let vtpm = addr_of_mut!(*VTPM.lock()); + VtpmRef::new(vtpm) +}
This is dropping the lock as soon as the function returns, which will lead to undefined behavior when using the `VtpmRef`. You need `VtpmRef` to hold a `SpinLockGuard<'a, Vtpm>` (or directly return that type from `vtpm_get_locked()`, which already implements `Deref` and `DerefMut`).
svsm
github_2023
others
135
coconut-svsm
roy-hopkins
@@ -0,0 +1,192 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM +// +// Authors: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! This crate implements the virtual TPM interfaces for the TPM 2.0 +//! Reference Implementation (by Microsoft) + +/// Functions required to build the Microsoft TPM libraries +#[cfg(not(feature = "default-test"))] +mod wrapper; + +extern crate alloc; + +use alloc::vec::Vec; +use core::{ffi::c_void, ptr::addr_of_mut}; +use libmstpm::bindings::{ + TPM_Manufacture, TPM_TearDown, _plat__LocalitySet, _plat__NVDisable, _plat__NVEnable, + _plat__RunCommand, _plat__SetNvAvail, _plat__Signal_PowerOn, _plat__Signal_Reset, +}; + +use crate::{ + address::VirtAddr, + protocols::{errors::SvsmReqError, vtpm::TpmPlatformCommand}, + types::PAGE_SIZE, + vtpm::{MsTpmSimulatorInterface, VtpmInterface, VtpmProtocolInterface}, +}; + +#[derive(Debug, Copy, Clone)] +pub struct MsTpm { + is_powered_on: bool, +} + +impl MsTpm { + pub const fn new() -> MsTpm { + MsTpm { + is_powered_on: false, + } + } + + fn teardown(&self) -> Result<(), SvsmReqError> { + let result = unsafe { TPM_TearDown() }; + match result { + 0 => Ok(()), + rc => { + log::error!("TPM_Teardown failed rc={}", rc); + Err(SvsmReqError::incomplete()) + } + } + } + + fn manufacture(&self, first_time: i32) -> Result<i32, SvsmReqError> { + let result = unsafe { TPM_Manufacture(first_time) }; + match result { + // TPM manufactured successfully + 0 => Ok(0), + // TPM already manufactured + 1 => Ok(1), + // TPM failed to manufacture + rc => { + log::error!("TPM_Manufacture failed rc={}", rc); + Err(SvsmReqError::incomplete()) + } + } + } +} + +const TPM_CMDS_SUPPORTED: &[TpmPlatformCommand] = &[TpmPlatformCommand::SendCommand]; + +impl VtpmProtocolInterface for MsTpm { + fn get_supported_commands(&self) -> &[TpmPlatformCommand] { + TPM_CMDS_SUPPORTED + } +} + +pub const TPM_BUFFER_MAX_SIZE: usize = PAGE_SIZE; + +impl MsTpmSimulatorInterface for MsTpm { + fn send_tpm_command( + &self, + buffer: &mut [u8], + length: &mut usize, + locality: u8, + ) -> Result<(), SvsmReqError> { + if !self.is_powered_on { + return Err(SvsmReqError::invalid_request()); + } + if *length > TPM_BUFFER_MAX_SIZE || *length > buffer.len() { + return Err(SvsmReqError::invalid_parameter()); + } + + let mut request_ffi = Vec::<u8>::with_capacity(*length); + request_ffi.extend_from_slice(&buffer[..*length]); + + let mut response_ffi = Vec::<u8>::with_capacity(TPM_BUFFER_MAX_SIZE); + let mut response_ffi_p = response_ffi.as_mut_ptr(); + let mut response_ffi_size = TPM_BUFFER_MAX_SIZE as u32; + + unsafe { + _plat__LocalitySet(locality); + _plat__RunCommand( + request_ffi.len() as u32, + request_ffi.as_mut_ptr().cast::<u8>(), + addr_of_mut!(response_ffi_size), + addr_of_mut!(response_ffi_p), + ); + if response_ffi_size == 0 || response_ffi_size as usize > response_ffi.capacity() { + return Err(SvsmReqError::invalid_request()); + } + response_ffi.set_len(response_ffi_size as usize); + } + + buffer.fill(0); + buffer + .get_mut(..response_ffi.len()) + .ok_or_else(SvsmReqError::invalid_request)? + .copy_from_slice(response_ffi.as_slice()); + *length = response_ffi.len(); + + Ok(()) + } + + fn signal_poweron(&mut self, only_reset: bool) -> Result<(), SvsmReqError> { + if self.is_powered_on && !only_reset { + return Ok(()); + } + if only_reset && !self.is_powered_on { + return Err(SvsmReqError::invalid_request()); + } + if !only_reset { + unsafe { _plat__Signal_PowerOn() }; + } + // It calls TPM_init() within to indicate that a TPM2_Startup is required. + unsafe { _plat__Signal_Reset() }; + self.is_powered_on = true; + + Ok(()) + } + + fn signal_nvon(&self) -> Result<(), SvsmReqError> { + if !self.is_powered_on { + return Err(SvsmReqError::invalid_request()); + } + unsafe { _plat__SetNvAvail() }; + + Ok(()) + } +} + +impl VtpmInterface for MsTpm { + fn is_powered_on(&self) -> bool { + self.is_powered_on + } + + fn init(&mut self) -> Result<(), SvsmReqError> { + // Initialize the MS TPM following the same steps done in the Simulator: + // + // 1. Manufacture it for the first time + // 2. Make sure it does not fail if it is re-manufactured + // 3. Teardown to indicate it needs to be manufactured + // 4. Manufacture it for the first time + // 5. Power it on indicating it requires startup. By default, OVMF will start + // and selftest it.
What is the purpose of this initialisation process? Maybe this should be moved to a `test-in-svsm` test and the startup process here simplified?
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -131,5 +131,4 @@ clean: rm -f ${STAGE1_OBJS} utils/gen_meta utils/print-meta rm -rf bin -.PHONY: test clean clippy bin/stage2.bin bin/svsm-kernel.elf bin/test-kernel.elf
Should we add `distclean` in `.PHONY` in the same commit where we define `distclean` target? (Maybe something went wrong with the rebase)
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2024 IBM +// +// Authors: Claudio Carvalho <cclaudio@linux.ibm.com> + +use std::process::Command; + +fn main() { + Command::new("make").status().unwrap();
If `make` fails here, is there any way to propagate the output? Even using `make V=2` in the root, I can't see the errors produced by this call (they might be useful, for example in my case it failed because it can't install `bindgen-cli`, but I discovered it only doing `make -C libmstpm ` )
svsm
github_2023
others
135
coconut-svsm
roy-hopkins
@@ -0,0 +1,141 @@ +DEPS_DIR = $(CURDIR)/deps + +LIBCRT_DIR = $(DEPS_DIR)/libcrt +OPENSSL_DIR = $(DEPS_DIR)/openssl +MSTPM_DIR = $(DEPS_DIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A = Platform/src/libplatform.a +LIBPLATFORM = $(MSTPM_DIR)/$(LIBPLATFORM_A) + +OPENSSL_MAKEFILE = $(OPENSSL_DIR)/Makefile +MSTPM_MAKEFILE = $(MSTPM_DIR)/Makefile + +LIBS = $(LIBCRT) $(LIBCRYPTO) $(LIBTPM) $(LIBPLATFORM) + +all: libmstpm.a src/bindings.rs + +libmstpm.a: $(LIBS) + rm -f $@ + ar rcsTPD $@ $^ + +# libcrt +$(LIBCRT): + $(MAKE) -C $(LIBCRT_DIR) + +# openssl +$(LIBCRYPTO): $(OPENSSL_MAKEFILE) $(LIBCRT) + $(MAKE) -C $(OPENSSL_DIR) -j$$(nproc) + +$(OPENSSL_MAKEFILE): + (cd $(OPENSSL_DIR) && \ + ./Configure \ + --config=$(DEPS_DIR)/openssl_svsm.conf \ + SVSM \ + no-afalgeng \ + no-async \ + no-autoerrinit \ + no-autoload-config \ + no-bf \ + no-blake2 \ + no-capieng \ + no-cast \ + no-chacha \ + no-cms \ + no-ct \ + no-deprecated \ + no-des \ + no-dgram \ + no-dsa \ + no-dynamic-engine \ + no-ec2m \ + no-engine \ + no-err \ + no-filenames \ + no-gost \ + no-hw \ + no-idea \ + no-md4 \ + no-mdc2 \ + no-pic \ + no-ocb \ + no-poly1305 \ + no-posix-io \ + no-rc2 \ + no-rc4 \ + no-rfc3779 \ + no-rmd160 \ + no-scrypt \ + no-seed \ + no-sock \ + no-srp \ + no-ssl \ + no-stdio \ + no-threads \ + no-ts \ + no-whirlpool \ + no-shared \ + no-sse2 \ + no-ui-console \ + no-asm \ + --with-rand-seed=getrandom \ + -I$(LIBCRT_DIR)/include \ + -Wl,rpath=$(LIBCRT_DIR) -lcrt -g -O0)
Debug information is turned on and optimisation level set to 0 here. Should optimisation be enabled?
svsm
github_2023
others
303
coconut-svsm
osteffenrh
@@ -6,7 +6,9 @@ members = [ # binary targets "kernel", # fuzzing - "fuzz" + "fuzz", + # ELF loader + "elf"
trailing commas are OK in TOML
svsm
github_2023
others
303
coconut-svsm
osteffenrh
@@ -0,0 +1,181 @@ +// SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +// +// Copyright (c) 2023-2024 SUSE LLC +// +// Author: Nicolai Stange <nstange@suse.de> +// +// vim: ts=4 sw=4 et
Do we really need editor specific formatting options in code files? There are things like [editorconfig](https://editorconfig.org/) that allows setting this easily for the whole project (supported by neovim out of the box) On the other hand, don't we run the rust formatter on everything automatically anyway?
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -71,11 +71,19 @@ impl IgvmBuilder { directive_a: &IgvmDirectiveHeader, directive_b: &IgvmDirectiveHeader, ) -> Ordering { - let IgvmDirectiveHeader::PageData { gpa: a, .. } = directive_a else { - panic!("Attempted to compare non-page directive"); + let a = if let IgvmDirectiveHeader::PageData { gpa, .. } = directive_a { + gpa + } else if let IgvmDirectiveHeader::SnpVpContext { gpa, .. } = directive_a { + gpa + } else { + panic!("Attempted to compare non-page/vp directive"); };
Or simply: ```suggestion let a = match directive_a { IgvmDirectiveHeader::PageData { gpa, .. } | IgvmDirectiveHeader::SnpVpContext { gpa, .. } => gpa, _ = panic!("Attempted to compare non-page/vp directive"), }; ```
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,279 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDataType, IgvmPlatformType, PAGE_SIZE_4K}; +use zerocopy::AsBytes; + +use crate::cmd_options::CmdOptions; +use crate::page_info::PageInfo; + +#[derive(PartialEq)] +enum SnpPageType { + None, + Normal, + Unmeasured, + Zero, + Secrets, + CpuId, + Vmsa, +} + +pub struct IgvmMeasure<'a> { + options: &'a CmdOptions, + digest: [u8; 48], + last_page_type: SnpPageType, + last_gpa: u64, + last_next_gpa: u64, + last_len: u64, + compatibility_mask: u32, + vmsa_count: u32, +} + +const PAGE_SIZE_2M: u64 = 2 * 1024 * 1024; + +impl<'a> IgvmMeasure<'a> { + pub fn new(options: &'a CmdOptions) -> Result<Self, Box<dyn Error>> { + Ok(Self { + options, + digest: [0u8; 48], + last_page_type: SnpPageType::None, + last_gpa: 0, + last_next_gpa: 0, + last_len: 0, + compatibility_mask: 0, + vmsa_count: 0, + }) + } + + fn find_compatibility_mask(&mut self, igvm: &IgvmFile) -> Result<(), Box<dyn Error>> { + for platform in igvm.platforms() { + let IgvmPlatformHeader::SupportedPlatform(platform) = platform; + match platform.platform_type { + IgvmPlatformType::SEV_SNP => { + self.compatibility_mask = platform.compatibility_mask; + return Ok(()); + } + _ => continue, + } + } + Err("IGVM file is not compatible with the specified platform.".into()) + } + + pub fn measure(&mut self) -> Result<[u8; 48], Box<dyn Error>> { + let igvm_buffer = fs::read(&self.options.igvm_file).map_err(|e| { + eprintln!("Failed to open firmware file {}", self.options.igvm_file); + e + })?; + let igvm = IgvmFile::new_from_binary(igvm_buffer.as_bytes(), None)?; + + self.find_compatibility_mask(&igvm)?; + + for directive in igvm.directives() { + match directive { + IgvmDirectiveHeader::PageData { + gpa, + compatibility_mask, + flags, + data_type, + data, + } => { + if (*compatibility_mask & self.compatibility_mask) != 0 { + self.measure_page(*gpa, flags, *data_type, data)?; + } + } + IgvmDirectiveHeader::ParameterInsert(param) => { + if (param.compatibility_mask & self.compatibility_mask) != 0 { + if self.options.check_kvm && (self.vmsa_count > 0) { + return Err("KVM check failure: The VMSA must be the final page \ + directive in the IGVM file. \ + This is because QEMU/KVM measures the VMSA page \ + when the measurement is finalized and not in the \ + order specified in the IGVM file. Make sure your \ + IGVM file places the VMSA directive after any other \ + measured or unmeasured page directives." + .into()); + } + self.measure_page( + param.gpa, + &IgvmPageDataFlags::new().with_unmeasured(true), + IgvmPageDataType::NORMAL, + &[], + )?; + } + } + IgvmDirectiveHeader::SnpVpContext { + gpa, + compatibility_mask, + vp_index: _vp_index, + vmsa, + } => { + self.measure_vmsa(*gpa, *compatibility_mask, vmsa)?; + } + _ => (), + } + } + self.log_page(SnpPageType::None, 0, 0); + + Ok(self.digest) + } + + fn log_page(&mut self, page_type: SnpPageType, gpa: u64, len: u64) { + if self.options.verbose { + if (page_type != self.last_page_type) || (gpa != self.last_next_gpa) { + if self.last_len > 0 { + let page_name = match self.last_page_type { + SnpPageType::None => "None", + SnpPageType::Normal => "Normal", + SnpPageType::Unmeasured => "Unmeasured", + SnpPageType::Zero => "Zero", + SnpPageType::Secrets => "Secrets", + SnpPageType::CpuId => "Cpuid", + SnpPageType::Vmsa => "VMSA", + }; + println!( + "gpa {:#x} len {:#x} ({} page)", + self.last_gpa, self.last_len, page_name + );
Perhaps it's better to implement `std::fmt::Display` for `SnpPageType` instead of doing the conversion here.
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,279 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDataType, IgvmPlatformType, PAGE_SIZE_4K}; +use zerocopy::AsBytes; + +use crate::cmd_options::CmdOptions; +use crate::page_info::PageInfo; + +#[derive(PartialEq)] +enum SnpPageType { + None, + Normal, + Unmeasured, + Zero, + Secrets, + CpuId, + Vmsa, +} + +pub struct IgvmMeasure<'a> { + options: &'a CmdOptions, + digest: [u8; 48], + last_page_type: SnpPageType, + last_gpa: u64, + last_next_gpa: u64, + last_len: u64, + compatibility_mask: u32, + vmsa_count: u32, +} + +const PAGE_SIZE_2M: u64 = 2 * 1024 * 1024; + +impl<'a> IgvmMeasure<'a> { + pub fn new(options: &'a CmdOptions) -> Result<Self, Box<dyn Error>> { + Ok(Self { + options, + digest: [0u8; 48], + last_page_type: SnpPageType::None, + last_gpa: 0, + last_next_gpa: 0, + last_len: 0, + compatibility_mask: 0, + vmsa_count: 0, + }) + } + + fn find_compatibility_mask(&mut self, igvm: &IgvmFile) -> Result<(), Box<dyn Error>> { + for platform in igvm.platforms() { + let IgvmPlatformHeader::SupportedPlatform(platform) = platform; + match platform.platform_type { + IgvmPlatformType::SEV_SNP => { + self.compatibility_mask = platform.compatibility_mask; + return Ok(()); + } + _ => continue, + } + } + Err("IGVM file is not compatible with the specified platform.".into()) + } + + pub fn measure(&mut self) -> Result<[u8; 48], Box<dyn Error>> { + let igvm_buffer = fs::read(&self.options.igvm_file).map_err(|e| { + eprintln!("Failed to open firmware file {}", self.options.igvm_file); + e + })?; + let igvm = IgvmFile::new_from_binary(igvm_buffer.as_bytes(), None)?; + + self.find_compatibility_mask(&igvm)?; + + for directive in igvm.directives() { + match directive { + IgvmDirectiveHeader::PageData { + gpa, + compatibility_mask, + flags, + data_type, + data, + } => { + if (*compatibility_mask & self.compatibility_mask) != 0 { + self.measure_page(*gpa, flags, *data_type, data)?; + } + } + IgvmDirectiveHeader::ParameterInsert(param) => { + if (param.compatibility_mask & self.compatibility_mask) != 0 { + if self.options.check_kvm && (self.vmsa_count > 0) { + return Err("KVM check failure: The VMSA must be the final page \ + directive in the IGVM file. \ + This is because QEMU/KVM measures the VMSA page \ + when the measurement is finalized and not in the \ + order specified in the IGVM file. Make sure your \ + IGVM file places the VMSA directive after any other \ + measured or unmeasured page directives." + .into()); + } + self.measure_page( + param.gpa, + &IgvmPageDataFlags::new().with_unmeasured(true), + IgvmPageDataType::NORMAL, + &[], + )?; + } + } + IgvmDirectiveHeader::SnpVpContext { + gpa, + compatibility_mask, + vp_index: _vp_index, + vmsa, + } => { + self.measure_vmsa(*gpa, *compatibility_mask, vmsa)?; + } + _ => (), + } + } + self.log_page(SnpPageType::None, 0, 0); + + Ok(self.digest) + } + + fn log_page(&mut self, page_type: SnpPageType, gpa: u64, len: u64) { + if self.options.verbose { + if (page_type != self.last_page_type) || (gpa != self.last_next_gpa) { + if self.last_len > 0 { + let page_name = match self.last_page_type { + SnpPageType::None => "None", + SnpPageType::Normal => "Normal", + SnpPageType::Unmeasured => "Unmeasured", + SnpPageType::Zero => "Zero", + SnpPageType::Secrets => "Secrets", + SnpPageType::CpuId => "Cpuid", + SnpPageType::Vmsa => "VMSA", + }; + println!( + "gpa {:#x} len {:#x} ({} page)", + self.last_gpa, self.last_len, page_name + ); + } + self.last_len = len; + self.last_gpa = gpa; + self.last_next_gpa = gpa + len; + self.last_page_type = page_type; + } else { + self.last_len += len; + self.last_next_gpa += len; + } + } + } + + fn measure_page( + &mut self, + gpa: u64, + flags: &IgvmPageDataFlags, + data_type: IgvmPageDataType, + data: &[u8], + ) -> Result<(), Box<dyn Error>> { + let page_len = if flags.is_2mb_page() { + PAGE_SIZE_2M + } else { + PAGE_SIZE_4K + }; + assert!(data.is_empty() || data.len() == page_len as usize); + + if data.is_empty() { + for page_offset in (0..page_len).step_by(PAGE_SIZE_4K as usize) { + self.measure_page_4k(gpa + page_offset, flags, data_type, &vec![]); + } + } else { + for (index, page_data) in data.chunks(PAGE_SIZE_4K as usize).enumerate() { + self.measure_page_4k( + gpa + index as u64 * PAGE_SIZE_4K, + flags, + data_type, + &page_data.to_vec(), + ); + } + } + Ok(()) + } + + fn measure_page_4k( + &mut self, + gpa: u64, + flags: &IgvmPageDataFlags, + data_type: IgvmPageDataType, + data: &Vec<u8>, + ) { + let page_info = match data_type { + IgvmPageDataType::NORMAL => { + if flags.unmeasured() { + self.log_page(SnpPageType::Unmeasured, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_unmeasured_page(self.digest, gpa)) + } else if data.is_empty() { + self.log_page(SnpPageType::Zero, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_zero_page(self.digest, gpa)) + } else { + self.log_page(SnpPageType::Normal, gpa, data.len() as u64); + Some(PageInfo::new_normal_page(self.digest, gpa, data)) + } + } + IgvmPageDataType::SECRETS => { + self.log_page(SnpPageType::Secrets, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_secrets_page(self.digest, gpa)) + } + IgvmPageDataType::CPUID_DATA => { + self.log_page(SnpPageType::CpuId, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_cpuid_page(self.digest, gpa)) + } + IgvmPageDataType::CPUID_XF => { + self.log_page(SnpPageType::CpuId, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_cpuid_page(self.digest, gpa)) + } + _ => None, + }; + if let Some(page_info) = page_info { + self.digest = page_info.update_hash(); + } + } + + fn check_vmsa(&mut self, gpa: u64, vmsa: &SevVmsa) -> Result<(), Box<dyn Error>> { + if self.options.check_kvm { + if self.vmsa_count > 0 { + return Err("KVM check failure: More than one VMSA has been provided \ + in the IGVM file. QEMU/KVM only supports setting of the \ + VMSA for the first virtual CPU." + .into()); + } + if gpa != 0xFFFFFFFFF000 { + return Err("KVM check failure: The GPA for the VMSA does not match \ + the address hardcoded in KVM. KVM will always populate \ + the VMSA at GPA 0xFFFFFFFFF000. The IGVM file must set \ + the GPA for the VMSA to this address." + .into()); + } + if vmsa.cr0 != 0x31 { + return Err("KVM check failure: CR0 in the VMSA in the IGVM file is \ + not set to 0x31. The value of CR0 is overridden by KVM \ + during initial measurement. Therefore the IGVM file must \ + be configured to match the value set by KVM." + .into()); + } + if !vmsa.sev_features.debug_swap() { + return Err("KVM check failure: DEBUG_SWAP(0x20) is not set in \ + sev_features in the VMSA file. This feature is \ + automatically applied by KVM during the initial \ + measurement so it must be specified in the VMSA in \ + the IGVM file in order to match." + .into());
Instead of having these verbose inline error strings, could we have an `IgvmMeasureError` enum that implements `std::fmt::Display` such that it prints these strings? e.g. ```rust enum IgvmMeasureError { InvalidVmsaCount(u32), InvalidVmsaGpa(u64), ... } impl std::fmt::Display for IgvmMeasureError { /* error strings here */ } impl std::error::Error for IgvmMeasureError { /* So it works with the `Box<dyn Error>>` return type */ } ```
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,279 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDataType, IgvmPlatformType, PAGE_SIZE_4K}; +use zerocopy::AsBytes; + +use crate::cmd_options::CmdOptions; +use crate::page_info::PageInfo; + +#[derive(PartialEq)] +enum SnpPageType { + None, + Normal, + Unmeasured, + Zero, + Secrets, + CpuId, + Vmsa, +} + +pub struct IgvmMeasure<'a> { + options: &'a CmdOptions, + digest: [u8; 48], + last_page_type: SnpPageType, + last_gpa: u64, + last_next_gpa: u64, + last_len: u64, + compatibility_mask: u32, + vmsa_count: u32, +} + +const PAGE_SIZE_2M: u64 = 2 * 1024 * 1024; + +impl<'a> IgvmMeasure<'a> { + pub fn new(options: &'a CmdOptions) -> Result<Self, Box<dyn Error>> { + Ok(Self { + options, + digest: [0u8; 48], + last_page_type: SnpPageType::None, + last_gpa: 0, + last_next_gpa: 0, + last_len: 0, + compatibility_mask: 0, + vmsa_count: 0, + }) + } + + fn find_compatibility_mask(&mut self, igvm: &IgvmFile) -> Result<(), Box<dyn Error>> { + for platform in igvm.platforms() { + let IgvmPlatformHeader::SupportedPlatform(platform) = platform; + match platform.platform_type { + IgvmPlatformType::SEV_SNP => { + self.compatibility_mask = platform.compatibility_mask; + return Ok(()); + } + _ => continue, + } + } + Err("IGVM file is not compatible with the specified platform.".into()) + } + + pub fn measure(&mut self) -> Result<[u8; 48], Box<dyn Error>> { + let igvm_buffer = fs::read(&self.options.igvm_file).map_err(|e| { + eprintln!("Failed to open firmware file {}", self.options.igvm_file); + e + })?; + let igvm = IgvmFile::new_from_binary(igvm_buffer.as_bytes(), None)?; + + self.find_compatibility_mask(&igvm)?; + + for directive in igvm.directives() { + match directive { + IgvmDirectiveHeader::PageData { + gpa, + compatibility_mask, + flags, + data_type, + data, + } => { + if (*compatibility_mask & self.compatibility_mask) != 0 { + self.measure_page(*gpa, flags, *data_type, data)?; + } + } + IgvmDirectiveHeader::ParameterInsert(param) => { + if (param.compatibility_mask & self.compatibility_mask) != 0 { + if self.options.check_kvm && (self.vmsa_count > 0) { + return Err("KVM check failure: The VMSA must be the final page \ + directive in the IGVM file. \ + This is because QEMU/KVM measures the VMSA page \ + when the measurement is finalized and not in the \ + order specified in the IGVM file. Make sure your \ + IGVM file places the VMSA directive after any other \ + measured or unmeasured page directives." + .into()); + } + self.measure_page( + param.gpa, + &IgvmPageDataFlags::new().with_unmeasured(true), + IgvmPageDataType::NORMAL, + &[], + )?; + } + } + IgvmDirectiveHeader::SnpVpContext { + gpa, + compatibility_mask, + vp_index: _vp_index, + vmsa, + } => { + self.measure_vmsa(*gpa, *compatibility_mask, vmsa)?; + } + _ => (), + } + } + self.log_page(SnpPageType::None, 0, 0); + + Ok(self.digest) + } + + fn log_page(&mut self, page_type: SnpPageType, gpa: u64, len: u64) { + if self.options.verbose { + if (page_type != self.last_page_type) || (gpa != self.last_next_gpa) { + if self.last_len > 0 { + let page_name = match self.last_page_type { + SnpPageType::None => "None", + SnpPageType::Normal => "Normal", + SnpPageType::Unmeasured => "Unmeasured", + SnpPageType::Zero => "Zero", + SnpPageType::Secrets => "Secrets", + SnpPageType::CpuId => "Cpuid", + SnpPageType::Vmsa => "VMSA", + }; + println!( + "gpa {:#x} len {:#x} ({} page)", + self.last_gpa, self.last_len, page_name + ); + } + self.last_len = len; + self.last_gpa = gpa; + self.last_next_gpa = gpa + len; + self.last_page_type = page_type; + } else { + self.last_len += len; + self.last_next_gpa += len; + } + } + } + + fn measure_page( + &mut self, + gpa: u64, + flags: &IgvmPageDataFlags, + data_type: IgvmPageDataType, + data: &[u8], + ) -> Result<(), Box<dyn Error>> { + let page_len = if flags.is_2mb_page() { + PAGE_SIZE_2M + } else { + PAGE_SIZE_4K + }; + assert!(data.is_empty() || data.len() == page_len as usize); + + if data.is_empty() { + for page_offset in (0..page_len).step_by(PAGE_SIZE_4K as usize) { + self.measure_page_4k(gpa + page_offset, flags, data_type, &vec![]); + } + } else { + for (index, page_data) in data.chunks(PAGE_SIZE_4K as usize).enumerate() { + self.measure_page_4k( + gpa + index as u64 * PAGE_SIZE_4K, + flags, + data_type, + &page_data.to_vec(), + ); + } + } + Ok(()) + } + + fn measure_page_4k( + &mut self, + gpa: u64, + flags: &IgvmPageDataFlags, + data_type: IgvmPageDataType, + data: &Vec<u8>, + ) { + let page_info = match data_type { + IgvmPageDataType::NORMAL => { + if flags.unmeasured() { + self.log_page(SnpPageType::Unmeasured, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_unmeasured_page(self.digest, gpa)) + } else if data.is_empty() { + self.log_page(SnpPageType::Zero, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_zero_page(self.digest, gpa)) + } else { + self.log_page(SnpPageType::Normal, gpa, data.len() as u64); + Some(PageInfo::new_normal_page(self.digest, gpa, data)) + } + } + IgvmPageDataType::SECRETS => { + self.log_page(SnpPageType::Secrets, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_secrets_page(self.digest, gpa)) + } + IgvmPageDataType::CPUID_DATA => { + self.log_page(SnpPageType::CpuId, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_cpuid_page(self.digest, gpa)) + } + IgvmPageDataType::CPUID_XF => { + self.log_page(SnpPageType::CpuId, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_cpuid_page(self.digest, gpa)) + } + _ => None, + }; + if let Some(page_info) = page_info { + self.digest = page_info.update_hash(); + } + } + + fn check_vmsa(&mut self, gpa: u64, vmsa: &SevVmsa) -> Result<(), Box<dyn Error>> { + if self.options.check_kvm { + if self.vmsa_count > 0 { + return Err("KVM check failure: More than one VMSA has been provided \ + in the IGVM file. QEMU/KVM only supports setting of the \ + VMSA for the first virtual CPU." + .into()); + } + if gpa != 0xFFFFFFFFF000 { + return Err("KVM check failure: The GPA for the VMSA does not match \ + the address hardcoded in KVM. KVM will always populate \ + the VMSA at GPA 0xFFFFFFFFF000. The IGVM file must set \ + the GPA for the VMSA to this address." + .into()); + } + if vmsa.cr0 != 0x31 { + return Err("KVM check failure: CR0 in the VMSA in the IGVM file is \ + not set to 0x31. The value of CR0 is overridden by KVM \ + during initial measurement. Therefore the IGVM file must \ + be configured to match the value set by KVM." + .into()); + } + if !vmsa.sev_features.debug_swap() { + return Err("KVM check failure: DEBUG_SWAP(0x20) is not set in \ + sev_features in the VMSA file. This feature is \ + automatically applied by KVM during the initial \ + measurement so it must be specified in the VMSA in \ + the IGVM file in order to match." + .into()); + } + } + Ok(()) + } + + fn measure_vmsa( + &mut self, + gpa: u64, + _compatibility_mask: u32, + vmsa: &SevVmsa, + ) -> Result<(), Box<dyn Error>> { + self.check_vmsa(gpa, vmsa)?; + + let mut vmsa_bytes = vmsa.as_bytes().to_vec(); + let mut vmsa_page = vec![0u8; PAGE_SIZE_4K as usize - vmsa_bytes.len()]; + vmsa_bytes.append(&mut vmsa_page);
```suggestion let mut vmsa_page = vmsa.as_bytes().to_vec(); vmsa_page.resize(PAGE_SIZE_4K as usize, 0); ```
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; + +use clap::Parser; +use cmd_options::CmdOptions; +use igvm_measure::IgvmMeasure; + +mod cmd_options; +mod igvm_measure; +mod page_info; + +fn main() -> Result<(), Box<dyn Error>> { + let options = CmdOptions::parse(); + let mut igvm = IgvmMeasure::new(&options)?; + let digest = igvm.measure()?; + + if !options.bare { + println!( + "\n===============================================================================================================" + ); + print!("igvmmeasure '{}'\nLaunch Digest: ", options.igvm_file); + } + + digest.to_vec().iter().for_each(|val| print!("{:02X}", val));
I think you can avoid this `to_vec()`
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -104,3 +107,23 @@ pub fn get_regular_report(buffer: &mut [u8]) -> Result<usize, SvsmReqError> { pub fn get_extended_report(buffer: &mut [u8], certs: &mut [u8]) -> Result<usize, SvsmReqError> { get_report(buffer, Some(certs)) } + +/// Retrieve a VMP0 attestation report from the PSP and report the launch +/// measurement in the log. +pub fn log_attestation() { + let vaddr = allocate_zeroed_page().unwrap(); + let buffer = unsafe { from_raw_parts_mut(vaddr.as_mut_ptr::<u8>(), PAGE_SIZE) }; + + match get_regular_report(buffer) { + Ok(response_len) => { + assert_eq!(response_len, size_of::<SnpReportResponse>()); + let response = SnpReportResponse::try_from_as_ref(buffer).unwrap(); + let report = response.report().expect("Invalid attestation report"); + log::info!("Launch measurement: {:02x?}", report.measurement); + } + Err(e) => { + panic!("Failed to get attestation report, e={e:?}"); + } + }; + free_page(vaddr); +}
We probably want to return errors here and panic in the caller if necessary. Otherwise add a `# Panics` section to the function docs.
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,279 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDataType, IgvmPlatformType, PAGE_SIZE_4K}; +use zerocopy::AsBytes; + +use crate::cmd_options::CmdOptions; +use crate::page_info::PageInfo; + +#[derive(PartialEq)] +enum SnpPageType { + None, + Normal, + Unmeasured, + Zero, + Secrets, + CpuId, + Vmsa, +} + +pub struct IgvmMeasure<'a> { + options: &'a CmdOptions, + digest: [u8; 48], + last_page_type: SnpPageType, + last_gpa: u64, + last_next_gpa: u64, + last_len: u64, + compatibility_mask: u32, + vmsa_count: u32, +} + +const PAGE_SIZE_2M: u64 = 2 * 1024 * 1024; + +impl<'a> IgvmMeasure<'a> { + pub fn new(options: &'a CmdOptions) -> Result<Self, Box<dyn Error>> {
This can just return `Self`
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -71,11 +71,19 @@ impl IgvmBuilder { directive_a: &IgvmDirectiveHeader, directive_b: &IgvmDirectiveHeader, ) -> Ordering { - let IgvmDirectiveHeader::PageData { gpa: a, .. } = directive_a else { - panic!("Attempted to compare non-page directive"); + let a = if let IgvmDirectiveHeader::PageData { gpa, .. } = directive_a { + gpa + } else if let IgvmDirectiveHeader::SnpVpContext { gpa, .. } = directive_a { + gpa + } else { + panic!("Attempted to compare non-page/vp directive"); }; - let IgvmDirectiveHeader::PageData { gpa: b, .. } = directive_b else { - panic!("Attempted to compare non-page directive"); + let b = if let IgvmDirectiveHeader::PageData { gpa, .. } = directive_b { + gpa + } else if let IgvmDirectiveHeader::SnpVpContext { gpa, .. } = directive_b { + gpa + } else { + panic!("Attempted to compare non-page/vp directive"); };
Same thing, a match here is a bit more clear
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -104,3 +107,31 @@ pub fn get_regular_report(buffer: &mut [u8]) -> Result<usize, SvsmReqError> { pub fn get_extended_report(buffer: &mut [u8], certs: &mut [u8]) -> Result<usize, SvsmReqError> { get_report(buffer, Some(certs)) } + +/// Retrieve a VMP0 attestation report from the PSP and report the launch +/// measurement in the log. +/// +/// # Return codes +/// +/// * Success +/// * () +/// +/// * Error +/// * [`SvsmReqError`] +pub fn log_attestation() -> Result<(), SvsmReqError> { + let vaddr = allocate_zeroed_page().unwrap(); + let buffer = unsafe { from_raw_parts_mut(vaddr.as_mut_ptr::<u8>(), PAGE_SIZE) }; + + let result = match get_regular_report(buffer) { + Ok(response_len) => { + assert_eq!(response_len, size_of::<SnpReportResponse>()); + let response = SnpReportResponse::try_from_as_ref(buffer).unwrap(); + let report = response.report().expect("Invalid attestation report");
Perhaps we should turn these (the assert, the unwrap and the `report()` call) into errors as well.
svsm
github_2023
others
294
coconut-svsm
jepio
@@ -0,0 +1,333 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDataType, IgvmPlatformType, PAGE_SIZE_4K}; +use zerocopy::AsBytes; + +use crate::cmd_options::CmdOptions; +use crate::page_info::PageInfo; + +enum IgvmMeasureError { + InvalidVmsaCount, + InvalidVmsaGpa, + InvalidVmsaCr0, + InvalidDebugSwap, + InvalidVmsaOrder, +} + +impl std::fmt::Display for IgvmMeasureError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + IgvmMeasureError::InvalidVmsaCount => { + write!( + f, + "KVM check failure: More than one VMSA has been provided \ + in the IGVM file. QEMU/KVM only supports setting of the \ + VMSA for the first virtual CPU." + ) + } + IgvmMeasureError::InvalidVmsaGpa => { + write!( + f, + "KVM check failure: The GPA for the VMSA does not match \ + the address hardcoded in KVM. KVM will always populate \ + the VMSA at GPA 0xFFFFFFFFF000. The IGVM file must set \ + the GPA for the VMSA to this address." + ) + } + IgvmMeasureError::InvalidVmsaCr0 => { + write!( + f, + "KVM check failure: CR0 in the VMSA in the IGVM file is \ + not set to 0x31. The value of CR0 is overridden by KVM \ + during initial measurement. Therefore the IGVM file must \ + be configured to match the value set by KVM." + ) + } + IgvmMeasureError::InvalidDebugSwap => { + write!( + f, + "KVM check failure: DEBUG_SWAP(0x20) is not set in \ + sev_features in the VMSA file. This feature is \ + automatically applied by KVM during the initial \ + measurement so it must be specified in the VMSA in \ + the IGVM file in order to match." + ) + } + IgvmMeasureError::InvalidVmsaOrder => { + write!( + f, + "KVM check failure: The VMSA must be the final page \ + directive in the IGVM file. \ + This is because QEMU/KVM measures the VMSA page \ + when the measurement is finalized and not in the \ + order specified in the IGVM file. Make sure your \ + IGVM file places the VMSA directive after any other \ + measured or unmeasured page directives." + ) + } + } + } +} +impl std::fmt::Debug for IgvmMeasureError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self) + } +} +impl Error for IgvmMeasureError {} + +#[derive(PartialEq)] +enum SnpPageType { + None, + Normal, + Unmeasured, + Zero, + Secrets, + CpuId, + Vmsa, +} + +impl std::fmt::Display for SnpPageType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + SnpPageType::None => "None", + SnpPageType::Normal => "Normal", + SnpPageType::Unmeasured => "Unmeasured", + SnpPageType::Zero => "Zero", + SnpPageType::Secrets => "Secrets", + SnpPageType::CpuId => "Cpuid", + SnpPageType::Vmsa => "VMSA", + } + ) + } +} + +pub struct IgvmMeasure<'a> { + options: &'a CmdOptions, + digest: [u8; 48], + last_page_type: SnpPageType, + last_gpa: u64, + last_next_gpa: u64, + last_len: u64, + compatibility_mask: u32, + vmsa_count: u32, +} + +const PAGE_SIZE_2M: u64 = 2 * 1024 * 1024; + +impl<'a> IgvmMeasure<'a> { + pub fn new(options: &'a CmdOptions) -> Self { + Self { + options, + digest: [0u8; 48], + last_page_type: SnpPageType::None, + last_gpa: 0, + last_next_gpa: 0, + last_len: 0, + compatibility_mask: 0, + vmsa_count: 0, + } + } + + fn find_compatibility_mask(&mut self, igvm: &IgvmFile) -> Result<(), Box<dyn Error>> { + for platform in igvm.platforms() { + let IgvmPlatformHeader::SupportedPlatform(platform) = platform; + match platform.platform_type { + IgvmPlatformType::SEV_SNP => { + self.compatibility_mask = platform.compatibility_mask; + return Ok(()); + } + _ => continue, + } + } + Err("IGVM file is not compatible with the specified platform.".into()) + } + + pub fn measure(&mut self) -> Result<[u8; 48], Box<dyn Error>> { + let igvm_buffer = fs::read(&self.options.igvm_file).map_err(|e| { + eprintln!("Failed to open firmware file {}", self.options.igvm_file); + e + })?; + let igvm = IgvmFile::new_from_binary(igvm_buffer.as_bytes(), None)?; + + self.find_compatibility_mask(&igvm)?; + + for directive in igvm.directives() { + match directive { + IgvmDirectiveHeader::PageData { + gpa, + compatibility_mask, + flags, + data_type, + data, + } => { + if (*compatibility_mask & self.compatibility_mask) != 0 { + self.measure_page(*gpa, flags, *data_type, data)?; + } + } + IgvmDirectiveHeader::ParameterInsert(param) => { + if (param.compatibility_mask & self.compatibility_mask) != 0 { + if self.options.check_kvm && (self.vmsa_count > 0) { + return Err(IgvmMeasureError::InvalidVmsaOrder.into()); + } + self.measure_page( + param.gpa, + &IgvmPageDataFlags::new().with_unmeasured(true), + IgvmPageDataType::NORMAL, + &[], + )?; + } + } + IgvmDirectiveHeader::SnpVpContext { + gpa, + compatibility_mask, + vp_index: _vp_index, + vmsa, + } => { + self.measure_vmsa(*gpa, *compatibility_mask, vmsa)?; + } + _ => (), + } + } + self.log_page(SnpPageType::None, 0, 0); + + Ok(self.digest) + } + + fn log_page(&mut self, page_type: SnpPageType, gpa: u64, len: u64) { + if self.options.verbose { + if (page_type != self.last_page_type) || (gpa != self.last_next_gpa) { + if self.last_len > 0 { + println!( + "gpa {:#x} len {:#x} ({} page)", + self.last_gpa, self.last_len, self.last_page_type + ); + } + self.last_len = len; + self.last_gpa = gpa; + self.last_next_gpa = gpa + len; + self.last_page_type = page_type; + } else { + self.last_len += len; + self.last_next_gpa += len; + } + } + } + + fn measure_page( + &mut self, + gpa: u64, + flags: &IgvmPageDataFlags, + data_type: IgvmPageDataType, + data: &[u8], + ) -> Result<(), Box<dyn Error>> { + let page_len = if flags.is_2mb_page() { + PAGE_SIZE_2M + } else { + PAGE_SIZE_4K + }; + assert!(data.is_empty() || data.len() == page_len as usize); + + if data.is_empty() { + for page_offset in (0..page_len).step_by(PAGE_SIZE_4K as usize) { + self.measure_page_4k(gpa + page_offset, flags, data_type, &vec![]); + } + } else { + for (index, page_data) in data.chunks(PAGE_SIZE_4K as usize).enumerate() { + self.measure_page_4k( + gpa + index as u64 * PAGE_SIZE_4K, + flags, + data_type, + &page_data.to_vec(), + ); + } + } + Ok(()) + } + + fn measure_page_4k( + &mut self, + gpa: u64, + flags: &IgvmPageDataFlags, + data_type: IgvmPageDataType, + data: &Vec<u8>, + ) { + let page_info = match data_type { + IgvmPageDataType::NORMAL => { + if flags.unmeasured() { + self.log_page(SnpPageType::Unmeasured, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_unmeasured_page(self.digest, gpa)) + } else if data.is_empty() { + self.log_page(SnpPageType::Zero, gpa, PAGE_SIZE_4K); + Some(PageInfo::new_zero_page(self.digest, gpa)) + } else {
this is not a legal transformation, we need to insert this as an actual page of zeros: ```suggestion } else if data.is_empty() { self.log_page(SnpPageType::Normal, gpa, PAGE_SIZE_4K); Some(PageInfo::new_normal_page(self.digest, gpa, &self.zero_page)) } else { ``` and then you would cache `zero_page: vec![0u8; PAGE_SIZE_4K as usize]` somewhere.
svsm
github_2023
others
297
coconut-svsm
joergroedel
@@ -716,22 +708,29 @@ pub fn get_init_pgtable_locked<'a>() -> LockGuard<'a, PageTableRef> { #[derive(Debug)] pub struct PageTableRef { - pgtable_ptr: *mut PageTable, + ptr: *mut PageTable, + owned: bool,
I do not fully understand why this is needed. The page-table which do not allocate the root-page from the allocator are global static. And thus their drop-method is never called.
svsm
github_2023
others
288
coconut-svsm
00xc
@@ -257,3 +257,369 @@ fn vc_decode_insn(ctx: &X86ExceptionContext) -> Result<Instruction, SvsmError> { fn vc_decoding_needed(error_code: usize) -> bool { !(SVM_EXIT_EXCP_BASE..=SVM_EXIT_LAST_EXCP).contains(&error_code) } + +#[cfg(test)] +mod test { + use crate::cpu::msr::{rdtsc, rdtscp, RdtscpOut}; + use crate::cpu::percpu::this_cpu_mut; + use crate::sev::ghcb::GHCB; + use crate::sev::utils::{get_dr7, raw_vmmcall, set_dr7}; + use core::arch::asm; + use core::arch::x86_64::__cpuid_count; + + #[test] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_has_memory_encryption_info_cpuid() { + const CPUID_EXTENDED_FUNCTION_INFO: u32 = 0x8000_0000; + const CPUID_MEMORY_ENCRYPTION_INFO: u32 = 0x8000_001F; + let extended_info = unsafe { __cpuid_count(CPUID_EXTENDED_FUNCTION_INFO, 0) }; + assert!(extended_info.eax >= CPUID_MEMORY_ENCRYPTION_INFO); + } + + #[test] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_has_amd_cpuid() { + const CPUID_VENDOR_INFO: u32 = 0; + + let vendor_info = unsafe { __cpuid_count(CPUID_VENDOR_INFO, 0) }; + + let vendor_name_bytes = [vendor_info.ebx, vendor_info.edx, vendor_info.ecx] + .map(|v| v.to_le_bytes()) + .concat(); + + assert_eq!(core::str::from_utf8(&vendor_name_bytes), Ok("AuthenticAMD")); + } + + const GHCB_FILL_TEST_VALUE: u8 = b'1'; + + fn fill_ghcb_with_test_data() { + let ghcb = this_cpu_mut().ghcb_unsafe(); + unsafe { + // The count param is 1 to only write one ghcb's worth of data + core::ptr::write_bytes(ghcb, GHCB_FILL_TEST_VALUE, 1); + } + } + fn verify_ghcb_was_altered() { + let ghcb = this_cpu_mut().ghcb_unsafe(); + let ghcb_bytes: &[u8; core::mem::size_of::<GHCB>()] = unsafe { &*(ghcb as *const _) }; + let changed_byte = ghcb_bytes.iter().find(|&&v| v != GHCB_FILL_TEST_VALUE); + assert!(changed_byte.is_some()); + } + + // Calls `f` with an assertion that it ended up altering the ghcb. + fn verify_ghcb_gets_altered<R, F>(f: F) -> R + where + F: FnOnce() -> R, + { + fill_ghcb_with_test_data(); + let result = f(); + verify_ghcb_was_altered(); + result + } + + const TESTDEV_ECHO_LAST_PORT: u16 = 0xe0; + + fn inb(port: u16) -> u8 { + unsafe { + let ret: u8; + asm!("inb %dx, %al", in("dx") port, out("al") ret, options(att_syntax)); + ret + } + } + fn inb_from_testdev_echo() -> u8 { + unsafe { + let ret: u8; + asm!("inb $0xe0, %al", out("al") ret, options(att_syntax)); + ret + } + } + + fn outb(port: u16, value: u8) { + unsafe { asm!("outb %al, %dx", in("al") value, in("dx") port, options(att_syntax)) } + } + + fn outb_to_testdev_echo(value: u8) { + unsafe { asm!("outb %al, $0xe0", in("al") value, options(att_syntax)) } + } + + fn inw(port: u16) -> u16 { + unsafe { + let ret: u16; + asm!("inw %dx, %ax", in("dx") port, out("ax") ret, options(att_syntax)); + ret + } + } + fn inw_from_testdev_echo() -> u16 { + unsafe { + let ret: u16; + asm!("inw $0xe0, %ax", out("ax") ret, options(att_syntax)); + ret + } + } + + fn outw(port: u16, value: u16) { + unsafe { asm!("outw %ax, %dx", in("ax") value, in("dx") port, options(att_syntax)) } + } + + fn outw_to_testdev_echo(value: u16) { + unsafe { asm!("outw %ax, $0xe0", in("ax") value, options(att_syntax)) } + } + + fn inl(port: u16) -> u32 { + unsafe { + let ret: u32; + asm!("inl %dx, %eax", in("dx") port, out("eax") ret, options(att_syntax)); + ret + } + } + fn inl_from_testdev_echo() -> u32 { + unsafe { + let ret: u32; + asm!("inl $0xe0, %eax", out("eax") ret, options(att_syntax)); + ret + } + } + + fn outl(port: u16, value: u32) { + unsafe { asm!("outl %eax, %dx", in("eax") value, in("dx") port, options(att_syntax)) } + } + + fn outl_to_testdev_echo(value: u32) { + unsafe { asm!("outl %eax, $0xe0", in("eax") value, options(att_syntax)) } + } + + fn rep_outsw(port: u16, data: &[u16]) { + unsafe { + asm!("rep outsw", in("dx") port, in("rsi") data.as_ptr(), in("rcx") data.len(), options(att_syntax)) + } + } + + #[test] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_port_io_8() { + const TEST_VAL: u8 = 0x12; + verify_ghcb_gets_altered(|| outb(TESTDEV_ECHO_LAST_PORT, TEST_VAL)); + assert_eq!( + TEST_VAL, + verify_ghcb_gets_altered(|| inb(TESTDEV_ECHO_LAST_PORT)) + ); + } + + #[test] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_port_io_16() { + const TEST_VAL: u16 = 0x4321; + verify_ghcb_gets_altered(|| outw(TESTDEV_ECHO_LAST_PORT, TEST_VAL)); + assert_eq!( + TEST_VAL, + verify_ghcb_gets_altered(|| inw(TESTDEV_ECHO_LAST_PORT)) + ); + } + + #[test] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_port_io_32() { + const TEST_VAL: u32 = 0xabcd1234; + verify_ghcb_gets_altered(|| outl(TESTDEV_ECHO_LAST_PORT, TEST_VAL)); + assert_eq!( + TEST_VAL, + verify_ghcb_gets_altered(|| inl(TESTDEV_ECHO_LAST_PORT)) + ); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_port_io_8_hardcoded() { + const TEST_VAL: u8 = 0x12; + verify_ghcb_gets_altered(|| outb_to_testdev_echo(TEST_VAL)); + assert_eq!(TEST_VAL, verify_ghcb_gets_altered(inb_from_testdev_echo)); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_port_io_16_hardcoded() { + const TEST_VAL: u16 = 0x4321; + verify_ghcb_gets_altered(|| outw_to_testdev_echo(TEST_VAL)); + assert_eq!(TEST_VAL, verify_ghcb_gets_altered(inw_from_testdev_echo)); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_port_io_32_hardcoded() { + const TEST_VAL: u32 = 0xabcd1234; + verify_ghcb_gets_altered(|| outl_to_testdev_echo(TEST_VAL)); + assert_eq!(TEST_VAL, verify_ghcb_gets_altered(inl_from_testdev_echo)); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_port_io_string_16_get_last() { + const TEST_DATA: &[u16] = &[0x1234, 0x5678, 0x9abc, 0xdef0]; + verify_ghcb_gets_altered(|| rep_outsw(TESTDEV_ECHO_LAST_PORT, TEST_DATA)); + assert_eq!( + TEST_DATA.last().unwrap(), + &verify_ghcb_gets_altered(|| inw(TESTDEV_ECHO_LAST_PORT)) + ); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_sev_snp_enablement_msr() { + const MSR_SEV_STATUS: u32 = 0b10; + const MSR_SEV_STATUS_SEV_SNP_ENABLED: u64 = 0b100; + + let sev_status = verify_ghcb_gets_altered(|| unsafe { rdmsr(MSR_SEV_STATUS) }); + assert_ne!(sev_status & MSR_SEV_STATUS_SEV_SNP_ENABLED, 0); + } + + const MSR_APIC_BASE: u32 = 0x1b; + + const APIC_DEFAULT_PHYS_BASE: u64 = 0xfee00000; // KVM's default + const APIC_BASE_PHYS_ADDR_MASK: u64 = 0xffffff000; // bit 12-35 + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_rdmsr_apic() { + let apic_base = verify_ghcb_gets_altered(|| unsafe { rdmsr(MSR_APIC_BASE) }); + assert_eq!(apic_base & APIC_BASE_PHYS_ADDR_MASK, APIC_DEFAULT_PHYS_BASE); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_rdmsr_debug_ctl() { + const MSR_DEBUG_CTL: u32 = 0x1d9; + let apic_base = verify_ghcb_gets_altered(|| unsafe { rdmsr(MSR_DEBUG_CTL) }); + assert_eq!(apic_base, 0); + } + + const MSR_TSC_AUX: u32 = 0xc0000103; + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_wrmsr_tsc_aux() { + let test_val = 0x1234; + verify_ghcb_gets_altered(|| unsafe { wrmsr(MSR_TSC_AUX, test_val) }); + let readback = verify_ghcb_gets_altered(|| unsafe { rdmsr(MSR_TSC_AUX) }); + assert_eq!(test_val, readback); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_vmmcall_error() { + let res = verify_ghcb_gets_altered(|| unsafe { raw_vmmcall(1005, 0, 0, 0) }); + assert_eq!(res, -1000); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_vmmcall_vapic_poll_irq() { + const VMMCALL_HC_VAPIC_POLL_IRQ: u32 = 1; + + let res = + verify_ghcb_gets_altered(|| unsafe { raw_vmmcall(VMMCALL_HC_VAPIC_POLL_IRQ, 0, 0, 0) }); + assert_eq!(res, 0); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_read_write_dr7() { + const DR7_DEFAULT: u64 = 0x400; + const DR7_TEST: u64 = 0x401; + + let old_dr7 = verify_ghcb_gets_altered(get_dr7); + assert_eq!(old_dr7, DR7_DEFAULT); + + verify_ghcb_gets_altered(|| unsafe { set_dr7(DR7_TEST) }); + let new_dr7 = verify_ghcb_gets_altered(get_dr7); + assert_eq!(new_dr7, DR7_TEST); + } + + #[test] + // #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + #[ignore = "Currently unhandled by #VC handler"] + fn test_rdtsc() { + let mut prev: u64 = rdtsc(); + for _ in 0..50 { + let cur = rdtsc(); + assert!(cur > prev); + prev = cur; + } + } + + unsafe fn rdmsr(ecx: u32) -> u64 { + let eax: u32; + let edx: u32; + asm!("rdmsr", out("eax") eax, out("edx") edx, in("ecx") ecx); + ((edx as u64) << 32) | (eax as u64) + } + + unsafe fn wrmsr(ecx: u32, value: u64) { + let eax = value as u32; + let edx = (value >> 32) as u32; + asm!("wrmsr", in("eax") eax, in("edx") edx, in("ecx") ecx); + }
We already have `read_msr()` / `write_msr()` in `kernel/src/cpu/msr.rs`, could you reuse those?
svsm
github_2023
others
288
coconut-svsm
00xc
@@ -257,3 +257,369 @@ fn vc_decode_insn(ctx: &X86ExceptionContext) -> Result<Instruction, SvsmError> { fn vc_decoding_needed(error_code: usize) -> bool { !(SVM_EXIT_EXCP_BASE..=SVM_EXIT_LAST_EXCP).contains(&error_code) } + +#[cfg(test)] +mod test { + use crate::cpu::msr::{rdtsc, rdtscp, RdtscpOut}; + use crate::cpu::percpu::this_cpu_mut; + use crate::sev::ghcb::GHCB; + use crate::sev::utils::{get_dr7, raw_vmmcall, set_dr7}; + use core::arch::asm; + use core::arch::x86_64::__cpuid_count; + + #[test] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_has_memory_encryption_info_cpuid() { + const CPUID_EXTENDED_FUNCTION_INFO: u32 = 0x8000_0000; + const CPUID_MEMORY_ENCRYPTION_INFO: u32 = 0x8000_001F; + let extended_info = unsafe { __cpuid_count(CPUID_EXTENDED_FUNCTION_INFO, 0) }; + assert!(extended_info.eax >= CPUID_MEMORY_ENCRYPTION_INFO); + } + + #[test] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_has_amd_cpuid() { + const CPUID_VENDOR_INFO: u32 = 0; + + let vendor_info = unsafe { __cpuid_count(CPUID_VENDOR_INFO, 0) }; + + let vendor_name_bytes = [vendor_info.ebx, vendor_info.edx, vendor_info.ecx] + .map(|v| v.to_le_bytes()) + .concat(); + + assert_eq!(core::str::from_utf8(&vendor_name_bytes), Ok("AuthenticAMD")); + } + + const GHCB_FILL_TEST_VALUE: u8 = b'1'; + + fn fill_ghcb_with_test_data() { + let ghcb = this_cpu_mut().ghcb_unsafe(); + unsafe { + // The count param is 1 to only write one ghcb's worth of data + core::ptr::write_bytes(ghcb, GHCB_FILL_TEST_VALUE, 1); + } + } + fn verify_ghcb_was_altered() { + let ghcb = this_cpu_mut().ghcb_unsafe(); + let ghcb_bytes: &[u8; core::mem::size_of::<GHCB>()] = unsafe { &*(ghcb as *const _) }; + let changed_byte = ghcb_bytes.iter().find(|&&v| v != GHCB_FILL_TEST_VALUE); + assert!(changed_byte.is_some());
This is creating an intermediate reference to the GHCB. I'd favor just using `slice::from_raw_parts()`, which is also less convoluted in my opinion. Also, you can test that at least one byte changed more easily with `Iterator::any()`: ```suggestion let ghcb_bytes = unsafe { core::slice::from_raw_parts(ghcb.cast::<u8>(), core::mem::size_of::<GHCB>()) }; assert!(ghcb_bytes.iter().any(|v| *v != GHCB_FILL_TEST_VALUE)); ```
svsm
github_2023
others
295
coconut-svsm
00xc
@@ -198,8 +199,10 @@ impl Instruction { /// /// The caller should validate that `rip` is set to a valid address /// and that the next [`MAX_INSN_SIZE`] bytes are within valid memory. -pub unsafe fn insn_fetch(rip: *const u8) -> [u8; MAX_INSN_SIZE] { - rip.cast::<[u8; MAX_INSN_SIZE]>().read() +pub unsafe fn insn_fetch( + rip: GuestPtr<[u8; MAX_INSN_SIZE]>, +) -> Result<[u8; MAX_INSN_SIZE], SvsmError> { + rip.read() }
I guess you could just inline this :)
svsm
github_2023
others
295
coconut-svsm
00xc
@@ -248,4 +248,15 @@ mod tests { assert_eq!(test_buffer[0], data_to_write); } + + #[test] + #[cfg_attr(miri, ignore = "inline assembly")] + fn test_read_15_bytes_valid_address() { + let test_buffer = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; + let test_addr = VirtAddr::from(test_buffer.as_ptr()); + let ptr: GuestPtr<[u8; 15]> = GuestPtr::new(test_addr); + let result = ptr.read().unwrap(); + + assert_eq!(result, test_buffer); + }
This looks good. While you are at it, you could probably add another test that reads invalid memory and that only runs inside the SVSM.
svsm
github_2023
others
295
coconut-svsm
00xc
@@ -259,4 +262,28 @@ mod tests { assert_eq!(result, test_buffer); } + + #[test] + #[cfg_attr(miri, ignore = "inline assembly")] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_read_invalid_address() { + let ptr: GuestPtr<u8> = GuestPtr::new(VirtAddr::new(0xDEAD_BEEF)); + + let err = ptr.read(); + assert!(err.is_err()); + } + + #[test] + #[cfg_attr(miri, ignore = "inline assembly")] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_read_invalid_region() { + let _test_root_mem = TestRootMem::setup(PAGE_SIZE); + let page = allocate_page().unwrap(); + + // ptr is starting on a mapped page and ends on unmapped memory + let ptr: GuestPtr<[u8; 0x10]> = GuestPtr::new(page + (PAGE_SIZE - 8)); + + let err = ptr.read(); + assert!(err.is_err()); + }
This test fails - the memory beyond the allocated page is not lent by the allocator, but it's mapped as part of its memory region. I suggest you simply remove this test.
svsm
github_2023
others
295
coconut-svsm
00xc
@@ -248,4 +251,39 @@ mod tests { assert_eq!(test_buffer[0], data_to_write); } + + #[test] + #[cfg_attr(miri, ignore = "inline assembly")] + fn test_read_15_bytes_valid_address() { + let test_buffer = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; + let test_addr = VirtAddr::from(test_buffer.as_ptr()); + let ptr: GuestPtr<[u8; 15]> = GuestPtr::new(test_addr); + let result = ptr.read().unwrap(); + + assert_eq!(result, test_buffer); + }
Could you move this into the new commit adding tests?
svsm
github_2023
others
292
coconut-svsm
00xc
@@ -111,8 +111,15 @@ impl GpaMap { 1 << 20 } Hypervisor::HyperV => { - // Load the kernel image after the firmware. - firmware_range.get_end() + // Load the kernel image after the firmware, but now lower than + // 1 MB. + let firmware_end = firmware_range.get_end(); + let addr_1mb = 1 << 20; + if firmware_end < addr_1mb { + addr_1mb + } else { + firmware_end + }
Or just: ```rust let firmware_end = firmware_range.get_end().max(1 << 20); ``` Anyway this LGTM.
svsm
github_2023
others
274
coconut-svsm
stefano-garzarella
@@ -224,6 +224,15 @@ Unit tests can be run inside the SVSM by $ QEMU=/path/to/qemu OVMF=/path/to/firmware/ make test-in-svsm ``` +Different (non-QEMU) hypervisors may provide the ACPI tables and ACPI RSDP at +different paths. If this is the case, they can be provided as environment +variables, e.g. +``` +$ ACPI_RSDP_PATH=etc/acpi/rsdp ACPI_TABLES_PATH=etc/acpi/tables FW_FILE=/path/to/firmware/OVMF.fd make
I'd suggest adding in the documentation the default paths and maybe use something different in the example. The rest LGTM.
svsm
github_2023
others
273
coconut-svsm
stefano-garzarella
@@ -47,12 +47,16 @@ impl fmt::Debug for Console { } } -pub static WRITER: SpinLock<Console> = SpinLock::new(Console { +static WRITER: SpinLock<Console> = SpinLock::new(Console { writer: Some(&DEFAULT_SERIAL_PORT), }); static CONSOLE_INITIALIZED: ImmutAfterInitCell<bool> = ImmutAfterInitCell::new(false); -pub fn init_console() { +pub fn init_console(writer: &'static SerialPort<'_>) { + if !*CONSOLE_INITIALIZED {
I think we are changing the behavior. Before this patch, the caller invoked `WRITER.lock().set()` without checking `CONSOLE_INITIALIZED`, so each time changed the serial port used by our console, here instead only the first invocation sets it, so I'm not sure if it's the behavior we wanted. It is true that we call it always with the same serial port, so it should be okay, but I think here we are mixing the initialization of the serial port, with the initialization of our console. IMHO we should keep them separate.
svsm
github_2023
others
269
coconut-svsm
roy-hopkins
@@ -362,8 +365,24 @@ pub mod svsm_gdbstub { } } - pub fn set_regs(&mut self, ctx: &TaskContext) { - self.ctx = (ctx as *const _) as usize; + fn ctx(&self) -> Option<&TaskContext> { + // SAFETY: this is a pointer to the exception context on the + // stack, so it is not aliased from a different task. We trust + // the debug exception handler to pass a well-aligned pointer + // pointing to valid memory. + unsafe { self.ctx.as_ref() } + } + + fn ctx_mut(&mut self) -> Option<&mut TaskContext> { + // SAFETY: this is a pointer to the exception context on the + // stack, so it is not aliased from a different task. We trust + // the debug exception handler to pass a well-aligned pointer + // pointing to valid memory. + unsafe { self.ctx.as_mut() } + } + + fn set_regs(&mut self, ctx: &mut TaskContext) { + self.ctx = core::ptr::from_mut(ctx)
Just a note - with rustc 1.74.1 you get this error: ``` error[E0658]: use of unstable library feature 'ptr_from_ref' --> kernel/src/debug/gdbstub.rs:385:24 | 385 | self.ctx = core::ptr::from_mut(ctx) | ^^^^^^^^^^^^^^^^^^^ | ``` Updating to 1.76.0 fixed it.
svsm
github_2023
others
237
coconut-svsm
cclaudio
@@ -81,26 +84,36 @@ $ sudo zypper refresh $ sudo zypper si -d qemu-kvm ``` +Support for IGVM within QEMU depends on the IGVM library. This will need to be +built and installed prior to building QEMU. + +``` +git clone https://github.com/microsoft/igvm +cd igvm +make -f igvm_c/Makefile +sudo make -f igvm_c/Makefile install +```
We may need more changes in the igvm repository. Although the `igvm#3` got merged, it is still failing to build. First I installed some dependencies: ``` $ cargo install cbindgen $ sudo zypper install cunit-devel ``` Then I tried to build it: ``` cclaudio@dobby:~/src/coconut/igvm> make -f igvm_c/Makefile cbindgen -c /home/cclaudio/src/coconut/igvm/igvm_c/cbindgen_igvm.toml /home/cclaudio/src/coconut/igvm/igvm_c/../igvm -o "/home/cclaudio/src/coconut/igvm/igvm_c/include/igvm.h" WARN: Skip igvm::IGVM_HANDLES - (not `no_mangle`). WARN: Skip igvm::IGVM_HANDLE_FACTORY - (not `no_mangle`). WARN: Skip igvm::X64_CR4_LA57 - (not `pub`). WARN: Skip igvm::X64_PTE_PRESENT - (not `pub`). WARN: Skip igvm::X64_PTE_READ_WRITE - (not `pub`). WARN: Skip igvm::X64_PTE_ACCESSED - (not `pub`). WARN: Skip igvm::X64_PTE_DIRTY - (not `pub`). WARN: Skip igvm::X64_PTE_LARGE_PAGE - (not `pub`). WARN: Skip igvm::PAGE_TABLE_ENTRY_COUNT - (not `pub`). WARN: Skip igvm::X64_PAGE_SHIFT - (not `pub`). WARN: Skip igvm::X64_PTE_BITS - (not `pub`). WARN: Cannot find a mangling for generic path GenericPath { path: Path { name: "U64" }, export_name: "U64", generics: [Type(Path(GenericPath { path: Path { name: "LittleEndian" }, export_name: "LittleEndian", generics: [], ctype: None }))], ctype: None }. This usually means that a type referenced by this generic was incompatible or not found. WARN: Missing `[defines]` entry for `feature = "igvm-c"` in cbindgen config. <...snip...> cbindgen -c /home/cclaudio/src/coconut/igvm/igvm_c/cbindgen_igvm_defs.toml /home/cclaudio/src/coconut/igvm/igvm_c/../igvm_defs -o "/home/cclaudio/src/coconut/igvm/igvm_c/include/igvm_defs.h" WARN: Skip igvm_defs::IGVM_MAGIC_VALUE - (Unsupported call expression. Call(ExprCall { attrs: [], func: Path(ExprPath { attrs: [], qself: None, path: Path { leading_colon: None, segments: [PathSegment { ident: Ident(u32), arguments: None }, Colon2, PathSegment { ident: Ident(from_le_bytes), arguments: None }] } }), paren_token: Paren, args: [Unary(ExprUnary { attrs: [], op: Deref(Star), expr: Lit(ExprLit { attrs: [], lit: ByteStr(LitByteStr { token: b"IGVM" }) }) })] })) WARN: Skip igvm_defs::IGVM_VHT_RANGE_PLATFORM - (Unsupported expression. Range(ExprRange { attrs: [], from: Some(Lit(ExprLit { attrs: [], lit: Int(LitInt { token: 0x1 }) })), limits: Closed(DotDotEq), to: Some(Lit(ExprLit { attrs: [], lit: Int(LitInt { token: 0x100 }) })) })) WARN: Skip igvm_defs::IGVM_VHT_RANGE_INIT - (Unsupported expression. Range(ExprRange { attrs: [], from: Some(Lit(ExprLit { attrs: [], lit: Int(LitInt { token: 0x101 }) })), limits: Closed(DotDotEq), to: Some(Lit(ExprLit { attrs: [], lit: Int(LitInt { token: 0x200 }) })) })) WARN: Skip igvm_defs::IGVM_VHT_RANGE_DIRECTIVE - (Unsupported expression. Range(ExprRange { attrs: [], from: Some(Lit(ExprLit { attrs: [], lit: Int(LitInt { token: 0x301 }) })), limits: Closed(DotDotEq), to: Some(Lit(ExprLit { attrs: [], lit: Int(LitInt { token: 0x400 }) })) })) WARN: Skip igvm_defs::IGVM_DT_IGVM_TYPE_PROPERTY - (Unsupported literal expression. Str(LitStr { token: "microsoft,igvm-type" })) WARN: Skip igvm_defs::IGVM_DT_IGVM_FLAGS_PROPERTY - (Unsupported literal expression. Str(LitStr { token: "microsoft,igvm-flags" })) WARN: Skip igvm_defs::IGVM_DT_VTL_PROPERTY - (Unsupported literal expression. Str(LitStr { token: "microsoft,vtl" })) WARN: Can't find IgvmPageDataFlags. This usually means that this type was incompatible or not found. WARN: Can't find u64_le. This usually means that this type was incompatible or not found. WARN: Can't find u32_le. This usually means that this type was incompatible or not found. WARN: Can't find RequiredMemoryFlags. This usually means that this type was incompatible or not found. WARN: Can't find MemoryMapEntryFlags. This usually means that this type was incompatible or not found. WARN: Missing `[defines]` entry for `feature = "unstable"` in cbindgen config. CARGO_TARGET_DIR=/home/cclaudio/src/coconut/igvm/igvm_c/../target_c cargo build --features "igvm-c" --manifest-path=/home/cclaudio/src/coconut/igvm/igvm_c/../igvm/Cargo.toml Compiling proc-macro2 v1.0.78 Compiling unicode-ident v1.0.12 Compiling syn v1.0.109 Compiling byteorder v1.5.0 Compiling once_cell v1.19.0 Compiling crc32fast v1.3.2 Compiling thiserror v1.0.56 Compiling static_assertions v1.1.0 Compiling cfg-if v1.0.0 Compiling pin-project-lite v0.2.13 Compiling hex v0.4.3 Compiling range_map_vec v0.1.0 Compiling tracing-core v0.1.32 Compiling quote v1.0.35 Compiling syn v2.0.48 Compiling open-enum-derive v0.4.1 Compiling zerocopy-derive v0.7.32 Compiling tracing-attributes v0.1.27 Compiling thiserror-impl v1.0.56 Compiling bitfield-struct v0.5.6 Compiling open-enum v0.4.1 Compiling zerocopy v0.7.32 Compiling tracing v0.1.40 Compiling igvm_defs v0.1.4 (/home/cclaudio/src/coconut/igvm/igvm_defs) Compiling igvm v0.1.4 (/home/cclaudio/src/coconut/igvm/igvm) Finished dev [unoptimized + debuginfo] target(s) in 5.47s cc -g3 -O0 -I /home/cclaudio/src/coconut/igvm/igvm_c -L "/home/cclaudio/src/coconut/igvm/igvm_c/../target_c/debug" -o "/home/cclaudio/src/coconut/igvm/igvm_c/../target_c/debug"/dump_igvm /home/cclaudio/src/coconut/igvm/igvm_c/include/igvm.h /home/cclaudio/src/coconut/igvm/igvm_c/sample/dump_igvm.c "/home/cclaudio/src/coconut/igvm/igvm_c/../target_c/debug"/libigvm.a -ligvm -lcunit /usr/lib64/gcc/x86_64-suse-linux/7/../../../../x86_64-suse-linux/bin/ld: /home/cclaudio/src/coconut/igvm/igvm_c/../target_c/debug/libigvm.a(std-b149a04e58514815.std.afc0969a1e8d0069-cgu.0.rcgu.o): undefined reference to symbol 'dlsym@@GLIBC_2.2.5' /usr/lib64/gcc/x86_64-suse-linux/7/../../../../x86_64-suse-linux/bin/ld: /lib64/libdl.so.2: error adding symbols: DSO missing from command line collect2: error: ld returned 1 exit status make: *** [igvm_c/Makefile:40: "/home/cclaudio/src/coconut/igvm/igvm_c/../target_c/debug"/dump_igvm] Error 1 ```
svsm
github_2023
others
256
coconut-svsm
stefano-garzarella
@@ -71,54 +69,61 @@ utils/print-meta: utils/print-meta.c utils/cbit: utils/cbit.c cc -O3 -Wall -o $@ $< -stage1/meta.bin: utils/gen_meta utils/print-meta +bin/meta.bin: utils/gen_meta utils/print-meta ./utils/gen_meta $@ -stage1/stage2.bin: +bin/stage2.bin: cargo build ${CARGO_ARGS} ${SVSM_ARGS} --bin stage2 + mkdir -v -p bin
Since we're touching this code and adding more calls to `mkdir -v -p bin`, what about adding a dedicated target, so we can avoid duplicating/calling it multiple times? I mean something like this: ``` bin: mkdir -v -p bin ... bin/stage2.bin: bin ... bin/svsm-kernel.elf: bin ... etc. ```
svsm
github_2023
others
256
coconut-svsm
stefano-garzarella
@@ -71,54 +69,61 @@ utils/print-meta: utils/print-meta.c utils/cbit: utils/cbit.c cc -O3 -Wall -o $@ $< -stage1/meta.bin: utils/gen_meta utils/print-meta +bin/meta.bin: utils/gen_meta utils/print-meta ./utils/gen_meta $@ -stage1/stage2.bin: +bin/stage2.bin: cargo build ${CARGO_ARGS} ${SVSM_ARGS} --bin stage2 + mkdir -v -p bin objcopy -O binary ${STAGE2_ELF} $@ -stage1/svsm-kernel.elf: +bin/svsm-kernel.elf: cargo build ${CARGO_ARGS} ${SVSM_ARGS} --bin svsm + mkdir -v -p bin objcopy -O elf64-x86-64 --strip-unneeded ${SVSM_KERNEL_ELF} $@ -stage1/test-kernel.elf: +bin/test-kernel.elf: LINK_TEST=1 cargo +nightly test -p svsm --config 'target.x86_64-unknown-none.runner=["sh", "-c", "cp $$0 ../${TEST_KERNEL_ELF}"]' - objcopy -O elf64-x86-64 --strip-unneeded ${TEST_KERNEL_ELF} stage1/test-kernel.elf + mkdir -v -p bin + objcopy -O elf64-x86-64 --strip-unneeded ${TEST_KERNEL_ELF} bin/test-kernel.elf -stage1/svsm-fs.bin: +bin/svsm-fs.bin: + mkdir -v -p bin ifneq ($(FS_FILE), none) - cp -f $(FS_FILE) stage1/svsm-fs.bin + cp -f $(FS_FILE) bin/svsm-fs.bin endif - touch stage1/svsm-fs.bin + touch bin/svsm-fs.bin -stage1/stage1.o: stage1/stage1.S stage1/stage2.bin stage1/svsm-fs.bin stage1/svsm-kernel.elf - ln -sf svsm-kernel.elf stage1/kernel.elf +stage1/stage1.o: stage1/stage1.S bin/stage2.bin bin/svsm-fs.bin bin/svsm-kernel.elf + mkdir -v -p bin + ln -sf svsm-kernel.elf bin/kernel.elf cc -c -o $@ stage1/stage1.S - rm -f stage1/kernel.elf + rm -f bin/kernel.elf -stage1/stage1-test.o: stage1/stage1.S stage1/stage2.bin stage1/svsm-fs.bin stage1/test-kernel.elf - ln -sf test-kernel.elf stage1/kernel.elf +stage1/stage1-test.o: stage1/stage1.S bin/stage2.bin bin/svsm-fs.bin bin/test-kernel.elf + mkdir -v -p bin + ln -sf test-kernel.elf bin/kernel.elf cc -c -o $@ stage1/stage1.S - rm -f stage1/kernel.elf + rm -f bin/kernel.elf -stage1/reset.o: stage1/reset.S stage1/meta.bin +stage1/reset.o: stage1/reset.S bin/meta.bin -stage1/stage1: ${STAGE1_OBJS} +bin/stage1: ${STAGE1_OBJS} $(CC) -o $@ $(STAGE1_OBJS) -nostdlib -Wl,--build-id=none -Wl,-Tstage1/stage1.lds -no-pie -stage1/stage1-test: ${STAGE1_TEST_OBJS} +bin/stage1-test: ${STAGE1_TEST_OBJS} $(CC) -o $@ $(STAGE1_TEST_OBJS) -nostdlib -Wl,--build-id=none -Wl,-Tstage1/stage1.lds -no-pie -svsm.bin: stage1/stage1 +svsm.bin: bin/stage1 objcopy -O binary $< $@ -svsm-test.bin: stage1/stage1-test +svsm-test.bin: bin/stage1-test objcopy -O binary $< $@ clean: cargo clean - rm -f stage1/stage2.bin svsm.bin stage1/meta.bin stage1/kernel.elf stage1/stage1 stage1/svsm-fs.bin ${STAGE1_OBJS} utils/gen_meta utils/print-meta + rm -f stage1/*.o stage1/*.bin stage1/*.elf
I think we can remove this line, since `*.elf` and `*.bin` files are now in `bin/`, and `*.o` are covered in the next line by `${STAGE1_OBJS}` ```suggestion ```
svsm
github_2023
others
256
coconut-svsm
stefano-garzarella
@@ -71,54 +69,61 @@ utils/print-meta: utils/print-meta.c utils/cbit: utils/cbit.c cc -O3 -Wall -o $@ $< -stage1/meta.bin: utils/gen_meta utils/print-meta +bin/meta.bin: utils/gen_meta utils/print-meta ./utils/gen_meta $@ -stage1/stage2.bin: +bin/stage2.bin: cargo build ${CARGO_ARGS} ${SVSM_ARGS} --bin stage2 + mkdir -v -p bin objcopy -O binary ${STAGE2_ELF} $@ -stage1/svsm-kernel.elf: +bin/svsm-kernel.elf: cargo build ${CARGO_ARGS} ${SVSM_ARGS} --bin svsm + mkdir -v -p bin objcopy -O elf64-x86-64 --strip-unneeded ${SVSM_KERNEL_ELF} $@ -stage1/test-kernel.elf: +bin/test-kernel.elf: LINK_TEST=1 cargo +nightly test -p svsm --config 'target.x86_64-unknown-none.runner=["sh", "-c", "cp $$0 ../${TEST_KERNEL_ELF}"]' - objcopy -O elf64-x86-64 --strip-unneeded ${TEST_KERNEL_ELF} stage1/test-kernel.elf + mkdir -v -p bin + objcopy -O elf64-x86-64 --strip-unneeded ${TEST_KERNEL_ELF} bin/test-kernel.elf -stage1/svsm-fs.bin: +bin/svsm-fs.bin: + mkdir -v -p bin ifneq ($(FS_FILE), none) - cp -f $(FS_FILE) stage1/svsm-fs.bin + cp -f $(FS_FILE) bin/svsm-fs.bin endif - touch stage1/svsm-fs.bin + touch bin/svsm-fs.bin -stage1/stage1.o: stage1/stage1.S stage1/stage2.bin stage1/svsm-fs.bin stage1/svsm-kernel.elf - ln -sf svsm-kernel.elf stage1/kernel.elf +stage1/stage1.o: stage1/stage1.S bin/stage2.bin bin/svsm-fs.bin bin/svsm-kernel.elf + mkdir -v -p bin + ln -sf svsm-kernel.elf bin/kernel.elf cc -c -o $@ stage1/stage1.S - rm -f stage1/kernel.elf + rm -f bin/kernel.elf -stage1/stage1-test.o: stage1/stage1.S stage1/stage2.bin stage1/svsm-fs.bin stage1/test-kernel.elf - ln -sf test-kernel.elf stage1/kernel.elf +stage1/stage1-test.o: stage1/stage1.S bin/stage2.bin bin/svsm-fs.bin bin/test-kernel.elf + mkdir -v -p bin + ln -sf test-kernel.elf bin/kernel.elf cc -c -o $@ stage1/stage1.S - rm -f stage1/kernel.elf + rm -f bin/kernel.elf -stage1/reset.o: stage1/reset.S stage1/meta.bin +stage1/reset.o: stage1/reset.S bin/meta.bin -stage1/stage1: ${STAGE1_OBJS} +bin/stage1: ${STAGE1_OBJS} $(CC) -o $@ $(STAGE1_OBJS) -nostdlib -Wl,--build-id=none -Wl,-Tstage1/stage1.lds -no-pie -stage1/stage1-test: ${STAGE1_TEST_OBJS} +bin/stage1-test: ${STAGE1_TEST_OBJS} $(CC) -o $@ $(STAGE1_TEST_OBJS) -nostdlib -Wl,--build-id=none -Wl,-Tstage1/stage1.lds -no-pie -svsm.bin: stage1/stage1 +svsm.bin: bin/stage1 objcopy -O binary $< $@ -svsm-test.bin: stage1/stage1-test +svsm-test.bin: bin/stage1-test
Should we move these two to bin as well, or since they are the main artifacts do we leave them in the main folder?
svsm
github_2023
others
265
coconut-svsm
roy-hopkins
@@ -4,6 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] +zerocopy.workspace = true
This effectively adds a dependency on zerocopy to the kernel as it shares the bootlib package. Is that ok?
svsm
github_2023
others
266
coconut-svsm
00xc
@@ -11,29 +11,71 @@ use super::super::tss::IST_DF; use super::super::vc::handle_vc_exception; use super::common::PF_ERROR_WRITE; use super::common::{ - idt_mut, IdtEntry, BP_VECTOR, DB_VECTOR, DF_VECTOR, GP_VECTOR, HV_VECTOR, PF_VECTOR, VC_VECTOR, + idt_mut, IdtEntry, AC_VECTOR, BP_VECTOR, BR_VECTOR, CP_VECTOR, DB_VECTOR, DE_VECTOR, DF_VECTOR, + GP_VECTOR, HV_VECTOR, MCE_VECTOR, MF_VECTOR, NMI_VECTOR, NM_VECTOR, NP_VECTOR, OF_VECTOR, + PF_VECTOR, SS_VECTOR, SX_VECTOR, TS_VECTOR, UD_VECTOR, VC_VECTOR, XF_VECTOR, }; use crate::address::VirtAddr; use crate::cpu::X86ExceptionContext; use crate::debug::gdbstub::svsm_gdbstub::handle_debug_exception; use core::arch::global_asm; +extern "C" { + fn asm_entry_de(); + fn asm_entry_db(); + fn asm_entry_nmi(); + fn asm_entry_bp(); + fn asm_entry_of(); + fn asm_entry_br(); + fn asm_entry_ud(); + fn asm_entry_nm(); + fn asm_entry_df(); + fn asm_entry_ts(); + fn asm_entry_np(); + fn asm_entry_ss(); + fn asm_entry_gp(); + fn asm_entry_pf(); + fn asm_entry_mf(); + fn asm_entry_ac(); + fn asm_entry_mce(); + fn asm_entry_xf(); + fn asm_entry_cp(); + fn asm_entry_hv(); + fn asm_entry_vc(); + fn asm_entry_sx(); +} + fn init_ist_vectors() { - unsafe { - let handler = VirtAddr::from(&svsm_idt_handler_array as *const u8) + (32 * DF_VECTOR); - idt_mut().set_entry( - DF_VECTOR, - IdtEntry::ist_entry(handler, IST_DF.try_into().unwrap()), - ); - } + idt_mut().set_entry( + DF_VECTOR, + IdtEntry::ist_entry_with_handler(asm_entry_df, IST_DF.try_into().unwrap()), + ); } pub fn early_idt_init() { - unsafe { - idt_mut() - .init(&svsm_idt_handler_array as *const u8, 32) - .load(); - } + idt_mut().set_entry(DE_VECTOR, IdtEntry::entry_with_handler(asm_entry_de)); + idt_mut().set_entry(DB_VECTOR, IdtEntry::entry_with_handler(asm_entry_db)); + idt_mut().set_entry(NMI_VECTOR, IdtEntry::entry_with_handler(asm_entry_nmi)); + idt_mut().set_entry(BP_VECTOR, IdtEntry::entry_with_handler(asm_entry_bp)); + idt_mut().set_entry(OF_VECTOR, IdtEntry::entry_with_handler(asm_entry_of)); + idt_mut().set_entry(BR_VECTOR, IdtEntry::entry_with_handler(asm_entry_br)); + idt_mut().set_entry(UD_VECTOR, IdtEntry::entry_with_handler(asm_entry_ud)); + idt_mut().set_entry(NM_VECTOR, IdtEntry::entry_with_handler(asm_entry_nm)); + idt_mut().set_entry(DF_VECTOR, IdtEntry::entry_with_handler(asm_entry_df)); + idt_mut().set_entry(TS_VECTOR, IdtEntry::entry_with_handler(asm_entry_ts)); + idt_mut().set_entry(NP_VECTOR, IdtEntry::entry_with_handler(asm_entry_np)); + idt_mut().set_entry(SS_VECTOR, IdtEntry::entry_with_handler(asm_entry_ss)); + idt_mut().set_entry(GP_VECTOR, IdtEntry::entry_with_handler(asm_entry_gp)); + idt_mut().set_entry(PF_VECTOR, IdtEntry::entry_with_handler(asm_entry_pf)); + idt_mut().set_entry(MF_VECTOR, IdtEntry::entry_with_handler(asm_entry_mf)); + idt_mut().set_entry(AC_VECTOR, IdtEntry::entry_with_handler(asm_entry_ac)); + idt_mut().set_entry(MCE_VECTOR, IdtEntry::entry_with_handler(asm_entry_mce)); + idt_mut().set_entry(XF_VECTOR, IdtEntry::entry_with_handler(asm_entry_xf)); + idt_mut().set_entry(CP_VECTOR, IdtEntry::entry_with_handler(asm_entry_cp)); + idt_mut().set_entry(HV_VECTOR, IdtEntry::entry_with_handler(asm_entry_hv)); + idt_mut().set_entry(VC_VECTOR, IdtEntry::entry_with_handler(asm_entry_vc)); + idt_mut().set_entry(SX_VECTOR, IdtEntry::entry_with_handler(asm_entry_sx)); + idt_mut().load();
`idt_mut()` acquires a lock, so perhaps we should acquire it just once: ```rust let idt = idt_mut(); idt.set_entry(DE_VECTOR, IdtEntry::entry_with_handler(asm_entry_de)); // ... idt.load(); ```
svsm
github_2023
others
266
coconut-svsm
00xc
@@ -92,6 +92,16 @@ impl IdtEntry { IdtEntry::create(target, SVSM_CS, ist) } + pub fn entry_with_handler(handler: unsafe extern "C" fn()) -> Self { + let target = VirtAddr::from(handler as *const () as u64); + IdtEntry::create(target, SVSM_CS, 0) + } + + pub fn ist_entry_with_handler(handler: unsafe extern "C" fn(), ist: u8) -> Self { + let target = VirtAddr::from(handler as *const () as u64); + IdtEntry::create(target, SVSM_CS, ist) + }
`VirtAddr` implements `From<*const T>` so these can just be: ```rust let target = VirtAddr::from(handler as *const ()); ```
svsm
github_2023
others
98
coconut-svsm
stefano-garzarella
@@ -68,25 +68,35 @@ pub fn pvalidate_range(start: VirtAddr, end: VirtAddr, valid: bool) -> Result<() if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end { // Try to validate as a huge page. // If we fail, try to fall back to regular-sized pages. - pvalidate(addr, true, valid).or_else(|err| match err { + pvalidate(addr, PvalidateSize::Huge, valid).or_else(|err| match err { SvsmError::SevSnp(SevSnpError::FAIL_SIZEMISMATCH(_)) => { pvalidate_range_4k(addr, addr + PAGE_SIZE_2M, valid) } _ => Err(err), })?; addr = addr + PAGE_SIZE_2M; } else { - pvalidate(addr, false, valid)?; + pvalidate(addr, PvalidateSize::Page, valid)?; addr = addr + PAGE_SIZE; } } Ok(()) } -pub fn pvalidate(vaddr: VirtAddr, huge_page: bool, valid: bool) -> Result<(), SvsmError> { +/// The size of the page passed to PVALIDATE. +#[derive(Clone, Copy, Debug)] +#[repr(u64)] +pub enum PvalidateSize { + /// Regular page (4K) + Page = 0, + // Huge page (2M)
3 slashes also here for the doc comment?
svsm
github_2023
others
98
coconut-svsm
stefano-garzarella
@@ -68,25 +68,35 @@ pub fn pvalidate_range(start: VirtAddr, end: VirtAddr, valid: bool) -> Result<() if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end { // Try to validate as a huge page. // If we fail, try to fall back to regular-sized pages. - pvalidate(addr, true, valid).or_else(|err| match err { + pvalidate(addr, PvalidateSize::Huge, valid).or_else(|err| match err { SvsmError::SevSnp(SevSnpError::FAIL_SIZEMISMATCH(_)) => { pvalidate_range_4k(addr, addr + PAGE_SIZE_2M, valid) } _ => Err(err), })?; addr = addr + PAGE_SIZE_2M; } else { - pvalidate(addr, false, valid)?; + pvalidate(addr, PvalidateSize::Page, valid)?; addr = addr + PAGE_SIZE; } } Ok(()) } -pub fn pvalidate(vaddr: VirtAddr, huge_page: bool, valid: bool) -> Result<(), SvsmError> { +/// The size of the page passed to PVALIDATE. +#[derive(Clone, Copy, Debug)] +#[repr(u64)] +pub enum PvalidateSize { + /// Regular page (4K) + Page = 0,
I find a bit confusing the name, what about `Regular` and `Huge` ? Or `RegularPage` and `HugePage`?
svsm
github_2023
others
98
coconut-svsm
stefano-garzarella
@@ -68,25 +68,35 @@ pub fn pvalidate_range(start: VirtAddr, end: VirtAddr, valid: bool) -> Result<() if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end { // Try to validate as a huge page. // If we fail, try to fall back to regular-sized pages. - pvalidate(addr, true, valid).or_else(|err| match err { + pvalidate(addr, PvalidateSize::Huge, valid).or_else(|err| match err { SvsmError::SevSnp(SevSnpError::FAIL_SIZEMISMATCH(_)) => { pvalidate_range_4k(addr, addr + PAGE_SIZE_2M, valid) } _ => Err(err), })?; addr = addr + PAGE_SIZE_2M; } else { - pvalidate(addr, false, valid)?; + pvalidate(addr, PvalidateSize::Page, valid)?; addr = addr + PAGE_SIZE; } } Ok(()) } -pub fn pvalidate(vaddr: VirtAddr, huge_page: bool, valid: bool) -> Result<(), SvsmError> { +/// The size of the page passed to PVALIDATE.
Should we mention in the documentation that the enum values are the one used for the PVALIDATE instructions? Maybe it's implied and we can avoid it, it just occurred to me while looking at the code because we didn't add a match to choose the value.
svsm
github_2023
others
98
coconut-svsm
stefano-garzarella
@@ -11,6 +11,21 @@ pub const PAGE_SHIFT_2M: usize = 21; pub const PAGE_SIZE: usize = 1 << PAGE_SHIFT; pub const PAGE_SIZE_2M: usize = PAGE_SIZE * 512; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PageSize { + Regular, + Huge, +} + +impl From<PageSize> for usize {
What is the advantage of implementing `From` for `usize` compared to embed the values in the `enum`? I mean something like this: ``` #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(usize)] pub enum PageSize { Regular = PAGE_SIZE, Huge = PAGE_SIZE_2M, } ``` I'm asking because I'm worried about starting to use `as usize` wrongly with the `PageSize` enum.
svsm
github_2023
others
260
coconut-svsm
chris-oo
@@ -53,7 +53,21 @@ jobs: uses: actions-rs/cargo@v1 with: command: clippy - args: --workspace --all-features --exclude svsm --target=x86_64-unknown-linux-gnu -- -D warnings + args: --workspace --all-features --exclude svsm --exclude svsm-fuzz --target=x86_64-unknown-linux-gnu -- -D warnings + + - name: Clippy on svsm-fuzz
This really wasn't included in the above clippy call? I think it should be... Ideally I think we don't run clippy on all the individual crates, but we use `--workspace`, `--exclude` and `--target` to filter crates that don't build on a given target
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -81,138 +99,216 @@ impl PageStorageType { const NEXT_MASK: u64 = !((1u64 << Self::NEXT_SHIFT) - 1); const ORDER_MASK: u64 = (1u64 << (Self::NEXT_SHIFT - Self::TYPE_SHIFT)) - 1; + /// Creates a new [`PageStorageType`] with the specified page type. + /// + /// # Arguments + /// + /// * `t` - The page type. + /// + /// # Returns + /// + /// A new instance of [`PageStorageType`]. const fn new(t: PageType) -> Self { Self(t as u64) } + /// Encodes the order of the page. + /// + /// # Arguments + /// + /// * `order` - The order to encode. + /// + /// # Returns + /// + /// The updated [`PageStorageType`]. fn encode_order(self, order: usize) -> Self { Self(self.0 | ((order as u64) & Self::ORDER_MASK) << Self::TYPE_SHIFT) } + /// Encodes the index of the next page. + /// + /// # Arguments + /// + /// * `next_page` - The index of the next page. + /// + /// # Returns + /// + /// The updated [`PageStorageType`]. fn encode_next(self, next_page: usize) -> Self { Self(self.0 | (next_page as u64) << Self::NEXT_SHIFT) } + /// Encodes the reference count. + /// + /// # Arguments + /// + /// * `refcount` - The reference count to encode. + /// + /// # Returns + /// + /// The updated [`PageStorageType`]. fn encode_refcount(self, refcount: u64) -> Self { Self(self.0 | refcount << Self::TYPE_SHIFT) } + /// Decodes the order of the page. + /// + /// # Returns + /// + /// The decoded order. fn decode_order(&self) -> usize { ((self.0 >> Self::TYPE_SHIFT) & Self::ORDER_MASK) as usize } + /// Decodes the index of the next page. + /// + /// # Returns + /// + /// The decoded index of the next page. fn decode_next(&self) -> usize { ((self.0 & Self::NEXT_MASK) >> Self::NEXT_SHIFT) as usize } + /// Decodes the reference count. + /// + /// # Returns + /// + /// The decoded reference count.
For these simple functions I don't think we need a `# Returns` section, but that's just personal taste.
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -81,138 +99,216 @@ impl PageStorageType { const NEXT_MASK: u64 = !((1u64 << Self::NEXT_SHIFT) - 1); const ORDER_MASK: u64 = (1u64 << (Self::NEXT_SHIFT - Self::TYPE_SHIFT)) - 1; + /// Creates a new [`PageStorageType`] with the specified page type. + /// + /// # Arguments + /// + /// * `t` - The page type. + /// + /// # Returns + /// + /// A new instance of [`PageStorageType`]. const fn new(t: PageType) -> Self { Self(t as u64) } + /// Encodes the order of the page. + /// + /// # Arguments + /// + /// * `order` - The order to encode. + /// + /// # Returns + /// + /// The updated [`PageStorageType`]. fn encode_order(self, order: usize) -> Self { Self(self.0 | ((order as u64) & Self::ORDER_MASK) << Self::TYPE_SHIFT) } + /// Encodes the index of the next page. + /// + /// # Arguments + /// + /// * `next_page` - The index of the next page. + /// + /// # Returns + /// + /// The updated [`PageStorageType`]. fn encode_next(self, next_page: usize) -> Self { Self(self.0 | (next_page as u64) << Self::NEXT_SHIFT) } + /// Encodes the reference count. + /// + /// # Arguments + /// + /// * `refcount` - The reference count to encode. + /// + /// # Returns + /// + /// The updated [`PageStorageType`]. fn encode_refcount(self, refcount: u64) -> Self { Self(self.0 | refcount << Self::TYPE_SHIFT) } + /// Decodes the order of the page. + /// + /// # Returns + /// + /// The decoded order. fn decode_order(&self) -> usize { ((self.0 >> Self::TYPE_SHIFT) & Self::ORDER_MASK) as usize } + /// Decodes the index of the next page. + /// + /// # Returns + /// + /// The decoded index of the next page. fn decode_next(&self) -> usize { ((self.0 & Self::NEXT_MASK) >> Self::NEXT_SHIFT) as usize } + /// Decodes the reference count. + /// + /// # Returns + /// + /// The decoded reference count. fn decode_refcount(&self) -> u64 { self.0 >> Self::TYPE_SHIFT } + /// Retrieves the page type from the [`PageStorageType`]. + /// + /// # Returns + /// + /// The page type or an `AllocError` if the page type is invalid. fn page_type(&self) -> Result<PageType, AllocError> { PageType::try_from(self.0 & Self::TYPE_MASK) } } +/// Struct representing information about a free memory page. #[derive(Clone, Copy, Debug)] struct FreeInfo { + /// Index of the next free page. next_page: usize, + /// Order of the free page. order: usize, } impl FreeInfo { + /// Encodes the [`FreeInfo`] into a [`PageStorageType`]. fn encode(&self) -> PageStorageType { PageStorageType::new(PageType::Free) .encode_order(self.order) .encode_next(self.next_page) } + /// Decodes a [`PageStorageType`] into a [`FreeInfo`].
```suggestion /// Decodes a [`FreeInfo`] from a [`PageStorageType`] ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -279,6 +381,7 @@ impl MemoryRegion { } } + /// Converts a physical address to a virtual address within the memory region.
```suggestion /// Converts a physical address within this memory region to a virtual address. /// Returns `None` if the physical address does not belong to the memory region ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -297,12 +400,15 @@ impl MemoryRegion { Some(self.start_virt + offset) } + /// Converts a virtual address to a physical address within the memory region.
```suggestion /// Converts a virtual address within this memory region to a physical address. /// Returns `None` if the virtual address does not belong to the memory region ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -312,40 +418,47 @@ impl MemoryRegion { self.start_virt.as_mut_ptr::<PageStorageType>().add(pfn) } + /// Checks if a page frame number is valid.
```suggestion /// Checks if a page frame number is valid. /// /// # Panics /// /// Panics if the page frame number is invalid. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -312,40 +418,47 @@ impl MemoryRegion { self.start_virt.as_mut_ptr::<PageStorageType>().add(pfn) } + /// Checks if a page frame number is valid. fn check_pfn(&self, pfn: usize) { if pfn >= self.page_count { panic!("Invalid Page Number {}", pfn); } } + /// Calculates the end virtual address of the memory region. fn end_virt(&self) -> VirtAddr { self.start_virt + (self.page_count * PAGE_SIZE) } + /// Writes page information for a given page frame number. fn write_page_info(&self, pfn: usize, pi: PageInfo) { self.check_pfn(pfn); let info: PageStorageType = pi.to_mem(); unsafe { self.page_info_ptr(pfn).write(info) };
```suggestion // SAFETY: we have checked that the pfn is valid via check_pfn() above. unsafe { self.page_info_ptr(pfn).write(info) }; ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -312,40 +418,47 @@ impl MemoryRegion { self.start_virt.as_mut_ptr::<PageStorageType>().add(pfn) } + /// Checks if a page frame number is valid. fn check_pfn(&self, pfn: usize) { if pfn >= self.page_count { panic!("Invalid Page Number {}", pfn); } } + /// Calculates the end virtual address of the memory region. fn end_virt(&self) -> VirtAddr { self.start_virt + (self.page_count * PAGE_SIZE) } + /// Writes page information for a given page frame number. fn write_page_info(&self, pfn: usize, pi: PageInfo) { self.check_pfn(pfn); let info: PageStorageType = pi.to_mem(); unsafe { self.page_info_ptr(pfn).write(info) }; } + /// Reads page information for a given page frame number. fn read_page_info(&self, pfn: usize) -> PageInfo { self.check_pfn(pfn); let info = unsafe { self.page_info_ptr(pfn).read() };
```suggestion // SAFETY: we have checked that the pfn is valid via check_pfn() above. unsafe { self.page_info_ptr(pfn).write(info) }; ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -385,6 +500,7 @@ impl MemoryRegion { self.mark_compound_page(pfn, order); } + /// Splits a page into two pages of a lower order.
```suggestion /// Splits a page into two pages of the next lower order. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -580,6 +713,7 @@ impl MemoryRegion { } } + /// Frees a raw page by updating the free list and marking it as a free page.
```suggestion /// Frees a raw page by updating the free list and marking it as a free page. /// /// # Panics /// /// Panics if `order` is greater than [`MAX_ORDER`]. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -538,6 +666,11 @@ impl MemoryRegion { fi.next_page } + /// Allocates a specific page frame number (`pfn`) within a given order. + /// If the page frame number is not found or is already allocated, an error + /// is returned. If the requested page frame number is the first in the + /// list, it is marked as allocated, and the next page in the list becomes + /// the new first page.
```suggestion /// Allocates a specific page frame number (`pfn`) within a given order. /// If the page frame number is not found or is already allocated, an error /// is returned. If the requested page frame number is the first in the /// list, it is marked as allocated, and the next page in the list becomes /// the new first page. /// /// # Panics /// /// Panics if `order` is greater than [`MAX_ORDER`]. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -712,45 +859,59 @@ impl MemoryRegion { } } +/// Represents a reference to a memory page, holding both virtual and +/// physical addresses. #[derive(Debug)] pub struct PageRef { virt_addr: VirtAddr, phys_addr: PhysAddr, } impl PageRef { + /// Creates a new [`PageRef`] instance with the given virtual and physical addresses. + /// + /// # Arguments + /// + /// * `virt_addr` - Virtual address of the memory page. + /// * `phys_addr` - Physical address of the memory page. pub const fn new(virt_addr: VirtAddr, phys_addr: PhysAddr) -> Self { Self { virt_addr, phys_addr, } } + /// Returns the virtual address of the memory page. pub fn virt_addr(&self) -> VirtAddr { self.virt_addr } + /// Returns the physical address of the memory page. pub fn phys_addr(&self) -> PhysAddr { self.phys_addr } } impl AsRef<[u8; PAGE_SIZE]> for PageRef { + /// Returns a reference to the underlying array representing the memory page. fn as_ref(&self) -> &[u8; PAGE_SIZE] { let ptr = self.virt_addr.as_ptr::<[u8; PAGE_SIZE]>(); unsafe { ptr.as_ref().unwrap() } } } impl AsMut<[u8; PAGE_SIZE]> for PageRef { + /// Returns a mutable reference to the underlying array representing the memory page. fn as_mut(&mut self) -> &mut [u8; PAGE_SIZE] { let ptr = self.virt_addr.as_mut_ptr::<[u8; PAGE_SIZE]>(); unsafe { ptr.as_mut().unwrap() } } } impl Clone for PageRef { + /// Clones the [`PageRef`] instance, obtaining a new reference to the same memory page. fn clone(&self) -> Self { + // Get a cloned reference of the page
Probably redundant I would say
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -760,11 +921,17 @@ impl Clone for PageRef { } impl Drop for PageRef { + /// Drops the [`PageRef`] instance, releasing the associated memory page.
```suggestion /// Drops the [`PageRef`], decreasing the reference count for the page. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -788,30 +955,73 @@ pub fn print_memory_info(info: &MemInfo) { ); } +/// Static spinlock-protected instance of [`MemoryRegion`] representing the +/// root memory region. static ROOT_MEM: SpinLock<MemoryRegion> = SpinLock::new(MemoryRegion::new()); +/// Allocates a single memory page from the root memory region. +/// +/// # Returns +/// +/// Result containing the virtual address of the allocated page or an +/// `SvsmError` if allocation fails. pub fn allocate_page() -> Result<VirtAddr, SvsmError> { Ok(ROOT_MEM.lock().allocate_page()?) } +/// Allocates multiple memory pages with a specified order from the root +/// memory region. +/// +/// # Arguments +/// +/// * `order` - Order of the allocation, determining the number of pages (2^order). +/// +/// # Returns +/// +/// Result containing the virtual address of the allocated pages or an +/// `SvsmError` if allocation fails. pub fn allocate_pages(order: usize) -> Result<VirtAddr, SvsmError> { Ok(ROOT_MEM.lock().allocate_pages(order)?) } +/// Allocate a slab page. +/// +/// # Returns +/// +/// Result containing the virtual address of the allocated slab page or an +/// `SvsmError` if allocation fails. pub fn allocate_slab_page() -> Result<VirtAddr, SvsmError> { Ok(ROOT_MEM.lock().allocate_slab_page()?) } +/// Allocate a zeroed page. +/// +/// # Returns +/// +/// Result containing the virtual address of the allocated zeroed page or an +/// `SvsmError` if allocation fails. pub fn allocate_zeroed_page() -> Result<VirtAddr, SvsmError> { Ok(ROOT_MEM.lock().allocate_zeroed_page()?) } +/// Allocate a file page. +/// +/// # Returns +/// +/// Result containing the virtual address of the allocated file page or an +/// `SvsmError` if allocation fails. pub fn allocate_file_page() -> Result<VirtAddr, SvsmError> { let vaddr = ROOT_MEM.lock().allocate_file_page()?; zero_mem_region(vaddr, vaddr + PAGE_SIZE); Ok(vaddr) } +/// Allocate a file page and obtain a reference.
```suggestion /// Allocate a reference-counted file page. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -827,14 +1037,18 @@ fn put_file_page(vaddr: VirtAddr) -> Result<(), SvsmError> { Ok(ROOT_MEM.lock().put_file_page(vaddr)?) } +/// Obtain a free page given a virtual address
```suggestion /// Free the page at the given virtual address. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -827,14 +1037,18 @@ fn put_file_page(vaddr: VirtAddr) -> Result<(), SvsmError> { Ok(ROOT_MEM.lock().put_file_page(vaddr)?) } +/// Obtain a free page given a virtual address pub fn free_page(vaddr: VirtAddr) { ROOT_MEM.lock().free_page(vaddr) } +/// Retrieve the locked memory info
```suggestion /// Retrieve information about the root memory ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -1245,7 +1517,14 @@ impl SvsmAllocator { } } +/// Implements the `GlobalAlloc` trait for [`SvsmAllocator`], allowing it to
```suggestion /// Implements the [`GlobalAlloc`] trait for [`SvsmAllocator`], allowing it to ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -1245,7 +1517,14 @@ impl SvsmAllocator { } } +/// Implements the `GlobalAlloc` trait for [`SvsmAllocator`], allowing it to +/// be used as a global allocator for Rust programs. unsafe impl GlobalAlloc for SvsmAllocator { + /// Allocates memory based on the specified layout. + /// + /// # Safety + /// + /// This function may return a null pointer if the allocation fails.
This is unnecessary, the safety requirements are already specified in [the trait documentation](https://doc.rust-lang.org/core/alloc/trait.GlobalAlloc.html). Also, the function is unsafe for different reasons than NULL pointers.