rust-vmm / vm-memory

Virtual machine's guest memory crate
Apache License 2.0
299 stars 97 forks source link

Get a slice of a `GuestRegionMmap` #286

Open tylerfanelli opened 5 months ago

tylerfanelli commented 5 months ago

Between versions 0.8 and 0.13, the AsSlice trait was deprecated for GuestRegionMmap. For users of the as_slice method, is there a way to recreate its functionality? That is, is there any current alternatives for this method that can gives us a slice of a guest memory region?

tylerfanelli commented 5 months ago

@roypat It seems that the AsSlice trait was removed here over concerns about taking slices of running VMs. In the project I use it for, we take the slice for VM creation, not from running VMs. Do you know of an alternative for the as_slice method?

roypat commented 4 months ago

Hi @tylerfanelli, sorry for the late response, I was on holiday over the Easter period. Generally, I would recommend VolatileSlice's methods/the Read/WriteVolatile traits for operating on guest memory. Alternatively, you could use as_ptr() and manually call std::slice::from_raw_parts to get a &[u8] instead, if you can prove in your application code that this is save to do.

bonzini commented 4 months ago

I think AsMutSlice can be added back, but not AsSlice. The as_slice() method can be added as unsafe.

tylerfanelli commented 4 months ago

@roypat No problem, thanks for the reply.

You would fetch this VolatileSlice using get_slice(), correct? With that I could copy the underlying memory to a normal slice with read_slice(), specifying the VolatileSlice's len() for the amount of bytes to read.

Do I have this right? If so, I don't think AsMutSlice nor AsSlice are required to be added back, especially if I'm the only one who asked for them.

roypat commented 4 months ago

@tylerfanelli

You would fetch this VolatileSlice using get_slice(), correct? With that I could copy the underlying memory to a normal slice with read_slice(), specifying the VolatileSlice's len() for the amount of bytes to read.

Do I have this right?

Yes, that would allow you to copy data from the VolatileSlice into a byte buffer. For the other way around, you'd use write_slice.

@bonzini

I think AsMutSlice can be added back, but not AsSlice. The as_slice() method can be added as unsafe.

I suppose having unsafe as_slice and as_slice_mut functions that are very clear about their requirements (no usage after VM has started, no aliasing mutable slices to the same memory region) would be fine (although I'm not 100% sure how they'd work with the xen feature). The reason I deprecated a bunch of them in #217 was because the vm-memory crate itself can never use them, since it does not have any "global" information about aliasing slices or the state of the virtual machine (AsSlice itself was actually pub(crate), so it wasn't usable outside of vm-memory, which is why it got removed altogether).