@@ -41,7 +41,7 @@ impl Kvm {
41
41
pub fn new ( ) -> Result < Self > {
42
42
// Open `/dev/kvm` using `O_CLOEXEC` flag.
43
43
let fd = Self :: open_with_cloexec ( true ) ?;
44
- // Safe because we verify that ret is valid and we own the fd.
44
+ // Safe because we verify that the fd is valid in `open_with_cloexec` and we own the fd.
45
45
Ok ( unsafe { Self :: new_with_fd_number ( fd) } )
46
46
}
47
47
@@ -54,6 +54,24 @@ impl Kvm {
54
54
///
55
55
/// * `fd` - File descriptor for `/dev/kvm`.
56
56
///
57
+ /// # Safety
58
+ ///
59
+ /// This function is unsafe as the primitives currently returned have the contract that
60
+ /// they are the sole owner of the file descriptor they are wrapping. Usage of this function
61
+ /// could accidentally allow violating this contract which can cause memory unsafety in code
62
+ /// that relies on it being true.
63
+ ///
64
+ /// The caller of this method must make sure the fd is valid and nothing else uses it.
65
+ ///
66
+ /// # Example
67
+ ///
68
+ /// ```
69
+ /// # use kvm_ioctls::Kvm;
70
+ /// let kvm_fd = Kvm::open_with_cloexec(true).unwrap();
71
+ /// // Safe because we verify that the fd is valid in `open_with_cloexec` and we own the fd.
72
+ /// let kvm = unsafe { Kvm::new_with_fd_number(kvm_fd) };
73
+ /// ```
74
+ ///
57
75
pub unsafe fn new_with_fd_number ( fd : RawFd ) -> Self {
58
76
Kvm {
59
77
kvm : File :: from_raw_fd ( fd) ,
@@ -430,10 +448,32 @@ impl Kvm {
430
448
431
449
/// Creates a VmFd object from a VM RawFd.
432
450
///
451
+ /// # Arguments
452
+ ///
453
+ /// * `fd` - the RawFd used for creating the VmFd object.
454
+ ///
455
+ /// # Safety
456
+ ///
433
457
/// This function is unsafe as the primitives currently returned have the contract that
434
458
/// they are the sole owner of the file descriptor they are wrapping. Usage of this function
435
459
/// could accidentally allow violating this contract which can cause memory unsafety in code
436
460
/// that relies on it being true.
461
+ ///
462
+ /// The caller of this method must make sure the fd is valid and nothing else uses it.
463
+ ///
464
+ /// # Example
465
+ ///
466
+ /// ```rust
467
+ /// # extern crate kvm_ioctls;
468
+ /// # use std::os::unix::io::AsRawFd;
469
+ /// # use kvm_ioctls::Kvm;
470
+ /// let kvm = Kvm::new().unwrap();
471
+ /// let vm = kvm.create_vm().unwrap();
472
+ /// let rawfd = unsafe { libc::dup(vm.as_raw_fd()) };
473
+ /// assert!(rawfd >= 0);
474
+ /// let vm = unsafe { kvm.create_vmfd_from_rawfd(rawfd).unwrap() };
475
+ /// ```
476
+ ///
437
477
pub unsafe fn create_vmfd_from_rawfd ( & self , fd : RawFd ) -> Result < VmFd > {
438
478
let run_mmap_size = self . get_vcpu_mmap_size ( ) ?;
439
479
Ok ( new_vmfd ( File :: from_raw_fd ( fd) , run_mmap_size) )
0 commit comments