summaryrefslogtreecommitdiffstats
path: root/src/data_collection/disks/unix/macos/io_kit/io_object.rs
blob: 0d567a865de4774fc8b1d2ffdee3bbb960707767 (plain)
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
//! Based on [heim's](https://github.com/heim-rs/heim/blob/master/heim-common/src/sys/macos/iokit/io_object.rs)
//! implementation.

use std::mem;

use anyhow::{anyhow, bail};
use core_foundation::base::{kCFAllocatorDefault, CFType, TCFType, ToVoid};
use core_foundation::dictionary::{
    CFDictionary, CFDictionaryGetTypeID, CFDictionaryRef, CFMutableDictionary,
    CFMutableDictionaryRef,
};
use core_foundation::number::{CFNumber, CFNumberGetTypeID};
use core_foundation::string::{CFString, CFStringGetTypeID};
use mach2::kern_return;

use super::bindings::*;

/// Safe wrapper around the IOKit `io_object_t` type.
#[derive(Debug)]
pub struct IoObject(io_object_t);

impl IoObject {
    /// Returns a typed dictionary with this object's properties.
    pub fn properties(&self) -> anyhow::Result<CFDictionary<CFString, CFType>> {
        // SAFETY: The IOKit call should be fine, the arguments are safe. The `assume_init` should also be fine, as
        // we guard against it with a check against `result` to ensure it succeeded.
        unsafe {
            let mut props = mem::MaybeUninit::<CFMutableDictionaryRef>::uninit();

            let result = IORegistryEntryCreateCFProperties(
                self.0,
                props.as_mut_ptr(),
                kCFAllocatorDefault,
                0,
            );

            if result != kern_return::KERN_SUCCESS {
                bail!("IORegistryEntryCreateCFProperties failed, error code {result}.")
            } else {
                let props = props.assume_init();
                Ok(CFMutableDictionary::wrap_under_create_rule(props).to_immutable())
            }
        }
    }

    /// Gets the [`kIOServicePlane`] parent [`io_object_t`] for this [`io_object_t`], if there
    /// is one.
    pub fn service_parent(&self) -> anyhow::Result<IoObject> {
        let mut parent: io_registry_entry_t = 0;

        // SAFETY: IOKit call, the arguments should be safe.
        let result = unsafe {
            IORegistryEntryGetParentEntry(self.0, kIOServicePlane.as_ptr().cast(), &mut parent)
        };

        if result != kern_return::KERN_SUCCESS {
            bail!("IORegistryEntryGetParentEntry failed, error code {result}.")
        } else {
            Ok(parent.into())
        }
    }

    // pub fn conforms_to_block_storage_driver(&self) -> bool {
    //     // SAFETY: IOKit call, the arguments should be safe.
    //     let result =
    //         unsafe { IOObjectConformsTo(self.0, "IOBlockStorageDriver\0".as_ptr().cast()) };

    //     result != 0
    // }
}

impl From<io_object_t> for IoObject {
    fn from(obj: io_object_t) -> IoObject {
        IoObject(obj)
    }
}

impl Drop for IoObject {
    fn drop(&mut self) {
        // SAFETY: IOKit call, the argument here (an `io_object_t`) should be safe and expected.
        let result = unsafe { IOObjectRelease(self.0) };
        assert_eq!(result, kern_return::KERN_SUCCESS);
    }
}

pub fn get_dict(
    dict: &CFDictionary<CFString, CFType>, raw_key: &'static str,
) -> anyhow::Result<CFDictionary<CFString, CFType>> {
    let key = CFString::from_static_string(raw_key);

    dict.find(&key)
        .map(|value_ref| {
            // SAFETY: Only used for debug asserts, system API call that should be safe.
            unsafe {
                debug_assert!(value_ref.type_of() == CFDictionaryGetTypeID());
            }

            // "Casting" `CFDictionary<*const void, *const void>` into a needed dict type
            let ptr = value_ref.to_void() as CFDictionaryRef;

            // SAFETY: System API call, it should be safe?
            unsafe { CFDictionary::wrap_under_get_rule(ptr) }
        })
        .ok_or_else(|| anyhow!("missing key"))
}

pub fn get_i64(
    dict: &CFDictionary<CFString, CFType>, raw_key: &'static str,
) -> anyhow::Result<i64> {
    let key = CFString::from_static_string(raw_key);

    dict.find(&key)
        .and_then(|value_ref| {
            // SAFETY: Only used for debug asserts, system API call that should be safe.
            unsafe {
                debug_assert!(value_ref.type_of() == CFNumberGetTypeID());
            }
            value_ref.downcast::<CFNumber>()
        })
        .and_then(|number| number.to_i64())
        .ok_or_else(|| anyhow!("missing key"))
}

pub fn get_string(
    dict: &CFDictionary<CFString, CFType>, raw_key: &'static str,
) -> anyhow::Result<String> {
    let key = CFString::from_static_string(raw_key);

    dict.find(&key)
        .and_then(|value_ref| {
            // SAFETY: Only used for debug asserts, system API call that should be safe.
            unsafe {
                debug_assert!(value_ref.type_of() == CFStringGetTypeID());
            }

            value_ref.downcast::<CFString>()
        })
        .map(|cf_string| cf_string.to_string())
        .ok_or_else(|| anyhow!("missing key"))
}