zx/
vmo.rs

1// Copyright 2017 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Type-safe bindings for Zircon vmo objects.
6
7use crate::{
8    AsHandleRef, Bti, Handle, HandleBased, HandleRef, Koid, Name, ObjectQuery, Property,
9    PropertyQuery, Resource, Rights, Status, Topic, object_get_info_single, object_get_property,
10    object_set_property, ok, sys,
11};
12use bitflags::bitflags;
13use std::mem::MaybeUninit;
14use std::ptr;
15use zerocopy::{FromBytes, Immutable};
16use zx_sys::PadByte;
17
18/// An object representing a Zircon
19/// [virtual memory object](https://fuchsia.dev/fuchsia-src/concepts/objects/vm_object.md).
20///
21/// As essentially a subtype of `Handle`, it can be freely interconverted.
22#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
23#[repr(transparent)]
24pub struct Vmo(Handle);
25impl_handle_based!(Vmo);
26
27static_assert_align!(
28    #[doc="Ergonomic equivalent of [sys::zx_info_vmo_t]. Must be ABI-compatible with it."]
29    #[repr(C)]
30    #[derive(Debug, Copy, Clone, Eq, PartialEq, FromBytes, Immutable)]
31    <sys::zx_info_vmo_t> pub struct VmoInfo {
32        pub koid <koid>: Koid,
33        pub name <name>: Name,
34        pub size_bytes <size_bytes>: u64,
35        pub parent_koid <parent_koid>: Koid,
36        pub num_children <num_children>: usize,
37        pub num_mappings <num_mappings>: usize,
38        pub share_count <share_count>: usize,
39        pub flags <flags>: VmoInfoFlags,
40        padding1: [PadByte; 4],
41        pub committed_bytes <committed_bytes>: u64,
42        pub handle_rights <handle_rights>: Rights,
43        cache_policy <cache_policy>: u32,
44        pub metadata_bytes <metadata_bytes>: u64,
45        pub committed_change_events <committed_change_events>: u64,
46        pub populated_bytes <populated_bytes>: u64,
47        pub committed_private_bytes <committed_private_bytes>: u64,
48        pub populated_private_bytes <populated_private_bytes>: u64,
49        pub committed_scaled_bytes <committed_scaled_bytes>: u64,
50        pub populated_scaled_bytes <populated_scaled_bytes>: u64,
51        pub committed_fractional_scaled_bytes <committed_fractional_scaled_bytes>: u64,
52        pub populated_fractional_scaled_bytes <populated_fractional_scaled_bytes>: u64,
53    }
54);
55
56impl VmoInfo {
57    pub fn cache_policy(&self) -> CachePolicy {
58        CachePolicy::from(self.cache_policy)
59    }
60}
61
62impl Default for VmoInfo {
63    fn default() -> VmoInfo {
64        Self::from(sys::zx_info_vmo_t::default())
65    }
66}
67
68impl From<sys::zx_info_vmo_t> for VmoInfo {
69    fn from(info: sys::zx_info_vmo_t) -> VmoInfo {
70        zerocopy::transmute!(info)
71    }
72}
73
74struct VmoInfoQuery;
75unsafe impl ObjectQuery for VmoInfoQuery {
76    const TOPIC: Topic = Topic::VMO;
77    type InfoTy = sys::zx_info_vmo_t;
78}
79
80impl Vmo {
81    /// Create a virtual memory object.
82    ///
83    /// Wraps the
84    /// `zx_vmo_create`
85    /// syscall. See the
86    /// [Shared Memory: Virtual Memory Objects (VMOs)](https://fuchsia.dev/fuchsia-src/concepts/kernel/concepts#shared_memory_virtual_memory_objects_vmos)
87    /// for more information.
88    pub fn create(size: u64) -> Result<Vmo, Status> {
89        Vmo::create_with_opts(VmoOptions::from_bits_truncate(0), size)
90    }
91
92    /// Create a virtual memory object with options.
93    ///
94    /// Wraps the
95    /// `zx_vmo_create`
96    /// syscall, allowing options to be passed.
97    pub fn create_with_opts(opts: VmoOptions, size: u64) -> Result<Vmo, Status> {
98        let mut handle = 0;
99        let status = unsafe { sys::zx_vmo_create(size, opts.bits(), &mut handle) };
100        ok(status)?;
101        unsafe { Ok(Vmo::from(Handle::from_raw(handle))) }
102    }
103
104    /// Create a physically contiguous virtual memory object.
105    ///
106    /// Wraps the
107    /// [`zx_vmo_create_contiguous`](https://fuchsia.dev/fuchsia-src/reference/syscalls/vmo_create_contiguous) syscall.
108    pub fn create_contiguous(bti: &Bti, size: usize, alignment_log2: u32) -> Result<Vmo, Status> {
109        let mut vmo_handle = sys::zx_handle_t::default();
110        let status = unsafe {
111            // SAFETY: regular system call with no unsafe parameters.
112            sys::zx_vmo_create_contiguous(bti.raw_handle(), size, alignment_log2, &mut vmo_handle)
113        };
114        ok(status)?;
115        unsafe {
116            // SAFETY: The syscall docs claim that upon success, vmo_handle will be a valid
117            // handle to a virtual memory object.
118            Ok(Vmo::from(Handle::from_raw(vmo_handle)))
119        }
120    }
121
122    /// Read from a virtual memory object.
123    ///
124    /// Wraps the `zx_vmo_read` syscall.
125    pub fn read(&self, data: &mut [u8], offset: u64) -> Result<(), Status> {
126        unsafe {
127            let status = sys::zx_vmo_read(self.raw_handle(), data.as_mut_ptr(), offset, data.len());
128            ok(status)
129        }
130    }
131
132    /// Provides a very thin wrapper over `zx_vmo_read`.
133    ///
134    /// # Safety
135    ///
136    /// Callers must guarantee that the buffer is valid to write to.
137    pub unsafe fn read_raw<T: FromBytes>(
138        &self,
139        buffer: *mut T,
140        buffer_length: usize,
141        offset: u64,
142    ) -> Result<(), Status> {
143        let status = sys::zx_vmo_read(
144            self.raw_handle(),
145            buffer.cast::<u8>(),
146            offset,
147            buffer_length * std::mem::size_of::<T>(),
148        );
149        ok(status)
150    }
151
152    /// Same as read, but reads into memory that might not be initialized, returning an initialized
153    /// slice of bytes on success.
154    ///
155    /// `Copy` is required to ensure that there are no custom `Drop` implementations. It is
156    /// difficult to correctly run custom drop code after initializing a `MaybeUninit`.
157    pub fn read_uninit<'a, T: Copy + FromBytes>(
158        &self,
159        data: &'a mut [MaybeUninit<T>],
160        offset: u64,
161    ) -> Result<&'a mut [T], Status> {
162        // SAFETY: This system call requires that the pointer and length we pass are valid to write
163        // to, which we guarantee here by getting the pointer and length from a valid slice.
164        unsafe {
165            self.read_raw(
166                // TODO(https://fxbug.dev/42079723) use MaybeUninit::slice_as_mut_ptr when stable
167                data.as_mut_ptr().cast::<T>(),
168                data.len(),
169                offset,
170            )?
171        }
172        // TODO(https://fxbug.dev/42079723) use MaybeUninit::slice_assume_init_mut when stable
173        Ok(
174            // SAFETY: We're converting &mut [MaybeUninit<u8>] back to &mut [u8], which is only
175            // valid to do if all elements of `data` have actually been initialized. Here we
176            // have to trust that the kernel didn't lie when it said it wrote to the entire
177            // buffer, but as long as that assumption is valid them it's safe to assume this
178            // slice is init.
179            unsafe { std::slice::from_raw_parts_mut(data.as_mut_ptr().cast::<T>(), data.len()) },
180        )
181    }
182
183    /// Same as read, but returns a Vec.
184    pub fn read_to_vec<T: Copy + FromBytes>(
185        &self,
186        offset: u64,
187        length: u64,
188    ) -> Result<Vec<T>, Status> {
189        let len = length.try_into().map_err(|_| Status::INVALID_ARGS)?;
190        let mut buffer = Vec::with_capacity(len);
191        self.read_uninit(buffer.spare_capacity_mut(), offset)?;
192        unsafe {
193            // SAFETY: since read_uninit succeeded we know that we can consider the buffer
194            // initialized.
195            buffer.set_len(len);
196        }
197        Ok(buffer)
198    }
199
200    /// Same as read, but returns an array.
201    pub fn read_to_array<T: Copy + FromBytes, const N: usize>(
202        &self,
203        offset: u64,
204    ) -> Result<[T; N], Status> {
205        // TODO(https://fxbug.dev/42079731): replace with MaybeUninit::uninit_array.
206        let array: MaybeUninit<[MaybeUninit<T>; N]> = MaybeUninit::uninit();
207        // SAFETY: We are converting from an uninitialized array to an array
208        // of uninitialized elements which is the same. See
209        // https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#initializing-an-array-element-by-element.
210        let mut array = unsafe { array.assume_init() };
211
212        // SAFETY: T is FromBytes, which means that any bit pattern is valid. Interpreting
213        // [MaybeUninit<T>] as [MaybeUninit<u8>] is safe because T's alignment requirements
214        // are larger than u8.
215        //
216        // TODO(https://fxbug.dev/42079727): Use MaybeUninit::slice_as_bytes_mut once stable.
217        let buffer = unsafe {
218            std::slice::from_raw_parts_mut(
219                array.as_mut_ptr().cast::<MaybeUninit<u8>>(),
220                N * std::mem::size_of::<T>(),
221            )
222        };
223
224        self.read_uninit(buffer, offset)?;
225        // SAFETY: This is safe because we have initialized all the elements in
226        // the array (since `read_uninit` returned successfully).
227        //
228        // TODO(https://fxbug.dev/42079725): replace with MaybeUninit::array_assume_init.
229        let buffer = array.map(|a| unsafe { a.assume_init() });
230        Ok(buffer)
231    }
232
233    /// Same as read, but returns a `T`.
234    pub fn read_to_object<T: Copy + FromBytes>(&self, offset: u64) -> Result<T, Status> {
235        let mut object = MaybeUninit::<T>::uninit();
236        // SAFETY: T is FromBytes, which means that any bit pattern is valid. Interpreting
237        // MaybeUninit<T> as [MaybeUninit<u8>] is safe because T's alignment requirements
238        // are larger than, or equal to, u8's.
239        //
240        // TODO(https://fxbug.dev/42079727): Use MaybeUninit::as_bytes_mut once stable.
241        let buffer = unsafe {
242            std::slice::from_raw_parts_mut(
243                object.as_mut_ptr().cast::<MaybeUninit<u8>>(),
244                std::mem::size_of::<T>(),
245            )
246        };
247        self.read_uninit(buffer, offset)?;
248
249        // SAFETY: The call to `read_uninit` succeeded so we know that `object`
250        // has been initialized.
251        let object = unsafe { object.assume_init() };
252        Ok(object)
253    }
254
255    /// Write to a virtual memory object.
256    ///
257    /// Wraps the `zx_vmo_write` syscall.
258    pub fn write(&self, data: &[u8], offset: u64) -> Result<(), Status> {
259        unsafe {
260            let status = sys::zx_vmo_write(self.raw_handle(), data.as_ptr(), offset, data.len());
261            ok(status)
262        }
263    }
264
265    /// Efficiently transfers data from one VMO to another.
266    pub fn transfer_data(
267        &self,
268        options: TransferDataOptions,
269        offset: u64,
270        length: u64,
271        src_vmo: &Vmo,
272        src_offset: u64,
273    ) -> Result<(), Status> {
274        let status = unsafe {
275            sys::zx_vmo_transfer_data(
276                self.raw_handle(),
277                options.bits(),
278                offset,
279                length,
280                src_vmo.raw_handle(),
281                src_offset,
282            )
283        };
284        ok(status)
285    }
286
287    /// Get the size of a virtual memory object.
288    ///
289    /// Wraps the `zx_vmo_get_size` syscall.
290    pub fn get_size(&self) -> Result<u64, Status> {
291        let mut size = 0;
292        let status = unsafe { sys::zx_vmo_get_size(self.raw_handle(), &mut size) };
293        ok(status).map(|()| size)
294    }
295
296    /// Attempt to change the size of a virtual memory object.
297    ///
298    /// Wraps the `zx_vmo_set_size` syscall.
299    pub fn set_size(&self, size: u64) -> Result<(), Status> {
300        let status = unsafe { sys::zx_vmo_set_size(self.raw_handle(), size) };
301        ok(status)
302    }
303
304    /// Get the stream size of a virtual memory object.
305    ///
306    /// Wraps the `zx_vmo_get_stream_size` syscall.
307    pub fn get_stream_size(&self) -> Result<u64, Status> {
308        let mut size = 0;
309        let status = unsafe { sys::zx_vmo_get_stream_size(self.raw_handle(), &mut size) };
310        ok(status).map(|()| size)
311    }
312
313    /// Attempt to set the stream size of a virtual memory object.
314    ///
315    /// Wraps the `zx_vmo_set_stream_size` syscall.
316    pub fn set_stream_size(&self, size: u64) -> Result<(), Status> {
317        let status = unsafe { sys::zx_vmo_set_stream_size(self.raw_handle(), size) };
318        ok(status)
319    }
320
321    /// Attempt to change the cache policy of a virtual memory object.
322    ///
323    /// Wraps the `zx_vmo_set_cache_policy` syscall.
324    pub fn set_cache_policy(&self, cache_policy: CachePolicy) -> Result<(), Status> {
325        let status =
326            unsafe { sys::zx_vmo_set_cache_policy(self.raw_handle(), cache_policy as u32) };
327        ok(status)
328    }
329
330    /// Perform an operation on a range of a virtual memory object.
331    ///
332    /// Wraps the
333    /// [zx_vmo_op_range](https://fuchsia.dev/fuchsia-src/reference/syscalls/vmo_op_range.md)
334    /// syscall.
335    pub fn op_range(&self, op: VmoOp, offset: u64, size: u64) -> Result<(), Status> {
336        let status = unsafe {
337            sys::zx_vmo_op_range(self.raw_handle(), op.into_raw(), offset, size, ptr::null_mut(), 0)
338        };
339        ok(status)
340    }
341
342    /// Wraps the [zx_object_get_info](https://fuchsia.dev/fuchsia-src/reference/syscalls/object_get_info.md)
343    /// syscall for the ZX_INFO_VMO topic.
344    pub fn info(&self) -> Result<VmoInfo, Status> {
345        Ok(VmoInfo::from(object_get_info_single::<VmoInfoQuery>(self.as_handle_ref())?))
346    }
347
348    /// Create a new virtual memory object that clones a range of this one.
349    ///
350    /// Wraps the
351    /// [zx_vmo_create_child](https://fuchsia.dev/fuchsia-src/reference/syscalls/vmo_create_child.md)
352    /// syscall.
353    pub fn create_child(
354        &self,
355        opts: VmoChildOptions,
356        offset: u64,
357        size: u64,
358    ) -> Result<Vmo, Status> {
359        let mut out = 0;
360        let status = unsafe {
361            sys::zx_vmo_create_child(self.raw_handle(), opts.bits(), offset, size, &mut out)
362        };
363        ok(status)?;
364        unsafe { Ok(Vmo::from(Handle::from_raw(out))) }
365    }
366
367    /// Replace a VMO, adding execute rights.
368    ///
369    /// Wraps the
370    /// [zx_vmo_replace_as_executable](https://fuchsia.dev/fuchsia-src/reference/syscalls/vmo_replace_as_executable.md)
371    /// syscall.
372    pub fn replace_as_executable(self, vmex: &Resource) -> Result<Vmo, Status> {
373        let mut out = 0;
374        let status = unsafe {
375            sys::zx_vmo_replace_as_executable(self.raw_handle(), vmex.raw_handle(), &mut out)
376        };
377        // zx_vmo_replace_as_executable always invalidates the passed in handle
378        // so we need to forget 'self' without executing its drop which will attempt
379        // to close the now-invalid handle value.
380        std::mem::forget(self);
381        ok(status)?;
382        unsafe { Ok(Vmo::from(Handle::from_raw(out))) }
383    }
384}
385
386bitflags! {
387    /// Options that may be used when creating a `Vmo`.
388    #[repr(transparent)]
389    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
390    pub struct VmoOptions: u32 {
391        const RESIZABLE = sys::ZX_VMO_RESIZABLE;
392        const TRAP_DIRTY = sys::ZX_VMO_TRAP_DIRTY;
393        const UNBOUNDED = sys::ZX_VMO_UNBOUNDED;
394    }
395}
396
397/// Flags that may be set when receiving info on a `Vmo`.
398#[repr(transparent)]
399#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, FromBytes, Immutable)]
400pub struct VmoInfoFlags(u32);
401
402bitflags! {
403    impl VmoInfoFlags : u32 {
404        const PAGED = sys::ZX_INFO_VMO_TYPE_PAGED;
405        const RESIZABLE = sys::ZX_INFO_VMO_RESIZABLE;
406        const IS_COW_CLONE = sys::ZX_INFO_VMO_IS_COW_CLONE;
407        const VIA_HANDLE = sys::ZX_INFO_VMO_VIA_HANDLE;
408        const VIA_MAPPING = sys::ZX_INFO_VMO_VIA_MAPPING;
409        const PAGER_BACKED = sys::ZX_INFO_VMO_PAGER_BACKED;
410        const CONTIGUOUS = sys::ZX_INFO_VMO_CONTIGUOUS;
411        const DISCARDABLE = sys::ZX_INFO_VMO_DISCARDABLE;
412        const IMMUTABLE = sys::ZX_INFO_VMO_IMMUTABLE;
413        const VIA_IOB_HANDLE = sys::ZX_INFO_VMO_VIA_IOB_HANDLE;
414    }
415}
416
417impl std::fmt::Debug for VmoInfoFlags {
418    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
419        bitflags::parser::to_writer(self, f)
420    }
421}
422
423bitflags! {
424    /// Options that may be used when creating a `Vmo` child.
425    #[repr(transparent)]
426    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
427    pub struct VmoChildOptions: u32 {
428        const SNAPSHOT = sys::ZX_VMO_CHILD_SNAPSHOT;
429        const SNAPSHOT_AT_LEAST_ON_WRITE = sys::ZX_VMO_CHILD_SNAPSHOT_AT_LEAST_ON_WRITE;
430        const RESIZABLE = sys::ZX_VMO_CHILD_RESIZABLE;
431        const SLICE = sys::ZX_VMO_CHILD_SLICE;
432        const NO_WRITE = sys::ZX_VMO_CHILD_NO_WRITE;
433        const REFERENCE = sys::ZX_VMO_CHILD_REFERENCE;
434        const SNAPSHOT_MODIFIED = sys::ZX_VMO_CHILD_SNAPSHOT_MODIFIED;
435    }
436}
437
438bitflags! {
439    /// Options that may be used when transferring data between VMOs.
440    #[repr(transparent)]
441    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
442    pub struct TransferDataOptions: u32 {
443    }
444}
445
446/// VM Object opcodes
447#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
448#[repr(transparent)]
449pub struct VmoOp(u32);
450impl VmoOp {
451    pub fn from_raw(raw: u32) -> VmoOp {
452        VmoOp(raw)
453    }
454    pub fn into_raw(self) -> u32 {
455        self.0
456    }
457}
458
459// VM Object Cache Policies.
460#[derive(Debug, Copy, Clone, Eq, PartialEq)]
461#[repr(u32)]
462pub enum CachePolicy {
463    Cached = sys::ZX_CACHE_POLICY_CACHED,
464    UnCached = sys::ZX_CACHE_POLICY_UNCACHED,
465    UnCachedDevice = sys::ZX_CACHE_POLICY_UNCACHED_DEVICE,
466    WriteCombining = sys::ZX_CACHE_POLICY_WRITE_COMBINING,
467    Unknown = u32::MAX,
468}
469
470impl From<u32> for CachePolicy {
471    fn from(v: u32) -> Self {
472        match v {
473            sys::ZX_CACHE_POLICY_CACHED => CachePolicy::Cached,
474            sys::ZX_CACHE_POLICY_UNCACHED => CachePolicy::UnCached,
475            sys::ZX_CACHE_POLICY_UNCACHED_DEVICE => CachePolicy::UnCachedDevice,
476            sys::ZX_CACHE_POLICY_WRITE_COMBINING => CachePolicy::WriteCombining,
477            _ => CachePolicy::Unknown,
478        }
479    }
480}
481
482impl Into<u32> for CachePolicy {
483    fn into(self) -> u32 {
484        match self {
485            CachePolicy::Cached => sys::ZX_CACHE_POLICY_CACHED,
486            CachePolicy::UnCached => sys::ZX_CACHE_POLICY_UNCACHED,
487            CachePolicy::UnCachedDevice => sys::ZX_CACHE_POLICY_UNCACHED_DEVICE,
488            CachePolicy::WriteCombining => sys::ZX_CACHE_POLICY_WRITE_COMBINING,
489            CachePolicy::Unknown => u32::MAX,
490        }
491    }
492}
493
494assoc_values!(VmoOp, [
495    COMMIT =           sys::ZX_VMO_OP_COMMIT;
496    DECOMMIT =         sys::ZX_VMO_OP_DECOMMIT;
497    LOCK =             sys::ZX_VMO_OP_LOCK;
498    UNLOCK =           sys::ZX_VMO_OP_UNLOCK;
499    CACHE_SYNC =       sys::ZX_VMO_OP_CACHE_SYNC;
500    CACHE_INVALIDATE = sys::ZX_VMO_OP_CACHE_INVALIDATE;
501    CACHE_CLEAN =      sys::ZX_VMO_OP_CACHE_CLEAN;
502    CACHE_CLEAN_INVALIDATE = sys::ZX_VMO_OP_CACHE_CLEAN_INVALIDATE;
503    ZERO =             sys::ZX_VMO_OP_ZERO;
504    TRY_LOCK =         sys::ZX_VMO_OP_TRY_LOCK;
505    DONT_NEED =        sys::ZX_VMO_OP_DONT_NEED;
506    ALWAYS_NEED =      sys::ZX_VMO_OP_ALWAYS_NEED;
507    PREFETCH =         sys::ZX_VMO_OP_PREFETCH;
508]);
509
510unsafe_handle_properties!(object: Vmo,
511    props: [
512        {query_ty: VMO_CONTENT_SIZE, tag: VmoContentSizeTag, prop_ty: u64, get:get_content_size, set: set_content_size},
513    ]
514);
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use crate::{Iommu, IommuDescDummy, ObjectType};
520    use fidl_fuchsia_kernel as fkernel;
521    use fuchsia_component::client::connect_channel_to_protocol;
522    use test_case::test_case;
523    use zerocopy::KnownLayout;
524
525    #[test]
526    fn vmo_create_contiguous_invalid_handle() {
527        let status = Vmo::create_contiguous(&Bti::from(Handle::invalid()), 4096, 0);
528        assert_eq!(status, Err(Status::BAD_HANDLE));
529    }
530
531    #[test]
532    fn vmo_create_contiguous() {
533        use zx::{Channel, HandleBased, MonotonicInstant};
534        let (client_end, server_end) = Channel::create();
535        connect_channel_to_protocol::<fkernel::IommuResourceMarker>(server_end).unwrap();
536        let service = fkernel::IommuResourceSynchronousProxy::new(client_end);
537        let resource =
538            service.get(MonotonicInstant::INFINITE).expect("couldn't get iommu resource");
539        // This test and fuchsia-zircon are different crates, so we need
540        // to use from_raw to convert between the zx handle and this test handle.
541        // See https://fxbug.dev/42173139 for details.
542        let resource = unsafe { Resource::from(Handle::from_raw(resource.into_raw())) };
543        let iommu = Iommu::create_dummy(&resource, IommuDescDummy::default()).unwrap();
544        let bti = Bti::create(&iommu, 0).unwrap();
545
546        let vmo = Vmo::create_contiguous(&bti, 8192, 0).unwrap();
547        let info = vmo.as_handle_ref().basic_info().unwrap();
548        assert_eq!(info.object_type, ObjectType::VMO);
549
550        let vmo_info = vmo.info().unwrap();
551        assert!(vmo_info.flags.contains(VmoInfoFlags::CONTIGUOUS));
552    }
553
554    #[test]
555    fn vmo_get_size() {
556        let size = 16 * 1024 * 1024;
557        let vmo = Vmo::create(size).unwrap();
558        assert_eq!(size, vmo.get_size().unwrap());
559    }
560
561    #[test]
562    fn vmo_set_size() {
563        // Use a multiple of page size to match VMOs page aligned size
564        let start_size = 4096;
565        let vmo = Vmo::create_with_opts(VmoOptions::RESIZABLE, start_size).unwrap();
566        assert_eq!(start_size, vmo.get_size().unwrap());
567
568        // Change the size and make sure the new size is reported
569        let new_size = 8192;
570        assert!(vmo.set_size(new_size).is_ok());
571        assert_eq!(new_size, vmo.get_size().unwrap());
572    }
573
574    #[test]
575    fn vmo_get_info_default() {
576        let size = 4096;
577        let vmo = Vmo::create(size).unwrap();
578        let info = vmo.info().unwrap();
579        assert!(!info.flags.contains(VmoInfoFlags::PAGER_BACKED));
580        assert!(info.flags.contains(VmoInfoFlags::PAGED));
581    }
582
583    #[test]
584    fn vmo_get_child_info() {
585        let size = 4096;
586        let vmo = Vmo::create(size).unwrap();
587        let info = vmo.info().unwrap();
588        assert!(!info.flags.contains(VmoInfoFlags::IS_COW_CLONE));
589
590        let child = vmo.create_child(VmoChildOptions::SNAPSHOT, 0, 512).unwrap();
591        let info = child.info().unwrap();
592        assert!(info.flags.contains(VmoInfoFlags::IS_COW_CLONE));
593
594        let child = vmo.create_child(VmoChildOptions::SNAPSHOT_AT_LEAST_ON_WRITE, 0, 512).unwrap();
595        let info = child.info().unwrap();
596        assert!(info.flags.contains(VmoInfoFlags::IS_COW_CLONE));
597
598        let child = vmo.create_child(VmoChildOptions::SLICE, 0, 512).unwrap();
599        let info = child.info().unwrap();
600        assert!(!info.flags.contains(VmoInfoFlags::IS_COW_CLONE));
601    }
602
603    #[test]
604    fn vmo_set_size_fails_on_non_resizable() {
605        let size = 4096;
606        let vmo = Vmo::create(size).unwrap();
607        assert_eq!(size, vmo.get_size().unwrap());
608
609        let new_size = 8192;
610        assert_eq!(Err(Status::UNAVAILABLE), vmo.set_size(new_size));
611        assert_eq!(size, vmo.get_size().unwrap());
612    }
613
614    #[test_case(0)]
615    #[test_case(1)]
616    fn vmo_read_to_array(read_offset: usize) {
617        const ACTUAL_SIZE: usize = 5;
618        const ACTUAL: [u8; ACTUAL_SIZE] = [1, 2, 3, 4, 5];
619        let vmo = Vmo::create(ACTUAL.len() as u64).unwrap();
620        vmo.write(&ACTUAL, 0).unwrap();
621        let read_len = ACTUAL_SIZE - read_offset;
622        assert_eq!(
623            &vmo.read_to_array::<u8, ACTUAL_SIZE>(read_offset as u64).unwrap()[..read_len],
624            &ACTUAL[read_offset..]
625        );
626    }
627
628    #[test_case(0)]
629    #[test_case(1)]
630    fn vmo_read_to_vec(read_offset: usize) {
631        const ACTUAL_SIZE: usize = 4;
632        const ACTUAL: [u8; ACTUAL_SIZE] = [6, 7, 8, 9];
633        let vmo = Vmo::create(ACTUAL.len() as u64).unwrap();
634        vmo.write(&ACTUAL, 0).unwrap();
635        let read_len = ACTUAL_SIZE - read_offset;
636        assert_eq!(
637            &vmo.read_to_vec::<u8>(read_offset as u64, read_len as u64).unwrap(),
638            &ACTUAL[read_offset..]
639        );
640    }
641
642    #[test_case(0)]
643    #[test_case(1)]
644    fn vmo_read_to_object(read_offset: usize) {
645        #[repr(C)]
646        #[derive(Copy, Clone, Debug, Eq, KnownLayout, FromBytes, PartialEq)]
647        struct Object {
648            a: u8,
649            b: u8,
650        }
651
652        const ACTUAL_SIZE: usize = std::mem::size_of::<Object>();
653        const ACTUAL: [u8; ACTUAL_SIZE + 1] = [10, 11, 12];
654        let vmo = Vmo::create(ACTUAL.len() as u64).unwrap();
655        vmo.write(&ACTUAL, 0).unwrap();
656        assert_eq!(
657            vmo.read_to_object::<Object>(read_offset as u64).unwrap(),
658            Object { a: ACTUAL[read_offset], b: ACTUAL[1 + read_offset] }
659        );
660    }
661
662    #[test]
663    fn vmo_read_write() {
664        let mut vec1 = vec![0; 16];
665        let vmo = Vmo::create(4096 as u64).unwrap();
666        assert!(vmo.write(b"abcdef", 0).is_ok());
667        assert!(vmo.read(&mut vec1, 0).is_ok());
668        assert_eq!(b"abcdef", &vec1[0..6]);
669        assert!(vmo.write(b"123", 2).is_ok());
670        assert!(vmo.read(&mut vec1, 0).is_ok());
671        assert_eq!(b"ab123f", &vec1[0..6]);
672
673        // Read one byte into the vmo.
674        assert!(vmo.read(&mut vec1, 1).is_ok());
675        assert_eq!(b"b123f", &vec1[0..5]);
676
677        assert_eq!(&vmo.read_to_vec::<u8>(0, 6).expect("read_to_vec failed"), b"ab123f");
678    }
679
680    #[test]
681    fn vmo_child_snapshot() {
682        let size = 4096 * 2;
683        let vmo = Vmo::create(size).unwrap();
684
685        vmo.write(&[1; 4096], 0).unwrap();
686        vmo.write(&[2; 4096], 4096).unwrap();
687
688        let child = vmo.create_child(VmoChildOptions::SNAPSHOT, 0, size).unwrap();
689
690        child.write(&[3; 4096], 0).unwrap();
691
692        vmo.write(&[4; 4096], 0).unwrap();
693        vmo.write(&[5; 4096], 4096).unwrap();
694
695        let mut page = [0; 4096];
696
697        // SNAPSHOT child observes no further changes to parent VMO.
698        child.read(&mut page[..], 0).unwrap();
699        assert_eq!(&page[..], &[3; 4096][..]);
700        child.read(&mut page[..], 4096).unwrap();
701        assert_eq!(&page[..], &[2; 4096][..]);
702    }
703
704    #[test]
705    fn vmo_child_snapshot_at_least_on_write() {
706        let size = 4096 * 2;
707        let vmo = Vmo::create(size).unwrap();
708
709        vmo.write(&[1; 4096], 0).unwrap();
710        vmo.write(&[2; 4096], 4096).unwrap();
711
712        let child = vmo.create_child(VmoChildOptions::SNAPSHOT_AT_LEAST_ON_WRITE, 0, size).unwrap();
713
714        child.write(&[3; 4096], 0).unwrap();
715
716        vmo.write(&[4; 4096], 0).unwrap();
717        vmo.write(&[5; 4096], 4096).unwrap();
718
719        let mut page = [0; 4096];
720
721        // SNAPSHOT_AT_LEAST_ON_WRITE child may observe changes to pages it has not yet written to,
722        // but such behavior is not guaranteed.
723        child.read(&mut page[..], 0).unwrap();
724        assert_eq!(&page[..], &[3; 4096][..]);
725        child.read(&mut page[..], 4096).unwrap();
726        assert!(
727            &page[..] == &[2; 4096][..] || &page[..] == &[5; 4096][..],
728            "expected page of 2 or 5, got {:?}",
729            &page[..]
730        );
731    }
732
733    #[test]
734    fn vmo_child_no_write() {
735        let size = 4096;
736        let vmo = Vmo::create(size).unwrap();
737        vmo.write(&[1; 4096], 0).unwrap();
738
739        let child =
740            vmo.create_child(VmoChildOptions::SLICE | VmoChildOptions::NO_WRITE, 0, size).unwrap();
741        assert_eq!(child.write(&[3; 4096], 0), Err(Status::ACCESS_DENIED));
742    }
743
744    #[test]
745    fn vmo_op_range_unsupported() {
746        let vmo = Vmo::create(12).unwrap();
747        assert_eq!(vmo.op_range(VmoOp::LOCK, 0, 1), Err(Status::NOT_SUPPORTED));
748        assert_eq!(vmo.op_range(VmoOp::UNLOCK, 0, 1), Err(Status::NOT_SUPPORTED));
749    }
750
751    #[test]
752    fn vmo_cache() {
753        let vmo = Vmo::create(12).unwrap();
754
755        // Cache operations should all succeed.
756        assert_eq!(vmo.op_range(VmoOp::CACHE_SYNC, 0, 12), Ok(()));
757        assert_eq!(vmo.op_range(VmoOp::CACHE_INVALIDATE, 0, 12), Ok(()));
758        assert_eq!(vmo.op_range(VmoOp::CACHE_CLEAN, 0, 12), Ok(()));
759        assert_eq!(vmo.op_range(VmoOp::CACHE_CLEAN_INVALIDATE, 0, 12), Ok(()));
760    }
761
762    #[test]
763    fn vmo_create_child() {
764        let original = Vmo::create(16).unwrap();
765        assert!(original.write(b"one", 0).is_ok());
766
767        // Clone the VMO, and make sure it contains what we expect.
768        let clone =
769            original.create_child(VmoChildOptions::SNAPSHOT_AT_LEAST_ON_WRITE, 0, 16).unwrap();
770        let mut read_buffer = vec![0; 16];
771        assert!(clone.read(&mut read_buffer, 0).is_ok());
772        assert_eq!(&read_buffer[0..3], b"one");
773
774        // Writing to the original will not affect the clone.
775        assert!(original.write(b"two", 0).is_ok());
776        assert!(original.read(&mut read_buffer, 0).is_ok());
777        assert_eq!(&read_buffer[0..3], b"two");
778        assert!(clone.read(&mut read_buffer, 0).is_ok());
779        assert_eq!(&read_buffer[0..3], b"one");
780
781        // However, writing to the clone will not affect the original.
782        assert!(clone.write(b"three", 0).is_ok());
783        assert!(original.read(&mut read_buffer, 0).is_ok());
784        assert_eq!(&read_buffer[0..3], b"two");
785        assert!(clone.read(&mut read_buffer, 0).is_ok());
786        assert_eq!(&read_buffer[0..5], b"three");
787    }
788
789    #[test]
790    fn vmo_replace_as_executeable() {
791        use zx::{Channel, HandleBased, MonotonicInstant};
792
793        let vmo = Vmo::create(16).unwrap();
794
795        let info = vmo.as_handle_ref().basic_info().unwrap();
796        assert!(!info.rights.contains(Rights::EXECUTE));
797
798        let (client_end, server_end) = Channel::create();
799        connect_channel_to_protocol::<fkernel::VmexResourceMarker>(server_end).unwrap();
800        let service = fkernel::VmexResourceSynchronousProxy::new(client_end);
801        let resource = service.get(MonotonicInstant::INFINITE).expect("couldn't get vmex resource");
802        let resource = unsafe { crate::Resource::from(Handle::from_raw(resource.into_raw())) };
803
804        let exec_vmo = vmo.replace_as_executable(&resource).unwrap();
805        let info = exec_vmo.as_handle_ref().basic_info().unwrap();
806        assert!(info.rights.contains(Rights::EXECUTE));
807    }
808
809    #[test]
810    fn vmo_content_size() {
811        let start_size = 1024;
812        let vmo = Vmo::create_with_opts(VmoOptions::RESIZABLE, start_size).unwrap();
813        assert_eq!(vmo.get_content_size().unwrap(), start_size);
814        vmo.set_content_size(&0).unwrap();
815        assert_eq!(vmo.get_content_size().unwrap(), 0);
816
817        // write should not change content size.
818        let content = b"abcdef";
819        assert!(vmo.write(content, 0).is_ok());
820        assert_eq!(vmo.get_content_size().unwrap(), 0);
821    }
822
823    #[test]
824    fn vmo_zero() {
825        let vmo = Vmo::create(16).unwrap();
826        let content = b"0123456789abcdef";
827        assert!(vmo.write(content, 0).is_ok());
828        let mut buf = vec![0u8; 16];
829        assert!(vmo.read(&mut buf[..], 0).is_ok());
830        assert_eq!(&buf[..], content);
831
832        assert!(vmo.op_range(VmoOp::ZERO, 0, 16).is_ok());
833        assert!(vmo.read(&mut buf[..], 0).is_ok());
834        assert_eq!(&buf[..], &[0u8; 16]);
835    }
836
837    #[test]
838    fn vmo_stream_size() {
839        let start_size = 1300;
840        let vmo = Vmo::create_with_opts(VmoOptions::UNBOUNDED, start_size).unwrap();
841        assert_eq!(vmo.get_stream_size().unwrap(), start_size);
842        vmo.set_stream_size(0).unwrap();
843        assert_eq!(vmo.get_stream_size().unwrap(), 0);
844
845        // write should not change content size.
846        let content = b"abcdef";
847        assert!(vmo.write(content, 0).is_ok());
848        assert_eq!(vmo.get_stream_size().unwrap(), 0);
849
850        // stream size can also grow.
851        let mut buf = vec![1; 6];
852        vmo.set_stream_size(6).unwrap();
853        assert!(vmo.read(&mut buf, 0).is_ok());
854        // growing will zero new bytes.
855        assert_eq!(buf, vec![0; 6]);
856    }
857}