arcbox-vz 0.4.10

Safe Rust bindings for Apple's Virtualization.framework
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! `VirtioFS` filesystem sharing configuration.
//!
//! This module provides types for sharing directories between the host and guest
//! using `VirtioFS` (virtio-fs).
//!
//! # Example
//!
//! ```rust,no_run
//! use arcbox_vz::{SharedDirectory, SingleDirectoryShare, VirtioFileSystemDeviceConfiguration};
//!
//! # fn example() -> Result<(), arcbox_vz::VZError> {
//! // Share a single directory
//! let shared = SharedDirectory::new("/path/to/share", false)?;
//! let share = SingleDirectoryShare::new(shared)?;
//!
//! let mut fs_config = VirtioFileSystemDeviceConfiguration::new("myshare")?;
//! fs_config.set_share(share);
//! # Ok(())
//! # }
//! ```
//!
//! # Guest Mounting
//!
//! In the guest, mount the shared directory:
//!
//! ```bash
//! mount -t virtiofs myshare /mnt/shared
//! ```

use crate::error::{VZError, VZResult};
use crate::ffi::{get_class, nsstring, nsurl_file_path, release};
use crate::msg_send;
use objc2::runtime::{AnyClass, AnyObject, Bool};
use std::collections::HashMap;
use std::ffi::c_void;
use std::path::Path;

// ============================================================================
// SharedDirectory
// ============================================================================

/// A directory to be shared with the guest.
///
/// This wraps `VZSharedDirectory` and represents a host directory
/// that can be shared with the guest VM.
///
/// # Example
///
/// ```rust,no_run
/// use arcbox_vz::SharedDirectory;
///
/// # fn example() -> Result<(), arcbox_vz::VZError> {
/// // Share a directory read-write
/// let shared = SharedDirectory::new("/home/user/projects", false)?;
///
/// // Share a directory read-only
/// let shared_ro = SharedDirectory::new("/usr/share/doc", true)?;
/// # Ok(())
/// # }
/// ```
pub struct SharedDirectory {
    inner: *mut AnyObject,
}

// SAFETY: Inner ObjC pointer is only used via msg_send! which dispatches to the ObjC runtime.
unsafe impl Send for SharedDirectory {}

impl SharedDirectory {
    /// Creates a new shared directory configuration.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the host directory to share
    /// * `read_only` - If true, the guest can only read from the directory
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The path doesn't exist
    /// - The path is not a directory
    /// - The `VZSharedDirectory` class is not available
    pub fn new(path: impl AsRef<Path>, read_only: bool) -> VZResult<Self> {
        let path = path.as_ref();

        // Validate path exists
        if !path.exists() {
            return Err(VZError::NotFound(path.display().to_string()));
        }

        // Validate it's a directory
        if !path.is_dir() {
            return Err(VZError::InvalidConfiguration(format!(
                "Path is not a directory: {}",
                path.display()
            )));
        }

        // SAFETY: ObjC alloc/init on valid VZSharedDirectory class. NSURL from validated path. readOnly is a Bool value.
        unsafe {
            let cls = get_class("VZSharedDirectory").ok_or_else(|| VZError::Internal {
                code: -1,
                message: "VZSharedDirectory class not found".into(),
            })?;

            // Create NSURL for the path
            let url = nsurl_file_path(&path.to_string_lossy());
            if url.is_null() {
                return Err(VZError::Internal {
                    code: -1,
                    message: "Failed to create NSURL for path".into(),
                });
            }

            // [VZSharedDirectory alloc]
            let obj: *mut AnyObject = msg_send!(cls, alloc);
            if obj.is_null() {
                return Err(VZError::Internal {
                    code: -1,
                    message: "Failed to allocate VZSharedDirectory".into(),
                });
            }

            // [obj initWithURL:url readOnly:readOnly]
            let init_sel = objc2::sel!(initWithURL:readOnly:);
            let init_fn: unsafe extern "C" fn(
                *mut AnyObject,
                objc2::runtime::Sel,
                *mut AnyObject,
                Bool,
            ) -> *mut AnyObject =
                std::mem::transmute(crate::ffi::runtime::objc_msgSend as *const c_void);
            let obj = init_fn(obj, init_sel, url, Bool::new(read_only));

            if obj.is_null() {
                return Err(VZError::Internal {
                    code: -1,
                    message: "Failed to initialize VZSharedDirectory".into(),
                });
            }

            tracing::debug!(
                "Created SharedDirectory for {:?} (read_only={})",
                path,
                read_only
            );

            Ok(Self { inner: obj })
        }
    }

    /// Consumes the shared directory and returns the raw pointer.
    #[must_use]
    pub fn into_ptr(self) -> *mut AnyObject {
        let ptr = self.inner;
        std::mem::forget(self);
        ptr
    }
}

impl Drop for SharedDirectory {
    fn drop(&mut self) {
        if !self.inner.is_null() {
            release(self.inner);
        }
    }
}

// ============================================================================
// DirectoryShare trait
// ============================================================================

/// Trait for directory share configurations.
///
/// This trait is implemented by different share types that can be
/// attached to a `VirtioFS` device.
pub trait DirectoryShare {
    /// Returns the raw pointer to the underlying share object.
    fn as_ptr(&self) -> *mut AnyObject;

    /// Consumes the share and returns the raw pointer.
    fn into_ptr(self) -> *mut AnyObject;
}

// ============================================================================
// SingleDirectoryShare
// ============================================================================

/// A share configuration for a single directory.
///
/// This wraps `VZSingleDirectoryShare` and provides a simple way to
/// share a single host directory with the guest.
///
/// # Example
///
/// ```rust,no_run
/// use arcbox_vz::{SharedDirectory, SingleDirectoryShare};
///
/// # fn example() -> Result<(), arcbox_vz::VZError> {
/// let shared = SharedDirectory::new("/path/to/share", false)?;
/// let share = SingleDirectoryShare::new(shared)?;
/// # Ok(())
/// # }
/// ```
pub struct SingleDirectoryShare {
    inner: *mut AnyObject,
}

// SAFETY: Inner ObjC pointer is only used via msg_send! which dispatches to the ObjC runtime.
unsafe impl Send for SingleDirectoryShare {}

impl SingleDirectoryShare {
    /// Creates a new single directory share.
    ///
    /// # Arguments
    ///
    /// * `directory` - The shared directory to expose
    pub fn new(directory: SharedDirectory) -> VZResult<Self> {
        // SAFETY: ObjC alloc/init on valid VZSingleDirectoryShare class with a valid SharedDirectory pointer.
        unsafe {
            let cls = get_class("VZSingleDirectoryShare").ok_or_else(|| VZError::Internal {
                code: -1,
                message: "VZSingleDirectoryShare class not found".into(),
            })?;

            // [VZSingleDirectoryShare alloc]
            let obj: *mut AnyObject = msg_send!(cls, alloc);
            if obj.is_null() {
                return Err(VZError::Internal {
                    code: -1,
                    message: "Failed to allocate VZSingleDirectoryShare".into(),
                });
            }

            // [obj initWithDirectory:directory]
            let init_sel = objc2::sel!(initWithDirectory:);
            let init_fn: unsafe extern "C" fn(
                *mut AnyObject,
                objc2::runtime::Sel,
                *mut AnyObject,
            ) -> *mut AnyObject =
                std::mem::transmute(crate::ffi::runtime::objc_msgSend as *const c_void);
            let obj = init_fn(obj, init_sel, directory.into_ptr());

            if obj.is_null() {
                return Err(VZError::Internal {
                    code: -1,
                    message: "Failed to initialize VZSingleDirectoryShare".into(),
                });
            }

            tracing::debug!("Created SingleDirectoryShare");

            Ok(Self { inner: obj })
        }
    }
}

impl DirectoryShare for SingleDirectoryShare {
    fn as_ptr(&self) -> *mut AnyObject {
        self.inner
    }

    fn into_ptr(self) -> *mut AnyObject {
        let ptr = self.inner;
        std::mem::forget(self);
        ptr
    }
}

impl Drop for SingleDirectoryShare {
    fn drop(&mut self) {
        if !self.inner.is_null() {
            release(self.inner);
        }
    }
}

// ============================================================================
// MultipleDirectoryShare
// ============================================================================

/// A share configuration for multiple directories.
///
/// This wraps `VZMultipleDirectoryShare` and allows sharing multiple
/// host directories under different names.
///
/// # Example
///
/// ```rust,no_run
/// use arcbox_vz::{SharedDirectory, MultipleDirectoryShare};
///
/// # fn example() -> Result<(), arcbox_vz::VZError> {
/// let home = SharedDirectory::new("/home/user", false)?;
/// let docs = SharedDirectory::new("/usr/share/doc", true)?;
///
/// let mut share = MultipleDirectoryShare::new()?;
/// share.add("home", home);
/// share.add("docs", docs);
/// # Ok(())
/// # }
/// ```
///
/// In the guest, these would be accessible as subdirectories of the mount point.
pub struct MultipleDirectoryShare {
    inner: *mut AnyObject,
    /// Keep track of added directories (Rust ownership)
    directories: HashMap<String, *mut AnyObject>,
}

// SAFETY: Inner ObjC pointer is only used via msg_send! which dispatches to the ObjC runtime.
unsafe impl Send for MultipleDirectoryShare {}

impl MultipleDirectoryShare {
    /// Creates a new multiple directory share.
    pub fn new() -> VZResult<Self> {
        // SAFETY: ObjC new on valid VZMultipleDirectoryShare class. retain prevents autorelease.
        unsafe {
            let cls = get_class("VZMultipleDirectoryShare").ok_or_else(|| VZError::Internal {
                code: -1,
                message: "VZMultipleDirectoryShare class not found".into(),
            })?;

            let obj: *mut AnyObject = msg_send!(cls, new);
            if obj.is_null() {
                return Err(VZError::Internal {
                    code: -1,
                    message: "Failed to create VZMultipleDirectoryShare".into(),
                });
            }

            // Retain
            let _: *mut AnyObject = msg_send!(obj, retain);

            tracing::debug!("Created MultipleDirectoryShare");

            Ok(Self {
                inner: obj,
                directories: HashMap::new(),
            })
        }
    }

    /// Adds a directory to the share.
    ///
    /// # Arguments
    ///
    /// * `name` - The name the directory will appear as in the guest
    /// * `directory` - The shared directory to add
    pub fn add(&mut self, name: &str, directory: SharedDirectory) -> &mut Self {
        // SAFETY: self.inner is a valid VZMultipleDirectoryShare. Sending setObject:forKey: to its directories NSMutableDictionary.
        unsafe {
            // Get the directories dictionary
            let dirs: *mut AnyObject = msg_send!(self.inner, directories);

            // [dirs setObject:directory forKey:name]
            let set_sel = objc2::sel!(setObject:forKey:);
            let set_fn: unsafe extern "C" fn(
                *mut AnyObject,
                objc2::runtime::Sel,
                *mut AnyObject,
                *mut AnyObject,
            ) = std::mem::transmute(crate::ffi::runtime::objc_msgSend as *const c_void);

            let key = nsstring(name);
            let dir_ptr = directory.into_ptr();
            set_fn(dirs, set_sel, dir_ptr, key);

            self.directories.insert(name.to_string(), dir_ptr);

            tracing::debug!("Added directory '{}' to MultipleDirectoryShare", name);
        }
        self
    }

    /// Returns the number of directories in the share.
    #[must_use]
    pub fn len(&self) -> usize {
        self.directories.len()
    }

    /// Returns true if the share has no directories.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.directories.is_empty()
    }
}

impl DirectoryShare for MultipleDirectoryShare {
    fn as_ptr(&self) -> *mut AnyObject {
        self.inner
    }

    fn into_ptr(self) -> *mut AnyObject {
        let ptr = self.inner;
        std::mem::forget(self);
        ptr
    }
}

impl Drop for MultipleDirectoryShare {
    fn drop(&mut self) {
        if !self.inner.is_null() {
            release(self.inner);
        }
        // Note: directories are owned by the VZMultipleDirectoryShare,
        // so we don't release them separately
    }
}

// ============================================================================
// VirtioFileSystemDeviceConfiguration
// ============================================================================

/// Configuration for a `VirtioFS` filesystem device.
///
/// This wraps `VZVirtioFileSystemDeviceConfiguration` and provides
/// filesystem sharing between host and guest.
///
/// # Example
///
/// ```rust,no_run
/// use arcbox_vz::{SharedDirectory, SingleDirectoryShare, VirtioFileSystemDeviceConfiguration};
///
/// # fn example() -> Result<(), arcbox_vz::VZError> {
/// // Create share
/// let shared = SharedDirectory::new("/home/user/projects", false)?;
/// let share = SingleDirectoryShare::new(shared)?;
///
/// // Create filesystem device
/// let mut fs_device = VirtioFileSystemDeviceConfiguration::new("projects")?;
/// fs_device.set_share(share);
/// # Ok(())
/// # }
/// ```
///
/// # Tag Requirements
///
/// The tag must:
/// - Not be empty
/// - Only contain alphanumeric characters and underscores
/// - Be unique among all filesystem devices in the VM
pub struct VirtioFileSystemDeviceConfiguration {
    inner: *mut AnyObject,
    tag: String,
}

// SAFETY: Inner ObjC pointer is only used via msg_send! which dispatches to the ObjC runtime.
unsafe impl Send for VirtioFileSystemDeviceConfiguration {}

impl VirtioFileSystemDeviceConfiguration {
    /// Creates a new `VirtioFS` device configuration.
    ///
    /// # Arguments
    ///
    /// * `tag` - The mount tag used to identify this share in the guest
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The tag is invalid (empty or contains invalid characters)
    /// - The `VZVirtioFileSystemDeviceConfiguration` class is not available
    pub fn new(tag: &str) -> VZResult<Self> {
        // Validate tag is not empty
        if tag.is_empty() {
            return Err(VZError::InvalidConfiguration(
                "VirtioFS tag cannot be empty".into(),
            ));
        }

        // SAFETY: ObjC alloc/init on valid VZVirtioFileSystemDeviceConfiguration class. Tag is validated via validateTag:error: before use.
        unsafe {
            let cls = get_class("VZVirtioFileSystemDeviceConfiguration").ok_or_else(|| {
                VZError::Internal {
                    code: -1,
                    message: "VZVirtioFileSystemDeviceConfiguration class not found".into(),
                }
            })?;

            // Validate tag using [VZVirtioFileSystemDeviceConfiguration validateTag:error:]
            let tag_ns = nsstring(tag);
            let mut error: *mut AnyObject = std::ptr::null_mut();

            let validate_sel = objc2::sel!(validateTag:error:);
            let validate_fn: unsafe extern "C" fn(
                *const AnyObject,
                objc2::runtime::Sel,
                *mut AnyObject,
                *mut *mut AnyObject,
            ) -> Bool = std::mem::transmute(crate::ffi::runtime::objc_msgSend as *const c_void);

            let valid = validate_fn(
                cls as *const AnyClass as *const AnyObject,
                validate_sel,
                tag_ns,
                &mut error,
            );

            if !valid.as_bool() {
                let error_msg = if error.is_null() {
                    format!("Invalid VirtioFS tag: {tag}")
                } else {
                    let desc: *mut AnyObject = msg_send!(error, localizedDescription);
                    crate::ffi::nsstring_to_string(desc)
                };
                return Err(VZError::InvalidConfiguration(error_msg));
            }

            // [VZVirtioFileSystemDeviceConfiguration alloc]
            let obj: *mut AnyObject = msg_send!(cls, alloc);
            if obj.is_null() {
                return Err(VZError::Internal {
                    code: -1,
                    message: "Failed to allocate VZVirtioFileSystemDeviceConfiguration".into(),
                });
            }

            // [obj initWithTag:tag]
            let init_sel = objc2::sel!(initWithTag:);
            let init_fn: unsafe extern "C" fn(
                *mut AnyObject,
                objc2::runtime::Sel,
                *mut AnyObject,
            ) -> *mut AnyObject =
                std::mem::transmute(crate::ffi::runtime::objc_msgSend as *const c_void);
            let obj = init_fn(obj, init_sel, tag_ns);

            if obj.is_null() {
                return Err(VZError::Internal {
                    code: -1,
                    message: "Failed to initialize VZVirtioFileSystemDeviceConfiguration".into(),
                });
            }

            tracing::debug!(
                "Created VirtioFileSystemDeviceConfiguration with tag '{}'",
                tag
            );

            Ok(Self {
                inner: obj,
                tag: tag.to_string(),
            })
        }
    }

    /// Sets the directory share for this filesystem device.
    ///
    /// # Arguments
    ///
    /// * `share` - The directory share configuration
    pub fn set_share<S: DirectoryShare>(&mut self, share: S) -> &mut Self {
        // SAFETY: self.inner is a valid VZVirtioFileSystemDeviceConfiguration. share.into_ptr() provides a valid directory share object.
        unsafe {
            let set_sel = objc2::sel!(setShare:);
            let set_fn: unsafe extern "C" fn(*mut AnyObject, objc2::runtime::Sel, *mut AnyObject) =
                std::mem::transmute(crate::ffi::runtime::objc_msgSend as *const c_void);
            set_fn(self.inner, set_sel, share.into_ptr());

            tracing::debug!("Set share for VirtioFS device '{}'", self.tag);
        }
        self
    }

    /// Returns the tag for this filesystem device.
    #[must_use]
    pub fn tag(&self) -> &str {
        &self.tag
    }

    /// Consumes the configuration and returns the raw pointer.
    #[must_use]
    pub fn into_ptr(self) -> *mut AnyObject {
        let ptr = self.inner;
        std::mem::forget(self);
        ptr
    }
}

impl Drop for VirtioFileSystemDeviceConfiguration {
    fn drop(&mut self) {
        if !self.inner.is_null() {
            release(self.inner);
        }
    }
}

// ============================================================================
// LinuxRosettaDirectoryShare (macOS 13+)
// ============================================================================

/// Availability status for Rosetta.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RosettaAvailability {
    /// Rosetta is not supported on this system.
    NotSupported,
    /// Rosetta is supported and installed.
    Supported,
    /// Rosetta needs to be installed.
    NotInstalled,
}

/// A share configuration for Linux Rosetta translation.
///
/// This wraps `VZLinuxRosettaDirectoryShare` and enables `x86_64` binary
/// translation on Apple Silicon Macs.
///
/// # Availability
///
/// This is only available on:
/// - macOS 13.0 or later
/// - Apple Silicon Macs
///
/// # Example
///
/// ```rust,no_run
/// use arcbox_vz::LinuxRosettaDirectoryShare;
///
/// # fn example() -> Result<(), arcbox_vz::VZError> {
/// if LinuxRosettaDirectoryShare::availability() == arcbox_vz::RosettaAvailability::Supported {
///     let rosetta = LinuxRosettaDirectoryShare::new()?;
///     // Add to VM configuration...
/// }
/// # Ok(())
/// # }
/// ```
pub struct LinuxRosettaDirectoryShare {
    inner: *mut AnyObject,
}

// SAFETY: Inner ObjC pointer is only used via msg_send! which dispatches to the ObjC runtime.
unsafe impl Send for LinuxRosettaDirectoryShare {}

impl LinuxRosettaDirectoryShare {
    /// Checks the availability of Rosetta on this system.
    pub fn availability() -> RosettaAvailability {
        // SAFETY: cls is a valid VZLinuxRosettaDirectoryShare class pointer from get_class. Sending availability to it.
        unsafe {
            let cls = match get_class("VZLinuxRosettaDirectoryShare") {
                Some(c) => c,
                None => return RosettaAvailability::NotSupported,
            };

            // [VZLinuxRosettaDirectoryShare availability]
            let avail_sel = objc2::sel!(availability);
            let avail_fn: unsafe extern "C" fn(*const AnyObject, objc2::runtime::Sel) -> i64 =
                std::mem::transmute(crate::ffi::runtime::objc_msgSend as *const c_void);
            let avail = avail_fn(cls as *const AnyClass as *const AnyObject, avail_sel);

            // VZLinuxRosettaAvailability enum values:
            // 0 = VZLinuxRosettaAvailabilityNotSupported
            // 1 = VZLinuxRosettaAvailabilitySupported (installed)
            // 2 = VZLinuxRosettaAvailabilityNotInstalled
            match avail {
                0 => RosettaAvailability::NotSupported,
                1 => RosettaAvailability::Supported,
                2 => RosettaAvailability::NotInstalled,
                _ => RosettaAvailability::NotSupported,
            }
        }
    }

    /// Creates a new Linux Rosetta directory share.
    ///
    /// # Errors
    ///
    /// Returns an error if Rosetta is not available or not installed.
    pub fn new() -> VZResult<Self> {
        let avail = Self::availability();
        if avail != RosettaAvailability::Supported {
            return Err(VZError::OperationFailed(format!(
                "Rosetta is not available: {avail:?}"
            )));
        }

        // SAFETY: ObjC new on valid VZLinuxRosettaDirectoryShare class. Availability is checked above. retain prevents autorelease.
        unsafe {
            let cls =
                get_class("VZLinuxRosettaDirectoryShare").ok_or_else(|| VZError::Internal {
                    code: -1,
                    message: "VZLinuxRosettaDirectoryShare class not found".into(),
                })?;

            let obj: *mut AnyObject = msg_send!(cls, new);
            if obj.is_null() {
                return Err(VZError::Internal {
                    code: -1,
                    message: "Failed to create VZLinuxRosettaDirectoryShare".into(),
                });
            }

            // Retain
            let _: *mut AnyObject = msg_send!(obj, retain);

            tracing::debug!("Created LinuxRosettaDirectoryShare");

            Ok(Self { inner: obj })
        }
    }
}

impl DirectoryShare for LinuxRosettaDirectoryShare {
    fn as_ptr(&self) -> *mut AnyObject {
        self.inner
    }

    fn into_ptr(self) -> *mut AnyObject {
        let ptr = self.inner;
        std::mem::forget(self);
        ptr
    }
}

impl Drop for LinuxRosettaDirectoryShare {
    fn drop(&mut self) {
        if !self.inner.is_null() {
            release(self.inner);
        }
    }
}