Debian Codegraph @

src/platform/macos_iokit/iokit_usb.rs

raw symbols SCIP
1 //! Wrappers for IOKit USB device and interface
2 //!
3 //! Based on Kate Temkin's [usrs](https://github.com/ktemkin/usrs)
4 //! licensed under MIT OR Apache-2.0.
5
6 use std::{collections::BTreeMap, io::ErrorKind, ptr, slice, time::Duration};
7
8 use core_foundation::{base::TCFType, runloop::CFRunLoopSource};
9 use core_foundation_sys::runloop::CFRunLoopSourceRef;
10 use io_kit_sys::{
11 ret::{kIOReturnNoResources, kIOReturnSuccess},
12 types::io_iterator_t,
13 };
14 use log::error;
15
16 use crate::{
17 platform::macos_iokit::{
18 iokit::usb_interface_type_id, iokit_c::kIOUsbInterfaceUserClientTypeID,
19 },
20 Error,
21 };
22
23 use super::{
24 iokit::{
25 self, call_iokit_function, check_iokit_return, usb_device_type_id, IoService,
26 IoServiceIterator, PluginInterface,
27 },
28 iokit_c::{
29 kIOCFPlugInInterfaceID, kIOUSBFindInterfaceDontCare, kIOUsbDeviceUserClientTypeID,
30 IOCFPlugInInterface, IOCreatePlugInInterfaceForService, IOUSBConfigurationDescriptor,
31 IOUSBFindInterfaceRequest,
32 },
33 };
34
35 /// Wrapper around an IOKit UsbDevice
36 pub(crate) struct IoKitDevice {
37 pub(crate) raw: *mut *mut iokit::UsbDevice,
38 }
39
40 impl IoKitDevice {
41 /// Get the raw USB device associated with the service.
42 pub(crate) fn new(service: IoService) -> Result<IoKitDevice, Error> {
43 unsafe {
44 // According to the libusb maintainers, this will sometimes spuriously
45 // return `kIOReturnNoResources` for reasons Apple won't explain, usually
46 // when a device is freshly plugged in. We'll allow this a few retries,
47 // accordingly.
48 //
49 // [This behavior actually makes sense to me -- when the device is first plugged
50 // in, it exists to IOKit, but hasn't been enumerated, yet. Accordingly, the device
51 // interface doesn't actually yet exist for us to grab, and/or doesn't yet have the
52 // right permissions for us to grab it. MacOS needs to see if a kernel driver binds
53 // to it; as its security model won't allow the userland to grab a device that the
54 // kernel owns.]
55 //
56 // If the kIOReturnNoResources persists, it's typically an indication that
57 // macOS is preventing us from touching the relevant device due to its security
58 // model. This happens when the device has a kernel-mode driver bound to the
59 // whole device -- the kernel owns it, and it's unwilling to give it to us.
60 for _ in 0..5 {
61 let mut _score: i32 = 0;
62 let mut raw_device_plugin: *mut *mut IOCFPlugInInterface = std::ptr::null_mut();
63
64 let rc = IOCreatePlugInInterfaceForService(
65 service.get(),
66 kIOUsbDeviceUserClientTypeID(),
67 kIOCFPlugInInterfaceID(),
68 &mut raw_device_plugin,
69 &mut _score,
70 );
71
72 if rc == kIOReturnNoResources {
73 std::thread::sleep(Duration::from_millis(1));
74 continue;
75 }
76
77 if rc != kIOReturnSuccess {
78 return Err(Error::from_raw_os_error(rc));
79 }
80
81 if raw_device_plugin.is_null() {
82 error!("IOKit indicated it successfully created a PlugInInterface, but the pointer was NULL");
83 return Err(Error::new(
84 ErrorKind::Other,
85 "Could not create PlugInInterface",
86 ));
87 }
88
89 let device_plugin = PluginInterface::new(raw_device_plugin);
90
91 let mut raw_device: *mut *mut iokit::UsbDevice = std::ptr::null_mut();
92
93 call_iokit_function!(
94 device_plugin.get(),
95 QueryInterface(
96 usb_device_type_id(),
97 &mut raw_device as *mut *mut *mut _ as *mut *mut c_void
98 )
99 );
100
101 // macOS claims that call will never fail, and will always produce a valid pointer.
102 // We don't trust it, so we're going to panic if it's lied to us.
103 if raw_device.is_null() {
104 panic!(
105 "query_interface returned a null pointer, which Apple says is impossible"
106 );
107 }
108
109 return Ok(IoKitDevice { raw: raw_device });
110 }
111
112 return Err(Error::new(
113 ErrorKind::NotFound,
114 "Couldn't create device after retries",
115 ));
116 }
117 }
118
119 pub(crate) fn create_async_event_source(&self) -> Result<CFRunLoopSource, Error> {
120 unsafe {
121 let mut raw_source: CFRunLoopSourceRef = std::ptr::null_mut();
122 check_iokit_return(call_iokit_function!(
123 self.raw,
124 CreateDeviceAsyncEventSource(&mut raw_source)
125 ))?;
126 Ok(CFRunLoopSource::wrap_under_create_rule(raw_source))
127 }
128 }
129
130 /// Returns an IOKit iterator that can be used to iterate over all interfaces on this device.
131 pub(crate) fn create_interface_iterator(&self) -> Result<IoServiceIterator, Error> {
132 unsafe {
133 let mut iterator: io_iterator_t = 0;
134
135 let mut dont_care = IOUSBFindInterfaceRequest {
136 bInterfaceClass: kIOUSBFindInterfaceDontCare,
137 bInterfaceSubClass: kIOUSBFindInterfaceDontCare,
138 bInterfaceProtocol: kIOUSBFindInterfaceDontCare,
139 bAlternateSetting: kIOUSBFindInterfaceDontCare,
140 };
141
142 check_iokit_return(call_iokit_function!(
143 self.raw,
144 CreateInterfaceIterator(&mut dont_care, &mut iterator)
145 ))?;
146
147 Ok(IoServiceIterator::new(iterator))
148 }
149 }
150
151 pub(crate) fn get_number_of_configurations(&self) -> Result<u8, Error> {
152 unsafe {
153 let mut num = 0;
154 check_iokit_return(call_iokit_function!(
155 self.raw,
156 GetNumberOfConfigurations(&mut num)
157 ))?;
158 Ok(num)
159 }
160 }
161
162 pub(crate) fn get_configuration_descriptor(&self, index: u8) -> Result<&[u8], Error> {
163 unsafe {
164 let mut ptr: *mut IOUSBConfigurationDescriptor = ptr::null_mut();
165 check_iokit_return(call_iokit_function!(
166 self.raw,
167 GetConfigurationDescriptorPtr(index, &mut ptr)
168 ))?;
169 let len = u16::to_le((*ptr).wTotalLength) as usize;
170 Ok(slice::from_raw_parts(ptr as *const u8, len))
171 }
172 }
173
174 pub(crate) fn get_configuration(&self) -> Result<u8, Error> {
175 unsafe {
176 let mut val = 0;
177 check_iokit_return(call_iokit_function!(self.raw, GetConfiguration(&mut val)))?;
178 Ok(val)
179 }
180 }
181 }
182
183 impl Drop for IoKitDevice {
184 fn drop(&mut self) {
185 unsafe {
186 call_iokit_function!(self.raw, Release());
187 }
188 }
189 }
190
191 unsafe impl Send for IoKitDevice {}
192 unsafe impl Sync for IoKitDevice {}
193
194 #[derive(Debug)]
195 #[allow(dead_code)]
196 pub(crate) struct EndpointInfo {
197 pub(crate) pipe_ref: u8,
198 pub(crate) direction: u8,
199 pub(crate) number: u8,
200 pub(crate) transfer_type: u8,
201 pub(crate) max_packet_size: u16,
202 pub(crate) interval: u8,
203 pub(crate) max_burst: u8,
204 pub(crate) mult: u8,
205 pub(crate) bytes_per_interval: u16,
206 }
207
208 impl EndpointInfo {
209 pub(crate) fn address(&self) -> u8 {
210 if self.direction == 0 {
211 self.number
212 } else {
213 self.number | 0x80
214 }
215 }
216 }
217
218 /// Wrapper around an IOKit UsbInterface
219 pub(crate) struct IoKitInterface {
220 pub(crate) raw: *mut *mut iokit::UsbInterface,
221 }
222
223 impl IoKitInterface {
224 pub(crate) fn new(service: IoService) -> Result<IoKitInterface, Error> {
225 unsafe {
226 let mut _score: i32 = 0;
227 let mut raw_interface_plugin: *mut *mut IOCFPlugInInterface = std::ptr::null_mut();
228
229 let rc = IOCreatePlugInInterfaceForService(
230 service.get(),
231 kIOUsbInterfaceUserClientTypeID(),
232 kIOCFPlugInInterfaceID(),
233 &mut raw_interface_plugin,
234 &mut _score,
235 );
236
237 if rc != kIOReturnSuccess {
238 return Err(Error::from_raw_os_error(rc));
239 }
240
241 if raw_interface_plugin.is_null() {
242 error!("IOKit indicated it successfully created a PlugInInterface, but the pointer was NULL");
243 return Err(Error::new(
244 ErrorKind::Other,
245 "Could not create PlugInInterface",
246 ));
247 }
248
249 let interface_plugin = PluginInterface::new(raw_interface_plugin);
250
251 let mut raw: *mut *mut iokit::UsbInterface = std::ptr::null_mut();
252
253 call_iokit_function!(
254 interface_plugin.get(),
255 QueryInterface(
256 usb_interface_type_id(),
257 &mut raw as *mut *mut *mut _ as *mut *mut c_void
258 )
259 );
260
261 // macOS claims that call will never fail, and will always produce a valid pointer.
262 // We don't trust it, so we're going to panic if it's lied to us.
263 if raw.is_null() {
264 panic!("query_interface returned a null pointer, which Apple says is impossible");
265 }
266
267 return Ok(IoKitInterface { raw });
268 }
269 }
270
271 pub(crate) fn open(&mut self) -> Result<(), Error> {
272 unsafe { check_iokit_return(call_iokit_function!(self.raw, USBInterfaceOpen())) }
273 }
274
275 pub(crate) fn close(&mut self) -> Result<(), Error> {
276 unsafe { check_iokit_return(call_iokit_function!(self.raw, USBInterfaceClose())) }
277 }
278
279 pub(crate) fn create_async_event_source(&self) -> Result<CFRunLoopSource, Error> {
280 unsafe {
281 let mut raw_source: CFRunLoopSourceRef = std::ptr::null_mut();
282 check_iokit_return(call_iokit_function!(
283 self.raw,
284 CreateInterfaceAsyncEventSource(&mut raw_source)
285 ))?;
286 Ok(CFRunLoopSource::wrap_under_create_rule(raw_source))
287 }
288 }
289
290 pub(crate) fn endpoints(&self) -> Result<BTreeMap<u8, EndpointInfo>, Error> {
291 unsafe {
292 let mut endpoints = BTreeMap::new();
293 let mut count = 0;
294 check_iokit_return(call_iokit_function!(self.raw, GetNumEndpoints(&mut count)))?;
295
296 // Pipe references are 1-indexed
297 for pipe_ref in 1..=count {
298 let mut direction: u8 = 0;
299 let mut number: u8 = 0;
300 let mut transfer_type: u8 = 0;
301 let mut max_packet_size: u16 = 0;
302 let mut interval: u8 = 0;
303 let mut max_burst: u8 = 0;
304 let mut mult: u8 = 0;
305 let mut bytes_per_interval: u16 = 0;
306
307 check_iokit_return(call_iokit_function!(
308 self.raw,
309 GetPipePropertiesV2(
310 pipe_ref,
311 &mut direction,
312 &mut number,
313 &mut transfer_type,
314 &mut max_packet_size,
315 &mut interval,
316 &mut max_burst,
317 &mut mult,
318 &mut bytes_per_interval
319 )
320 ))?;
321
322 let endpoint = EndpointInfo {
323 pipe_ref,
324 direction,
325 number,
326 transfer_type,
327 max_packet_size,
328 interval,
329 max_burst,
330 mult,
331 bytes_per_interval,
332 };
333
334 endpoints.insert(endpoint.address(), endpoint);
335 }
336 Ok(endpoints)
337 }
338 }
339 }
340
341 impl Drop for IoKitInterface {
342 fn drop(&mut self) {
343 unsafe {
344 call_iokit_function!(self.raw, Release());
345 }
346 }
347 }
348
349 unsafe impl Send for IoKitInterface {}
350 unsafe impl Sync for IoKitInterface {}