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
//! CoreFoundation and IOKit objects for the macOS readings: owners that release
//! on every path, and a borrowed view with checked readers, so the readings
//! above it hold no raw reference and call nothing unsafe.
use core::{
ffi::{CStr, c_char, c_void},
marker::PhantomData,
};
use super::{ffi, kern_error};
use crate::{Error, Result};
/// A CoreFoundation object this code owns (one reference), released on drop.
pub(super) struct Cf(ffi::CfRef);
impl Cf {
/// Takes the one reference a Create or Copy function returned; null is `None`.
/// The owner is made only for a real object: `then_some` would make one for
/// null too and drop it, which is `CFRelease(NULL)`, a crash.
pub(super) fn new(object: ffi::CfRef) -> Option<Cf> {
if object.is_null() {
None
} else {
Some(Cf(object))
}
}
/// An immutable UTF-8 `CFString`.
pub(super) fn string(what: &'static str, text: &str) -> Result<Cf> {
let len = ffi::CfIndex::try_from(text.len()).unwrap_or(0);
// SAFETY: `text` is `len` readable bytes; the null allocator is the
// default one.
let object = unsafe {
ffi::CFStringCreateWithBytes(
core::ptr::null(),
text.as_ptr(),
len,
ffi::CF_STRING_ENCODING_UTF8,
0,
)
};
Cf::new(object).ok_or_else(|| kern_error(what, "CFStringCreateWithBytes", 0))
}
/// The reference, for a call that only reads it.
pub(super) fn raw(&self) -> ffi::CfRef {
self.0
}
/// The object as a borrowed value.
pub(super) fn get(&self) -> Ref<'_> {
Ref {
object: self.0,
owner: PhantomData,
}
}
/// A reference the Get rule lends out of this object: CoreFoundation keeps
/// it alive as long as `self`, and null is `None`.
pub(super) fn lent(&self, object: ffi::CfRef) -> Option<Ref<'_>> {
(!object.is_null()).then_some(Ref {
object,
owner: PhantomData,
})
}
}
impl Drop for Cf {
fn drop(&mut self) {
// SAFETY: this value owns one reference, released once.
unsafe { ffi::CFRelease(self.0) };
}
}
/// A live CoreFoundation object, valid while its owner is. The readers check
/// the object's type first: a registry property can be anything.
#[derive(Clone, Copy)]
pub(super) struct Ref<'a> {
object: ffi::CfRef,
owner: PhantomData<&'a Cf>,
}
impl<'a> Ref<'a> {
fn is(self, type_id: ffi::CfTypeId) -> bool {
// SAFETY: `self.object` is a live CoreFoundation object.
let id = unsafe { ffi::CFGetTypeID(self.object) };
id == type_id
}
/// The reference, for a call that only reads it.
pub(super) fn raw(self) -> ffi::CfRef {
self.object
}
pub(super) fn is_dictionary(self) -> bool {
self.is(ffi::CFDictionaryGetTypeID())
}
/// The value of `key`, when this is a dictionary holding it.
pub(super) fn value(self, key: &Cf) -> Option<Ref<'a>> {
if !self.is_dictionary() {
return None;
}
// SAFETY: `self.object` is a dictionary and `key` a live object. The
// value is borrowed from the dictionary (Get rule).
let object = unsafe { ffi::CFDictionaryGetValue(self.object, key.raw()) };
(!object.is_null()).then_some(Ref {
object,
owner: PhantomData,
})
}
/// The elements of an array, the first `max` of them.
pub(super) fn items(self, max: usize) -> impl Iterator<Item = Ref<'a>> {
let count = if self.is(ffi::CFArrayGetTypeID()) {
// SAFETY: `self.object` is an array.
let count = unsafe { ffi::CFArrayGetCount(self.object) };
count.clamp(0, ffi::CfIndex::try_from(max).unwrap_or(ffi::CfIndex::MAX))
} else {
0
};
(0..count).filter_map(move |index| {
// SAFETY: `self.object` is an array and `index` is within its
// count. The element is borrowed from the array (Get rule).
let object = unsafe { ffi::CFArrayGetValueAtIndex(self.object, index) };
(!object.is_null()).then_some(Ref {
object,
owner: PhantomData,
})
})
}
/// The value of a `CFNumber` that fits 64 bits exactly.
pub(super) fn int(self) -> Option<i64> {
if !self.is(ffi::CFNumberGetTypeID()) {
return None;
}
let mut n: i64 = 0;
// SAFETY: `self.object` is a `CFNumber` and `n` a writable 64-bit
// integer, the size of `kCFNumberSInt64Type`.
let exact = unsafe {
ffi::CFNumberGetValue(
self.object,
ffi::CF_NUMBER_SINT64_TYPE,
(&raw mut n).cast::<c_void>(),
)
};
(exact != 0).then_some(n)
}
/// The value of a `CFBoolean`.
pub(super) fn flag(self) -> Option<bool> {
if !self.is(ffi::CFBooleanGetTypeID()) {
return None;
}
// SAFETY: `self.object` is a `CFBoolean`.
let value = unsafe { ffi::CFBooleanGetValue(self.object) };
Some(value != 0)
}
/// A `CFString` as UTF-8 in `buf`, up to its NUL; `None` when it is another
/// type or does not fit. The string goes nowhere but `buf`.
pub(super) fn text(self, buf: &mut [u8]) -> Option<&[u8]> {
if !self.is(ffi::CFStringGetTypeID()) {
return None;
}
let size = ffi::CfIndex::try_from(buf.len()).ok()?;
// SAFETY: `self.object` is a `CFString` and `buf` is `size` writable
// bytes; the call writes at most that many, the NUL included.
let ok = unsafe {
ffi::CFStringGetCString(
self.object,
buf.as_mut_ptr().cast::<c_char>(),
size,
ffi::CF_STRING_ENCODING_UTF8,
)
};
if ok == 0 {
return None;
}
let end = buf.iter().position(|&b| b == 0)?;
Some(&buf[..end])
}
/// The bytes of a `CFData`.
pub(super) fn data(self) -> Option<&'a [u8]> {
if !self.is(ffi::CFDataGetTypeID()) {
return None;
}
// SAFETY: `self.object` is a `CFData`.
let len = usize::try_from(unsafe { ffi::CFDataGetLength(self.object) }).ok()?;
// SAFETY: as above.
let bytes = unsafe { ffi::CFDataGetBytePtr(self.object) };
if bytes.is_null() {
return None;
}
// SAFETY: an immutable `CFData` holds `len` bytes at `bytes` for as long
// as it lives, which `'a` does not outlast.
Some(unsafe { core::slice::from_raw_parts(bytes, len) })
}
}
/// An IOKit object this code owns, released on drop.
pub(super) struct Io(pub(super) ffi::IoObject);
impl Io {
/// Takes an object an IOKit call returned; 0 is `None`, and nothing is
/// released for it (see `Cf::new`).
pub(super) fn new(object: ffi::IoObject) -> Option<Io> {
if object == 0 { None } else { Some(Io(object)) }
}
/// The service a matching dictionary finds. The dictionary's one reference
/// is consumed on every path, so `matching` must not be used again.
pub(super) fn matching(matching: ffi::CfRef) -> Option<Io> {
if matching.is_null() {
return None;
}
// SAFETY: `matching` is a dictionary with one reference, which the call
// consumes; the object returned, if any, is owned by the result.
let service =
unsafe { ffi::IOServiceGetMatchingService(ffi::IO_MAIN_PORT_DEFAULT, matching) };
Io::new(service)
}
/// The first service of an IOKit class.
pub(super) fn service(class: &CStr) -> Option<Io> {
// SAFETY: the class name is NUL-terminated. The dictionary returned
// carries one reference, which `matching` consumes.
let matching = unsafe { ffi::IOServiceMatching(class.as_ptr()) };
Io::matching(matching)
}
/// The registry entry at `path` (`IODeviceTree:/chosen`).
pub(super) fn at_path(path: &CStr) -> Option<Io> {
// SAFETY: the path is NUL-terminated; the object returned, if any, is
// owned by the result.
let entry =
unsafe { ffi::IORegistryEntryFromPath(ffi::IO_MAIN_PORT_DEFAULT, path.as_ptr()) };
Io::new(entry)
}
/// The BSD device's media (`disk3s1`).
pub(super) fn bsd_device(name: &CStr) -> Option<Io> {
// SAFETY: the name is NUL-terminated. The dictionary returned carries
// one reference, which `matching` consumes.
let matching =
unsafe { ffi::IOBSDNameMatching(ffi::IO_MAIN_PORT_DEFAULT, 0, name.as_ptr()) };
Io::matching(matching)
}
/// A copy of a property of this registry entry.
pub(super) fn property(&self, key: &Cf) -> Option<Cf> {
// SAFETY: `self.0` is a live registry entry and `key` a live `CFString`;
// the null allocator is the default one. The result, if any, carries
// one reference, owned by the returned value.
Cf::new(unsafe {
ffi::IORegistryEntryCreateCFProperty(self.0, key.raw(), core::ptr::null(), 0)
})
}
/// Calls `f` with each service of an IOKit class (its subclasses
/// included), at most `max` of them; more is `TooLarge`.
pub(super) fn for_each(
class: &CStr,
max: usize,
what: &'static str,
mut f: impl FnMut(&Io) -> Result<()>,
) -> Result<()> {
// SAFETY: the class name is NUL-terminated. The dictionary returned
// carries one reference, consumed below.
let matching = unsafe { ffi::IOServiceMatching(class.as_ptr()) };
if matching.is_null() {
return Err(kern_error(what, "IOServiceMatching", 0));
}
let mut iterator: ffi::IoObject = 0;
// SAFETY: `matching` is a dictionary with one reference, which the
// call consumes on every path; `iterator` is writable.
let kr = unsafe {
ffi::IOServiceGetMatchingServices(
ffi::IO_MAIN_PORT_DEFAULT,
matching,
&raw mut iterator,
)
};
if kr != ffi::KERN_SUCCESS {
return Err(kern_error(what, "IOServiceGetMatchingServices", kr));
}
let Some(iterator) = Io::new(iterator) else {
return Ok(());
};
for n in 0..=max {
// SAFETY: `iterator` is a live iterator this function owns; the
// object returned, if any, is owned by `service`.
let Some(service) = Io::new(unsafe { ffi::IOIteratorNext(iterator.0) }) else {
return Ok(());
};
if n == max {
break;
}
f(&service)?;
}
Err(Error::TooLarge {
what,
limit: max as u64,
})
}
/// The name of this object's class (`AGXAcceleratorG13X`), up to its NUL.
pub(super) fn class(&self) -> Option<Vec<u8>> {
let mut name: ffi::IoName = [0; 128];
// SAFETY: `self.0` is a live object and `name` the 128 writable bytes
// of an `io_name_t`, which the call fills NUL-terminated.
let kr = unsafe { ffi::IOObjectGetClass(self.0, name.as_mut_ptr()) };
if kr != ffi::KERN_SUCCESS {
return None;
}
let bytes = super::c_array_bytes(&name);
(!bytes.is_empty()).then_some(bytes)
}
/// This entry's first parent in the service plane.
pub(super) fn parent(&self) -> Option<Io> {
let mut parent: ffi::IoObject = 0;
// SAFETY: `self.0` is a live registry entry, the plane name is
// NUL-terminated, and `parent` is writable; a parent returned is owned
// by the result.
let kr = unsafe {
ffi::IORegistryEntryGetParentEntry(self.0, c"IOService".as_ptr(), &raw mut parent)
};
let parent = Io::new(parent)?;
(kr == ffi::KERN_SUCCESS).then_some(parent)
}
/// This entry's first child in the service plane.
pub(super) fn child(&self) -> Option<Io> {
let mut child: ffi::IoObject = 0;
// SAFETY: as in `parent`.
let kr = unsafe {
ffi::IORegistryEntryGetChildEntry(self.0, c"IOService".as_ptr(), &raw mut child)
};
let child = Io::new(child)?;
(kr == ffi::KERN_SUCCESS).then_some(child)
}
}
impl Drop for Io {
fn drop(&mut self) {
// SAFETY: this value owns the object, released once.
unsafe { ffi::IOObjectRelease(self.0) };
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_iokit_null_is_none_and_never_released() {
// A property a registry entry does not have comes back null: before the
// fix, taking it released NULL and CoreFoundation stopped the process.
assert!(Cf::new(core::ptr::null()).is_none());
assert!(Io::new(0).is_none());
let platform = Io::service(c"IOPlatformExpertDevice").unwrap();
let missing = Cf::string("test", "sys-lib: no such property").unwrap();
assert!(platform.property(&missing).is_none());
}
}